Unverified Commit 63d7705f authored by Shu Ding's avatar Shu Ding Committed by GitHub

Fix directive parsing in SWC (#45671)

The server directive is allowed to have other directives and comments
above. This PR fixes the transform with tests added for failing cases.

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have a helpful link attached, see
[`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the
feature request has been accepted for implementation before opening a
PR.
- [ ] Related issues linked using `fixes #number`
- [ ]
[e2e](https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have a helpful link attached, see
[`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm build && pnpm lint`
- [ ] The "examples guidelines" are followed from [our contributing
doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)
parent d9412b76
...@@ -93,16 +93,12 @@ impl<C: Comments> VisitMut for ServerActions<C> { ...@@ -93,16 +93,12 @@ impl<C: Comments> VisitMut for ServerActions<C> {
// All export functions in a server file are actions // All export functions in a server file are actions
in_action_fn = true; in_action_fn = true;
} else { } else {
// Check if the first item is `"use server"` // Check if the function has `"use server"`
if let Some(body) = &mut f.function.body { if let Some(body) = &mut f.function.body {
if let Some(Stmt::Expr(first)) = body.stmts.first() { let directive_index = get_server_directive_index_in_fn(&body.stmts);
match &*first.expr { if directive_index >= 0 {
Expr::Lit(Lit::Str(Str { value, .. })) if value == "use server" => { in_action_fn = true;
in_action_fn = true; body.stmts.remove(directive_index.try_into().unwrap());
body.stmts.remove(0);
}
_ => {}
}
} }
} }
} }
...@@ -128,7 +124,7 @@ impl<C: Comments> VisitMut for ServerActions<C> { ...@@ -128,7 +124,7 @@ impl<C: Comments> VisitMut for ServerActions<C> {
if !f.function.is_async { if !f.function.is_async {
HANDLER.with(|handler| { HANDLER.with(|handler| {
handler handler
.struct_span_err(f.ident.span, "Server actions must be async") .struct_span_err(f.ident.span, "Server actions must be async functions")
.emit(); .emit();
}); });
} }
...@@ -321,18 +317,11 @@ impl<C: Comments> VisitMut for ServerActions<C> { ...@@ -321,18 +317,11 @@ impl<C: Comments> VisitMut for ServerActions<C> {
} }
fn visit_mut_module_items(&mut self, stmts: &mut Vec<ModuleItem>) { fn visit_mut_module_items(&mut self, stmts: &mut Vec<ModuleItem>) {
if let Some(ModuleItem::Stmt(Stmt::Expr(first))) = stmts.first() { let directive_index = get_server_directive_index_in_module(stmts);
match &*first.expr { if directive_index >= 0 {
Expr::Lit(Lit::Str(Str { value, .. })) if value == "use server" => { self.in_action_file = true;
self.in_action_file = true; self.has_action = true;
self.has_action = true; stmts.remove(directive_index.try_into().unwrap());
}
_ => {}
}
}
if self.in_action_file {
stmts.remove(0);
} }
let old_annotations = self.annotations.take(); let old_annotations = self.annotations.take();
...@@ -404,6 +393,42 @@ fn annotate(fn_name: &Ident, field_name: &str, value: Box<Expr>) -> Stmt { ...@@ -404,6 +393,42 @@ fn annotate(fn_name: &Ident, field_name: &str, value: Box<Expr>) -> Stmt {
}) })
} }
fn get_server_directive_index_in_module(stmts: &[ModuleItem]) -> i32 {
for (i, stmt) in stmts.iter().enumerate() {
if let ModuleItem::Stmt(Stmt::Expr(first)) = stmt {
match &*first.expr {
Expr::Lit(Lit::Str(Str { value, .. })) => {
if value == "use server" {
return i as i32;
}
}
_ => return -1,
}
} else {
return -1;
}
}
-1
}
fn get_server_directive_index_in_fn(stmts: &[Stmt]) -> i32 {
for (i, stmt) in stmts.iter().enumerate() {
if let Stmt::Expr(first) = stmt {
match &*first.expr {
Expr::Lit(Lit::Str(Str { value, .. })) => {
if value == "use server" {
return i as i32;
}
}
_ => return -1,
}
} else {
return -1;
}
}
-1
}
fn collect_idents_in_array_pat(elems: &[Option<Pat>]) -> Vec<Id> { fn collect_idents_in_array_pat(elems: &[Option<Pat>]) -> Vec<Id> {
let mut ids = Vec::new(); let mut ids = Vec::new();
......
use next_binding::swc::{ use next_binding::swc::{
core::{ core::{
common::FileName, common::{chain, FileName, Mark},
ecma::{ ecma::{
parser::{EsConfig, Syntax}, parser::{EsConfig, Syntax},
transforms::testing::{test_fixture, FixtureTestConfig}, transforms::{
base::resolver,
testing::{test_fixture, FixtureTestConfig},
},
}, },
}, },
testing::fixture, testing::fixture,
...@@ -14,6 +17,7 @@ use next_swc::{ ...@@ -14,6 +17,7 @@ use next_swc::{
next_font_loaders::{next_font_loaders, Config as FontLoaderConfig}, next_font_loaders::{next_font_loaders, Config as FontLoaderConfig},
next_ssg::next_ssg, next_ssg::next_ssg,
react_server_components::server_components, react_server_components::server_components,
server_actions::{self, server_actions},
}; };
use std::path::PathBuf; use std::path::PathBuf;
...@@ -144,3 +148,27 @@ fn next_font_loaders_errors(input: PathBuf) { ...@@ -144,3 +148,27 @@ fn next_font_loaders_errors(input: PathBuf) {
}, },
); );
} }
#[fixture("tests/errors/server-actions/**/input.js")]
fn react_server_actions_errors(input: PathBuf) {
let output = input.parent().unwrap().join("output.js");
test_fixture(
syntax(),
&|_tr| {
chain!(
resolver(Mark::new(), Mark::new(), false),
server_actions(
&FileName::Real("/app/item.js".into()),
server_actions::Config { is_server: true },
_tr.comments.as_ref().clone(),
)
)
},
&input,
&output,
FixtureTestConfig {
allow_error: true,
..Default::default()
},
);
}
/* __next_internal_action_entry_do_not_use__ foo */ export function foo() {}
foo.$$typeof = Symbol.for("react.server.reference");
foo.$$filepath = "/app/item.js";
foo.$$name = "foo";
x Server actions must be async functions
,-[input.js:2:1]
2 |
3 | export function foo() {}
: ^^^
`----
'use strict';
// comment
'use server';
export function bar() {}
/* __next_internal_action_entry_do_not_use__ bar */ 'use strict';
export function bar() {}
bar.$$typeof = Symbol.for("react.server.reference");
bar.$$filepath = "/app/item.js";
bar.$$name = "bar";
x Server actions must be async functions
,-[input.js:6:1]
6 |
7 | export function bar() {}
: ^^^
`----
async function myAction(a, b, c) {
// comment
"use strict";
"use server";
console.log('a')
}
export default function Page() {
return <Button action={myAction}>Delete</Button>;
}
\ No newline at end of file
/* __next_internal_action_entry_do_not_use__ $ACTION_myAction */ async function myAction(a, b, c) {
// comment
"use strict";
console.log('a');
}
myAction.$$typeof = Symbol.for("react.server.reference");
myAction.$$filepath = "/app/item.js";
myAction.$$name = "$ACTION_myAction";
export const $ACTION_myAction = myAction;
export default function Page() {
return <Button action={myAction}>Delete</Button>;
}
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