Unverified Commit bdbf63ae authored by Niklas Mischkulnig's avatar Niklas Mischkulnig Committed by GitHub

fix(next-custom-transforms): never place generated imports before directives (#98717)

## Summary

**What?** Fixes the error reported for a module that has a top-level
`"use client"` directive and an inline `"use server"` function
directive, e.g. `<form action={async () => { "use server" }} />` in a
client page.

**Why?** Under Turbopack this reported a bogus error — `The "use client"
directive must be placed before other expressions` — even though the
directive was already at the top of the file. The actual mistake (an
inline server action inside a Client Component) was never surfaced.

**How?** On Turbopack's RSC layer the server actions transform runs
*before* the React Server Components assert. When it hoists an inline
action it prepended its generated imports (`registerServerReference`,
action encryption, cache runtime) at index 0 of the module — *above* the
`"use client"` directive, which the transform does not consume. The RSC
assert then saw an import before the directive and reported it as
misplaced.
Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
parent 6cfca45f
...@@ -27,7 +27,7 @@ use swc_core::{ ...@@ -27,7 +27,7 @@ use swc_core::{
ecma::{ ecma::{
ast::*, ast::*,
codegen::{self, Emitter, text_writer::JsWriter}, codegen::{self, Emitter, text_writer::JsWriter},
utils::{ExprFactory, private_ident, quote_ident}, utils::{ExprFactory, prepend_stmts, private_ident, quote_ident},
visit::{VisitMut, VisitMutWith, noop_visit_mut_type, visit_mut_pass}, visit::{VisitMut, VisitMutWith, noop_visit_mut_type, visit_mut_pass},
}, },
quote, quote,
...@@ -556,7 +556,8 @@ impl<C: Comments> ServerActions<C> { ...@@ -556,7 +556,8 @@ impl<C: Comments> ServerActions<C> {
match &mut new_body { match &mut new_body {
ArrowFunctionBody::FunctionBody(body) => { ArrowFunctionBody::FunctionBody(body) => {
body.stmts.insert(0, decryption_decl.into()); // Insert after the body's leading directives, never before them.
prepend_stmts(&mut body.stmts, std::iter::once(decryption_decl.into()));
} }
ArrowFunctionBody::Expr(body_expr) => { ArrowFunctionBody::Expr(body_expr) => {
new_body = ArrowFunctionBody::FunctionBody(FunctionBody { new_body = ArrowFunctionBody::FunctionBody(FunctionBody {
...@@ -716,7 +717,8 @@ impl<C: Comments> ServerActions<C> { ...@@ -716,7 +717,8 @@ impl<C: Comments> ServerActions<C> {
}; };
if let Some(body) = &mut new_body { if let Some(body) = &mut new_body {
body.stmts.insert(0, decryption_decl.into()); // Insert after the body's leading directives, never before them.
prepend_stmts(&mut body.stmts, std::iter::once(decryption_decl.into()));
} else { } else {
new_body = Some(FunctionBody { new_body = Some(FunctionBody {
span: DUMMY_SP, span: DUMMY_SP,
...@@ -2584,7 +2586,8 @@ impl<C: Comments> VisitMut for ServerActions<C> { ...@@ -2584,7 +2586,8 @@ impl<C: Comments> VisitMut for ServerActions<C> {
// import { cache as $$cache__ } from "private-next-rsc-cache-wrapper"; // import { cache as $$cache__ } from "private-next-rsc-cache-wrapper";
// import { cache as $$reactCache__ } from "react"; // import { cache as $$reactCache__ } from "react";
if self.has_cache && self.config.is_react_server_layer { if self.has_cache && self.config.is_react_server_layer {
new.push(ModuleItem::ModuleDecl(ModuleDecl::Import(ImportDecl { let cache_imports = vec![
ModuleItem::ModuleDecl(ModuleDecl::Import(ImportDecl {
span: DUMMY_SP, span: DUMMY_SP,
specifiers: vec![ImportSpecifier::Named(ImportNamedSpecifier { specifiers: vec![ImportSpecifier::Named(ImportNamedSpecifier {
span: DUMMY_SP, span: DUMMY_SP,
...@@ -2600,9 +2603,8 @@ impl<C: Comments> VisitMut for ServerActions<C> { ...@@ -2600,9 +2603,8 @@ impl<C: Comments> VisitMut for ServerActions<C> {
type_only: false, type_only: false,
with: None, with: None,
phase: Default::default(), phase: Default::default(),
}))); })),
ModuleItem::ModuleDecl(ModuleDecl::Import(ImportDecl {
new.push(ModuleItem::ModuleDecl(ModuleDecl::Import(ImportDecl {
span: DUMMY_SP, span: DUMMY_SP,
specifiers: vec![ImportSpecifier::Named(ImportNamedSpecifier { specifiers: vec![ImportSpecifier::Named(ImportNamedSpecifier {
span: DUMMY_SP, span: DUMMY_SP,
...@@ -2618,16 +2620,18 @@ impl<C: Comments> VisitMut for ServerActions<C> { ...@@ -2618,16 +2620,18 @@ impl<C: Comments> VisitMut for ServerActions<C> {
type_only: false, type_only: false,
with: None, with: None,
phase: Default::default(), phase: Default::default(),
}))); })),
];
// Make them the first items // Insert after the leading directives, never before them.
new.rotate_right(2); prepend_stmts(&mut new, cache_imports.into_iter());
} }
if (self.has_action || self.has_cache) && self.config.is_react_server_layer { if (self.has_action || self.has_cache) && self.config.is_react_server_layer {
// Inlined actions are only allowed on the server layer. // Inlined actions are only allowed on the server layer.
// import { registerServerReference } from 'private-next-rsc-server-reference' // import { registerServerReference } from 'private-next-rsc-server-reference'
new.push(ModuleItem::ModuleDecl(ModuleDecl::Import(ImportDecl { let mut server_reference_imports =
vec![ModuleItem::ModuleDecl(ModuleDecl::Import(ImportDecl {
span: DUMMY_SP, span: DUMMY_SP,
specifiers: vec![ImportSpecifier::Named(ImportNamedSpecifier { specifiers: vec![ImportSpecifier::Named(ImportNamedSpecifier {
span: DUMMY_SP, span: DUMMY_SP,
...@@ -2643,15 +2647,14 @@ impl<C: Comments> VisitMut for ServerActions<C> { ...@@ -2643,15 +2647,14 @@ impl<C: Comments> VisitMut for ServerActions<C> {
type_only: false, type_only: false,
with: None, with: None,
phase: Default::default(), phase: Default::default(),
}))); }))];
let mut import_count = 1;
// Encryption and decryption only happens when there are bound arguments. // Encryption and decryption only happens when there are bound arguments.
if self.has_server_reference_with_bound_args { if self.has_server_reference_with_bound_args {
// import { encryptActionBoundArgs, decryptActionBoundArgs } from // import { encryptActionBoundArgs, decryptActionBoundArgs } from
// 'private-next-rsc-action-encryption' // 'private-next-rsc-action-encryption'
new.push(ModuleItem::ModuleDecl(ModuleDecl::Import(ImportDecl { server_reference_imports.push(ModuleItem::ModuleDecl(ModuleDecl::Import(
ImportDecl {
span: DUMMY_SP, span: DUMMY_SP,
specifiers: vec![ specifiers: vec![
ImportSpecifier::Named(ImportNamedSpecifier { ImportSpecifier::Named(ImportNamedSpecifier {
...@@ -2675,12 +2678,12 @@ impl<C: Comments> VisitMut for ServerActions<C> { ...@@ -2675,12 +2678,12 @@ impl<C: Comments> VisitMut for ServerActions<C> {
type_only: false, type_only: false,
with: None, with: None,
phase: Default::default(), phase: Default::default(),
}))); },
import_count += 1; )));
} }
// Make them the first items // Insert after the leading directives, never before them.
new.rotate_right(import_count); prepend_stmts(&mut new, server_reference_imports.into_iter());
} }
if self.has_action || self.has_cache { if self.has_action || self.has_cache {
...@@ -2729,8 +2732,8 @@ impl<C: Comments> VisitMut for ServerActions<C> { ...@@ -2729,8 +2732,8 @@ impl<C: Comments> VisitMut for ServerActions<C> {
.into(), .into(),
}, },
); );
new.push(client_layer_import.unwrap()); // Insert after the leading directives, never before them.
new.rotate_right(1); prepend_stmts(&mut new, std::iter::once(client_layer_import.unwrap()));
new.extend( new.extend(
client_layer_exports client_layer_exports
.into_iter() .into_iter()
......
...@@ -14,11 +14,13 @@ use swc_core::{ ...@@ -14,11 +14,13 @@ use swc_core::{
atoms::atom, atoms::atom,
common::{FileName, Mark}, common::{FileName, Mark},
ecma::{ ecma::{
ast::fn_pass,
parser::{EsSyntax, Syntax}, parser::{EsSyntax, Syntax},
transforms::{ transforms::{
base::resolver, base::resolver,
testing::{FixtureTestConfig, test_fixture}, testing::{FixtureTestConfig, test_fixture},
}, },
visit::VisitWith,
}, },
}; };
use testing::fixture; use testing::fixture;
...@@ -213,6 +215,62 @@ fn react_server_actions_errors(input: PathBuf) { ...@@ -213,6 +215,62 @@ fn react_server_actions_errors(input: PathBuf) {
); );
} }
// Turbopack runs the server actions transform before the React Server Components assert on
// the RSC layer (unlike webpack, which runs the RSC transform first). See
// `crates/next-core/src/next_server/context.rs` (AppRSC module rules).
#[fixture("tests/errors/server-actions-turbopack-rsc/**/input.js")]
fn server_actions_turbopack_rsc_errors(input: PathBuf) {
use next_custom_transforms::transforms::react_server_components::{
Config, Options, server_components_assert,
};
let output = input.parent().unwrap().join("output.js");
test_fixture(
syntax(),
&|tr| {
let unresolved_mark = Mark::new();
(
resolver(unresolved_mark, Mark::new(), false),
server_actions(
&FileName::Real("/app/item.js".into()),
None,
server_actions::Config {
is_react_server_layer: true,
is_development: true,
use_cache_enabled: true,
hash_salt: "".into(),
cache_kinds: FxHashSet::default(),
},
tr.comments.as_ref().clone(),
unresolved_mark,
tr.cm.clone(),
Default::default(),
ServerActionsMode::Turbopack,
),
fn_pass(|program| {
program.visit_with(&mut server_components_assert(
FileName::Real(PathBuf::from("/app/item.js")),
Config::WithOptions(Options {
is_react_server_layer: true,
cache_components_enabled: true,
use_cache_enabled: true,
taint_enabled: true,
page_extensions: vec![],
}),
None,
));
}),
)
},
&input,
&output,
FixtureTestConfig {
allow_error: true,
module: Some(true),
..Default::default()
},
);
}
#[fixture("tests/errors/strip-page-exports/**/input.js")] #[fixture("tests/errors/strip-page-exports/**/input.js")]
fn next_transform_strip_page_exports_errors(input: PathBuf) { fn next_transform_strip_page_exports_errors(input: PathBuf) {
let output = input.parent().unwrap().join("output.js"); let output = input.parent().unwrap().join("output.js");
......
'use client'
'use strict'
export default function Page() {
return (
<form
action={async () => {
'use server'
}}
/>
)
}
/* __next_internal_action_entry_do_not_use__ [{"006a88810ecce4a4e8b59d53b8327d7e98bbf251d7":{"name":"$$RSC_SERVER_ACTION_0"}},"/app/item.js",""] */ 'use client';
'use strict';
import { registerServerReference } from "private-next-rsc-server-reference";
export const $$RSC_SERVER_ACTION_0 = async function action() {};
registerServerReference($$RSC_SERVER_ACTION_0, "006a88810ecce4a4e8b59d53b8327d7e98bbf251d7", null);
export default function Page() {
return <form action={$$RSC_SERVER_ACTION_0}/>;
}
'use client'
export default function Page() {
return (
<form
action={async () => {
'use server'
}}
/>
)
}
/* __next_internal_client_entry_do_not_use__ default auto */ export default function Page() {
return <form action={async ()=>{
'use server';
}}/>;
}
x It is not allowed to define inline "use server" annotated Server Actions in Client Components.
| To use Server Actions in a Client Component, you can either export them from a separate file with "use server" at the top, or pass them down through props from a Server Component.
|
| Read more: https://nextjs.org/docs/app/api-reference/directives/use-server#using-server-functions-in-a-client-component
|
,-[input.js:7:1]
6 | action={async () => {
7 | 'use server'
: ^^^^^^^^^^^^
8 | }}
`----
import type { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
'use client'
export default function Page() {
return (
<form
action={async () => {
'use server'
}}
/>
)
}
import { nextTestSetup } from 'e2e-utils'
import { getRedboxSource, waitForRedbox } from 'next-test-utils'
describe('inline-use-server-directive-in-client', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('reports the inline "use server" error instead of a bogus "use client" placement error', async () => {
const browser = await next.browser('/')
await waitForRedbox(browser)
const source = await getRedboxSource(browser)
expect(source).toContain(
'It is not allowed to define inline "use server" annotated Server Actions in Client Components.'
)
expect(source).not.toContain('must be placed before other expressions')
})
})
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {}
export default nextConfig
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