rspack_loader_swc 0.102.2

rspack builtin swc loader
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
// This file is derived from Next.js
// Copyright (c) 2024 Vercel, Inc.
// Licensed under the MIT License

use std::{cell::RefCell, iter::FromIterator, sync::Arc};

use once_cell::sync::Lazy;
use regex::Regex;
use rspack_core::{RscMeta, RscModuleType};
use rustc_hash::FxHashMap;
use serde::Deserialize;
use swc_core::{
  atoms::{Wtf8Atom, atom},
  common::{FileName, Span, errors::HANDLER, util::take::Take},
  ecma::{
    ast::*,
    visit::{
      Visit, VisitMut, VisitMutWith, VisitWith, noop_visit_mut_type, noop_visit_type,
      visit_mut_pass,
    },
  },
};

use super::{cjs_finder::contains_cjs, import_analyzer::ImportMap, to_client_ref::to_client_ref};

static NODE_MODULES_PATH_REGEX: Lazy<Regex> = Lazy::new(|| {
  #[allow(clippy::unwrap_used)]
  Regex::new(r"node_modules[\\/]").unwrap()
});

#[derive(Clone, Debug, Deserialize)]
#[serde(untagged)]
pub enum Config {
  All,
  WithOptions(Options),
}

#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Options {
  pub is_react_server_layer: bool,
  pub enable_server_entry: bool,
  /// Whether to disable the compile-time check that reports errors when React
  /// client-only API imports are used in server components.
  /// Defaults to `false`.
  #[serde(default)]
  pub disable_client_api_checks: bool,
}

struct DirectiveImportCollection {
  pub is_server_entry: bool,
  pub is_client_entry: bool,
  pub is_action_file: bool,
  pub imports: Vec<ModuleImports>,
  pub export_names: Vec<Wtf8Atom>,
}

/// A visitor that transforms given module to use module proxy if it's a React
/// server component.
/// **NOTE** Turbopack uses ClientDirectiveTransformer for the
/// same purpose, so does not run this transform.
struct ReactServerComponents<'a> {
  is_react_server_layer: bool,
  enable_server_entry: bool,
  disable_client_api_checks: bool,
  filepath: String,
  resource_path: String,
  rsc_meta: &'a RefCell<Option<RscMeta>>,
  directive_import_collection: Option<DirectiveImportCollection>,
}

#[derive(Clone, Debug)]
struct ModuleImports {
  source: (Wtf8Atom, Span),
  specifiers: Vec<(Wtf8Atom, Span)>,
}

enum RSCErrorKind {
  /// When `use client` and `use server` are in the same file.
  /// It's not possible to have both directives in the same file.
  RedundantDirectives(Span),
  ErrClientDirective(Span),
  ErrReactApi((String, Span)),
  ErrServerImport((String, Span)),
  ErrClientImport((String, Span)),
}

impl VisitMut for ReactServerComponents<'_> {
  noop_visit_mut_type!();

  fn visit_mut_module(&mut self, module: &mut Module) {
    // Run the validator first to assert, collect directives and imports.
    let mut validator = ReactServerComponentValidator::new(
      self.is_react_server_layer,
      self.filepath.clone(),
      self.disable_client_api_checks,
    );

    module.visit_with(&mut validator);
    self.directive_import_collection = validator.directive_import_collection;

    #[allow(clippy::unwrap_used)]
    let directive_import_collection = self.directive_import_collection.as_ref().unwrap();

    let is_server_entry = self.enable_server_entry && directive_import_collection.is_server_entry;
    let is_client_entry = directive_import_collection.is_client_entry;
    let client_refs = directive_import_collection.export_names.clone();

    self.remove_top_level_directive(module);

    let is_cjs = contains_cjs(module);

    if self.is_react_server_layer {
      if is_server_entry {
        self.set_server_entry_metadata(is_cjs);
      } else if is_client_entry {
        self.set_client_metadata(is_cjs);
        if to_client_ref(module, &self.resource_path, &client_refs, is_cjs) {
          return;
        }
      }
    }
    module.visit_mut_children_with(self)
  }
}

