-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathmod.rs
1326 lines (1121 loc) · 34.9 KB
/
mod.rs
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
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use self::util::BoolOrObject;
use crate::{builder::PassBuilder, SwcComments, SwcImportResolver};
use anyhow::{bail, Context, Error};
use dashmap::DashMap;
use either::Either;
use once_cell::sync::Lazy;
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::{
cell::RefCell,
collections::{HashMap, HashSet},
env,
hash::BuildHasher,
path::{Path, PathBuf},
rc::Rc as RustRc,
sync::Arc,
usize,
};
use swc_atoms::JsWord;
pub use swc_common::chain;
use swc_common::{
collections::{AHashMap, AHashSet},
errors::Handler,
FileName, Mark, SourceMap,
};
use swc_ecma_ast::{Expr, ExprStmt, ModuleItem, Stmt};
use swc_ecma_ext_transforms::jest;
use swc_ecma_loader::resolvers::{
lru::CachingResolver, node::NodeModulesResolver, tsc::TsConfigResolver,
};
use swc_ecma_minifier::option::{
terser::{TerserCompressorOptions, TerserEcmaVersion},
MangleOptions, ManglePropertiesOptions,
};
pub use swc_ecma_parser::JscTarget;
use swc_ecma_parser::{lexer::Lexer, Parser, StringInput, Syntax, TsConfig};
use swc_ecma_transforms::{
hygiene, modules,
modules::{hoist::import_hoister, path::NodeImportResolver, util::Scope},
optimization::{const_modules, inline_globals, json_parse, simplifier},
pass::{noop, Optional},
proposals::{decorators, export_default_from, import_assertions},
react, resolver_with_mark, typescript,
};
use swc_ecma_visit::Fold;
#[cfg(test)]
mod tests;
pub mod util;
#[derive(Default, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ParseOptions {
#[serde(default)]
pub comments: bool,
#[serde(flatten)]
pub syntax: Syntax,
#[serde(default = "default_is_module")]
pub is_module: bool,
#[serde(default)]
pub target: JscTarget,
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct Options {
#[serde(flatten)]
pub config: Config,
#[serde(skip_deserializing, default)]
pub skip_helper_injection: bool,
#[serde(skip_deserializing, default)]
pub disable_hygiene: bool,
#[serde(skip_deserializing, default)]
pub disable_fixer: bool,
#[serde(skip_deserializing, default)]
pub global_mark: Option<Mark>,
#[cfg(not(target_arch = "wasm32"))]
#[serde(default = "default_cwd")]
pub cwd: PathBuf,
#[serde(default)]
pub caller: Option<CallerOptions>,
#[serde(default)]
pub filename: String,
#[serde(default)]
pub config_file: Option<ConfigFile>,
#[serde(default)]
pub root: Option<PathBuf>,
#[serde(default)]
pub root_mode: RootMode,
#[serde(default = "default_swcrc")]
pub swcrc: bool,
#[cfg(not(target_arch = "wasm32"))]
#[serde(default)]
pub swcrc_roots: Option<PathBuf>,
#[serde(default = "default_env_name")]
pub env_name: String,
#[serde(default)]
pub source_maps: Option<SourceMapsConfig>,
#[serde(default)]
pub source_file_name: Option<String>,
#[serde(default)]
pub source_root: Option<String>,
#[serde(default = "default_is_module")]
pub is_module: bool,
#[serde(default)]
pub output_path: Option<PathBuf>,
}
impl Options {
pub fn codegen_target(&self) -> Option<JscTarget> {
self.config.jsc.target
}
}
fn default_is_module() -> bool {
true
}
/// Configuration related to source map generated by swc.
#[derive(Clone, Serialize, Deserialize, Debug)]
#[serde(untagged)]
pub enum SourceMapsConfig {
Bool(bool),
Str(String),
}
impl SourceMapsConfig {
pub fn enabled(&self) -> bool {
match *self {
SourceMapsConfig::Bool(b) => b,
SourceMapsConfig::Str(ref s) => {
assert_eq!(s, "inline", "Source map must be true, false or inline");
true
}
}
}
}
impl Default for SourceMapsConfig {
fn default() -> Self {
SourceMapsConfig::Bool(true)
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum InputSourceMap {
Bool(bool),
Str(String),
}
impl Default for InputSourceMap {
fn default() -> Self {
InputSourceMap::Bool(false)
}
}
impl Options {
pub fn build<'a>(
&self,
cm: &Arc<SourceMap>,
base: &FileName,
output_path: Option<&Path>,
source_file_name: Option<String>,
handler: &Handler,
is_module: bool,
config: Option<Config>,
comments: Option<&'a SwcComments>,
custom_before_pass: impl 'a + swc_ecma_visit::Fold,
) -> BuiltConfig<impl 'a + swc_ecma_visit::Fold> {
let mut config = config.unwrap_or_else(Default::default);
config.merge(&self.config);
let mut source_maps = self.source_maps.clone();
source_maps.merge(&config.source_maps);
let JscConfig {
transform,
syntax,
external_helpers,
target,
loose,
keep_class_names,
base_url,
paths,
minify: js_minify,
..
} = config.jsc;
let target = target.unwrap_or_default();
let syntax = syntax.unwrap_or_default();
let mut transform = transform.unwrap_or_default();
let preserve_comments = js_minify.as_ref().map(|v| v.format.comments.clone());
if syntax.typescript() {
transform.legacy_decorator = true;
}
let optimizer = transform.optimizer;
let enable_optimizer = optimizer.is_some();
let const_modules = {
let enabled = transform.const_modules.is_some();
let config = transform.const_modules.unwrap_or_default();
let globals = config.globals;
Optional::new(const_modules(cm.clone(), globals), enabled)
};
let json_parse_pass = {
if let Some(ref cfg) = optimizer.as_ref().and_then(|v| v.jsonify) {
Either::Left(json_parse(cfg.min_cost))
} else {
Either::Right(noop())
}
};
let optimization = {
let pass =
if let Some(opts) = optimizer.map(|o| o.globals.unwrap_or_else(Default::default)) {
opts.build(cm, handler)
} else {
GlobalPassOption::default().build(cm, handler)
};
pass
};
let top_level_mark = self
.global_mark
.unwrap_or_else(|| Mark::fresh(Mark::root()));
let pass = chain!(
const_modules,
optimization,
Optional::new(export_default_from(), syntax.export_default_from()),
Optional::new(simplifier(Default::default()), enable_optimizer),
json_parse_pass
);
let pass = PassBuilder::new(&cm, &handler, loose, top_level_mark, pass)
.target(target)
.skip_helper_injection(self.skip_helper_injection)
.minify(js_minify)
.hygiene(if self.disable_hygiene {
None
} else {
Some(hygiene::Config { keep_class_names })
})
.fixer(!self.disable_fixer)
.preset_env(config.env)
.finalize(
base_url,
paths.into_iter().collect(),
base,
syntax,
config.module,
comments,
);
let pass = chain!(
// Decorators may use type information
Optional::new(
decorators(decorators::Config {
legacy: transform.legacy_decorator,
emit_metadata: transform.decorator_metadata,
}),
syntax.decorators()
),
import_assertions(),
Optional::new(
typescript::strip_with_jsx(
cm.clone(),
typescript::Config {
pragma: Some(transform.react.pragma.clone()),
pragma_frag: Some(transform.react.pragma_frag.clone()),
..Default::default()
},
comments.clone(),
top_level_mark
),
syntax.typescript()
),
resolver_with_mark(top_level_mark),
custom_before_pass,
// handle jsx
Optional::new(
react::react(
cm.clone(),
comments.clone(),
transform.react,
top_level_mark
),
syntax.jsx()
),
pass,
Optional::new(jest::jest(), transform.hidden.jest)
);
BuiltConfig {
minify: config.minify,
pass,
external_helpers,
syntax,
target,
is_module,
source_maps: source_maps.unwrap_or(SourceMapsConfig::Bool(false)),
inline_sources_content: config.inline_sources_content,
input_source_map: self.config.input_source_map.clone(),
output_path: output_path.map(|v| v.to_path_buf()),
source_file_name,
preserve_comments,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum RootMode {
#[serde(rename = "root")]
Root,
#[serde(rename = "upward")]
Upward,
#[serde(rename = "upward-optional")]
UpwardOptional,
}
impl Default for RootMode {
fn default() -> Self {
RootMode::Root
}
}
const fn default_swcrc() -> bool {
true
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ConfigFile {
Bool(bool),
Str(String),
}
impl Default for ConfigFile {
fn default() -> Self {
ConfigFile::Bool(true)
}
}
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CallerOptions {
pub name: String,
}
#[cfg(not(target_arch = "wasm32"))]
fn default_cwd() -> PathBuf {
::std::env::current_dir().unwrap()
}
/// `.swcrc` file
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged, rename = "swcrc")]
pub enum Rc {
Single(Config),
Multi(Vec<Config>),
}
impl Default for Rc {
fn default() -> Self {
Rc::Multi(vec![
Config {
env: None,
test: None,
exclude: Some(FileMatcher::Regex("\\.tsx?$".into())),
jsc: JscConfig {
syntax: Some(Default::default()),
transform: None,
external_helpers: false,
target: Default::default(),
loose: false,
keep_class_names: false,
..Default::default()
},
module: None,
minify: false,
source_maps: None,
input_source_map: InputSourceMap::default(),
..Default::default()
},
Config {
env: None,
test: Some(FileMatcher::Regex("\\.tsx$".into())),
exclude: None,
jsc: JscConfig {
syntax: Some(Syntax::Typescript(TsConfig {
tsx: true,
..Default::default()
})),
transform: None,
external_helpers: false,
target: Default::default(),
loose: false,
keep_class_names: false,
..Default::default()
},
module: None,
minify: false,
source_maps: None,
input_source_map: InputSourceMap::default(),
..Default::default()
},
Config {
env: None,
test: Some(FileMatcher::Regex("\\.ts$".into())),
exclude: None,
jsc: JscConfig {
syntax: Some(Syntax::Typescript(TsConfig {
tsx: false,
..Default::default()
})),
transform: None,
external_helpers: false,
target: Default::default(),
loose: false,
keep_class_names: false,
..Default::default()
},
module: None,
minify: false,
source_maps: None,
input_source_map: InputSourceMap::default(),
..Default::default()
},
])
}
}
impl Rc {
/// This method returns `Ok(None)` if the file should be ignored.
pub fn into_config(self, filename: Option<&Path>) -> Result<Option<Config>, Error> {
let cs = match self {
Rc::Single(mut c) => match filename {
Some(filename) => {
if c.matches(filename)? {
c.adjust(filename);
return Ok(Some(c));
} else {
return Ok(None);
}
}
// TODO
None => return Ok(Some(c)),
},
Rc::Multi(cs) => cs,
};
match filename {
Some(filename) => {
for mut c in cs {
if c.matches(filename)? {
c.adjust(filename);
return Ok(Some(c));
}
}
}
None => return Ok(Some(Config::default())),
}
bail!(".swcrc exists but not matched")
}
}
/// A single object in the `.swcrc` file
#[derive(Debug, Default, Clone, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct Config {
#[serde(default)]
pub env: Option<swc_ecma_preset_env::Config>,
#[serde(default)]
pub test: Option<FileMatcher>,
#[serde(default)]
pub exclude: Option<FileMatcher>,
#[serde(default)]
pub jsc: JscConfig,
#[serde(default)]
pub module: Option<ModuleConfig>,
#[serde(default)]
pub minify: bool,
#[serde(default)]
pub input_source_map: InputSourceMap,
/// Possible values are: `'inline'`, `true`, `false`.
#[serde(default)]
pub source_maps: Option<SourceMapsConfig>,
#[serde(default)]
pub inline_sources_content: bool,
}
/// Second argument of `minify`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct JsMinifyOptions {
#[serde(default)]
pub compress: BoolOrObject<TerserCompressorOptions>,
#[serde(default)]
pub mangle: BoolOrObject<MangleOptions>,
#[serde(default)]
pub format: JsMinifyFormatOptions,
#[serde(default)]
pub ecma: TerserEcmaVersion,
#[serde(default)]
pub keep_classnames: bool,
#[serde(default)]
pub keep_fnames: bool,
#[serde(default)]
pub module: bool,
#[serde(default)]
pub safari10: bool,
#[serde(default)]
pub toplevel: bool,
#[serde(default)]
pub source_map: BoolOrObject<TerserSourceMapOption>,
#[serde(default)]
pub output_path: Option<String>,
#[serde(default = "true_by_default")]
pub inline_sources_content: bool,
}
fn true_by_default() -> bool {
true
}
/// `jsc.minify.sourceMap`
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct TerserSourceMapOption {
#[serde(default)]
pub filename: Option<String>,
#[serde(default)]
pub url: Option<String>,
#[serde(default)]
pub root: Option<String>,
#[serde(default)]
pub content: Option<String>,
}
/// `jsc.minify.format`.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct JsMinifyFormatOptions {
/// Not implemented yet.
#[serde(default, alias = "ascii_only")]
pub ascii_only: bool,
/// Not implemented yet.
#[serde(default)]
pub beautify: bool,
/// Not implemented yet.
#[serde(default)]
pub braces: bool,
#[serde(default)]
pub comments: BoolOrObject<JsMinifyCommentOption>,
/// Not implemented yet.
#[serde(default)]
pub ecma: usize,
/// Not implemented yet.
#[serde(default, alias = "indent_level")]
pub indent_level: usize,
/// Not implemented yet.
#[serde(default, alias = "indent_start")]
pub indent_start: bool,
/// Not implemented yet.
#[serde(default, alias = "inline_script")]
pub inline_script: bool,
/// Not implemented yet.
#[serde(default, alias = "keep_numbers")]
pub keep_numbers: bool,
/// Not implemented yet.
#[serde(default, alias = "keep_quoted_props")]
pub keep_quoted_props: bool,
/// Not implemented yet.
#[serde(default, alias = "max_line_len")]
pub max_line_len: BoolOrObject<usize>,
/// Not implemented yet.
#[serde(default)]
pub preamble: String,
/// Not implemented yet.
#[serde(default, alias = "quote_keys")]
pub quote_keys: bool,
/// Not implemented yet.
#[serde(default, alias = "quote_style")]
pub quote_style: usize,
/// Not implemented yet.
#[serde(default, alias = "preserve_annotations")]
pub preserve_annotations: bool,
/// Not implemented yet.
#[serde(default)]
pub safari10: bool,
/// Not implemented yet.
#[serde(default)]
pub semicolons: bool,
/// Not implemented yet.
#[serde(default)]
pub shebang: bool,
/// Not implemented yet.
#[serde(default)]
pub webkit: bool,
/// Not implemented yet.
#[serde(default, alias = "warp_iife")]
pub wrap_iife: bool,
/// Not implemented yet.
#[serde(default, alias = "wrap_func_args")]
pub wrap_func_args: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum JsMinifyCommentOption {
#[serde(rename = "some")]
PreserveSomeComments,
#[serde(rename = "all")]
PreserveAllComments,
}
impl Default for JsMinifyCommentOption {
fn default() -> Self {
JsMinifyCommentOption::PreserveSomeComments
}
}
impl Config {
/// Adjust config for `file`.
///
///
///
/// - typescript: `tsx` will be modified if file extension is `ts`.
pub fn adjust(&mut self, file: &Path) {
match &mut self.jsc.syntax {
Some(Syntax::Typescript(TsConfig { tsx, .. })) => {
let is_ts = file.extension().map(|v| v == "ts").unwrap_or(false);
if is_ts {
*tsx = false;
}
}
_ => {}
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum FileMatcher {
Regex(String),
Multi(Vec<FileMatcher>),
}
impl Default for FileMatcher {
fn default() -> Self {
Self::Regex(String::from(""))
}
}
impl FileMatcher {
pub fn matches(&self, filename: &Path) -> Result<bool, Error> {
static CACHE: Lazy<DashMap<String, Regex, ahash::RandomState>> =
Lazy::new(Default::default);
match self {
FileMatcher::Regex(ref s) => {
if s.is_empty() {
return Ok(false);
}
if !CACHE.contains_key(&*s) {
let re = Regex::new(&s).with_context(|| format!("invalid regex: {}", s))?;
CACHE.insert(s.clone(), re);
}
let re = CACHE.get(&*s).unwrap();
let filename = if cfg!(target_os = "windows") {
filename.to_string_lossy().replace("\\", "/")
} else {
filename.to_string_lossy().to_string()
};
Ok(re.is_match(&filename))
}
FileMatcher::Multi(ref v) => {
//
for m in v {
if m.matches(filename)? {
return Ok(true);
}
}
Ok(false)
}
}
}
}
impl Config {
pub fn matches(&self, filename: &Path) -> Result<bool, Error> {
if let Some(ref exclude) = self.exclude {
if exclude.matches(filename)? {
return Ok(false);
}
}
if let Some(ref include) = self.test {
if include.matches(filename)? {
return Ok(true);
}
return Ok(false);
}
Ok(true)
}
}
/// One `BuiltConfig` per a directory with swcrc
pub struct BuiltConfig<P: swc_ecma_visit::Fold> {
pub pass: P,
pub syntax: Syntax,
pub target: JscTarget,
/// Minification for **codegen**. Minifier transforms will be inserted into
/// `pass`.
pub minify: bool,
pub external_helpers: bool,
pub source_maps: SourceMapsConfig,
pub input_source_map: InputSourceMap,
pub is_module: bool,
pub output_path: Option<PathBuf>,
pub source_file_name: Option<String>,
pub preserve_comments: Option<BoolOrObject<JsMinifyCommentOption>>,
pub inline_sources_content: bool,
}
/// `jsc` in `.swcrc`.
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct JscConfig {
#[serde(rename = "parser", default)]
pub syntax: Option<Syntax>,
#[serde(default)]
pub transform: Option<TransformConfig>,
#[serde(default)]
pub external_helpers: bool,
#[serde(default)]
pub target: Option<JscTarget>,
#[serde(default)]
pub loose: bool,
#[serde(default)]
pub keep_class_names: bool,
#[serde(default)]
pub base_url: PathBuf,
#[serde(default)]
pub paths: Paths,
#[serde(default)]
pub minify: Option<JsMinifyOptions>,
#[serde(default)]
pub experimental: JscExperimental,
}
/// `jsc.experimental` in `.swcrc`
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct JscExperimental {}
impl Merge for JscExperimental {
fn merge(&mut self, _from: &Self) {}
}
/// `paths` sectiob of `tsconfig.json`.
pub type Paths = AHashMap<String, Vec<String>>;
pub(crate) type CompiledPaths = Vec<(String, Vec<String>)>;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
#[serde(tag = "type")]
pub enum ModuleConfig {
#[serde(rename = "commonjs")]
CommonJs(modules::common_js::Config),
#[serde(rename = "umd")]
Umd(modules::umd::Config),
#[serde(rename = "amd")]
Amd(modules::amd::Config),
#[serde(rename = "es6")]
Es6,
}
impl ModuleConfig {
pub fn build(
cm: Arc<SourceMap>,
base_url: PathBuf,
paths: CompiledPaths,
base: &FileName,
root_mark: Mark,
config: Option<ModuleConfig>,
scope: RustRc<RefCell<Scope>>,
) -> Box<dyn swc_ecma_visit::Fold> {
let base = match base {
FileName::Real(v) if !paths.is_empty() => {
FileName::Real(v.canonicalize().unwrap_or_else(|_| v.to_path_buf()))
}
_ => base.clone(),
};
match config {
None | Some(ModuleConfig::Es6) => Box::new(import_hoister()),
Some(ModuleConfig::CommonJs(config)) => {
if paths.is_empty() {
Box::new(modules::common_js::common_js(
root_mark,
config,
Some(scope),
))
} else {
let resolver = build_resolver(base_url, paths);
Box::new(modules::common_js::common_js_with_resolver(
resolver,
base,
root_mark,
config,
Some(scope),
))
}
}
Some(ModuleConfig::Umd(config)) => {
if paths.is_empty() {
Box::new(modules::umd::umd(cm, root_mark, config))
} else {
let resolver = build_resolver(base_url, paths);
Box::new(modules::umd::umd_with_resolver(
resolver, base, cm, root_mark, config,
))
}
}
Some(ModuleConfig::Amd(config)) => {
if paths.is_empty() {
Box::new(modules::amd::amd(config))
} else {
let resolver = build_resolver(base_url, paths);
Box::new(modules::amd::amd_with_resolver(resolver, base, config))
}
}
}
}
}
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct TransformConfig {
#[serde(default)]
pub react: react::Options,
#[serde(default)]
pub const_modules: Option<ConstModulesConfig>,
#[serde(default)]
pub optimizer: Option<OptimizerConfig>,
#[serde(default)]
pub legacy_decorator: bool,
#[serde(default)]
pub decorator_metadata: bool,
#[serde(default)]
pub hidden: HiddenTransformConfig,
}
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct HiddenTransformConfig {
#[serde(default)]
pub jest: bool,
}
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct ConstModulesConfig {
#[serde(default)]
pub globals: HashMap<JsWord, HashMap<JsWord, String>>,
}
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct OptimizerConfig {
#[serde(default)]
pub globals: Option<GlobalPassOption>,
#[serde(default)]
pub jsonify: Option<JsonifyOption>,
}
#[derive(Debug, Default, Clone, Copy, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct JsonifyOption {
#[serde(default = "default_jsonify_min_cost")]
pub min_cost: usize,
}
fn default_jsonify_min_cost() -> usize {
1024
}
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct GlobalPassOption {
#[serde(default)]
pub vars: AHashMap<String, String>,
#[serde(default = "default_envs")]
pub envs: AHashSet<String>,
}
fn default_envs() -> AHashSet<String> {
let mut v = HashSet::default();
v.insert(String::from("NODE_ENV"));
v.insert(String::from("SWC_ENV"));
v
}