Skip to content

Commit

Permalink
fix(next-swc): Fix span for invalid 'use server' directives (#62259)
Browse files Browse the repository at this point in the history
### What?

Highlight only `'use server'`, instead of the whole function body.

### Why?

Other statements of the body is not related to the error.


### How?

x-ref:
https://vercel.slack.com/archives/C04CAN8CGCE/p1708353068632249?thread_ts=1708351927.544179&cid=C04CAN8CGCE

Closes PACK-2538
  • Loading branch information
kdy1 authored Feb 22, 2024
1 parent 3e92d8a commit 8d6c1a6
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use std::{
use hex::encode as hex_encode;
use serde::Deserialize;
use sha1::{Digest, Sha1};
use swc_core::common::Span;
use turbopack_binding::swc::core::{
common::{
comments::{Comment, CommentKind, Comments},
Expand Down Expand Up @@ -125,18 +126,20 @@ impl<C: Comments> ServerActions<C> {
} else {
// Check if the function has `"use server"`
if let Some(body) = maybe_body {
let mut action_span = None;
remove_server_directive_index_in_fn(
&mut body.stmts,
remove_directive,
&mut is_action_fn,
&mut action_span,
self.config.enabled,
);

if is_action_fn && !self.config.is_react_server_layer && !self.in_action_file {
HANDLER.with(|handler| {
handler
.struct_span_err(
body.span,
action_span.unwrap_or(body.span),
"It is not allowed to define inline \"use server\" annotated Server Actions in Client Components.\nTo 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.\n\nRead more: https://nextjs.org/docs/app/api-reference/functions/server-actions#with-client-components\n",
)
.emit()
Expand Down Expand Up @@ -1396,6 +1399,7 @@ fn remove_server_directive_index_in_fn(
stmts: &mut Vec<Stmt>,
remove_directive: bool,
is_action_fn: &mut bool,
action_span: &mut Option<Span>,
enabled: bool,
) {
let mut is_directive = true;
Expand All @@ -1407,6 +1411,8 @@ fn remove_server_directive_index_in_fn(
}) = stmt
{
if value == "use server" {
*action_span = Some(*span);

if is_directive {
*is_action_fn = true;
if !enabled {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,9 @@
|
| Read more: https://nextjs.org/docs/app/api-reference/functions/server-actions#with-client-components
|
,-[input.js:3:1]
3 | export default function App() {
4 | ,-> async function fn() {
5 | | 'use server'
6 | `-> }
7 | return <div>App</div>
,-[input.js:4:1]
4 | async function fn() {
5 | 'use server'
: ^^^^^^^^^^^^
6 | }
`----

0 comments on commit 8d6c1a6

Please sign in to comment.