impl ReactServerComponents<'_> {
  /// removes specific directive from the AST.
  fn remove_top_level_directive(&mut self, module: &mut Module) {
    module.body.retain(|item| {
      if let ModuleItem::Stmt(stmt) = item
        && let Some(expr_stmt) = stmt.as_expr()
        && let Expr::Lit(Lit::Str(Str { value, .. })) = &*expr_stmt.expr
        && &**value == "use client"
      {
        // Remove the directive.
        return false;
      }
      true
    });
  }

  fn set_server_entry_metadata(&mut self, is_cjs: bool) {
    #[allow(clippy::unwrap_used)]
    let export_names = &self
      .directive_import_collection
      .as_ref()
      .unwrap()
      .export_names;

    let mut rsc_meta = self.rsc_meta.borrow_mut();
    match rsc_meta.as_mut() {
      Some(rsc_meta) => {
        rsc_meta.module_type = RscModuleType::ServerEntry;
        rsc_meta.server_refs = export_names.clone();
        rsc_meta.is_cjs = is_cjs;
      }
      None => {
        *rsc_meta = Some(RscMeta {
          module_type: RscModuleType::ServerEntry,
          server_refs: export_names.clone(),
          client_refs: Default::default(),
          import_meta_rsc: false,
          is_cjs,
          action_ids: Default::default(),
        });
      }
    }
  }

  fn set_client_metadata(&mut self, is_cjs: bool) {
    #[allow(clippy::unwrap_used)]
    let export_names = &self
      .directive_import_collection
      .as_ref()
      .unwrap()
      .export_names;

    let mut rsc_meta = self.rsc_meta.borrow_mut();
    match rsc_meta.as_mut() {
      Some(rsc_meta) => {
        rsc_meta.module_type = RscModuleType::Client;
        rsc_meta.client_refs = export_names.clone();
        rsc_meta.is_cjs = is_cjs;
      }
      None => {
        *rsc_meta = Some(RscMeta {
          module_type: RscModuleType::Client,
          server_refs: Default::default(),
          client_refs: export_names.clone(),
          import_meta_rsc: false,
          is_cjs,
          action_ids: Default::default(),
        });
      }
    }
  }
}

/// Consolidated place to parse, generate error messages for the RSC parsing
/// errors.
fn report_error(error_kind: RSCErrorKind) {
  let (msg, spans) = match error_kind {
    RSCErrorKind::RedundantDirectives(span) => (
      "It's not possible to have both `use client` and `use server` directives in the \
             same file."
        .to_string(),
      vec![span],
    ),
    RSCErrorKind::ErrClientDirective(span) => (
      "The \"use client\" directive must be placed before other expressions. Move it to \
             the top of the file to resolve this issue."
        .to_string(),
      vec![span],
    ),
    RSCErrorKind::ErrReactApi((source, span)) => {
      let msg = if source == "Component" {
        "You’re importing a class component. It only works in a Client Component but none of its parents are marked with \"use client\", so they're Server Components by default.\n\n".to_string()
      } else {
        format!(
          "You're importing a component that needs `{source}`. This React Hook only works in a Client Component. To fix, mark the file (or its parent) with the `\"use client\"` directive.\n\n"
        )
      };

      (msg, vec![span])
    }
    RSCErrorKind::ErrServerImport((source, span)) => (
      format!(
        "You're importing a module that depends on \"{source}\". This package only works in a Client Component. To fix, mark the file (or its parent) with the `\"use client\"` directive.\n\n"
      ),
      vec![span],
    ),
    RSCErrorKind::ErrClientImport((source, span)) => (
      format!(
        "You're importing a module that depends on \"{source}\". This package only works in a Server Component or a top-level `\"use server\"` module.\n\n"
      ),
      vec![span],
    ),
  };

  HANDLER.with(|handler| handler.struct_span_err(spans, msg.as_str()).emit())
}

