Unverified Commit e652a6f6 authored by OJ Kwon's avatar OJ Kwon Committed by GitHub

feat(transforms): enable rsc transforms for the remaining contexts (#61231)

### What?

This PR wraps up supporting rsc transforms (mostly for the assertion) in
Turbopack. PR contains a few changes to support it, including:

- adjust / expand transform rules for the corresponding contexts
- fix file name / node_modules check
- extract visitors for the assertion / transforms

This change enables most of the rsc-build* tests and some more other
tests. The only failing tests in the rsc-build-errors is due to
Turbopack not triggering hmr with empty file.

Closes PACK-2303
parent 59bf406d
......@@ -57,6 +57,7 @@ use crate::{
},
transforms::{
emotion::get_emotion_transform_rule, get_ecma_transform_rule,
next_react_server_components::get_next_react_server_components_transform_rule,
relay::get_relay_transform_rule,
styled_components::get_styled_components_transform_rule,
styled_jsx::get_styled_jsx_transform_rule,
......@@ -382,12 +383,21 @@ pub async fn get_server_module_options_context(
ServerContextType::Pages { .. }
| ServerContextType::PagesData { .. }
| ServerContextType::PagesApi { .. } => {
let custom_source_transform_rules: Vec<ModuleRule> =
let mut custom_source_transform_rules: Vec<ModuleRule> =
vec![styled_components_transform_rule, styled_jsx_transform_rule]
.into_iter()
.flatten()
.collect();
let mut foreign_custom_transform_rules = custom_source_transform_rules.clone();
if let ServerContextType::Pages { .. } = ty.into_value() {
custom_source_transform_rules.push(
get_next_react_server_components_transform_rule(next_config, false, None)
.await?,
);
}
base_next_server_rules.extend(custom_source_transform_rules);
base_next_server_rules.extend(source_transform_rules);
......@@ -408,8 +418,9 @@ pub async fn get_server_module_options_context(
..Default::default()
};
foreign_custom_transform_rules.extend(internal_custom_rules);
let foreign_code_module_options_context = ModuleOptionsContext {
custom_rules: internal_custom_rules.clone(),
custom_rules: foreign_custom_transform_rules.clone(),
enable_webpack_loaders: foreign_webpack_loaders,
// NOTE(WEB-1016) PostCSS transforms should also apply to foreign code.
enable_postcss_transform: enable_foreign_postcss_transform,
......@@ -419,7 +430,7 @@ pub async fn get_server_module_options_context(
let internal_module_options_context = ModuleOptionsContext {
enable_typescript_transform: Some(TypescriptTransformOptions::default().cell()),
enable_jsx: Some(JsxTransformOptions::default().cell()),
custom_rules: internal_custom_rules,
custom_rules: foreign_custom_transform_rules,
..module_options_context.clone()
};
......@@ -444,25 +455,33 @@ pub async fn get_server_module_options_context(
..module_options_context
}
}
ServerContextType::AppSSR { .. } => {
let custom_source_transform_rules: Vec<ModuleRule> =
ServerContextType::AppSSR { app_dir, .. } => {
let mut custom_source_transform_rules: Vec<ModuleRule> =
vec![styled_components_transform_rule, styled_jsx_transform_rule]
.into_iter()
.flatten()
.collect();
let mut foreign_custom_transform_rules = custom_source_transform_rules.clone();
custom_source_transform_rules.push(
get_next_react_server_components_transform_rule(next_config, false, Some(app_dir))
.await?,
);
base_next_server_rules.extend(custom_source_transform_rules.clone());
base_next_server_rules.extend(source_transform_rules);
let module_options_context = ModuleOptionsContext {
custom_rules: custom_source_transform_rules,
execution_context: Some(execution_context),
use_lightningcss,
tree_shaking_mode: Some(TreeShakingMode::ReexportsOnly),
..Default::default()
};
foreign_custom_transform_rules.extend(internal_custom_rules);
let foreign_code_module_options_context = ModuleOptionsContext {
custom_rules: internal_custom_rules.clone(),
custom_rules: foreign_custom_transform_rules.clone(),
enable_webpack_loaders: foreign_webpack_loaders,
// NOTE(WEB-1016) PostCSS transforms should also apply to foreign code.
enable_postcss_transform: enable_foreign_postcss_transform,
......@@ -470,7 +489,7 @@ pub async fn get_server_module_options_context(
};
let internal_module_options_context = ModuleOptionsContext {
enable_typescript_transform: Some(TypescriptTransformOptions::default().cell()),
custom_rules: internal_custom_rules,
custom_rules: foreign_custom_transform_rules,
..module_options_context.clone()
};
......@@ -496,6 +515,7 @@ pub async fn get_server_module_options_context(
}
}
ServerContextType::AppRSC {
app_dir,
ecmascript_client_reference_transition_name,
..
} => {
......@@ -517,6 +537,13 @@ pub async fn get_server_module_options_context(
));
}
let mut foreign_custom_transform_rules = custom_source_transform_rules.clone();
custom_source_transform_rules.push(
get_next_react_server_components_transform_rule(next_config, true, Some(app_dir))
.await?,
);
base_next_server_rules.extend(custom_source_transform_rules.clone());
base_next_server_rules.extend(source_transform_rules);
......@@ -527,9 +554,9 @@ pub async fn get_server_module_options_context(
..Default::default()
};
custom_source_transform_rules.extend(internal_custom_rules);
foreign_custom_transform_rules.extend(internal_custom_rules);
let foreign_code_module_options_context = ModuleOptionsContext {
custom_rules: custom_source_transform_rules.clone(),
custom_rules: foreign_custom_transform_rules.clone(),
enable_webpack_loaders: foreign_webpack_loaders,
// NOTE(WEB-1016) PostCSS transforms should also apply to foreign code.
enable_postcss_transform: enable_foreign_postcss_transform,
......@@ -537,7 +564,7 @@ pub async fn get_server_module_options_context(
};
let internal_module_options_context = ModuleOptionsContext {
enable_typescript_transform: Some(TypescriptTransformOptions::default().cell()),
custom_rules: custom_source_transform_rules,
custom_rules: foreign_custom_transform_rules,
..module_options_context.clone()
};
ModuleOptionsContext {
......
......@@ -14,9 +14,7 @@ use crate::{
get_server_actions_transform_rule, next_amp_attributes::get_next_amp_attr_rule,
next_cjs_optimizer::get_next_cjs_optimizer_rule,
next_disallow_re_export_all_in_page::get_next_disallow_export_all_in_page_rule,
next_pure::get_next_pure_rule,
next_react_server_components::get_next_react_server_components_transform_rule,
server_actions::ActionsTransform,
next_pure::get_next_pure_rule, server_actions::ActionsTransform,
},
};
......@@ -74,8 +72,6 @@ pub async fn get_next_server_transforms_rules(
mdx_rs,
));
rules.push(get_next_react_server_components_transform_rule(next_config, true).await?);
if let Some(client_transition) = client_transition {
rules.push(get_next_css_client_reference_transforms_rule(
client_transition,
......
use std::path::PathBuf;
use anyhow::Result;
use async_trait::async_trait;
use next_custom_transforms::transforms::react_server_components::*;
use swc_core::{
common::{util::take::Take, FileName},
ecma::{
ast::{Module, Program},
visit::FoldWith,
},
common::FileName,
ecma::{ast::Program, visit::VisitWith},
};
use turbo_tasks::Vc;
use turbo_tasks_fs::FileSystemPath;
use turbopack_binding::turbopack::{
ecmascript::{CustomTransformer, TransformContext},
turbopack::module_options::ModuleRule,
......@@ -20,13 +16,31 @@ use super::get_ecma_transform_rule;
use crate::next_config::NextConfig;
/// Returns a rule which applies the Next.js react server components transform.
/// This transform owns responsibility to assert various import / usage
/// conditions against each code's context. Refer below table how we are
/// applying this rules against various contexts.
///
/// +-----------------+---------+--------------------+
/// | Context\Enabled | Enabled | isReactServerLayer |
/// +-----------------+---------+--------------------+
/// | SSR | true | false |
/// | Client | true | false |
/// | Middleware | false | false |
/// | Api | false | false |
/// | RSC | true | true |
/// | Pages | true | false |
/// +-----------------+---------+--------------------+
pub async fn get_next_react_server_components_transform_rule(
next_config: Vc<NextConfig>,
is_react_server_layer: bool,
app_dir: Option<Vc<FileSystemPath>>,
) -> Result<ModuleRule> {
let enable_mdx_rs = *next_config.mdx_rs().await?;
Ok(get_ecma_transform_rule(
Box::new(NextJsReactServerComponents::new(is_react_server_layer)),
Box::new(NextJsReactServerComponents::new(
is_react_server_layer,
app_dir,
)),
enable_mdx_rs,
true,
))
......@@ -35,12 +49,14 @@ pub async fn get_next_react_server_components_transform_rule(
#[derive(Debug)]
struct NextJsReactServerComponents {
is_react_server_layer: bool,
app_dir: Option<Vc<FileSystemPath>>,
}
impl NextJsReactServerComponents {
fn new(is_react_server_layer: bool) -> Self {
fn new(is_react_server_layer: bool, app_dir: Option<Vc<FileSystemPath>>) -> Self {
Self {
is_react_server_layer,
app_dir,
}
}
}
......@@ -48,19 +64,24 @@ impl NextJsReactServerComponents {
#[async_trait]
impl CustomTransformer for NextJsReactServerComponents {
async fn transform(&self, program: &mut Program, ctx: &TransformContext<'_>) -> Result<()> {
let p = std::mem::replace(program, Program::Module(Module::dummy()));
let file_name = if ctx.file_path_str.is_empty() {
FileName::Anon
} else {
FileName::Real(ctx.file_path_str.into())
};
let mut visitor = server_components(
FileName::Custom(ctx.file_path_str.to_string()),
let mut visitor = server_components_assert(
file_name,
Config::WithOptions(Options {
is_react_server_layer: self.is_react_server_layer,
}),
ctx.comments,
Some(PathBuf::from(ctx.file_path.parent().await?.path.clone())),
match self.app_dir {
None => None,
Some(path) => Some(path.await?.path.clone().into()),
},
);
*program = p.fold_with(&mut visitor);
program.visit_with(&mut visitor);
Ok(())
}
}
......@@ -2,6 +2,7 @@ use std::{collections::HashMap, path::PathBuf};
use regex::Regex;
use serde::Deserialize;
use swc_core::ecma::visit::VisitWith;
use turbopack_binding::swc::core::{
common::{
comments::{Comment, CommentKind, Comments},
......@@ -12,7 +13,9 @@ use turbopack_binding::swc::core::{
ast::*,
atoms::{js_word, JsWord},
utils::{prepend_stmts, quote_ident, quote_str, ExprFactory},
visit::{as_folder, noop_visit_mut_type, Fold, VisitMut, VisitMutWith},
visit::{
as_folder, noop_visit_mut_type, noop_visit_type, Fold, Visit, VisitMut, VisitMutWith,
},
},
};
......@@ -40,18 +43,18 @@ pub struct Options {
pub is_react_server_layer: bool,
}
/// 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,
filepath: String,
app_dir: Option<PathBuf>,
comments: C,
export_names: Vec<String>,
invalid_server_imports: Vec<JsWord>,
invalid_client_imports: Vec<JsWord>,
invalid_server_react_apis: Vec<JsWord>,
invalid_server_react_dom_apis: Vec<JsWord>,
directive_import_collection: Option<(bool, bool, Vec<ModuleImports>, Vec<String>)>,
}
#[derive(Clone, Debug)]
struct ModuleImports {
source: (JsWord, Span),
specifiers: Vec<(JsWord, Span)>,
......@@ -71,11 +74,151 @@ enum RSCErrorKind {
NextRscErrInvalidApi((String, Span)),
}
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.filepath.clone(),
self.app_dir.clone(),
);
module.visit_with(&mut validator);
self.directive_import_collection = validator.directive_import_collection;
let is_client_entry = self
.directive_import_collection
.as_ref()
.expect("directive_import_collection must be set")
.0;
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);
return;
}
} else if is_client_entry {
self.prepend_comment_node(module, is_cjs);
}
module.visit_mut_children_with(self)
}
}
impl<C: Comments> ReactServerComponents<C> {
/// Consolidated place to parse, generate error messages for the RSC parsing
/// errors.
fn report_error(&self, error_kind: RSCErrorKind) {
let (msg, span) = match error_kind {
/// removes specific directive from the AST.
fn remove_top_level_directive(&mut self, module: &mut Module) {
let _ = &module.body.retain(|item| {
if let ModuleItem::Stmt(stmt) = item {
if let Some(expr_stmt) = stmt.as_expr() {
if let Expr::Lit(Lit::Str(Str { value, .. })) = &*expr_stmt.expr {
if &**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) {
// 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,
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()],
type_args: Default::default(),
}))),
definite: false,
}],
declare: false,
})))),
ModuleItem::Stmt(Stmt::Expr(ExprStmt {
span: DUMMY_SP,
expr: Box::new(Expr::Assign(AssignExpr {
span: DUMMY_SP,
left: PatOrExpr::Expr(Box::new(Expr::Member(MemberExpr {
span: DUMMY_SP,
obj: Box::new(Expr::Ident(quote_ident!("module"))),
prop: MemberProp::Ident(quote_ident!("exports")),
}))),
op: op!("="),
right: Box::new(Expr::Call(CallExpr {
span: DUMMY_SP,
callee: quote_ident!("createProxy").as_callee(),
args: vec![filepath.as_arg()],
type_args: Default::default(),
})),
})),
})),
]
.into_iter(),
);
self.prepend_comment_node(module, is_cjs);
}
fn prepend_comment_node(&self, module: &Module, is_cjs: bool) {
let export_names = &self
.directive_import_collection
.as_ref()
.expect("directive_import_collection must be set")
.3;
// 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__ {} {} ",
export_names.join(","),
if is_cjs { "cjs" } else { "auto" }
)
.into(),
},
);
}
}
/// 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, span) = match error_kind {
RSCErrorKind::RedundantDirectives(span) => (
"It's not possible to have both `use client` and `use server` directives in the \
same file."
......@@ -100,14 +243,11 @@ impl<C: Comments> ReactServerComponents<C> {
(msg, span)
}
RSCErrorKind::NextRscErrClientImport((source, span)) => {
// [NOTE]: in turbopack currently only type of AppRsc runs this transform,
// so it won't hit pages_dir case
let is_app_dir = self
.app_dir
let is_app_dir = app_dir
.as_ref()
.map(|app_dir| {
if let Some(app_dir) = app_dir.as_os_str().to_str() {
self.filepath.starts_with(app_dir)
filepath.starts_with(app_dir)
} else {
false
}
......@@ -132,7 +272,7 @@ impl<C: Comments> ReactServerComponents<C> {
},
RSCErrorKind::NextRscErrErrorFileServerComponent(span) => {
(
format!("{} 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/getting-started/react-essentials#client-components\n\n", self.filepath),
format!("{} 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/getting-started/react-essentials#client-components\n\n", filepath),
span
)
},
......@@ -149,280 +289,236 @@ impl<C: Comments> ReactServerComponents<C> {
),
};
HANDLER.with(|handler| handler.struct_span_err(span, msg.as_str()).emit())
}
HANDLER.with(|handler| handler.struct_span_err(span, msg.as_str()).emit())
}
impl<C: Comments> VisitMut for ReactServerComponents<C> {
noop_visit_mut_type!();
fn visit_mut_module(&mut self, module: &mut Module) {
let (is_client_entry, is_action_file, imports) =
self.collect_top_level_directives_and_imports(module);
let is_cjs = contains_cjs(module);
if self.is_react_server_layer {
if is_client_entry {
self.to_module_ref(module, is_cjs);
return;
} else {
// 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(&imports, module);
}
} else {
// Only assert client graph if the file is not an action file,
// and bundle target is "client" e.g.
// * client components pages
// * pages bundles on browser layer
if !is_action_file {
self.assert_client_graph(&imports);
self.assert_invalid_api(module, true);
}
if is_client_entry {
self.prepend_comment_node(module, is_cjs);
}
}
module.visit_mut_children_with(self)
}
}
impl<C: Comments> ReactServerComponents<C> {
// Collects top level directives and imports, then removes specific ones
// from the AST.
fn collect_top_level_directives_and_imports(
&mut self,
module: &mut Module,
) -> (bool, bool, Vec<ModuleImports>) {
let mut imports: Vec<ModuleImports> = vec![];
let mut finished_directives = false;
let mut is_client_entry = false;
let mut is_action_file = false;
let _ = &module.body.retain(|item| {
match item {
ModuleItem::Stmt(stmt) => {
if !stmt.is_expr() {
// Not an expression.
finished_directives = true;
}
/// Collects top level directives and imports
fn collect_top_level_directives_and_imports(
app_dir: &Option<PathBuf>,
filepath: &str,
module: &Module,
) -> (bool, bool, Vec<ModuleImports>, Vec<String>) {
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 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 {
self.report_error(
RSCErrorKind::RedundantDirectives(
expr_stmt.span,
),
);
}
} else {
self.report_error(
RSCErrorKind::NextRscErrClientDirective(
expr_stmt.span,
),
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::RedundantDirectives(expr_stmt.span),
);
}
// Remove the directive.
return false;
} else if &**value == "use server" && !finished_directives {
is_action_file = true;
if is_client_entry {
self.report_error(RSCErrorKind::RedundantDirectives(
expr_stmt.span,
));
}
} else {
report_error(
app_dir,
filepath,
RSCErrorKind::NextRscErrClientDirective(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 {
if &**value == "use client" {
self.report_error(
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::RedundantDirectives(expr_stmt.span),
);
}
}
_ => {
// Other expression types.
finished_directives = true;
}
// 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 {
if &**value == "use client" {
report_error(
app_dir,
filepath,
RSCErrorKind::NextRscErrClientDirective(expr_stmt.span),
);
}
}
}
}
None => {
// Not an expression.
finished_directives = true;
_ => {
// Other expression types.
finished_directives = true;
}
}
}
None => {
// Not an expression.
finished_directives = true;
}
}
ModuleItem::ModuleDecl(ModuleDecl::Import(import)) => {
let source = import.src.value.clone();
let specifiers = import
.specifiers
.iter()
.map(|specifier| match specifier {
ImportSpecifier::Named(named) => match &named.imported {
Some(imported) => match &imported {
ModuleExportName::Ident(i) => (i.to_id().0, i.span),
ModuleExportName::Str(s) => (s.value.clone(), s.span),
},
None => (named.local.to_id().0, named.local.span),
}
ModuleItem::ModuleDecl(ModuleDecl::Import(import)) => {
let source = import.src.value.clone();
let specifiers = import
.specifiers
.iter()
.map(|specifier| match specifier {
ImportSpecifier::Named(named) => match &named.imported {
Some(imported) => match &imported {
ModuleExportName::Ident(i) => (i.to_id().0, i.span),
ModuleExportName::Str(s) => (s.value.clone(), s.span),
},
ImportSpecifier::Default(d) => (js_word!(""), d.span),
ImportSpecifier::Namespace(n) => ("*".into(), n.span),
})
.collect();
None => (named.local.to_id().0, named.local.span),
},
ImportSpecifier::Default(d) => (js_word!(""), d.span),
ImportSpecifier::Namespace(n) => ("*".into(), n.span),
})
.collect();
imports.push(ModuleImports {
source: (source, import.span),
specifiers,
});
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 {
self.export_names.push(match specifier {
ExportSpecifier::Default(_) => "default".to_string(),
ExportSpecifier::Namespace(_) => "*".to_string(),
ExportSpecifier::Named(named) => match &named.exported {
Some(exported) => match &exported {
ModuleExportName::Ident(i) => i.sym.to_string(),
ModuleExportName::Str(s) => s.value.to_string(),
},
_ => match &named.orig {
ModuleExportName::Ident(i) => i.sym.to_string(),
ModuleExportName::Str(s) => s.value.to_string(),
},
finished_directives = true;
}
// Collect all export names.
ModuleItem::ModuleDecl(ModuleDecl::ExportNamed(e)) => {
for specifier in &e.specifiers {
export_names.push(match specifier {
ExportSpecifier::Default(_) => "default".to_string(),
ExportSpecifier::Namespace(_) => "*".to_string(),
ExportSpecifier::Named(named) => match &named.exported {
Some(exported) => match &exported {
ModuleExportName::Ident(i) => i.sym.to_string(),
ModuleExportName::Str(s) => s.value.to_string(),
},
})
}
finished_directives = true;
_ => match &named.orig {
ModuleExportName::Ident(i) => i.sym.to_string(),
ModuleExportName::Str(s) => s.value.to_string(),
},
},
})
}
ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(ExportDecl { decl, .. })) => {
match decl {
Decl::Class(ClassDecl { ident, .. }) => {
self.export_names.push(ident.sym.to_string());
}
Decl::Fn(FnDecl { ident, .. }) => {
self.export_names.push(ident.sym.to_string());
}
Decl::Var(var) => {
for decl in &var.decls {
if let Pat::Ident(ident) = &decl.name {
self.export_names.push(ident.id.sym.to_string());
}
finished_directives = true;
}
ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(ExportDecl { decl, .. })) => {
match decl {
Decl::Class(ClassDecl { ident, .. }) => {
export_names.push(ident.sym.to_string());
}
Decl::Fn(FnDecl { ident, .. }) => {
export_names.push(ident.sym.to_string());
}
Decl::Var(var) => {
for decl in &var.decls {
if let Pat::Ident(ident) = &decl.name {
export_names.push(ident.id.sym.to_string());
}
}
_ => {}
}
finished_directives = true;
}
ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultDecl(ExportDefaultDecl {
decl: _,
..
})) => {
self.export_names.push("default".to_string());
finished_directives = true;
}
ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultExpr(ExportDefaultExpr {
expr: _,
..
})) => {
self.export_names.push("default".to_string());
finished_directives = true;
}
ModuleItem::ModuleDecl(ModuleDecl::ExportAll(_)) => {
self.export_names.push("*".to_string());
}
_ => {
finished_directives = true;
_ => {}
}
finished_directives = true;
}
true
});
(is_client_entry, is_action_file, imports)
}
ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultDecl(ExportDefaultDecl {
decl: _,
..
})) => {
export_names.push("default".to_string());
finished_directives = true;
}
ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultExpr(ExportDefaultExpr {
expr: _,
..
})) => {
export_names.push("default".to_string());
finished_directives = true;
}
ModuleItem::ModuleDecl(ModuleDecl::ExportAll(_)) => {
export_names.push("*".to_string());
}
_ => {
finished_directives = 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) {
// Clear all the statements and module declarations.
module.body.clear();
(is_client_entry, is_action_file, imports, export_names)
}
let proxy_ident = quote_ident!("createProxy");
let filepath = quote_str!(&*self.filepath);
/// A visitor to assert given module file is a valid React server component.
struct ReactServerComponentValidator {
is_react_server_layer: bool,
filepath: String,
app_dir: Option<PathBuf>,
invalid_server_imports: Vec<JsWord>,
invalid_client_imports: Vec<JsWord>,
invalid_server_react_apis: Vec<JsWord>,
invalid_server_react_dom_apis: Vec<JsWord>,
pub directive_import_collection: Option<(bool, bool, Vec<ModuleImports>, Vec<String>)>,
}
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,
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()],
type_args: Default::default(),
}))),
definite: false,
}],
declare: false,
})))),
ModuleItem::Stmt(Stmt::Expr(ExprStmt {
span: DUMMY_SP,
expr: Box::new(Expr::Assign(AssignExpr {
span: DUMMY_SP,
left: PatOrExpr::Expr(Box::new(Expr::Member(MemberExpr {
span: DUMMY_SP,
obj: Box::new(Expr::Ident(quote_ident!("module"))),
prop: MemberProp::Ident(quote_ident!("exports")),
}))),
op: op!("="),
right: Box::new(Expr::Call(CallExpr {
span: DUMMY_SP,
callee: quote_ident!("createProxy").as_callee(),
args: vec![filepath.as_arg()],
type_args: Default::default(),
})),
})),
})),
]
.into_iter(),
);
impl ReactServerComponentValidator {
pub fn new(is_react_server_layer: bool, filename: String, app_dir: Option<PathBuf>) -> Self {
Self {
is_react_server_layer,
filepath: filename,
app_dir,
directive_import_collection: None,
invalid_server_imports: vec![
JsWord::from("client-only"),
JsWord::from("react-dom/client"),
JsWord::from("react-dom/server"),
JsWord::from("next/router"),
],
invalid_client_imports: vec![JsWord::from("server-only"), JsWord::from("next/headers")],
invalid_server_react_dom_apis: vec![
JsWord::from("findDOMNode"),
JsWord::from("flushSync"),
JsWord::from("unstable_batchedUpdates"),
JsWord::from("useFormStatus"),
JsWord::from("useFormState"),
],
invalid_server_react_apis: vec![
JsWord::from("Component"),
JsWord::from("createContext"),
JsWord::from("createFactory"),
JsWord::from("PureComponent"),
JsWord::from("useDeferredValue"),
JsWord::from("useEffect"),
JsWord::from("useImperativeHandle"),
JsWord::from("useInsertionEffect"),
JsWord::from("useLayoutEffect"),
JsWord::from("useReducer"),
JsWord::from("useRef"),
JsWord::from("useState"),
JsWord::from("useSyncExternalStore"),
JsWord::from("useTransition"),
JsWord::from("useOptimistic"),
],
}
}
self.prepend_comment_node(module, is_cjs);
fn is_from_node_modules(&self, filepath: &str) -> bool {
Regex::new(r"node_modules[\\/]").unwrap().is_match(filepath)
}
fn assert_server_graph(&self, imports: &[ModuleImports], module: &Module) {
......@@ -433,28 +529,37 @@ impl<C: Comments> ReactServerComponents<C> {
for import in imports {
let source = import.source.0.clone();
if self.invalid_server_imports.contains(&source) {
self.report_error(RSCErrorKind::NextRscErrServerImport((
source.to_string(),
import.source.1,
)));
report_error(
&self.app_dir,
&self.filepath,
RSCErrorKind::NextRscErrServerImport((source.to_string(), import.source.1)),
);
}
if source == *"react" {
for specifier in &import.specifiers {
if self.invalid_server_react_apis.contains(&specifier.0) {
self.report_error(RSCErrorKind::NextRscErrReactApi((
specifier.0.to_string(),
specifier.1,
)));
report_error(
&self.app_dir,
&self.filepath,
RSCErrorKind::NextRscErrReactApi((
specifier.0.to_string(),
specifier.1,
)),
);
}
}
}
if source == *"react-dom" {
for specifier in &import.specifiers {
if self.invalid_server_react_dom_apis.contains(&specifier.0) {
self.report_error(RSCErrorKind::NextRscErrReactApi((
specifier.0.to_string(),
specifier.1,
)));
report_error(
&self.app_dir,
&self.filepath,
RSCErrorKind::NextRscErrReactApi((
specifier.0.to_string(),
specifier.1,
)),
);
}
}
}
......@@ -481,7 +586,11 @@ impl<C: Comments> ReactServerComponents<C> {
module.span
};
self.report_error(RSCErrorKind::NextRscErrErrorFileServerComponent(span));
report_error(
&self.app_dir,
&self.filepath,
RSCErrorKind::NextRscErrErrorFileServerComponent(span),
);
}
}
}
......@@ -495,10 +604,11 @@ impl<C: Comments> ReactServerComponents<C> {
for import in imports {
let source = import.source.0.clone();
if self.invalid_client_imports.contains(&source) {
self.report_error(RSCErrorKind::NextRscErrClientImport((
source.to_string(),
import.source.1,
)));
report_error(
&self.app_dir,
&self.filepath,
RSCErrorKind::NextRscErrClientImport((source.to_string(), import.source.1)),
);
}
}
}
......@@ -581,54 +691,102 @@ impl<C: Comments> ReactServerComponents<C> {
// Client entry can't export `generateMetadata` or `metadata`.
if is_client_entry {
if has_gm_export || has_metadata_export {
self.report_error(RSCErrorKind::NextRscErrClientMetadataExport((
invalid_export_name.clone(),
span,
)));
report_error(
&self.app_dir,
&self.filepath,
RSCErrorKind::NextRscErrClientMetadataExport((
invalid_export_name.clone(),
span,
)),
);
}
} else {
// Server entry can't export `generateMetadata` and `metadata` together.
if has_gm_export && has_metadata_export {
self.report_error(RSCErrorKind::NextRscErrConflictMetadataExport(span));
report_error(
&self.app_dir,
&self.filepath,
RSCErrorKind::NextRscErrConflictMetadataExport(span),
);
}
}
// Assert `getServerSideProps` and `getStaticProps` exports.
if invalid_export_name == "getServerSideProps"
|| invalid_export_name == "getStaticProps"
{
self.report_error(RSCErrorKind::NextRscErrInvalidApi((
invalid_export_name.clone(),
span,
)));
report_error(
&self.app_dir,
&self.filepath,
RSCErrorKind::NextRscErrInvalidApi((invalid_export_name.clone(), span)),
);
}
}
}
}
fn prepend_comment_node(&self, module: &Module, is_cjs: bool) {
// 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__ {} {} ",
self.export_names.join(","),
if is_cjs { "cjs" } else { "auto" }
)
.into(),
},
);
}
impl Visit for ReactServerComponentValidator {
noop_visit_type!();
fn is_from_node_modules(&self, filepath: &str) -> bool {
Regex::new(r"[\\/]node_modules[\\/]")
.unwrap()
.is_match(filepath)
fn visit_module(&mut self, module: &Module) {
let (is_client_entry, is_action_file, imports, export_names) =
collect_top_level_directives_and_imports(&self.app_dir, &self.filepath, module);
self.directive_import_collection = Some((
is_client_entry,
is_action_file,
imports.clone(),
export_names,
));
if self.is_react_server_layer {
if is_client_entry {
return;
} else {
// 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(&imports, module);
}
} else {
// Only assert client graph if the file is not an action file,
// and bundle target is "client" e.g.
// * client components pages
// * pages bundles on browser layer
if !is_action_file {
self.assert_client_graph(&imports);
self.assert_invalid_api(module, true);
}
}
module.visit_children_with(self);
}
}
/// Returns a visitor to assert react server components without any transform.
/// This is for the Turbopack which have its own transform phase for the server
/// components proxy. Also this returns a visitor instead of fold, performs
/// better than running whole transform as a folder.
pub fn server_components_assert(
filename: FileName,
config: Config,
app_dir: Option<PathBuf>,
) -> impl Visit {
let is_react_server_layer: bool = match &config {
Config::WithOptions(x) => x.is_react_server_layer,
_ => false,
};
let filename = match filename {
FileName::Custom(path) => format!("<{}>", path),
_ => filename.to_string(),
};
ReactServerComponentValidator::new(is_react_server_layer, filename, app_dir)
}
/// Runs react server component transform for the module proxy, as well as
/// running assertion.
pub fn server_components<C: Comments>(
filename: FileName,
config: Config,
......@@ -647,37 +805,6 @@ pub fn server_components<C: Comments>(
_ => filename.to_string(),
},
app_dir,
export_names: vec![],
invalid_server_imports: vec![
JsWord::from("client-only"),
JsWord::from("react-dom/client"),
JsWord::from("react-dom/server"),
JsWord::from("next/router"),
],
invalid_client_imports: vec![JsWord::from("server-only"), JsWord::from("next/headers")],
invalid_server_react_dom_apis: vec![
JsWord::from("findDOMNode"),
JsWord::from("flushSync"),
JsWord::from("unstable_batchedUpdates"),
JsWord::from("useFormStatus"),
JsWord::from("useFormState"),
],
invalid_server_react_apis: vec![
JsWord::from("Component"),
JsWord::from("createContext"),
JsWord::from("createFactory"),
JsWord::from("PureComponent"),
JsWord::from("useDeferredValue"),
JsWord::from("useEffect"),
JsWord::from("useImperativeHandle"),
JsWord::from("useInsertionEffect"),
JsWord::from("useLayoutEffect"),
JsWord::from("useReducer"),
JsWord::from("useRef"),
JsWord::from("useState"),
JsWord::from("useSyncExternalStore"),
JsWord::from("useTransition"),
JsWord::from("useOptimistic"),
],
directive_import_collection: None,
})
}
......@@ -356,26 +356,36 @@ describe('Error overlay - RSC build errors', () => {
() => session.getRedboxSource(),
/must be a Client \n| Component/
)
expect(
next.normalizeTestDirContent(await session.getRedboxSource())
).toMatchInlineSnapshot(
`
"./app/server-with-errors/error-file/error.js
Error:
x TEST_DIR/app/server-with-errors/error-file/error.js must be a Client Component. Add the "use client" directive the top
| of the file to resolve this issue.
| Learn more: https://nextjs.org/docs/getting-started/react-essentials#client-components
|
|
,-[TEST_DIR/app/server-with-errors/error-file/error.js:1:1]
1 | export default function Error() {}
: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
\`----
Import trace for requested module:
./app/server-with-errors/error-file/error.js"
`
)
if (process.env.TURBOPACK) {
expect(next.normalizeTestDirContent(await session.getRedboxSource()))
.toMatchInlineSnapshot(`
"./app/server-with-errors/error-file/error.js:1:0
Parsing ecmascript source code failed
> 1 | export default function Error() {}
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
app/server-with-errors/error-file/error.js must be a Client Component. Add the "use client" directive the top of the file to resolve this issue.
Learn more: https://nextjs.org/docs/getting-started/react-essentials#client-components"
`)
} else {
expect(next.normalizeTestDirContent(await session.getRedboxSource()))
.toMatchInlineSnapshot(`
"./app/server-with-errors/error-file/error.js
Error:
x TEST_DIR/app/server-with-errors/error-file/error.js must be a Client Component. Add the "use client" directive the top
| of the file to resolve this issue.
| Learn more: https://nextjs.org/docs/getting-started/react-essentials#client-components
|
|
,-[TEST_DIR/app/server-with-errors/error-file/error.js:1:1]
1 | export default function Error() {}
: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
\`----
Import trace for requested module:
./app/server-with-errors/error-file/error.js"
`)
}
await cleanup()
})
......
......@@ -54,26 +54,41 @@ describe('Error Overlay for server components compiler errors in pages', () => {
/That only works in a Server Component/
)
expect(next.normalizeTestDirContent(await session.getRedboxSource()))
.toMatchInlineSnapshot(`
"./components/Comp.js
Error:
x You're importing a component that needs next/headers. That only works in a Server Component which is not supported in the pages/ directory. Read more: https://nextjs.org/docs/getting-started/
| react-essentials#server-components
|
|
,-[TEST_DIR/components/Comp.js:1:1]
1 | import { cookies } from 'next/headers'
: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2 |
3 | export default function Page() {
4 | return <p>hello world</p>
\`----
Import trace for requested module:
./components/Comp.js
./pages/index.js"
`)
if (process.env.TURBOPACK) {
expect(next.normalizeTestDirContent(await session.getRedboxSource()))
.toMatchInlineSnapshot(`
"./components/Comp.js:1:0
Parsing ecmascript source code failed
> 1 | import { cookies } from 'next/headers'
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2 |
3 | export default function Page() {
4 | return <p>hello world</p>
You're importing a component that needs next/headers. That only works in a Server Component which is not supported in the pages/ directory. Read more: https://nextjs.org/docs/getting-started/react-essentials#server-components"
`)
} else {
expect(next.normalizeTestDirContent(await session.getRedboxSource()))
.toMatchInlineSnapshot(`
"./components/Comp.js
Error:
x You're importing a component that needs next/headers. That only works in a Server Component which is not supported in the pages/ directory. Read more: https://nextjs.org/docs/getting-started/
| react-essentials#server-components
|
|
,-[TEST_DIR/components/Comp.js:1:1]
1 | import { cookies } from 'next/headers'
: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2 |
3 | export default function Page() {
4 | return <p>hello world</p>
\`----
Import trace for requested module:
./components/Comp.js
./pages/index.js"
`)
}
await cleanup()
})
......@@ -98,27 +113,41 @@ describe('Error Overlay for server components compiler errors in pages', () => {
/That only works in a Server Component/
)
expect(next.normalizeTestDirContent(await session.getRedboxSource()))
.toMatchInlineSnapshot(`
"./components/Comp.js
Error:
x You're importing a component that needs server-only. That only works in a Server Component which is not supported in the pages/ directory. Read more: https://nextjs.org/docs/getting-started/
| react-essentials#server-components
|
|
,-[TEST_DIR/components/Comp.js:1:1]
1 | import 'server-only'
: ^^^^^^^^^^^^^^^^^^^^
2 |
3 | export default function Page() {
4 | return 'hello world'
\`----
Import trace for requested module:
./components/Comp.js
./pages/index.js"
`)
if (process.env.TURBOPACK) {
expect(next.normalizeTestDirContent(await session.getRedboxSource()))
.toMatchInlineSnapshot(`
"./components/Comp.js:1:0
Parsing ecmascript source code failed
> 1 | import 'server-only'
| ^^^^^^^^^^^^^^^^^^^^
2 |
3 | export default function Page() {
4 | return 'hello world'
You're importing a component that needs server-only. That only works in a Server Component which is not supported in the pages/ directory. Read more: https://nextjs.org/docs/getting-started/react-essentials#server-components"
`)
} else {
expect(next.normalizeTestDirContent(await session.getRedboxSource()))
.toMatchInlineSnapshot(`
"./components/Comp.js
Error:
x You're importing a component that needs server-only. That only works in a Server Component which is not supported in the pages/ directory. Read more: https://nextjs.org/docs/getting-started/
| react-essentials#server-components
|
|
,-[TEST_DIR/components/Comp.js:1:1]
1 | import 'server-only'
: ^^^^^^^^^^^^^^^^^^^^
2 |
3 | export default function Page() {
4 | return 'hello world'
\`----
Import trace for requested module:
./components/Comp.js
./pages/index.js"
`)
}
await cleanup()
})
})
......@@ -1167,16 +1167,16 @@
"Error overlay - RSC build errors should error when useTransition from react is used in server component",
"Error overlay - RSC build errors should freeze parent resolved metadata to avoid mutating in generateMetadata",
"Error overlay - RSC build errors should throw an error when \"Component\" is imported in server components",
"Error overlay - RSC build errors should throw an error when \"use client\" is on the top level but after other expressions"
],
"failed": [
"Error overlay - RSC build errors should throw an error when \"use client\" is on the top level but after other expressions",
"Error overlay - RSC build errors should allow to use and handle rsc poisoning server-only",
"Error overlay - RSC build errors should throw an error when error file is a server component",
"Error overlay - RSC build errors should throw an error when error file is a server component with empty error file",
"Error overlay - RSC build errors should throw an error when getServerSideProps is used",
"Error overlay - RSC build errors should throw an error when metadata export is used in client components",
"Error overlay - RSC build errors should throw an error when metadata exports are used together in server components"
],
"failed": [
"Error overlay - RSC build errors should throw an error when error file is a server component with empty error file"
],
"pending": [
"Error overlay - RSC build errors should throw an error when getStaticProps is used"
],
......@@ -1413,11 +1413,11 @@
"runtimeError": false
},
"test/development/acceptance/server-component-compiler-errors-in-pages.test.ts": {
"passed": [],
"failed": [
"passed": [
"Error Overlay for server components compiler errors in pages importing 'next/headers' in pages",
"Error Overlay for server components compiler errors in pages importing 'server-only' in pages"
],
"failed": [],
"pending": [],
"flakey": [],
"runtimeError": false
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment