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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
//! The main crate of the swc project.
//!
//!
//!
//! # Customizing
//!
//!
//! This is documentation for building custom build tools on top of swc.
//!
//! ## Dependency version management
//!
//! `swc` has [swc_css](https://docs.rs/swc_css), which re-exports required modules.
//!
//! ## Testing
//!
//! See [testing] and [swc_ecma_transforms_testing](https://docs.rs/swc_ecma_transforms_testing).
//!
//! ## Custom javascript transforms
//!
//!
//!
//! ### What is [JsWord](swc_atoms::JsWord)?
//!
//! It's basically an interned string. See [swc_atoms].
//!
//! ### Choosing between [JsWord](swc_atoms::JsWord) vs String
//!
//! You should  prefer [JsWord](swc_atoms::JsWord) over [String] if it's going
//! to be stored in an AST node.
//!
//! See [swc_atoms] for detailed description.
//!
//! ### Fold vs VisitMut vs Visit
//!
//! See [swc_visit] for detailed description.
//!
//!
//!  - [Fold](swc_ecma_visit::Fold)
//!  - [VisitMut](swc_ecma_visit::VisitMut)
//!  - [Visit](swc_ecma_visit::Visit)
//!
//!
//! ### Variable management (Scoping)
//!
//! See [swc_ecma_transforms_base::resolver::resolver_with_mark].
//!
//! #### How identifiers work
//!
//! See the doc on [swc_ecma_ast::Ident] or on
//! [swc_ecma_transforms_base::resolver::resolver_with_mark].
//!
//! #### Comparing two identifiers
//!
//! See [swc_ecma_utils::Id]. You can use [swc_ecma_utils::IdentLike::to_id] to
//! extract important parts of an [swc_ecma_ast::Ident].
//!
//! #### Creating a unique identifier
//!
//! See [swc_ecma_utils::private_ident].
//!
//! #### Prepending statements
//!
//! If you want to prepend statements to the beginning of a file, you can use
//! [swc_ecma_utils::prepend_stmts] or [swc_ecma_utils::prepend] if `len == 1`.
//!
//! These methods are aware of the fact that `"use strict"` directive should be
//! first in a file, and insert statements after directives.
//!
//! ### Improving readability
//!
//! Each stuffs are documented at itself.
//!
//!  - If you are creating or binding an [swc_ecma_ast::Expr] with operator, you
//!    can use [swc_ecma_ast::op].
//!
//!  - If you want to create [swc_ecma_ast::CallExpr], you can use
//!    [swc_ecma_utils::ExprFactory::as_callee] to create `callee`.
//!
//!  - If you want to create [swc_ecma_ast::CallExpr] or
//!    [swc_ecma_ast::NewExpr], you can use
//!    [swc_ecma_utils::ExprFactory::as_arg] to create arguments.
//!
//!
//!  - If you want to create [swc_ecma_ast::MemberExpr] where all identifiers
//!    are static (e.g. `Object.prototype.hasOwnProperty`), you can use
//!    [swc_ecma_utils::member_expr].
//!
//!  - If you want to create [swc_ecma_ast::MemberExpr], you can use
//!    [swc_ecma_utils::ExprFactory::as_obj] to create object field.
//!
//!
//! ### Reducing binary size
//!
//! The visitor expands to a lot of code. You can reduce it by using macros like
//!
//!  - [noop_fold_type](swc_ecma_visit::noop_fold_type)
//!  - [noop_visit_mut_type](swc_ecma_visit::noop_visit_mut_type)
//!  - [noop_visit_type](swc_ecma_visit::noop_visit_type)
//!
//! Note that this will make typescript-related nodes not processed, but it's
//! typically fine as `typescript::strip` is invoked at the start and it removes
//! typescript-specific nodes.
//!
//! ### Porting `expr.evaluate()` of babel
//!
//! See [swc_ecma_minifier::eval::Evaluator].
#![deny(unused)]
#![allow(clippy::too_many_arguments)]
#![allow(clippy::mutable_key_type)]
#![cfg_attr(docsrs, feature(doc_cfg))]

pub extern crate swc_atoms as atoms;
extern crate swc_common as common;

use std::{
    fs::{read_to_string, File},
    path::{Path, PathBuf},
    sync::Arc,
};