/// Collects top level directives and imports
fn collect_top_level_directives_and_imports(module: &Module) -> DirectiveImportCollection {
  let mut imports: Vec<ModuleImports> = vec![];
  let mut finished_directives = false;
  let mut is_server_entry = false;
  let mut is_client_entry = false;
  let mut is_action_file = false;

  let mut export_names: Vec<Wtf8Atom> = vec![];

  let _ = &module.body.iter().for_each(|item| {
    match item {
      ModuleItem::Stmt(stmt) => {
        if !stmt.is_expr() {
          // Not an expression.
          finished_directives = true;
        }

        match stmt.as_expr() {
          Some(expr_stmt) => {
            match &*expr_stmt.expr {
              Expr::Lit(Lit::Str(Str { value, .. })) => {
                if &**value == "use server-entry" {
                  is_server_entry = true;
                } else if &**value == "use client" {
                  if !finished_directives {
                    is_client_entry = true;

                    if is_action_file {
                      report_error(RSCErrorKind::RedundantDirectives(expr_stmt.span));
                    }
                  } else {
                    report_error(RSCErrorKind::ErrClientDirective(expr_stmt.span));
                  }
                } else if &**value == "use server" && !finished_directives {
                  is_action_file = true;

                  if is_client_entry {
                    report_error(RSCErrorKind::RedundantDirectives(expr_stmt.span));
                  }
                }
              }
              // Match `ParenthesisExpression` which is some formatting tools
              // usually do: ('use client'). In these case we need to throw
              // an exception because they are not valid directives.
              Expr::Paren(ParenExpr { expr, .. }) => {
                finished_directives = true;
                if let Expr::Lit(Lit::Str(Str { value, .. })) = &**expr
                  && &**value == "use client"
                {
                  report_error(RSCErrorKind::ErrClientDirective(expr_stmt.span));
                }
              }
              Expr::Assign(AssignExpr {
                op: AssignOp::Assign,
                left:
                  AssignTarget::Simple(SimpleAssignTarget::Member(MemberExpr {
                    obj,
                    prop: MemberProp::Ident(prop),
                    ..
                  })),
                ..
              }) if matches!(&**obj, Expr::Ident(obj) if &*obj.sym == "module")
                && &*prop.sym == "exports" =>
              {
                export_names.push(Wtf8Atom::from("default"));
                finished_directives = true;
              }
              _ => {
                // Other expression types.
                finished_directives = true;
              }
            }
          }
          None => {
            // Not an expression.
            finished_directives = true;
          }
        }
      }
      ModuleItem::ModuleDecl(ModuleDecl::Import(
        import @ ImportDecl {
          type_only: false, ..
        },
      )) => {
        let source = import.src.value.clone();
        let specifiers = import
          .specifiers
          .iter()
          .filter(|specifier| {
            !matches!(
              specifier,
              ImportSpecifier::Named(ImportNamedSpecifier {
                is_type_only: true,
                ..
              })
            )
          })
          .map(|specifier| match specifier {
            ImportSpecifier::Named(named) => match &named.imported {
              Some(imported) => match &imported {
                ModuleExportName::Ident(i) => (Wtf8Atom::from(i.to_id().0), i.span),
                ModuleExportName::Str(s) => (s.value.clone(), s.span),
              },
              None => (Wtf8Atom::from(named.local.to_id().0), named.local.span),
            },
            ImportSpecifier::Default(d) => (Wtf8Atom::from(""), d.span),
            ImportSpecifier::Namespace(n) => (Wtf8Atom::from("*"), n.span),
          })
          .collect();

        imports.push(ModuleImports {
          source: (source, import.span),
          specifiers,
        });

        finished_directives = true;
      }
      // Collect all export names.
      ModuleItem::ModuleDecl(ModuleDecl::ExportNamed(e)) => {
        for specifier in &e.specifiers {
          export_names.push(match specifier {
            ExportSpecifier::Default(_) => Wtf8Atom::from("default"),
            ExportSpecifier::Namespace(_) => Wtf8Atom::from("*"),
            ExportSpecifier::Named(named) => match &named.exported {
              Some(exported) => match &exported {
                ModuleExportName::Ident(i) => Wtf8Atom::from(i.sym.clone()),
                ModuleExportName::Str(s) => s.value.clone(),
              },
              _ => match &named.orig {
                ModuleExportName::Ident(i) => Wtf8Atom::from(i.sym.clone()),
                ModuleExportName::Str(s) => s.value.clone(),
              },
            },
          })
        }
        finished_directives = true;
      }
      ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(ExportDecl { decl, .. })) => {
        match decl {
          Decl::Class(ClassDecl { ident, .. }) => {
            export_names.push(Wtf8Atom::from(ident.sym.clone()));
          }
          Decl::Fn(FnDecl { ident, .. }) => {
            export_names.push(Wtf8Atom::from(ident.sym.clone()));
          }
          Decl::Var(var) => {
            for decl in &var.decls {
              if let Pat::Ident(ident) = &decl.name {
                export_names.push(Wtf8Atom::from(ident.id.sym.clone()));
              }
            }
          }
          _ => {}
        }
        finished_directives = true;
      }
      ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultDecl(ExportDefaultDecl {
        decl: _, ..
      })) => {
        export_names.push(Wtf8Atom::from("default"));
        finished_directives = true;
      }
      ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultExpr(ExportDefaultExpr {
        expr: _, ..
      })) => {
        export_names.push(Wtf8Atom::from("default"));
        finished_directives = true;
      }
      ModuleItem::ModuleDecl(ModuleDecl::ExportAll(_)) => {
        export_names.push(Wtf8Atom::from("*"));
      }
      _ => {
        finished_directives = true;
      }
    }
  });

  DirectiveImportCollection {
    is_server_entry,
    is_client_entry,
    is_action_file,
    imports,
    export_names,
  }
}

