File size: 12,601 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
use std::{fmt::Debug, hash::Hash, sync::Arc};

use anyhow::Result;
use async_trait::async_trait;
use rustc_hash::FxHashMap;
use swc_core::{
    atoms::{Atom, atom},
    base::SwcComments,
    common::{Mark, SourceMap, comments::Comments},
    ecma::{
        ast::{ExprStmt, ModuleItem, Pass, Program, Stmt},
        preset_env::{self, Targets},
        transforms::{
            base::{
                assumptions::Assumptions,
                helpers::{HELPERS, HelperData, Helpers},
            },
            optimization::inline_globals,
            react::react,
        },
        utils::IsDirective,
    },
    quote,
};
use turbo_rcstr::RcStr;
use turbo_tasks::{ResolvedVc, Vc};
use turbo_tasks_fs::FileSystemPath;
use turbopack_core::{environment::Environment, source::Source};

use crate::runtime_functions::{TURBOPACK_MODULE, TURBOPACK_REFRESH};

#[turbo_tasks::value]
#[derive(Debug, Clone, Hash)]
pub enum EcmascriptInputTransform {
    Plugin(ResolvedVc<TransformPlugin>),
    PresetEnv(ResolvedVc<Environment>),
    React {
        #[serde(default)]
        development: bool,
        #[serde(default)]
        refresh: bool,
        // swc.jsc.transform.react.importSource
        import_source: ResolvedVc<Option<RcStr>>,
        // swc.jsc.transform.react.runtime,
        runtime: ResolvedVc<Option<RcStr>>,
    },
    GlobalTypeofs {
        window_value: String,
    },
    // These options are subset of swc_core::ecma::transforms::typescript::Config, but
    // it doesn't derive `Copy` so repeating values in here
    TypeScript {
        #[serde(default)]
        use_define_for_class_fields: bool,
    },
    Decorators {
        #[serde(default)]
        is_legacy: bool,
        #[serde(default)]
        is_ecma: bool,
        #[serde(default)]
        emit_decorators_metadata: bool,
        #[serde(default)]
        use_define_for_class_fields: bool,
    },
}

/// The CustomTransformer trait allows you to implement your own custom SWC
/// transformer to run over all ECMAScript files imported in the graph.
#[async_trait]
pub trait CustomTransformer: Debug {
    async fn transform(&self, program: &mut Program, ctx: &TransformContext<'_>) -> Result<()>;
}

/// A wrapper around a TransformPlugin instance, allowing it to operate with
/// the turbo_task caching requirements.
#[turbo_tasks::value(
    transparent,
    serialization = "none",
    eq = "manual",
    into = "new",
    cell = "new"
)]
#[derive(Debug)]
pub struct TransformPlugin(#[turbo_tasks(trace_ignore)] Box<dyn CustomTransformer + Send + Sync>);

#[async_trait]
impl CustomTransformer for TransformPlugin {
    async fn transform(&self, program: &mut Program, ctx: &TransformContext<'_>) -> Result<()> {
        self.0.transform(program, ctx).await
    }
}

#[turbo_tasks::value(transparent)]
#[derive(Debug, Clone, Hash)]
pub struct EcmascriptInputTransforms(Vec<EcmascriptInputTransform>);

#[turbo_tasks::value_impl]
impl EcmascriptInputTransforms {
    #[turbo_tasks::function]
    pub fn empty() -> Vc<Self> {
        Vc::cell(Vec::new())
    }

    #[turbo_tasks::function]
    pub async fn extend(self: Vc<Self>, other: Vc<EcmascriptInputTransforms>) -> Result<Vc<Self>> {
        let mut transforms = self.owned().await?;
        transforms.extend(other.owned().await?);
        Ok(Vc::cell(transforms))
    }
}

pub struct TransformContext<'a> {
    pub comments: &'a SwcComments,
    pub top_level_mark: Mark,
    pub unresolved_mark: Mark,
    pub source_map: &'a Arc<SourceMap>,
    pub file_path_str: &'a str,
    pub file_name_str: &'a str,
    pub file_name_hash: u128,
    pub query_str: RcStr,
    pub file_path: FileSystemPath,
    pub source: ResolvedVc<Box<dyn Source>>,
}

