-
Notifications
You must be signed in to change notification settings - Fork 31k
Expand file tree
/
Copy pathreact_server_components.rs
More file actions
1260 lines (1171 loc) · 48.9 KB
/
react_server_components.rs
File metadata and controls
1260 lines (1171 loc) · 48.9 KB
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 std::{
fmt::{self, Display},
iter::FromIterator,
path::PathBuf,
rc::Rc,
sync::Arc,
};
use once_cell::sync::Lazy;
use regex::Regex;
use rustc_hash::FxHashMap;
use serde::Deserialize;
fn build_page_extensions_regex(page_extensions: &[String]) -> String {
if page_extensions.is_empty() {
"(ts|js)x?".to_string()
} else {
let escaped: Vec<String> = page_extensions
.iter()
.map(|ext| regex::escape(ext))
.collect();
format!("({})", escaped.join("|"))
}
}
use swc_core::{
atoms::{Atom, Wtf8Atom, atom},
common::{
DUMMY_SP, FileName, Span, Spanned,
comments::{Comment, CommentKind, Comments},
errors::HANDLER,
util::take::Take,
},
ecma::{
ast::*,
utils::{ExprFactory, prepend_stmts, quote_ident, quote_str},
visit::{
Visit, VisitMut, VisitMutWith, VisitWith, noop_visit_mut_type, noop_visit_type,
visit_mut_pass,
},
},
};
use super::{cjs_finder::contains_cjs, import_analyzer::ImportMap};
use crate::FxIndexMap;
#[derive(Clone, Debug, Deserialize)]
#[serde(untagged)]
pub enum Config {
All(bool),
WithOptions(Options),
}
impl Config {
pub fn truthy(&self) -> bool {
match self {
Config::All(b) => *b,
Config::WithOptions(_) => true,
}
}
}
#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Options {
pub is_react_server_layer: bool,
pub cache_components_enabled: bool,
pub use_cache_enabled: bool,
#[serde(default)]
pub taint_enabled: bool,
#[serde(default)]
pub page_extensions: Vec<String>,
}
/// 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<C: Comments> {
is_react_server_layer: bool,
cache_components_enabled: bool,
use_cache_enabled: bool,
taint_enabled: bool,
filepath: String,
app_dir: Option<PathBuf>,
comments: C,
page_extensions: Vec<String>,
}
#[derive(Clone, Debug)]
struct ModuleImports {
source: (Wtf8Atom, Span),
specifiers: Vec<(Atom, Span)>,
}
#[allow(clippy::enum_variant_names)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ModuleDirective {
UseClient,
UseServer,
UseCache,
}
enum RSCErrorKind {
UseClientWithUseServer(Span),
UseClientWithUseCache(Span),
NextRscErrServerImport((String, Span)),
NextRscErrClientImport((String, Span)),
NextRscErrClientDirective(Span),
NextRscErrReactApi((String, Span)),
NextRscErrErrorFileServerComponent(Span),
NextRscErrClientMetadataExport((String, Span)),
NextRscErrConflictMetadataExport((Span, Span)),
NextRscErrInvalidApi((String, Span)),
NextRscErrDeprecatedApi((String, String, Span)),
NextSsrDynamicFalseNotAllowed(Span),
NextRscErrIncompatibleRouteSegmentConfig(Span, String, NextConfigProperty),
NextRscErrRequiresRouteSegmentConfig(Span, String, NextConfigProperty),
NextRscErrTaintWithoutConfig((String, Span)),
}
#[derive(Clone, Debug, Copy)]
enum NextConfigProperty {
CacheComponents,
UseCache,
}
impl Display for NextConfigProperty {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
NextConfigProperty::CacheComponents => write!(f, "cacheComponents"),
NextConfigProperty::UseCache => write!(f, "experimental.useCache"),
}
}
}
enum InvalidExportKind {
General,
Metadata,
RouteSegmentConfig(NextConfigProperty),
RequiresRouteSegmentConfig(NextConfigProperty),
}
impl<C: Comments> VisitMut for ReactServerComponents<C> {
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.cache_components_enabled,
self.use_cache_enabled,
self.taint_enabled,
self.filepath.clone(),
self.app_dir.clone(),
self.page_extensions.clone(),
);
module.visit_with(&mut validator);
let is_client_entry = validator.module_directive == Some(ModuleDirective::UseClient);
let export_names = validator.export_names;
self.remove_top_level_directive(module);
let is_cjs = contains_cjs(module);
if self.is_react_server_layer {
if is_client_entry {
self.to_module_ref(module, is_cjs, &export_names);
return;
}
} else if is_client_entry {
self.prepend_comment_node(module, is_cjs, &export_names);
}
module.visit_mut_children_with(self)
}
}
impl<C: Comments> ReactServerComponents<C> {
/// 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
});
}
// Convert the client module to the module reference code and add a special
// comment to the top of the file.
fn to_module_ref(&self, module: &mut Module, is_cjs: bool, export_names: &[Atom]) {
// Clear all the statements and module declarations.
module.body.clear();
let proxy_ident = quote_ident!("createProxy");
let filepath = quote_str!(&*self.filepath);
prepend_stmts(
&mut module.body,
vec![
ModuleItem::Stmt(Stmt::Decl(Decl::Var(Box::new(VarDecl {
span: DUMMY_SP,
kind: VarDeclKind::Const,
decls: vec![VarDeclarator {
span: DUMMY_SP,
name: Pat::Object(ObjectPat {
span: DUMMY_SP,
props: vec![ObjectPatProp::Assign(AssignPatProp {
span: DUMMY_SP,
key: proxy_ident.into(),
value: None,
})],
optional: false,
type_ann: None,
}),
init: Some(Box::new(Expr::Call(CallExpr {
span: DUMMY_SP,
callee: quote_ident!("require").as_callee(),
args: vec![quote_str!("private-next-rsc-mod-ref-proxy").as_arg()],
..Default::default()
}))),
definite: false,
}],
..Default::default()
})))),
ModuleItem::Stmt(Stmt::Expr(ExprStmt {
span: DUMMY_SP,
expr: Box::new(Expr::Assign(AssignExpr {
span: DUMMY_SP,
left: MemberExpr {
span: DUMMY_SP,
obj: Box::new(Expr::Ident(quote_ident!("module").into())),
prop: MemberProp::Ident(quote_ident!("exports")),
}
.into(),
op: op!("="),
right: Box::new(Expr::Call(CallExpr {
span: DUMMY_SP,
callee: quote_ident!("createProxy").as_callee(),
args: vec![filepath.as_arg()],
..Default::default()
})),
})),
})),
]
.into_iter(),
);
self.prepend_comment_node(module, is_cjs, export_names);
}
fn prepend_comment_node(&self, module: &Module, is_cjs: bool, export_names: &[Atom]) {
// Prepend a special comment to the top of the file that contains
// module export names and the detected module type.
self.comments.add_leading(
module.span.lo,
Comment {
span: DUMMY_SP,
kind: CommentKind::Block,
text: format!(
" __next_internal_client_entry_do_not_use__ {} {} ",
join_atoms(export_names),
if is_cjs { "cjs" } else { "auto" }
)
.into(),
},
);
}
}
fn join_atoms(atoms: &[Atom]) -> String {
atoms
.iter()
.map(|atom| atom.as_ref())
.collect::<Vec<_>>()
.join(",")
}
/// Consolidated place to parse, generate error messages for the RSC parsing
/// errors.
fn report_error(app_dir: &Option<PathBuf>, filepath: &str, error_kind: RSCErrorKind) {
let (msg, spans) = match error_kind {
RSCErrorKind::UseClientWithUseServer(span) => (
"It's not possible to have both \"use client\" and \"use server\" directives in the \
same file."
.to_string(),
vec![span],
),
RSCErrorKind::UseClientWithUseCache(span) => (
"It's not possible to have both \"use client\" and \"use cache\" directives in the \
same file."
.to_string(),
vec![span],
),
RSCErrorKind::NextRscErrClientDirective(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::NextRscErrServerImport((source, span)) => {
let msg = match source.as_str() {
// If importing "react-dom/server", we should show a different error.
"react-dom/server" => "You're importing a component that imports react-dom/server. To fix it, render or return the content directly as a Server Component instead for perf and security.\nLearn more: https://nextjs.org/docs/app/building-your-application/rendering".to_string(),
// If importing "next/router", we should tell them to use "next/navigation".
"next/router" => "You have a Server Component that imports next/router. Use next/navigation instead.\nLearn more: https://nextjs.org/docs/app/api-reference/functions/use-router".to_string(),
_ => format!("You're importing a component that imports {source}. It only works in a Client Component but none of its parents are marked with \"use client\", so they're Server Components by default.\nLearn more: https://nextjs.org/docs/app/building-your-application/rendering")
};
(msg, vec![span])
}
RSCErrorKind::NextRscErrClientImport((source, span)) => {
let is_app_dir = app_dir
.as_ref()
.map(|app_dir| {
if let Some(app_dir) = app_dir.as_os_str().to_str() {
filepath.starts_with(app_dir)
} else {
false
}
})
.unwrap_or_default();
let msg = if !is_app_dir {
format!("You're importing a component that needs \"{source}\". That only works in a Server Component which is not supported in the pages/ directory. Read more: https://nextjs.org/docs/app/building-your-application/rendering/server-components\n\n")
} else {
format!("You're importing a component that needs \"{source}\". That only works in a Server Component but one of its parents is marked with \"use client\", so it's a Client Component.\nLearn more: https://nextjs.org/docs/app/building-your-application/rendering\n\n")
};
(msg, vec![span])
}
RSCErrorKind::NextRscErrReactApi((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.\nLearn more: https://nextjs.org/docs/app/building-your-application/rendering/client-components\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 Learn more: https://nextjs.org/docs/app/api-reference/directives/use-client\n\n")
};
(msg, vec![span])
},
RSCErrorKind::NextRscErrErrorFileServerComponent(span) => {
(
format!("{filepath} must be a Client Component. Add the \"use client\" directive the top of the file to resolve this issue.\nLearn more: https://nextjs.org/docs/app/api-reference/directives/use-client\n\n"),
vec![span]
)
},
RSCErrorKind::NextRscErrClientMetadataExport((source, span)) => {
(format!("You are attempting to export \"{source}\" from a component marked with \"use client\", which is disallowed. \"{source}\" must be resolved on the server before the page component is rendered. Keep your page as a Server Component and move Client Component logic to a separate file. Read more: https://nextjs.org/docs/app/api-reference/functions/generate-metadata#why-generatemetadata-is-server-component-only\n\n"), vec![span])
},
RSCErrorKind::NextRscErrConflictMetadataExport((span1, span2)) => (
"\"metadata\" and \"generateMetadata\" cannot be exported at the same time, please keep one of them. Read more: https://nextjs.org/docs/app/api-reference/file-conventions/metadata\n\n".to_string(),
vec![span1, span2]
),
RSCErrorKind::NextRscErrInvalidApi((source, span)) => (
format!("\"{source}\" is not supported in app/. Read more: https://nextjs.org/docs/app/building-your-application/data-fetching\n\n"), vec![span]
),
RSCErrorKind::NextRscErrDeprecatedApi((source, item, span)) => match (&*source, &*item) {
("next/server", "ImageResponse") => (
"ImageResponse moved from \"next/server\" to \"next/og\" since Next.js 14, please \
import from \"next/og\" instead"
.to_string(),
vec![span],
),
_ => (format!("\"{source}\" is deprecated."), vec![span]),
},
RSCErrorKind::NextSsrDynamicFalseNotAllowed(span) => (
"`ssr: false` is not allowed with `next/dynamic` in Server Components. Please move it into a Client Component."
.to_string(),
vec![span],
),
RSCErrorKind::NextRscErrIncompatibleRouteSegmentConfig(span, segment, property) => (
format!("Route segment config \"{segment}\" is not compatible with `nextConfig.{property}`. Please remove it."),
vec![span],
),
RSCErrorKind::NextRscErrRequiresRouteSegmentConfig(span, segment, property) => (
format!("Route segment config \"{segment}\" requires `nextConfig.{property}` to be enabled."),
vec![span],
),
RSCErrorKind::NextRscErrTaintWithoutConfig((api_name, span)) => (
format!(
"You're importing `{api_name}` from React which requires `experimental.taint: true` in your Next.js config. Learn more: https://nextjs.org/docs/app/api-reference/config/next-config-js/taint"
),
vec![span],
),
};
HANDLER.with(|handler| handler.struct_span_err(spans, msg.as_str()).emit())
}
/// Collects module directive, imports, and exports from top-level statements
fn collect_module_info(
app_dir: &Option<PathBuf>,
filepath: &str,
module: &Module,
) -> (Option<ModuleDirective>, Vec<ModuleImports>, Vec<Atom>) {
let mut imports: Vec<ModuleImports> = vec![];
let mut finished_directives = false;
let mut is_client_entry = false;
let mut is_action_file = false;
let mut is_cache_file = false;
let mut export_names = 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 client" {
if !finished_directives {
is_client_entry = true;
if is_action_file {
report_error(
app_dir,
filepath,
RSCErrorKind::UseClientWithUseServer(
expr_stmt.span,
),
);
} else if is_cache_file {
report_error(
app_dir,
filepath,
RSCErrorKind::UseClientWithUseCache(expr_stmt.span),
);
}
} else {
report_error(
app_dir,
filepath,
RSCErrorKind::NextRscErrClientDirective(expr_stmt.span),
);
}
} else if &**value == "use server" && !finished_directives {
is_action_file = true;
if is_client_entry {
report_error(
app_dir,
filepath,
RSCErrorKind::UseClientWithUseServer(expr_stmt.span),
);
}
} else if (&**value == "use cache"
|| value.starts_with("use cache: "))
&& !finished_directives
{
is_cache_file = true;
if is_client_entry {
report_error(
app_dir,
filepath,
RSCErrorKind::UseClientWithUseCache(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(
app_dir,
filepath,
RSCErrorKind::NextRscErrClientDirective(expr_stmt.span),
);
}
}
_ => {
// 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) => (imported.atom().into_owned(), imported.span()),
None => (named.local.to_id().0, named.local.span),
},
ImportSpecifier::Default(d) => (atom!(""), d.span),
ImportSpecifier::Namespace(n) => (atom!("*"), 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(_) => atom!("default"),
ExportSpecifier::Namespace(_) => atom!("*"),
ExportSpecifier::Named(named) => named
.exported
.as_ref()
.unwrap_or(&named.orig)
.atom()
.into_owned(),
})
}
finished_directives = true;
}
ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(ExportDecl { decl, .. })) => {
match decl {
Decl::Class(ClassDecl { ident, .. }) => {
export_names.push(ident.sym.clone());
}
Decl::Fn(FnDecl { ident, .. }) => {
export_names.push(ident.sym.clone());
}
Decl::Var(var) => {
for decl in &var.decls {
if let Pat::Ident(ident) = &decl.name {
export_names.push(ident.id.sym.clone());
}
}
}
_ => {}
}
finished_directives = true;
}
ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultDecl(ExportDefaultDecl {
decl: _,
..
})) => {
export_names.push(atom!("default"));
finished_directives = true;
}
ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultExpr(ExportDefaultExpr {
expr: _,
..
})) => {
export_names.push(atom!("default"));
finished_directives = true;
}
ModuleItem::ModuleDecl(ModuleDecl::ExportAll(_)) => {
export_names.push(atom!("*"));
}
_ => {
finished_directives = true;
}
}
});
let directive = if is_client_entry {
Some(ModuleDirective::UseClient)
} else if is_action_file {
Some(ModuleDirective::UseServer)
} else if is_cache_file {
Some(ModuleDirective::UseCache)
} else {
None
};
(directive, imports, export_names)
}
/// A visitor to assert given module file is a valid React server component.
struct ReactServerComponentValidator {
is_react_server_layer: bool,
cache_components_enabled: bool,
use_cache_enabled: bool,
taint_enabled: bool,
filepath: String,
app_dir: Option<PathBuf>,
invalid_server_imports: Vec<Wtf8Atom>,
invalid_server_lib_apis_mapping: FxHashMap<Wtf8Atom, Vec<&'static str>>,
deprecated_apis_mapping: FxHashMap<Wtf8Atom, Vec<&'static str>>,
invalid_client_imports: Vec<Wtf8Atom>,
invalid_client_lib_apis_mapping: FxHashMap<Wtf8Atom, Vec<&'static str>>,
/// React taint APIs that require `experimental.taint` config
react_taint_apis: Vec<&'static str>,
pub module_directive: Option<ModuleDirective>,
pub export_names: Vec<Atom>,
imports: ImportMap,
page_extensions: Vec<String>,
}
impl ReactServerComponentValidator {
pub fn new(
is_react_server_layer: bool,
cache_components_enabled: bool,
use_cache_enabled: bool,
taint_enabled: bool,
filename: String,
app_dir: Option<PathBuf>,
page_extensions: Vec<String>,
) -> Self {
Self {
is_react_server_layer,
cache_components_enabled,
use_cache_enabled,
taint_enabled,
filepath: filename,
app_dir,
module_directive: None,
export_names: vec![],
// react -> [apis]
// react-dom -> [apis]
// next/navigation -> [apis]
invalid_server_lib_apis_mapping: FxHashMap::from_iter([
(
atom!("react").into(),
vec![
"Component",
"createContext",
"createFactory",
"PureComponent",
"useDeferredValue",
"useEffect",
"useEffectEvent",
"useImperativeHandle",
"useInsertionEffect",
"useLayoutEffect",
"useReducer",
"useRef",
"useState",
"useSyncExternalStore",
"useTransition",
"useOptimistic",
"useActionState",
"experimental_useOptimistic",
],
),
(
atom!("react-dom").into(),
vec![
"flushSync",
"unstable_batchedUpdates",
"useFormStatus",
"useFormState",
],
),
(atom!("next/error").into(), vec!["unstable_catchError"]),
(
atom!("next/navigation").into(),
vec![
"useSearchParams",
"usePathname",
"useSelectedLayoutSegment",
"useSelectedLayoutSegments",
"useParams",
"useRouter",
"useServerInsertedHTML",
"ServerInsertedHTMLContext",
"unstable_isUnrecognizedActionError",
],
),
(atom!("next/link").into(), vec!["useLinkStatus"]),
]),
deprecated_apis_mapping: FxHashMap::from_iter([(
atom!("next/server").into(),
vec!["ImageResponse"],
)]),
invalid_server_imports: vec![
atom!("client-only").into(),
atom!("react-dom/client").into(),
atom!("react-dom/server").into(),
atom!("next/router").into(),
],
invalid_client_imports: vec![
atom!("server-only").into(),
atom!("next/headers").into(),
atom!("next/root-params").into(),
],
invalid_client_lib_apis_mapping: FxHashMap::from_iter([
(atom!("next/server").into(), vec!["after"]),
(
atom!("next/cache").into(),
vec![
"revalidatePath",
"revalidateTag",
// "unstable_cache", // useless in client, but doesn't technically error
"cacheLife",
"unstable_cacheLife",
"cacheTag",
"unstable_cacheTag",
// "unstable_noStore" // no-op in client, but allowed for legacy reasons
],
),
]),
react_taint_apis: vec![
"experimental_taintObjectReference",
"experimental_taintUniqueValue",
],
imports: ImportMap::default(),
page_extensions,
}
}
fn is_from_node_modules(&self, filepath: &str) -> bool {
static RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"node_modules[\\/]").unwrap());
RE.is_match(filepath)
}
fn is_callee_next_dynamic(&self, callee: &Callee) -> bool {
match callee {
Callee::Expr(expr) => self.imports.is_import(expr, "next/dynamic", "default"),
_ => false,
}
}
// 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: &Wtf8Atom, import: &ModuleImports) {
let deprecated_apis = self.deprecated_apis_mapping.get(import_source);
if let Some(deprecated_apis) = deprecated_apis {
for specifier in &import.specifiers {
if deprecated_apis.contains(&specifier.0.as_str()) {
report_error(
&self.app_dir,
&self.filepath,
RSCErrorKind::NextRscErrDeprecatedApi((
import_source.to_string_lossy().into_owned(),
specifier.0.to_string(),
specifier.1,
)),
);
}
}
}
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 invalid_apis.contains(&specifier.0.as_str()) {
report_error(
&self.app_dir,
&self.filepath,
RSCErrorKind::NextRscErrReactApi((specifier.0.to_string(), specifier.1)),
);
}
}
}
}
/// Check for React taint API imports when taint is not enabled
fn assert_react_taint_apis(&self, imports: &[ModuleImports]) {
// Skip check if taint is enabled or if file is from node_modules
if self.taint_enabled || self.is_from_node_modules(&self.filepath) {
return;
}
for import in imports {
let source = &import.source.0;
// Only check imports from 'react'
if source.as_str() != Some("react") {
continue;
}
for specifier in &import.specifiers {
if self.react_taint_apis.contains(&specifier.0.as_str()) {
report_error(
&self.app_dir,
&self.filepath,
RSCErrorKind::NextRscErrTaintWithoutConfig((
specifier.0.to_string(),
specifier.1,
)),
);
}
}
}
}
fn assert_server_graph(&self, imports: &[ModuleImports], module: &Module) {
// If the
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(
&self.app_dir,
&self.filepath,
RSCErrorKind::NextRscErrServerImport((
source.to_string_lossy().into_owned(),
import.source.1,
)),
);
}
self.assert_invalid_server_lib_apis(source, import);
}
self.assert_invalid_api(module, false);
self.assert_server_filename(module);
}
fn assert_server_filename(&self, module: &Module) {
if self.is_from_node_modules(&self.filepath) {
return;
}
let ext_pattern = build_page_extensions_regex(&self.page_extensions);
let re = Regex::new(&format!(r"[\\/]((global-)?error)\.{ext_pattern}$")).unwrap();
let is_error_file = re.is_match(&self.filepath);
if is_error_file
&& let Some(app_dir) = &self.app_dir
&& let Some(app_dir) = app_dir.to_str()
&& self.filepath.starts_with(app_dir)
{
let span = if let Some(first_item) = module.body.first() {
first_item.span()
} else {
module.span
};
report_error(
&self.app_dir,
&self.filepath,
RSCErrorKind::NextRscErrErrorFileServerComponent(span),
);
}
}
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(
&self.app_dir,
&self.filepath,
RSCErrorKind::NextRscErrClientImport((
source.to_string_lossy().into_owned(),
import.source.1,
)),
);
}
let invalid_apis = self.invalid_client_lib_apis_mapping.get(source);
if let Some(invalid_apis) = invalid_apis {
for specifier in &import.specifiers {
if invalid_apis.contains(&specifier.0.as_str()) {
report_error(
&self.app_dir,
&self.filepath,
RSCErrorKind::NextRscErrClientImport((
specifier.0.to_string(),
specifier.1,
)),
);
}
}
}
}
}
fn assert_invalid_api(&self, module: &Module, is_client_entry: bool) {
if self.is_from_node_modules(&self.filepath) {
return;
}
let ext_pattern = build_page_extensions_regex(&self.page_extensions);
let re = Regex::new(&format!(r"[\\/](page|layout|route)\.{ext_pattern}$")).unwrap();
let is_app_entry = re.is_match(&self.filepath);
if is_app_entry {
let mut possibly_invalid_exports: FxIndexMap<Atom, (InvalidExportKind, Span)> =
FxIndexMap::default();
let mut collect_possibly_invalid_exports =
|export_name: &Atom, span: &Span| match &**export_name {
"getServerSideProps" | "getStaticProps" => {
possibly_invalid_exports
.insert(export_name.clone(), (InvalidExportKind::General, *span));
}
"generateMetadata" | "metadata" => {
possibly_invalid_exports
.insert(export_name.clone(), (InvalidExportKind::Metadata, *span));
}
"runtime" => {
if self.cache_components_enabled {
possibly_invalid_exports.insert(
export_name.clone(),
(
InvalidExportKind::RouteSegmentConfig(
NextConfigProperty::CacheComponents,
),
*span,
),
);
} else if self.use_cache_enabled {
possibly_invalid_exports.insert(
export_name.clone(),
(
InvalidExportKind::RouteSegmentConfig(
NextConfigProperty::UseCache,
),
*span,
),
);
}
}
"dynamicParams" | "dynamic" | "fetchCache" | "revalidate"
| "experimental_ppr" => {
if self.cache_components_enabled {
possibly_invalid_exports.insert(
export_name.clone(),
(
InvalidExportKind::RouteSegmentConfig(
NextConfigProperty::CacheComponents,
),
*span,
),
);
}
}
"unstable_instant" => {
if !self.cache_components_enabled {
possibly_invalid_exports.insert(
export_name.clone(),
(
InvalidExportKind::RequiresRouteSegmentConfig(
NextConfigProperty::CacheComponents,
),
*span,
),
);
}
}
_ => (),
};
for export in &module.body {
match export {
ModuleItem::ModuleDecl(ModuleDecl::ExportNamed(export)) => {
for specifier in &export.specifiers {
if let ExportSpecifier::Named(named) = specifier {
collect_possibly_invalid_exports(&named.orig.atom(), &named.span);
}
}
}
ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(export)) => match &export.decl {
Decl::Fn(f) => {
collect_possibly_invalid_exports(&f.ident.sym, &f.ident.span);
}
Decl::Var(v) => {
for decl in &v.decls {
if let Pat::Ident(i) = &decl.name {
collect_possibly_invalid_exports(&i.sym, &i.span);
}
}