/// A visitor to assert given module file is a valid React server component.
struct ReactServerComponentValidator {
  is_react_server_layer: bool,
  disable_client_api_checks: bool,
  filepath: String,
  invalid_server_lib_apis_mapping: FxHashMap<&'static str, Vec<&'static str>>,
  invalid_server_imports: Vec<Wtf8Atom>,
  invalid_client_imports: Vec<Wtf8Atom>,
  pub directive_import_collection: Option<DirectiveImportCollection>,
  imports: ImportMap,
}

impl ReactServerComponentValidator {
  pub fn new(
    is_react_server_layer: bool,
    filename: String,
    disable_client_api_checks: bool,
  ) -> Self {
    Self {
      is_react_server_layer,
      disable_client_api_checks,
      filepath: filename,
      directive_import_collection: None,
      // react -> [apis]
      // react-dom -> [apis]
      invalid_server_lib_apis_mapping: FxHashMap::from_iter([
        (
          "react",
          vec![
            "Component",
            "createContext",
            "createFactory",
            "PureComponent",
            "useDeferredValue",
            "useEffect",
            "useImperativeHandle",
            "useInsertionEffect",
            "useLayoutEffect",
            "useReducer",
            "useRef",
            "useState",
            "useSyncExternalStore",
            "useTransition",
            "useOptimistic",
            "useActionState",
            "experimental_useOptimistic",
          ],
        ),
        (
          "react-dom",
          vec![
            "flushSync",
            "unstable_batchedUpdates",
            "useFormStatus",
            "useFormState",
          ],
        ),
      ]),
      invalid_server_imports: vec![
        atom!("client-only").into(),
        atom!("react-dom/client").into(),
        atom!("react-dom/server").into(),
      ],
      invalid_client_imports: vec![atom!("server-only").into()],
      imports: ImportMap::default(),
    }
  }