use anyhow::{bail, Context, Error};
use base64::prelude::{Engine, BASE64_STANDARD};
use common::{
    comments::{Comment, SingleThreadedComments},
    errors::HANDLER,
};
use jsonc_parser::{parse_to_serde_value, ParseOptions};
use once_cell::sync::Lazy;
use serde_json::error::Category;
pub use sourcemap;
use swc_common::{
    chain, comments::Comments, errors::Handler, sync::Lrc, FileName, Mark, SourceFile, SourceMap,
    Spanned, GLOBALS,
};
pub use swc_compiler_base::{PrintArgs, TransformOutput};
pub use swc_config::config_types::{BoolConfig, BoolOr, BoolOrDataConfig};
use swc_ecma_ast::{EsVersion, Program};
use swc_ecma_codegen::Node;
use swc_ecma_loader::resolvers::{
    lru::CachingResolver, node::NodeModulesResolver, tsc::TsConfigResolver,
};
use swc_ecma_minifier::option::{MinifyOptions, TopLevelOptions};
use swc_ecma_parser::{EsConfig, Syntax};
use swc_ecma_transforms::{
    fixer,
    helpers::{self, Helpers},
    hygiene,
    modules::path::NodeImportResolver,
    pass::noop,
    resolver,
};
use swc_ecma_transforms_base::fixer::paren_remover;
use swc_ecma_visit::{FoldWith, VisitMutWith, VisitWith};
pub use swc_error_reporters::handler::{try_with_handler, HandlerOpts};
pub use swc_node_comments::SwcComments;
use swc_timer::timer;
use url::Url;

pub use crate::builder::PassBuilder;
use crate::config::{
    BuiltInput, Config, ConfigFile, InputSourceMap, IsModule, JsMinifyCommentOption,
    JsMinifyOptions, Options, OutputCharset, Rc, RootMode, SourceMapsConfig,
};

mod builder;
pub mod config;
mod dropped_comments_preserver;
mod plugin;
pub mod resolver {
    use std::path::PathBuf;

    use swc_common::collections::AHashMap;
    use swc_ecma_loader::{
        resolvers::{lru::CachingResolver, node::NodeModulesResolver, tsc::TsConfigResolver},
        TargetEnv,
    };

    use crate::config::CompiledPaths;

    pub type NodeResolver = CachingResolver<NodeModulesResolver>;

    pub fn paths_resolver(
        target_env: TargetEnv,
        alias: AHashMap<String, String>,
        base_url: PathBuf,
        paths: CompiledPaths,
        preserve_symlinks: bool,
    ) -> CachingResolver<TsConfigResolver<NodeModulesResolver>> {
        let r = TsConfigResolver::new(
            NodeModulesResolver::without_node_modules(target_env, alias, preserve_symlinks),
            base_url,
            paths,
        );
        CachingResolver::new(40, r)
    }

    pub fn environment_resolver(
        target_env: TargetEnv,
        alias: AHashMap<String, String>,
        preserve_symlinks: bool,
    ) -> NodeResolver {
        CachingResolver::new(
            40,
            NodeModulesResolver::new(target_env, alias, preserve_symlinks),
        )
    }
}

type SwcImportResolver = Arc<
    NodeImportResolver<CachingResolver<TsConfigResolver<CachingResolver<NodeModulesResolver>>>>,
>;

/// All methods accept [Handler], which is a storage for errors.
///
/// The caller should check if the handler contains any errors after calling
/// method.
pub struct Compiler {
    /// CodeMap
    pub cm: Arc<SourceMap>,
    comments: SwcComments,
}

/// These are **low-level** apis.
impl Compiler {
    pub fn comments(&self) -> &SwcComments {
        &self.comments
    }

    /// Runs `op` in current compiler's context.
    ///
    /// Note: Other methods of `Compiler` already uses this internally.
    pub fn run<R, F>(&self, op: F) -> R
    where
        F: FnOnce() -> R,
    {
        debug_assert!(
            GLOBALS.is_set(),
            "`swc_common::GLOBALS` is required for this operation"
        );

        op()
    }