impl EcmascriptInputTransform {
    pub async fn apply(
        &self,
        program: &mut Program,
        ctx: &TransformContext<'_>,
        helpers: HelperData,
    ) -> Result<HelperData> {
        let &TransformContext {
            comments,
            source_map,
            top_level_mark,
            unresolved_mark,
            ..
        } = ctx;

        Ok(match self {
            EcmascriptInputTransform::GlobalTypeofs { window_value } => {
                let mut typeofs: FxHashMap<Atom, Atom> = Default::default();
                typeofs.insert(Atom::from("window"), Atom::from(&**window_value));

                apply_transform(
                    program,
                    helpers,
                    inline_globals(
                        unresolved_mark,
                        Default::default(),
                        Default::default(),
                        Default::default(),
                        Arc::new(typeofs),
                    ),
                )
            }
            EcmascriptInputTransform::React {
                development,
                refresh,
                import_source,
                runtime,
            } => {
                use swc_core::ecma::transforms::react::{Options, Runtime};
                let runtime = if let Some(runtime) = &*runtime.await? {
                    match runtime.as_str() {
                        "classic" => Runtime::Classic,
                        "automatic" => Runtime::Automatic,
                        _ => {
                            return Err(anyhow::anyhow!(
                                "Invalid value for swc.jsc.transform.react.runtime: {}",
                                runtime
                            ));
                        }
                    }
                } else {
                    Runtime::Automatic
                };

                let config = Options {
                    runtime: Some(runtime),
                    development: Some(*development),
                    import_source: import_source.await?.as_deref().map(Atom::from),
                    refresh: if *refresh {
                        debug_assert_eq!(TURBOPACK_REFRESH.full, "__turbopack_context__.k");
                        Some(swc_core::ecma::transforms::react::RefreshOptions {
                            refresh_reg: atom!("__turbopack_context__.k.register"),
                            refresh_sig: atom!("__turbopack_context__.k.signature"),
                            ..Default::default()
                        })
                    } else {
                        None
                    },
                    ..Default::default()
                };

                // Explicit type annotation to ensure that we don't duplicate transforms in the
                // final binary
                let helpers = apply_transform(
                    program,
                    helpers,
                    react::<&dyn Comments>(
                        source_map.clone(),
                        Some(&comments),
                        config,
                        top_level_mark,
                        unresolved_mark,
                    ),
                );

                if *refresh {
                    debug_assert_eq!(TURBOPACK_REFRESH.full, "__turbopack_context__.k");
                    debug_assert_eq!(TURBOPACK_MODULE.full, "__turbopack_context__.m");
                    let stmt = quote!(
                        // AMP / No-JS mode does not inject these helpers
                        "if (typeof globalThis.$RefreshHelpers$ === 'object' && \
                         globalThis.$RefreshHelpers !== null) { \
                         __turbopack_context__.k.registerExports(__turbopack_context__.m, \
                         globalThis.$RefreshHelpers$); }" as Stmt
                    );

                    match program {
                        Program::Module(module) => {
                            module.body.push(ModuleItem::Stmt(stmt));
                        }
                        Program::Script(script) => {
                            script.body.push(stmt);
                        }
                    }
                }

                helpers
            }
            EcmascriptInputTransform::PresetEnv(env) => {
                let versions = env.runtime_versions().await?;
                let config = swc_core::ecma::preset_env::EnvConfig::from(
                    swc_core::ecma::preset_env::Config {
                        targets: Some(Targets::Versions(*versions)),
                        mode: None, // Don't insert core-js polyfills
                        ..Default::default()
                    },
                );

                // Explicit type annotation to ensure that we don't duplicate transforms in the
                // final binary
                apply_transform(
                    program,
                    helpers,
                    preset_env::transform_from_env::<&'_ dyn Comments>(
                        unresolved_mark,
                        Some(&comments),
                        config,
                        Assumptions::default(),
                    ),
                )
            }
            EcmascriptInputTransform::TypeScript {
                // TODO(WEB-1213)
                use_define_for_class_fields: _use_define_for_class_fields,
            } => {
                use swc_core::ecma::transforms::typescript::typescript;
                let config = Default::default();
                apply_transform(
                    program,
                    helpers,
                    typescript(config, unresolved_mark, top_level_mark),
                )
            }
            EcmascriptInputTransform::Decorators {
                is_legacy,
                is_ecma: _,
                emit_decorators_metadata,
                // TODO(WEB-1213)
                use_define_for_class_fields: _use_define_for_class_fields,
            } => {
                use swc_core::ecma::transforms::proposal::decorators::{Config, decorators};
                let config = Config {
                    legacy: *is_legacy,
                    emit_metadata: *emit_decorators_metadata,
                    ..Default::default()
                };

                apply_transform(program, helpers, decorators(config))
            }
            EcmascriptInputTransform::Plugin(transform) => {
                // We cannot pass helpers to plugins, so we return them as is
                transform.await?.transform(program, ctx).await?;
                helpers
            }
        })
    }
}

fn apply_transform(program: &mut Program, helpers: HelperData, op: impl Pass) -> HelperData {
    let helpers = Helpers::from_data(helpers);
    HELPERS.set(&helpers, || {
        program.mutate(op);
    });
    helpers.data()
}

pub fn remove_shebang(program: &mut Program) {
    match program {
        Program::Module(m) => {
            m.shebang = None;
        }
        Program::Script(s) => {
            s.shebang = None;
        }
    }
}

pub fn remove_directives(program: &mut Program) {
    match program {
        Program::Module(module) => {
            let directive_count = module
                .body
                .iter()
                .take_while(|i| match i {
                    ModuleItem::Stmt(stmt) => stmt.directive_continue(),
                    ModuleItem::ModuleDecl(_) => false,
                })
                .take_while(|i| match i {
                    ModuleItem::Stmt(stmt) => match stmt {
                        Stmt::Expr(ExprStmt { expr, .. }) => expr
                            .as_lit()
                            .and_then(|lit| lit.as_str())
                            .and_then(|str| str.raw.as_ref())
                            .is_some_and(|raw| {
                                raw.starts_with("\"use ") || raw.starts_with("'use ")
                            }),
                        _ => false,
                    },
                    ModuleItem::ModuleDecl(_) => false,
                })
                .count();
            module.body.drain(0..directive_count);
        }
        Program::Script(script) => {
            let directive_count = script
                .body
                .iter()
                .take_while(|stmt| stmt.directive_continue())
                .take_while(|stmt| match stmt {
                    Stmt::Expr(ExprStmt { expr, .. }) => expr
                        .as_lit()
                        .and_then(|lit| lit.as_str())
                        .and_then(|str| str.raw.as_ref())
                        .is_some_and(|raw| raw.starts_with("\"use ") || raw.starts_with("'use ")),
                    _ => false,
                })
                .count();
            script.body.drain(0..directive_count);
        }
    }
}