nestrs-cli-rs 0.1.0

Rust port of the Nest CLI for the nestrs organization.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
//! Build and watch orchestration for Rust-native nestrs projects.
//!
//! Upstream source: `../nest-cli/lib/compiler`.

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use crate::configuration::{
    Asset, Builder, CompilerOptions, DEFAULT_OUT_DIR, DEFAULT_SOURCE_ROOT, ProjectConfiguration,
};
use crate::utils::get_default_tsconfig_path::get_default_tsconfig_path_in;

pub mod assets_manager;
pub mod base_compiler;
pub mod compiler;
pub mod defaults;
pub mod helpers;
pub mod hooks;
pub mod interfaces;
pub mod plugins;
pub mod rust_toolchain_loader;
pub mod swc;
pub mod watch_compiler;
pub mod webpack_compiler;

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConfigValue {
    Bool(bool),
    String(String),
    Object(BTreeMap<String, ConfigValue>),
}

pub fn get_value_of_path<'a>(
    object: &'a BTreeMap<String, ConfigValue>,
    property_path: &str,
) -> Option<&'a ConfigValue> {
    let mut current = object;
    let mut current_value = None;
    let mut path = String::new();
    let mut is_concat_in_progress = false;

    for fragment in property_path.split('.') {
        if fragment.starts_with('"') && fragment.ends_with('"') {
            path = strip_double_quotes(fragment);
        } else if fragment.starts_with('"') {
            path.push_str(&strip_double_quotes(fragment));
            path.push('.');
            is_concat_in_progress = true;
            continue;
        } else if is_concat_in_progress && !fragment.ends_with('"') {
            path.push_str(fragment);
            path.push('.');
            continue;
        } else if fragment.ends_with('"') {
            path.push_str(&strip_double_quotes(fragment));
            is_concat_in_progress = false;
        } else {
            path = fragment.to_string();
        }

        current_value = current.get(&path);
        match current_value {
            Some(ConfigValue::Object(next)) => current = next,
            Some(_) => {}
            None => return None,
        }
        path.clear();
    }

    current_value
}

pub fn get_value_or_default<'a>(
    object: &'a BTreeMap<String, ConfigValue>,
    property_path: &str,
    default: &'a ConfigValue,
) -> &'a ConfigValue {
    get_value_of_path(object, property_path).unwrap_or(default)
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum BuilderVariant {
    #[default]
    Cargo,
    Tsc,
    Swc,
    Webpack,
}

impl BuilderVariant {
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Tsc => "tsc",
            Self::Cargo => "cargo",
            Self::Swc => "swc",
            Self::Webpack => "webpack",
        }
    }
}

#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct CompilerCommandOptions {
    pub path: Option<String>,
    pub webpack: Option<bool>,
    pub webpack_path: Option<String>,
    pub builder: Option<BuilderVariant>,
    pub watch: Option<bool>,
    pub watch_assets: Option<bool>,
    pub type_check: Option<bool>,
    pub preserve_watch_output: Option<bool>,
}

