Unverified Commit 775e8986 authored by OJ Kwon's avatar OJ Kwon Committed by GitHub

feat(next-core): build time client|server-only assertion (#61732)

### What

This PR injects a build-time error for the turbopack if
`client|server-only` is imported in incorrect context. The basic idea is
using resolve plugin, so in resolve time if matching context (which
alises erroneous import), raise a build time error.

Unfortunately this won't fix all of the tests in `invalid-imports`, due
to

1. resolveplugin does not have way to trace import from transformed, so
not able to detect `styled-jsx` from using `<styled..` tags
2. webpack (in our implementation) and turbopack's resolveplugin have
different order of transform / module trace chain, so enabling resolve
plugin in some context raises build error instead of runtime error in
rsc-build-error.

Closes PACK-2397
parent 2d0ed6c3
...@@ -531,6 +531,10 @@ async fn insert_next_server_special_aliases( ...@@ -531,6 +531,10 @@ async fn insert_next_server_special_aliases(
} }
// see https://github.com/vercel/next.js/blob/8013ef7372fc545d49dbd060461224ceb563b454/packages/next/src/build/webpack-config.ts#L1449-L1531 // see https://github.com/vercel/next.js/blob/8013ef7372fc545d49dbd060461224ceb563b454/packages/next/src/build/webpack-config.ts#L1449-L1531
// Sets runtime aliases for the import to client|server-only. Depends on the
// context, it'll resolve to the noop where it's allowed, or aliased into
// the error which throws a runtime error. This works with in combination of
// build-time error as well, refer https://github.com/vercel/next.js/blob/0060de1c4905593ea875fa7250d4b5d5ce10897d/packages/next-swc/crates/next-core/src/next_server/context.rs#L103
match ty { match ty {
ServerContextType::Pages { .. } => { ServerContextType::Pages { .. } => {
insert_exact_alias_map( insert_exact_alias_map(
...@@ -548,7 +552,6 @@ async fn insert_next_server_special_aliases( ...@@ -548,7 +552,6 @@ async fn insert_next_server_special_aliases(
| ServerContextType::PagesApi { .. } | ServerContextType::PagesApi { .. }
| ServerContextType::AppRSC { .. } | ServerContextType::AppRSC { .. }
| ServerContextType::AppRoute { .. } | ServerContextType::AppRoute { .. }
| ServerContextType::Middleware
| ServerContextType::Instrumentation => { | ServerContextType::Instrumentation => {
insert_exact_alias_map( insert_exact_alias_map(
import_map, import_map,
...@@ -573,21 +576,22 @@ async fn insert_next_server_special_aliases( ...@@ -573,21 +576,22 @@ async fn insert_next_server_special_aliases(
}, },
); );
} }
} // Potential the bundle introduced into middleware and api can be poisoned by
// client-only but not being used, so we disabled the `client-only` erroring
// Potential the bundle introduced into middleware and api can be poisoned by // on these layers. `server-only` is still available.
// client-only but not being used, so we disabled the `client-only` erroring ServerContextType::Middleware => {
// on these layers. `server-only` is still available. insert_exact_alias_map(
if ty == ServerContextType::Middleware { import_map,
insert_exact_alias_map( project_path,
import_map, indexmap! {
project_path, "server-only" => "next/dist/compiled/server-only/empty".to_string(),
indexmap! { "client-only" => "next/dist/compiled/client-only/index".to_string(),
"client-only" => "next/dist/compiled/client-only/index".to_string(), "next/dist/compiled/server-only" => "next/dist/compiled/server-only/empty".to_string(),
"next/dist/compiled/client-only" => "next/dist/compiled/client-only/index".to_string(), "next/dist/compiled/client-only" => "next/dist/compiled/client-only/index".to_string(),
"next/dist/compiled/client-only/error" => "next/dist/compiled/client-only/index".to_string(), "next/dist/compiled/client-only/error" => "next/dist/compiled/client-only/index".to_string(),
}, },
); );
}
} }
import_map.insert_exact_alias( import_map.insert_exact_alias(
......
...@@ -52,8 +52,9 @@ use crate::{ ...@@ -52,8 +52,9 @@ use crate::{
next_server::resolve::ExternalPredicate, next_server::resolve::ExternalPredicate,
next_shared::{ next_shared::{
resolve::{ resolve::{
ModuleFeatureReportResolvePlugin, NextExternalResolvePlugin, get_invalid_client_only_resolve_plugin, ModuleFeatureReportResolvePlugin,
NextNodeSharedRuntimeResolvePlugin, UnsupportedModulesResolvePlugin, NextExternalResolvePlugin, NextNodeSharedRuntimeResolvePlugin,
UnsupportedModulesResolvePlugin,
}, },
transforms::{ transforms::{
emotion::get_emotion_transform_rule, get_ecma_transform_rule, emotion::get_emotion_transform_rule, get_ecma_transform_rule,
...@@ -114,6 +115,7 @@ pub async fn get_server_resolve_options_context( ...@@ -114,6 +115,7 @@ pub async fn get_server_resolve_options_context(
let root_dir = project_path.root().resolve().await?; let root_dir = project_path.root().resolve().await?;
let module_feature_report_resolve_plugin = ModuleFeatureReportResolvePlugin::new(project_path); let module_feature_report_resolve_plugin = ModuleFeatureReportResolvePlugin::new(project_path);
let unsupported_modules_resolve_plugin = UnsupportedModulesResolvePlugin::new(project_path); let unsupported_modules_resolve_plugin = UnsupportedModulesResolvePlugin::new(project_path);
let invalid_client_only_resolve_plugin = get_invalid_client_only_resolve_plugin(project_path);
// Always load these predefined packages as external. // Always load these predefined packages as external.
let mut external_packages: Vec<String> = load_next_js_templateon( let mut external_packages: Vec<String> = load_next_js_templateon(
...@@ -165,7 +167,7 @@ pub async fn get_server_resolve_options_context( ...@@ -165,7 +167,7 @@ pub async fn get_server_resolve_options_context(
let next_node_shared_runtime_plugin = let next_node_shared_runtime_plugin =
NextNodeSharedRuntimeResolvePlugin::new(project_path, Value::new(ty)); NextNodeSharedRuntimeResolvePlugin::new(project_path, Value::new(ty));
let plugins = match ty { let mut plugins = match ty {
ServerContextType::Pages { .. } ServerContextType::Pages { .. }
| ServerContextType::PagesData { .. } | ServerContextType::PagesData { .. }
| ServerContextType::PagesApi { .. } => { | ServerContextType::PagesApi { .. } => {
...@@ -204,6 +206,34 @@ pub async fn get_server_resolve_options_context( ...@@ -204,6 +206,34 @@ pub async fn get_server_resolve_options_context(
] ]
} }
}; };
// Inject resolve plugin to assert incorrect import to client|server-only for
// the corresponding context. Refer https://github.com/vercel/next.js/blob/ad15817f0368ba154bed6d85320335d4b67b7348/packages/next/src/build/webpack-config.ts#L1205-L1235
// how it is applied in the webpack config.
// Unlike webpack which alias client-only -> runtime code -> build-time error
// code, we use resolve plugin to detect original import directly. This
// means each resolve plugin must be injected only for the context where the
// alias resolves into the error. The alias lives in here: https://github.com/vercel/next.js/blob/0060de1c4905593ea875fa7250d4b5d5ce10897d/packages/next-swc/crates/next-core/src/next_import_map.rs#L534
match ty {
ServerContextType::Pages { .. } => {
//noop
}
ServerContextType::PagesData { .. }
| ServerContextType::PagesApi { .. }
| ServerContextType::AppRSC { .. }
| ServerContextType::AppRoute { .. }
| ServerContextType::Instrumentation => {
plugins.push(Vc::upcast(invalid_client_only_resolve_plugin));
}
ServerContextType::AppSSR { .. } => {
//[TODO] Build error in this context makes rsc-build-error.ts fail which expects runtime error code
// looks like webpack and turbopack have different order, webpack runs rsc transform first, turbopack triggers resolve plugin first.
}
ServerContextType::Middleware => {
//noop
}
}
let resolve_options_context = ResolveOptionsContext { let resolve_options_context = ResolveOptionsContext {
enable_node_modules: Some(root_dir), enable_node_modules: Some(root_dir),
enable_node_externals: true, enable_node_externals: true,
......
...@@ -2,7 +2,7 @@ use std::collections::{HashMap, HashSet}; ...@@ -2,7 +2,7 @@ use std::collections::{HashMap, HashSet};
use anyhow::Result; use anyhow::Result;
use lazy_static::lazy_static; use lazy_static::lazy_static;
use turbo_tasks::{TaskInput, Value, Vc}; use turbo_tasks::{Value, Vc};
use turbo_tasks_fs::glob::Glob; use turbo_tasks_fs::glob::Glob;
use turbopack_binding::{ use turbopack_binding::{
turbo::tasks_fs::FileSystemPath, turbo::tasks_fs::FileSystemPath,
...@@ -44,8 +44,6 @@ lazy_static! { ...@@ -44,8 +44,6 @@ lazy_static! {
), ),
("@next", vec!["/font/google", "/font/local"]) ("@next", vec!["/font/google", "/font/local"])
]); ]);
static ref CLIENT_ONLY_IMPORTS: HashSet<&'static str> = ["client-only", "next/dist/compiled/server-only/error"].into();
static ref SERVER_ONLY_IMPORTS: HashSet<&'static str> = ["server-only", "next/dist/compiled/server-only/index"].into();
} }
#[turbo_tasks::value] #[turbo_tasks::value]
...@@ -110,24 +108,17 @@ impl ResolvePlugin for UnsupportedModulesResolvePlugin { ...@@ -110,24 +108,17 @@ impl ResolvePlugin for UnsupportedModulesResolvePlugin {
} }
} }
#[turbo_tasks::value(shared)]
#[derive(Debug, Copy, Clone, TaskInput, Ord, PartialOrd, Hash)]
pub(crate) enum InvalidImportType {
ClientOnly,
ServerOnly,
}
#[turbo_tasks::value(shared)] #[turbo_tasks::value(shared)]
pub struct InvalidImportModuleIssue { pub struct InvalidImportModuleIssue {
pub file_path: Vc<FileSystemPath>, pub file_path: Vc<FileSystemPath>,
pub import_type: InvalidImportType, pub messages: Vec<String>,
} }
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl Issue for InvalidImportModuleIssue { impl Issue for InvalidImportModuleIssue {
#[turbo_tasks::function] #[turbo_tasks::function]
fn severity(&self) -> Vc<IssueSeverity> { fn severity(&self) -> Vc<IssueSeverity> {
IssueSeverity::Warning.into() IssueSeverity::Error.into()
} }
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -147,36 +138,50 @@ impl Issue for InvalidImportModuleIssue { ...@@ -147,36 +138,50 @@ impl Issue for InvalidImportModuleIssue {
#[turbo_tasks::function] #[turbo_tasks::function]
async fn description(&self) -> Result<Vc<OptionStyledString>> { async fn description(&self) -> Result<Vc<OptionStyledString>> {
let message = match self.import_type { let raw_context = &*self.file_path.await?;
InvalidImportType::ClientOnly => {
"'client-only' cannot be imported from a Server Component module. It should only \ let mut messages = self.messages.clone();
be used from a Client Component." messages.push("\n".to_string());
}
InvalidImportType::ServerOnly => { //[TODO]: how do we get the import trace?
"'server-only' cannot be imported from a Client Component module. It should only \ messages.push(format!(
be used from a Server Component." "The error was caused by importing '{}'",
} raw_context.path
}; ));
Ok(Vc::cell(Some( Ok(Vc::cell(Some(
StyledString::Text(message.to_string()).cell(), StyledString::Line(
messages
.iter()
.map(|v| StyledString::Text(v.into()))
.collect::<Vec<StyledString>>(),
)
.cell(),
))) )))
} }
} }
/// A resolve plugin detects import to the `client-only`/`server-only`, then /// A resolver plugin emits an error when specific context imports
/// emits an error according to the context. /// specified import requests. It doesn't detect if the import is correctly
/// alised or not unlike webpack-config does; Instead it should be correctly
/// configured when each context sets up its resolve options.
#[turbo_tasks::value] #[turbo_tasks::value]
pub(crate) struct InvalidImportResolvePlugin { pub(crate) struct InvalidImportResolvePlugin {
root: Vc<FileSystemPath>, root: Vc<FileSystemPath>,
import_type: InvalidImportType, invalid_import: String,
message: Vec<String>,
} }
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl InvalidImportResolvePlugin { impl InvalidImportResolvePlugin {
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn new(root: Vc<FileSystemPath>, import_type: InvalidImportType) -> Vc<Self> { pub fn new(root: Vc<FileSystemPath>, invalid_import: String, message: Vec<String>) -> Vc<Self> {
InvalidImportResolvePlugin { root, import_type }.cell() InvalidImportResolvePlugin {
root,
invalid_import,
message,
}
.cell()
} }
} }
...@@ -191,48 +196,60 @@ impl ResolvePlugin for InvalidImportResolvePlugin { ...@@ -191,48 +196,60 @@ impl ResolvePlugin for InvalidImportResolvePlugin {
async fn after_resolve( async fn after_resolve(
&self, &self,
_fs_path: Vc<FileSystemPath>, _fs_path: Vc<FileSystemPath>,
file_path: Vc<FileSystemPath>, context: Vc<FileSystemPath>,
_reference_type: Value<ReferenceType>, _reference_type: Value<ReferenceType>,
request: Vc<Request>, request: Vc<Request>,
) -> Result<Vc<ResolveResultOption>> { ) -> Result<Vc<ResolveResultOption>> {
let imports = if self.import_type == InvalidImportType::ClientOnly { if let Request::Module { module, .. } = &*request.await? {
&*CLIENT_ONLY_IMPORTS if module.as_str() == self.invalid_import.as_str() {
} else { InvalidImportModuleIssue {
&*SERVER_ONLY_IMPORTS file_path: context,
}; messages: self.message.clone(),
if let Request::Module {
module,
path,
query: _,
} = &*request.await?
{
if imports.contains(module.as_str()) {
UnsupportedModuleIssue {
file_path,
package: module.into(),
package_path: None,
} }
.cell() .cell()
.emit(); .emit();
} }
if let Pattern::Constant(path) = path {
if imports.contains(path.as_str()) {
InvalidImportModuleIssue {
file_path,
import_type: self.import_type,
}
.cell()
.emit();
}
}
} }
Ok(ResolveResultOption::none()) Ok(ResolveResultOption::none())
} }
} }
/// Returns a resolve plugin if context have imports to `client-only`.
/// Only the contexts that alises `client-only` to
/// `next/dist/compiled/client-only/error` should use this.
pub(crate) fn get_invalid_client_only_resolve_plugin(
root: Vc<FileSystemPath>,
) -> Vc<InvalidImportResolvePlugin> {
InvalidImportResolvePlugin::new(
root,
"client-only".to_string(),
vec![
"'client-only' cannot be imported from a Client Component module. It should only be \
used from a Server Component."
.to_string(),
],
)
}
/// Returns a resolve plugin if context have imports to `server-only`.
/// Only the contexts that alises `server-only` to
/// `next/dist/compiled/server-only/index` should use this.
#[allow(unused)]
pub(crate) fn get_invalid_server_only_resolve_plugin(
root: Vc<FileSystemPath>,
) -> Vc<InvalidImportResolvePlugin> {
InvalidImportResolvePlugin::new(
root,
"server-only".to_string(),
vec![
"'server-only' cannot be imported from a Client Component module. It should only be \
used from a Server Component."
.to_string(),
],
)
}
#[turbo_tasks::value] #[turbo_tasks::value]
pub(crate) struct NextExternalResolvePlugin { pub(crate) struct NextExternalResolvePlugin {
root: Vc<FileSystemPath>, root: Vc<FileSystemPath>,
......
...@@ -141,7 +141,15 @@ describe('Error Overlay invalid imports', () => { ...@@ -141,7 +141,15 @@ describe('Error Overlay invalid imports', () => {
await session.patch(pageFile, withoutUseClient) await session.patch(pageFile, withoutUseClient)
expect(await session.hasRedbox()).toBe(true) expect(await session.hasRedbox()).toBe(true)
expect(await session.getRedboxSource()).toMatchInlineSnapshot(` if (process.env.TURBOPACK) {
expect(await session.getRedboxSource()).toMatchInlineSnapshot(`
"./node_modules/client-only-package
Invalid import
'client-only' cannot be imported from a Client Component module. It should only be used from a Server Component.
The error was caused by importing 'node_modules/client-only-package'"
`)
} else {
expect(await session.getRedboxSource()).toMatchInlineSnapshot(`
"./app/comp2.js "./app/comp2.js
'client-only' cannot be imported from a Server Component module. It should only be used from a Client Component. 'client-only' cannot be imported from a Server Component module. It should only be used from a Client Component.
...@@ -152,6 +160,7 @@ describe('Error Overlay invalid imports', () => { ...@@ -152,6 +160,7 @@ describe('Error Overlay invalid imports', () => {
./app/comp1.js ./app/comp1.js
./app/page.js" ./app/page.js"
`) `)
}
await cleanup() await cleanup()
}) })
...@@ -214,7 +223,15 @@ describe('Error Overlay invalid imports', () => { ...@@ -214,7 +223,15 @@ describe('Error Overlay invalid imports', () => {
await session.patch(file, "'use client'\n" + content) await session.patch(file, "'use client'\n" + content)
expect(await session.hasRedbox()).toBe(true) expect(await session.hasRedbox()).toBe(true)
expect(await session.getRedboxSource()).toMatchInlineSnapshot(` if (process.env.TURBOPACK) {
expect(await session.getRedboxSource()).toMatchInlineSnapshot(`
"./node_modules/server-only-package
Invalid import
'server-only' cannot be imported from a Client Component module. It should only be used from a Server Component.
The error was caused by importing 'node_modules/server-only-package'"
`)
} else {
expect(await session.getRedboxSource()).toMatchInlineSnapshot(`
"./app/comp2.js "./app/comp2.js
'server-only' cannot be imported from a Client Component module. It should only be used from a Server Component. 'server-only' cannot be imported from a Client Component module. It should only be used from a Server Component.
...@@ -225,6 +242,7 @@ describe('Error Overlay invalid imports', () => { ...@@ -225,6 +242,7 @@ describe('Error Overlay invalid imports', () => {
./app/comp1.js ./app/comp1.js
./app/page.js" ./app/page.js"
`) `)
}
await cleanup() await cleanup()
}) })
......
...@@ -1119,9 +1119,10 @@ ...@@ -1119,9 +1119,10 @@
"runtimeError": false "runtimeError": false
}, },
"test/development/acceptance-app/invalid-imports.test.ts": { "test/development/acceptance-app/invalid-imports.test.ts": {
"passed": [], "passed": [
"Error Overlay invalid imports should show error when external package imports client-only in server component"
],
"failed": [ "failed": [
"Error Overlay invalid imports should show error when external package imports client-only in server component",
"Error Overlay invalid imports should show error when external package imports server-only in client component", "Error Overlay invalid imports should show error when external package imports server-only in client component",
"Error Overlay invalid imports should show error when using styled-jsx in server component" "Error Overlay invalid imports should show error when using styled-jsx in server component"
], ],
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