    fn get_orig_src_map(
        &self,
        fm: &SourceFile,
        input_src_map: &InputSourceMap,
        comments: &[Comment],
        is_default: bool,
    ) -> Result<Option<sourcemap::SourceMap>, Error> {
        self.run(|| -> Result<_, Error> {
            let name = &fm.name;

            let read_inline_sourcemap =
                |data_url: Option<&str>| -> Result<Option<sourcemap::SourceMap>, Error> {
                    match data_url {
                        Some(data_url) => {
                            let url = Url::parse(data_url).with_context(|| {
                                format!("failed to parse inline source map url\n{}", data_url)
                            })?;

                            let idx = match url.path().find("base64,") {
                                Some(v) => v,
                                None => {
                                    bail!(
                                        "failed to parse inline source map: not base64: {:?}",
                                        url
                                    )
                                }
                            };

                            let content = url.path()[idx + "base64,".len()..].trim();

                            let res = BASE64_STANDARD
                                .decode(content.as_bytes())
                                .context("failed to decode base64-encoded source map")?;

                            Ok(Some(sourcemap::SourceMap::from_slice(&res).context(
                                "failed to read input source map from inlined base64 encoded \
                                 string",
                            )?))
                        }
                        None => {
                            bail!("failed to parse inline source map: `sourceMappingURL` not found")
                        }
                    }
                };

            let read_file_sourcemap =
                |data_url: Option<&str>| -> Result<Option<sourcemap::SourceMap>, Error> {
                    match &name {
                        FileName::Real(filename) => {
                            let dir = match filename.parent() {
                                Some(v) => v,
                                None => {
                                    bail!("unexpected: root directory is given as a input file")
                                }
                            };

                            let map_path = match data_url {
                                Some(data_url) => {
                                    let mut map_path = dir.join(data_url);
                                    if !map_path.exists() {
                                        // Old behavior. This check would prevent
                                        // regressions.
                                        // Perhaps it shouldn't be supported. Sometimes
                                        // developers don't want to expose their source
                                        // code.
                                        // Map files are for internal troubleshooting
                                        // convenience.
                                        map_path =
                                            PathBuf::from(format!("{}.map", filename.display()));
                                        if !map_path.exists() {
                                            bail!(
                                                "failed to find input source map file {:?} in \
                                                 {:?} file",
                                                map_path.display(),
                                                filename.display()
                                            )
                                        }
                                    }

                                    Some(map_path)
                                }
                                None => {
                                    // Old behavior.
                                    let map_path =
                                        PathBuf::from(format!("{}.map", filename.display()));
                                    if map_path.exists() {
                                        Some(map_path)
                                    } else {
                                        None
                                    }
                                }
                            };

                            match map_path {
                                Some(map_path) => {
                                    let path = map_path.display().to_string();
                                    let file = File::open(&path);

                                    // Old behavior.
                                    let file = if !is_default {
                                        file?
                                    } else {
                                        match file {
                                            Ok(v) => v,
                                            Err(_) => return Ok(None),
                                        }
                                    };

                                    Ok(Some(sourcemap::SourceMap::from_reader(file).with_context(
                                        || {
                                            format!(
                                                "failed to read input source map
                                from file at {}",
                                                path
                                            )
                                        },
                                    )?))
                                }
                                None => Ok(None),
                            }
                        }
                        _ => Ok(None),
                    }
                };

            let read_sourcemap = || -> Option<sourcemap::SourceMap> {
                let s = "sourceMappingURL=";

                let text = comments.iter().rev().find_map(|c| {
                    let idx = c.text.rfind(s)?;
                    let (_, url) = c.text.split_at(idx + s.len());

                    Some(url.trim())
                });

                match read_inline_sourcemap(text) {
                    Ok(r) => r,
                    Err(err) => {
                        // Load original source map if possible
                        match read_file_sourcemap(text) {
                            Ok(v) => v,
                            Err(_) => {
                                tracing::error!("failed to read input source map: {:?}", err);
                                None
                            }
                        }
                    }
                }
            };

            // Load original source map
            match input_src_map {
                InputSourceMap::Bool(false) => Ok(None),
                InputSourceMap::Bool(true) => Ok(read_sourcemap()),
                InputSourceMap::Str(ref s) => {
                    if s == "inline" {
                        Ok(read_sourcemap())
                    } else {
                        // Load source map passed by user
                        Ok(Some(
                            sourcemap::SourceMap::from_slice(s.as_bytes()).context(
                                "failed to read input source map from user-provided sourcemap",
                            )?,
                        ))
                    }
                }
            }
        })
    }

    /// This method parses a javascript / typescript file
    pub fn parse_js(
        &self,
        fm: Arc<SourceFile>,
        handler: &Handler,
        target: EsVersion,
        syntax: Syntax,
        is_module: IsModule,
        comments: Option<&dyn Comments>,
    ) -> Result<Program, Error> {
        swc_compiler_base::parse_js(
            self.cm.clone(),
            fm,
            handler,
            target,
            syntax,
            is_module,
            comments,
        )
    }

    /// Converts ast node to source string and sourcemap.
    ///
    ///
    /// This method receives target file path, but does not write file to the
    /// path. See: https://github.com/swc-project/swc/issues/1255
    #[allow(clippy::too_many_arguments)]
    pub fn print<T>(&self, node: &T, args: PrintArgs) -> Result<TransformOutput, Error>
    where
        T: Node + VisitWith<swc_compiler_base::IdentCollector>,
    {
        swc_compiler_base::print(self.cm.clone(), node, args)
    }
}

/// High-level apis.
impl Compiler {
    pub fn new(cm: Arc<SourceMap>) -> Self {
        Compiler {
            cm,
            comments: Default::default(),
        }
    }

    #[tracing::instrument(skip_all)]
    pub fn read_config(&self, opts: &Options, name: &FileName) -> Result<Option<Config>, Error> {
        static CUR_DIR: Lazy<PathBuf> = Lazy::new(|| {
            if cfg!(target_arch = "wasm32") {
                PathBuf::new()
            } else {
                ::std::env::current_dir().unwrap()
            }
        });

        self.run(|| -> Result<_, Error> {
            let Options {
                ref root,
                root_mode,
                swcrc,
                config_file,
                ..
            } = opts;

            let root = root.as_ref().unwrap_or(&CUR_DIR);

            let swcrc_path = match config_file {
                Some(ConfigFile::Str(s)) => Some(PathBuf::from(s.clone())),
                _ => {
                    if *swcrc {
                        if let FileName::Real(ref path) = name {
                            find_swcrc(path, root, *root_mode)
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                }
            };

            let config_file = match swcrc_path.as_deref() {
                Some(s) => Some(load_swcrc(s)?),
                _ => None,
            };
            let filename_path = match name {
                FileName::Real(p) => Some(&**p),
                _ => None,
            };

            if let Some(filename_path) = filename_path {
                if let Some(config) = config_file {
                    let dir = swcrc_path
                        .as_deref()
                        .and_then(|p| p.parent())
                        .expect(".swcrc path should have parent dir");

                    let mut config = config
                        .into_config(Some(filename_path))
                        .context("failed to process config file")?;

                    if let Some(c) = &mut config {
                        if c.jsc.base_url != PathBuf::new() {
                            let joined = dir.join(&c.jsc.base_url);
                            c.jsc.base_url = if cfg!(target_os = "windows")
                                && c.jsc.base_url.as_os_str() == "."
                            {
                                dir.canonicalize().with_context(|| {
                                    format!(
                                        "failed to canonicalize base url using the path of \
                                         .swcrc\nDir: {}\n(Used logic for windows)",
                                        dir.display(),
                                    )
                                })?
                            } else {
                                joined.canonicalize().with_context(|| {
                                    format!(
                                        "failed to canonicalize base url using the path of \
                                         .swcrc\nPath: {}\nDir: {}\nbaseUrl: {}",
                                        joined.display(),
                                        dir.display(),
                                        c.jsc.base_url.display()
                                    )
                                })?
                            };
                        }
                    }

                    return Ok(config);
                }

                let config_file = config_file.unwrap_or_default();
                let config = config_file.into_config(Some(filename_path))?;

                return Ok(config);
            }

            let config = match config_file {
                Some(config_file) => config_file.into_config(None)?,
                None => Rc::default().into_config(None)?,
            };

            match config {
                Some(config) => Ok(Some(config)),
                None => {
                    bail!("no config matched for file ({})", name)
                }
            }
        })
        .with_context(|| format!("failed to read .swcrc file for input file at `{}`", name))
    }

    /// This method returns [None] if a file should be skipped.
    ///
    /// This method handles merging of config.
    ///
    /// This method does **not** parse module.
    #[tracing::instrument(skip_all)]
    pub fn parse_js_as_input<'a, P>(
        &'a self,
        fm: Lrc<SourceFile>,
        program: Option<Program>,
        handler: &'a Handler,
        opts: &Options,
        name: &FileName,
        comments: Option<&'a SingleThreadedComments>,
        before_pass: impl 'a + FnOnce(&Program) -> P,
    ) -> Result<Option<BuiltInput<impl 'a + swc_ecma_visit::Fold>>, Error>
    where
        P: 'a + swc_ecma_visit::Fold,
    {
        self.run(move || {
            let _timer = timer!("Compiler.parse");

            if let FileName::Real(ref path) = name {
                if !opts.config.matches(path)? {
                    return Ok(None);
                }
            }

            let config = self.read_config(opts, name)?;
            let config = match config {
                Some(v) => v,
                None => return Ok(None),
            };

            let built = opts.build_as_input(
                &self.cm,
                name,
                move |syntax, target, is_module| match program {
                    Some(v) => Ok(v),
                    _ => self.parse_js(
                        fm.clone(),
                        handler,
                        target,
                        syntax,
                        is_module,
                        comments.as_ref().map(|v| v as _),
                    ),
                },
                opts.output_path.as_deref(),
                opts.source_root.clone(),
                opts.source_file_name.clone(),
                handler,
                Some(config),
                comments,
                before_pass,
            )?;
            Ok(Some(built))
        })
    }

    pub fn run_transform<F, Ret>(&self, handler: &Handler, external_helpers: bool, op: F) -> Ret
    where
        F: FnOnce() -> Ret,
    {
        self.run(|| {
            helpers::HELPERS.set(&Helpers::new(external_helpers), || HANDLER.set(handler, op))
        })
    }

    #[tracing::instrument(skip_all)]
    pub fn transform(
        &self,
        handler: &Handler,
        program: Program,
        external_helpers: bool,
        mut pass: impl swc_ecma_visit::Fold,
    ) -> Program {
        self.run_transform(handler, external_helpers, || {
            // Fold module
            program.fold_with(&mut pass)
        })
    }

    /// `custom_after_pass` is applied after swc transforms are applied.
    ///
    /// `program`: If you already parsed `Program`, you can pass it.
    ///
    /// # Guarantee
    ///
    /// `swc` invokes `custom_before_pass` after
    ///
    ///  - Handling decorators, if configured
    ///  - Applying `resolver`
    ///  - Stripping typescript nodes
    ///
    /// This means, you can use `noop_visit_type`, `noop_fold_type` and
    /// `noop_visit_mut_type` in your visitor to reduce the binary size.
    #[tracing::instrument(skip_all)]
    pub fn process_js_with_custom_pass<P1, P2>(
        &self,
        fm: Arc<SourceFile>,
        program: Option<Program>,
        handler: &Handler,
        opts: &Options,
        comments: SingleThreadedComments,
        custom_before_pass: impl FnOnce(&Program) -> P1,
        custom_after_pass: impl FnOnce(&Program) -> P2,
    ) -> Result<TransformOutput, Error>
    where
        P1: swc_ecma_visit::Fold,
        P2: swc_ecma_visit::Fold,
    {
        self.run(|| -> Result<_, Error> {
            let config = self.run(|| {
                self.parse_js_as_input(
                    fm.clone(),
                    program,
                    handler,
                    opts,
                    &fm.name,
                    Some(&comments),
                    |program| custom_before_pass(program),
                )
            })?;
            let config = match config {
                Some(v) => v,
                None => {
                    bail!("cannot process file because it's ignored by .swcrc")
                }
            };

            let after_pass = custom_after_pass(&config.program);

            let config = config.with_pass(|pass| chain!(pass, after_pass));

            let orig = if config.source_maps.enabled() {
                self.get_orig_src_map(
                    &fm,
                    &config.input_source_map,
                    config
                        .comments
                        .get_trailing(config.program.span_hi())
                        .as_deref()
                        .unwrap_or_default(),
                    false,
                )?
            } else {
                None
            };

            self.apply_transforms(handler, orig.as_ref(), config)
        })
    }

    #[tracing::instrument(skip(self, handler, opts))]
    pub fn process_js_file(
        &self,
        fm: Arc<SourceFile>,
        handler: &Handler,
        opts: &Options,
    ) -> Result<TransformOutput, Error> {
        self.process_js_with_custom_pass(
            fm,
            None,
            handler,
            opts,
            SingleThreadedComments::default(),
            |_| noop(),
            |_| noop(),
        )
    }

    #[tracing::instrument(skip_all)]
    pub fn minify(
        &self,
        fm: Arc<SourceFile>,
        handler: &Handler,
        opts: &JsMinifyOptions,
    ) -> Result<TransformOutput, Error> {
        self.run(|| {
            let _timer = timer!("Compiler::minify");

            let target = opts.ecma.clone().into();

            let (source_map, orig) = opts
                .source_map
                .as_ref()
                .map(|obj| -> Result<_, Error> {
                    let orig = obj.content.as_ref().map(|s| s.to_sourcemap()).transpose()?;

                    Ok((SourceMapsConfig::Bool(true), orig))
                })
                .unwrap_as_option(|v| {
                    Some(Ok(match v {
                        Some(true) => (SourceMapsConfig::Bool(true), None),
                        _ => (SourceMapsConfig::Bool(false), None),
                    }))
                })
                .unwrap()?;

            let mut min_opts = MinifyOptions {
                compress: opts
                    .compress
                    .clone()
                    .unwrap_as_option(|default| match default {
                        Some(true) | None => Some(Default::default()),
                        _ => None,
                    })
                    .map(|v| v.into_config(self.cm.clone())),
                mangle: opts
                    .mangle
                    .clone()
                    .unwrap_as_option(|default| match default {
                        Some(true) | None => Some(Default::default()),
                        _ => None,
                    }),
                ..Default::default()
            };

            // top_level defaults to true if module is true

            // https://github.com/swc-project/swc/issues/2254

            if opts.module {
                if let Some(opts) = &mut min_opts.compress {
                    if opts.top_level.is_none() {
                        opts.top_level = Some(TopLevelOptions { functions: true });
                    }
                }

                if let Some(opts) = &mut min_opts.mangle {
                    if opts.top_level.is_none() {
                        opts.top_level = Some(true);
                    }
                }
            }

            if opts.keep_fnames {
                if let Some(opts) = &mut min_opts.compress {
                    opts.keep_fnames = true;
                }
                if let Some(opts) = &mut min_opts.mangle {
                    opts.keep_fn_names = true;
                }
            }

            let comments = SingleThreadedComments::default();

            let module = self
                .parse_js(
                    fm.clone(),
                    handler,
                    target,
                    Syntax::Es(EsConfig {
                        jsx: true,
                        decorators: true,
                        decorators_before_export: true,
                        import_attributes: true,
                        ..Default::default()
                    }),
                    IsModule::Bool(opts.module),
                    Some(&comments),
                )
                .context("failed to parse input file")?;

            let source_map_names = if source_map.enabled() {
                let mut v = swc_compiler_base::IdentCollector {
                    names: Default::default(),
                };

                module.visit_with(&mut v);

                v.names
            } else {
                Default::default()
            };

            let unresolved_mark = Mark::new();
            let top_level_mark = Mark::new();

            let is_mangler_enabled = min_opts.mangle.is_some();

            let module = self.run_transform(handler, false, || {
                let module = module.fold_with(&mut paren_remover(Some(&comments)));

                let module =
                    module.fold_with(&mut resolver(unresolved_mark, top_level_mark, false));

                let mut module = swc_ecma_minifier::optimize(
                    module,
                    self.cm.clone(),
                    Some(&comments),
                    None,
                    &min_opts,
                    &swc_ecma_minifier::option::ExtraOptions {
                        unresolved_mark,
                        top_level_mark,
                    },
                );

                if !is_mangler_enabled {
                    module.visit_mut_with(&mut hygiene())
                }
                module.fold_with(&mut fixer(Some(&comments as &dyn Comments)))
            });

            let preserve_comments = opts
                .format
                .comments
                .clone()
                .into_inner()
                .unwrap_or(BoolOr::Data(JsMinifyCommentOption::PreserveSomeComments));
            swc_compiler_base::minify_file_comments(&comments, preserve_comments);

            self.print(
                &module,
                PrintArgs {
                    source_root: None,
                    source_file_name: Some(&fm.name.to_string()),
                    output_path: opts.output_path.clone().map(From::from),
                    inline_sources_content: opts.inline_sources_content,
                    source_map,
                    source_map_names: &source_map_names,
                    orig: orig.as_ref(),
                    comments: Some(&comments),
                    emit_source_map_columns: opts.emit_source_map_columns,
                    preamble: &opts.format.preamble,
                    codegen_config: swc_ecma_codegen::Config::default()
                        .with_target(target)
                        .with_minify(true)
                        .with_ascii_only(opts.format.ascii_only)
                        .with_emit_assert_for_import_attributes(
                            opts.format.emit_assert_for_import_attributes,
                        ),
                },
            )
        })
    }

    /// You can use custom pass with this method.
    ///
    /// There exists a [PassBuilder] to help building custom passes.
    #[tracing::instrument(skip_all)]
    pub fn process_js(
        &self,
        handler: &Handler,
        program: Program,
        opts: &Options,
    ) -> Result<TransformOutput, Error> {
        let loc = self.cm.lookup_char_pos(program.span().lo());
        let fm = loc.file;

        self.process_js_with_custom_pass(
            fm,
            Some(program),
            handler,
            opts,
            SingleThreadedComments::default(),
            |_| noop(),
            |_| noop(),
        )
    }

    #[tracing::instrument(name = "swc::Compiler::apply_transforms", skip_all)]
    fn apply_transforms(
        &self,
        handler: &Handler,
        orig: Option<&sourcemap::SourceMap>,
        config: BuiltInput<impl swc_ecma_visit::Fold>,
    ) -> Result<TransformOutput, Error> {
        self.run(|| {
            let program = config.program;
            let source_map_names = if config.source_maps.enabled() {
                let mut v = swc_compiler_base::IdentCollector {
                    names: Default::default(),
                };

                program.visit_with(&mut v);

                v.names
            } else {
                Default::default()
            };

            let mut pass = config.pass;
            let program = helpers::HELPERS.set(&Helpers::new(config.external_helpers), || {
                HANDLER.set(handler, || {
                    // Fold module
                    program.fold_with(&mut pass)
                })
            });

            if let Some(comments) = &config.comments {
                swc_compiler_base::minify_file_comments(comments, config.preserve_comments);
            }

            self.print(
                &program,
                PrintArgs {
                    source_root: config.source_root.as_deref(),
                    source_file_name: config.source_file_name.as_deref(),
                    output_path: config.output_path,
                    inline_sources_content: config.inline_sources_content,
                    source_map: config.source_maps,
                    source_map_names: &source_map_names,
                    orig,
                    comments: config.comments.as_ref().map(|v| v as _),
                    emit_source_map_columns: config.emit_source_map_columns,
                    preamble: &config.output.preamble,
                    codegen_config: swc_ecma_codegen::Config::default()
                        .with_target(config.target)
                        .with_minify(config.minify)
                        .with_ascii_only(
                            config
                                .output
                                .charset
                                .map(|v| matches!(v, OutputCharset::Ascii))
                                .unwrap_or(false),
                        )
                        .with_emit_assert_for_import_attributes(
                            config.emit_assert_for_import_attributes,
                        ),
                },
            )
        })
    }
}

fn find_swcrc(path: &Path, root: &Path, root_mode: RootMode) -> Option<PathBuf> {
    let mut parent = path.parent();
    while let Some(dir) = parent {
        let swcrc = dir.join(".swcrc");

        if swcrc.exists() {
            return Some(swcrc);
        }

        if dir == root && root_mode == RootMode::Root {
            break;
        }
        parent = dir.parent();
    }

    None
}

#[tracing::instrument(skip_all)]
fn load_swcrc(path: &Path) -> Result<Rc, Error> {
    let content = read_to_string(path).context("failed to read config (.swcrc) file")?;

    parse_swcrc(&content)
}

fn parse_swcrc(s: &str) -> Result<Rc, Error> {
    fn convert_json_err(e: serde_json::Error) -> Error {
        let line = e.line();
        let column = e.column();

        let msg = match e.classify() {
            Category::Io => "io error",
            Category::Syntax => "syntax error",
            Category::Data => "unmatched data",
            Category::Eof => "unexpected eof",
        };
        Error::new(e).context(format!(
            "failed to deserialize .swcrc (json) file: {}: {}:{}",
            msg, line, column
        ))
    }

    let v = parse_to_serde_value(
        s.trim_start_matches('\u{feff}'),
        &ParseOptions {
            allow_comments: true,
            allow_trailing_commas: true,
            allow_loose_object_property_names: false,
        },
    )?
    .ok_or_else(|| Error::msg("failed to deserialize empty .swcrc (json) file"))?;

    if let Ok(rc) = serde_json::from_value(v.clone()) {
        return Ok(rc);
    }

    serde_json::from_value(v)
        .map(Rc::Single)
        .map_err(convert_json_err)
}