#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct BuildCommand {
    pub apps: Vec<String>,
    pub options: CompilerCommandOptions,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BuildPlanRequest {
    pub cwd: PathBuf,
    pub command: BuildCommand,
    pub project: ProjectConfiguration,
    pub compiler_options: CompilerOptions,
    pub ts_build_info_file: Option<PathBuf>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BuildPlan {
    pub inputs: CompilerInputs,
    pub watch: Option<WatchOptions>,
    pub asset_deletes_on_unlink: Vec<AssetDeleteOnUnlink>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CompilerInputs {
    pub builder: BuilderVariant,
    pub cwd: PathBuf,
    pub apps: Vec<String>,
    pub ts_config_path: PathBuf,
    pub webpack_config_path: Option<PathBuf>,
    pub source_root: PathBuf,
    pub entry_file: String,
    pub output_dir: PathBuf,
    pub type_check: bool,
    pub assets: Vec<AssetPlan>,
    pub output_cleanup: Option<OutputCleanup>,
    pub swc: Option<SwcCompilerPlan>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SwcCompilerPlan {
    pub swcrc_path: Option<PathBuf>,
    pub cli_options: SwcCliOptions,
    pub type_checker: Option<SwcTypeCheckerPlan>,
    pub watch: Option<SwcWatchPlan>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SwcCliOptions {
    pub out_dir: PathBuf,
    pub filenames: Vec<PathBuf>,
    pub sync: bool,
    pub extensions: Vec<String>,
    pub copy_files: bool,
    pub include_dotfiles: bool,
    pub quiet: bool,
    pub watch: bool,
    pub strip_leading_paths: bool,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SwcTypeCheckerPlan {
    TypeCheckerHost(SwcTypeCheckerHostPlan),
    ForkedTypeChecker(SwcForkedTypeCheckerPlan),
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SwcTypeCheckerHostPlan {
    pub ts_config_path: PathBuf,
    pub output_dir: PathBuf,
    pub watch: bool,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SwcForkedTypeCheckerPlan {
    pub ts_config_path: PathBuf,
    pub app_name: Option<String>,
    pub source_root: PathBuf,
    pub watch: bool,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SwcWatchPlan {
    pub watch_files_in_src_dir: SwcWatchFilesInSrcDirPlan,
    pub watch_files_in_out_dir: SwcWatchFilesInOutDirPlan,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SwcWatchFilesInSrcDirPlan {
    pub src_dir: Option<PathBuf>,
    pub extensions: Vec<String>,
    pub ignore_initial: bool,
    pub await_write_finish_stability_threshold_ms: u64,
    pub await_write_finish_poll_interval_ms: u64,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SwcWatchFilesInOutDirPlan {
    pub out_dir: PathBuf,
    pub extensions: Vec<String>,
    pub debounce_ms: u64,
    pub ignore_initial: bool,
    pub await_write_finish_stability_threshold_ms: u64,
    pub await_write_finish_poll_interval_ms: u64,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AssetPlan {
    pub glob: String,
    pub include: Option<PathBuf>,
    pub exclude: Option<String>,
    pub out_dir: PathBuf,
    pub flat: bool,
    pub watch_assets: bool,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct OutputCleanup {
    pub out_dir: PathBuf,
    pub ts_build_info_file: Option<PathBuf>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WatchOptions {
    pub manual_restart: bool,
    pub preserve_watch_output: bool,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AssetDeleteOnUnlink {
    pub glob: String,
    pub out_dir: PathBuf,
}

pub fn get_builder(
    options: &CompilerCommandOptions,
    compiler_options: &CompilerOptions,
) -> BuilderVariant {
    if options.webpack == Some(true) {
        return BuilderVariant::Webpack;
    }

    if let Some(builder) = options.builder {
        return builder;
    }

    if compiler_options.webpack {
        return BuilderVariant::Webpack;
    }

    match compiler_options.builder {
        Builder::Cargo => BuilderVariant::Cargo,
        Builder::Tsc(_) => BuilderVariant::Tsc,
        Builder::Swc(_) => BuilderVariant::Swc,
        Builder::Webpack(_) => BuilderVariant::Webpack,
    }
}

pub fn get_tsc_config_path(
    options: &CompilerCommandOptions,
    compiler_options: &CompilerOptions,
) -> PathBuf {
    get_tsc_config_path_in(Path::new("."), options, compiler_options)
}

pub fn get_tsc_config_path_in(
    cwd: &Path,
    options: &CompilerCommandOptions,
    compiler_options: &CompilerOptions,
) -> PathBuf {
    if let Some(path) = &options.path {
        return PathBuf::from(path);
    }

    if let Some(path) = &compiler_options.ts_config_path {
        return PathBuf::from(path);
    }

    if let Builder::Tsc(builder_options) = &compiler_options.builder {
        if let Some(path) = &builder_options.config_path {
            return PathBuf::from(path);
        }
    }

    PathBuf::from(get_default_tsconfig_path_in(cwd))
}

pub fn get_webpack_config_path(
    options: &CompilerCommandOptions,
    compiler_options: &CompilerOptions,
) -> Option<PathBuf> {
    if let Some(path) = &options.webpack_path {
        return Some(PathBuf::from(path));
    }

    if let Some(path) = &compiler_options.webpack_config_path {
        return Some(PathBuf::from(path));
    }

    if let Builder::Webpack(builder_options) = &compiler_options.builder {
        return builder_options.config_path.as_ref().map(PathBuf::from);
    }

    None
}

pub fn create_build_plan(request: BuildPlanRequest) -> BuildPlan {
    let options = &request.command.options;
    let builder = get_builder(options, &request.compiler_options);
    let output_dir = get_output_dir(&request.compiler_options);
    let source_root = request
        .project
        .source_root
        .as_ref()
        .map(PathBuf::from)
        .unwrap_or_else(|| PathBuf::from(DEFAULT_SOURCE_ROOT));
    let entry_file = request
        .project
        .entry_file
        .clone()
        .unwrap_or_else(|| "main".to_string());
    let assets = create_asset_plans(
        &request.compiler_options.assets,
        &output_dir,
        options.watch_assets.unwrap_or(false),
    );
    let asset_deletes_on_unlink = assets
        .iter()
        .filter(|asset| asset.watch_assets)
        .map(|asset| AssetDeleteOnUnlink {
            glob: asset.glob.clone(),
            out_dir: asset.out_dir.clone(),
        })
        .collect();
    let watch_enabled = options.watch.unwrap_or(false);
    let type_check = options.type_check.unwrap_or(false);
    let ts_config_path = get_tsc_config_path_in(&request.cwd, options, &request.compiler_options);
    let swc = (builder == BuilderVariant::Swc).then(|| {
        create_swc_compiler_plan(
            &request.command.apps,
            &request.compiler_options,
            &ts_config_path,
            &source_root,
            &output_dir,
            type_check,
            watch_enabled,
        )
    });

    BuildPlan {
        inputs: CompilerInputs {
            builder,
            cwd: request.cwd,
            apps: request.command.apps,
            ts_config_path,
            webpack_config_path: get_webpack_config_path(options, &request.compiler_options),
            source_root,
            entry_file,
            output_dir: output_dir.clone(),
            type_check,
            assets,
            output_cleanup: request
                .compiler_options
                .delete_out_dir
                .unwrap_or(false)
                .then_some(OutputCleanup {
                    out_dir: output_dir,
                    ts_build_info_file: request.ts_build_info_file,
                }),
            swc,
        },
        watch: watch_enabled.then_some(WatchOptions {
            manual_restart: request.compiler_options.manual_restart,
            preserve_watch_output: options.preserve_watch_output.unwrap_or(false),
        }),
        asset_deletes_on_unlink,
    }
}

fn create_swc_compiler_plan(
    apps: &[String],
    compiler_options: &CompilerOptions,
    ts_config_path: &PathBuf,
    source_root: &PathBuf,
    output_dir: &PathBuf,
    type_check: bool,
    watch: bool,
) -> SwcCompilerPlan {
    let builder_options = match &compiler_options.builder {
        Builder::Swc(options) => Some(options),
        _ => None,
    };
    let cli_options = create_swc_cli_options(builder_options, source_root, output_dir, watch);

    SwcCompilerPlan {
        swcrc_path: builder_options
            .and_then(|options| options.swcrc_path.as_ref())
            .map(PathBuf::from),
        type_checker: type_check.then(|| {
            if watch {
                SwcTypeCheckerPlan::ForkedTypeChecker(SwcForkedTypeCheckerPlan {
                    ts_config_path: ts_config_path.clone(),
                    app_name: apps.first().cloned(),
                    source_root: source_root.clone(),
                    watch,
                })
            } else {
                SwcTypeCheckerPlan::TypeCheckerHost(SwcTypeCheckerHostPlan {
                    ts_config_path: ts_config_path.clone(),
                    output_dir: output_dir.clone(),
                    watch,
                })
            }
        }),
        watch: watch.then(|| create_swc_watch_plan(&cli_options)),
        cli_options,
    }
}

fn create_swc_cli_options(
    builder_options: Option<&crate::configuration::SwcBuilderOptions>,
    source_root: &PathBuf,
    output_dir: &PathBuf,
    watch: bool,
) -> SwcCliOptions {
    let default_filenames = vec![source_root.clone()];
    let default_extensions = vec![".js".to_string(), ".ts".to_string()];

    SwcCliOptions {
        out_dir: builder_options
            .and_then(|options| options.out_dir.as_ref())
            .map(PathBuf::from)
            .unwrap_or_else(|| output_dir.clone()),
        filenames: builder_options
            .map(|options| path_list_or_default(&options.filenames, default_filenames.clone()))
            .unwrap_or(default_filenames),
        sync: builder_options
            .and_then(|options| options.sync)
            .unwrap_or(false),
        extensions: builder_options
            .map(|options| string_list_or_default(&options.extensions, default_extensions.clone()))
            .unwrap_or(default_extensions),
        copy_files: builder_options
            .and_then(|options| options.copy_files)
            .unwrap_or(false),
        include_dotfiles: builder_options
            .and_then(|options| options.include_dotfiles)
            .unwrap_or(false),
        quiet: builder_options
            .and_then(|options| options.quiet)
            .unwrap_or(false),
        watch,
        strip_leading_paths: true,
    }
}

fn create_swc_watch_plan(cli_options: &SwcCliOptions) -> SwcWatchPlan {
    SwcWatchPlan {
        watch_files_in_src_dir: SwcWatchFilesInSrcDirPlan {
            src_dir: cli_options.filenames.first().cloned(),
            extensions: cli_options.extensions.clone(),
            ignore_initial: true,
            await_write_finish_stability_threshold_ms: 50,
            await_write_finish_poll_interval_ms: 10,
        },
        watch_files_in_out_dir: SwcWatchFilesInOutDirPlan {
            out_dir: cli_options.out_dir.clone(),
            extensions: vec![".js".to_string(), ".mjs".to_string()],
            debounce_ms: 150,
            ignore_initial: true,
            await_write_finish_stability_threshold_ms: 50,
            await_write_finish_poll_interval_ms: 10,
        },
    }
}

fn path_list_or_default(values: &[String], default: Vec<PathBuf>) -> Vec<PathBuf> {
    if values.is_empty() {
        default
    } else {
        values.iter().map(PathBuf::from).collect()
    }
}

fn string_list_or_default(values: &[String], default: Vec<String>) -> Vec<String> {
    if values.is_empty() {
        default
    } else {
        values.to_vec()
    }
}

fn get_output_dir(compiler_options: &CompilerOptions) -> PathBuf {
    if let Builder::Swc(options) = &compiler_options.builder {
        if let Some(out_dir) = &options.out_dir {
            return PathBuf::from(out_dir);
        }
    }

    PathBuf::from(DEFAULT_OUT_DIR)
}

fn create_asset_plans(
    assets: &[Asset],
    default_out_dir: &PathBuf,
    default_watch_assets: bool,
) -> Vec<AssetPlan> {
    assets
        .iter()
        .map(|asset| match asset {
            Asset::Glob(glob) => AssetPlan {
                glob: glob.clone(),
                include: None,
                exclude: None,
                out_dir: default_out_dir.clone(),
                flat: false,
                watch_assets: default_watch_assets,
            },
            Asset::Entry(entry) => AssetPlan {
                glob: entry.glob.clone(),
                include: entry.include.as_ref().map(PathBuf::from),
                exclude: entry.exclude.clone(),
                out_dir: entry
                    .out_dir
                    .as_ref()
                    .map(PathBuf::from)
                    .unwrap_or_else(|| default_out_dir.clone()),
                flat: entry.flat.unwrap_or(false),
                watch_assets: entry.watch_assets.unwrap_or(default_watch_assets),
            },
        })
        .collect()
}

fn strip_double_quotes(text: &str) -> String {
    text.replace('"', "")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn reads_path_with_quoted_fragment_containing_dot() {
        let mut app = BTreeMap::new();
        app.insert(
            "sourceRoot".to_string(),
            ConfigValue::String("src".to_string()),
        );

        let mut projects = BTreeMap::new();
        projects.insert("api.v1".to_string(), ConfigValue::Object(app));

        let mut root = BTreeMap::new();
        root.insert("projects".to_string(), ConfigValue::Object(projects));

        assert_eq!(
            get_value_of_path(&root, "projects.\"api.v1\".sourceRoot"),
            Some(&ConfigValue::String("src".to_string()))
        );
    }
}