  fn is_from_node_modules(&self, filepath: &str) -> bool {
    NODE_MODULES_PATH_REGEX.is_match(filepath)
  }

  // Asserts the server lib apis
  // e.g.
  // assert_invalid_server_lib_apis("react", import)
  // assert_invalid_server_lib_apis("react-dom", import)
  fn assert_invalid_server_lib_apis(&self, import_source: &str, import: &ModuleImports) {
    let invalid_apis = self.invalid_server_lib_apis_mapping.get(import_source);
    if let Some(invalid_apis) = invalid_apis {
      for specifier in &import.specifiers {
        if let Some(specifier_name) = specifier.0.as_str()
          && invalid_apis.contains(&specifier_name)
        {
          report_error(RSCErrorKind::ErrReactApi((
            specifier_name.to_string(),
            specifier.1,
          )));
        }
      }
    }
  }

  fn assert_server_graph(&self, imports: &[ModuleImports]) {
    if self.is_from_node_modules(&self.filepath) {
      return;
    }
    for import in imports {
      let source = &import.source.0;
      if self.invalid_server_imports.contains(source) {
        report_error(RSCErrorKind::ErrServerImport((
          source.to_string_lossy().into_owned(),
          import.source.1,
        )));
      }

      if let Some(source_str) = source.as_str()
        && !self.disable_client_api_checks
      {
        self.assert_invalid_server_lib_apis(source_str, import);
      }
    }
  }

  fn assert_client_graph(&self, imports: &[ModuleImports]) {
    if self.is_from_node_modules(&self.filepath) {
      return;
    }
    for import in imports {
      let source = &import.source.0;
      if self.invalid_client_imports.contains(source) {
        report_error(RSCErrorKind::ErrClientImport((
          source.to_string_lossy().into_owned(),
          import.source.1,
        )));
      }
    }
  }
}

impl Visit for ReactServerComponentValidator {
  noop_visit_type!();

  // coerce parsed script to run validation for the context, which is still
  // required even if file is empty
  fn visit_script(&mut self, script: &swc_core::ecma::ast::Script) {
    if script.body.is_empty() {
      self.visit_module(&Module::dummy());
    }
  }

  fn visit_module(&mut self, module: &Module) {
    self.imports = ImportMap::analyze(module);

    let directive_import_collection = collect_top_level_directives_and_imports(module);

    if self.is_react_server_layer && !directive_import_collection.is_client_entry {
      // Only assert server graph if file's bundle target is "server", e.g.
      // * server components pages
      // * pages bundles on SSR layer
      // * middleware
      // * app/pages api routes
      self.assert_server_graph(&directive_import_collection.imports)
    } else if !self.is_react_server_layer && !directive_import_collection.is_action_file {
      self.assert_client_graph(&directive_import_collection.imports)
    }
    self.directive_import_collection = Some(directive_import_collection);

    module.visit_children_with(self);
  }
}

/// Runs react server component transform for the module proxy, as well as
/// running assertion.
pub fn server_components(
  filename: Arc<FileName>,
  resource_path: String,
  config: Config,
  rsc_meta: &RefCell<Option<RscMeta>>,
) -> impl Pass + VisitMut {
  let is_react_server_layer: bool = match &config {
    Config::WithOptions(x) => x.is_react_server_layer,
    _ => false,
  };
  let enable_server_entry = match &config {
    Config::WithOptions(x) => x.enable_server_entry,
    _ => false,
  };
  let disable_client_api_checks = match &config {
    Config::WithOptions(x) => x.disable_client_api_checks,
    _ => false,
  };
  visit_mut_pass(ReactServerComponents {
    is_react_server_layer,
    enable_server_entry,
    disable_client_api_checks,
    rsc_meta,
    filepath: match &*filename {
      FileName::Custom(path) => format!("<{path}>"),
      _ => filename.to_string(),
    },
    resource_path,
    directive_import_collection: None,
  })
}