Skip to content

Commit 8366e09

Browse files
ryansolidClaude via Cursorcursoragent
authored
fix(compiler): extract "use server" function declarations nested in a function (#3369)
The bubbling pre-pass turns every function declaration into `const name = function name() {}` at the top of its block so the transform only handles expression forms. Babel skipped the body of each bubbled declaration (`tmp.skip()`), so a declaration nested inside another function was never bubbled, never became an expression, and a directive on it was silently ignored: the body shipped to the client and ran there. The capture validator walks every function, so the same declaration still had its captures rejected. One spelling produced a compile error, the other a client-side body. The bubbler now descends into each bubbled body, so nested declarations are extracted like any other marked function, at any depth and inside nested blocks. The const lands at the top of its block, so a use above the declaration still resolves. Ids follow the binding path (`outer.inner`). Only files that extract at least one function keep the pass's output, so the extra bubbling never reaches a file without server functions. No existing fixture contains a nested declaration, so the frozen references are unchanged. Co-authored-by: Claude via Cursor <[email protected]> Co-authored-by: Cursor <[email protected]>
1 parent 4935c7d commit 8366e09

5 files changed

Lines changed: 215 additions & 13 deletions

File tree

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
---
2+
"@solidjs/compiler": patch
3+
---
4+
5+
A `"use server"` function declaration nested inside another function is now extracted like any other server function.
6+
7+
- Previously the directive on a nested declaration was silently ignored: the body shipped to the client and ran there, while captures from the enclosing function were still rejected at compile time.
8+
- The declaration is hoisted to a `const` at the top of its block, so calling it before its source position still works.
9+
- Its id follows the binding path, such as `outer.inner`.

‎packages/compiler/README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,7 @@ result.functions; // [{ id, name, exports }] for manifest building
153153

154154
A function-level `"use server"` function is extracted out of its lexical position, so it may only reference its own parameters and locals, module top-level bindings, and globals. Capturing anything else is a compile error. That includes `this` and `arguments` in a marked arrow, which an arrow takes from the function it was written in. Use a `function` if the server function needs its own `this` or `arguments`.
155155

156-
A function-level directive only works where the pass can extract the function: a function declaration, a function expression, or an arrow with a block body. Methods, getters, and setters are never extracted, so a directive on one is a compile error rather than a directive that silently does nothing. Assign a function to a property instead.
156+
A function-level directive only works where the pass can extract the function: a function declaration (at any nesting depth), a function expression, or an arrow with a block body. Methods, getters, and setters are never extracted, so a directive on one is a compile error rather than a directive that silently does nothing. Assign a function to a property instead.
157157

158158
A module-level `"use server"` module can only export server functions. Its client build is rebuilt from those exports alone, so anything else would be missing from the browser bundle. Re-exports, `export *`, class and enum exports, destructured exports, and exports declared without an initializer are compile errors naming the export and its position. Type-only and `declare` exports are erased and are fine.
159159

‎packages/compiler/__tests__/directives-id-scheme.test.js‎

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -299,9 +299,10 @@ describe("the wire id scheme, differentially", () => {
299299
});
300300

301301
it("takes a segment from a nested function declaration", () => {
302-
// Declarations nested inside another function are not bubbled into a
303-
// `const`, so the function itself has to contribute the segment, or two
304-
// same-named arrows in sibling declarations collide on `outer.s`.
302+
// Two same-named arrows in sibling declarations must not collide on
303+
// `outer.s`. Reported in post-bubble order (nested declarations hoist in
304+
// reverse source order like top-level ones), which moves the reporting
305+
// order without moving an id.
305306
const source = `
306307
export function outer() {
307308
function a() { const s = async () => { "use server"; return 1; }; return s; }
@@ -310,9 +311,23 @@ describe("the wire id scheme, differentially", () => {
310311
}
311312
`;
312313
const hash = hashHex("src/decl.js");
313-
expect(ids(source, { filename: "/project/src/decl.js", root: "/project" })).toEqual([
314-
`outer.a.s-${hash}`,
315-
`outer.b.s-${hash}`
314+
expect(ids(source, { filename: "/project/src/decl.js", root: "/project" }).sort()).toEqual(
315+
[`outer.a.s-${hash}`, `outer.b.s-${hash}`].sort()
316+
);
317+
});
318+
319+
it("names a marked nested function declaration by its path", () => {
320+
// A declaration nested in another function is bubbled into a `const`
321+
// like a top-level one, so it is extracted and named the same way.
322+
const source = `
323+
export function outer() {
324+
async function inner() { "use server"; return 1; }
325+
return inner;
326+
}
327+
`;
328+
const hash = hashHex("src/nested-decl.js");
329+
expect(ids(source, { filename: "/project/src/nested-decl.js", root: "/project" })).toEqual([
330+
`outer.inner-${hash}`
316331
]);
317332
});
318333

Lines changed: 155 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,155 @@
1+
// Function declarations nested inside another function carrying a
2+
// function-level `"use server"` directive.
3+
//
4+
// The bubbling pre-pass turns every function declaration into
5+
// `const name = function name() {}` at the top of its block so the transform
6+
// only has to handle expression forms. The Babel original skipped the body of
7+
// each bubbled declaration, so a declaration nested inside another function
8+
// was never bubbled and a directive on it was silently ignored: the body
9+
// shipped to the client and ran there, while the capture validator (which
10+
// walks every function) still rejected its captures. These tests pin that a
11+
// nested declaration is extracted like any other marked function, in both
12+
// modes, and that hoisting still holds after the rewrite.
13+
14+
const path = require("path");
15+
16+
const compilerDir = path.resolve(__dirname, "..");
17+
const { transformDirectives } = require(compilerDir);
18+
19+
const RUNTIME = "@solidjs/web/server-functions";
20+
const ROOT = "/project";
21+
const FILENAME = `${ROOT}/src/module.js`;
22+
23+
function compile(code, overrides = {}) {
24+
return transformDirectives(code, {
25+
filename: FILENAME,
26+
root: ROOT,
27+
mode: "server",
28+
env: "production",
29+
directive: "use server",
30+
register: { kind: "named", name: "registerServerReference", source: RUNTIME },
31+
create: { kind: "named", name: "createServerReference", source: RUNTIME },
32+
...overrides
33+
});
34+
}
35+
36+
const lines = code => code.split("\n").map(line => line.trim());
37+
38+
describe("nested function declarations", () => {
39+
const source = [
40+
"export function outer() {",
41+
" async function inner() {",
42+
' "use server";',
43+
" return 1;",
44+
" }",
45+
" return inner;",
46+
"}"
47+
].join("\n");
48+
49+
it("extracts a marked declaration nested in a function (server)", () => {
50+
const result = compile(source);
51+
expect(result.valid).toBe(true);
52+
expect(result.functions.map(f => f.name)).toEqual(["outer.inner"]);
53+
const out = lines(result.code);
54+
// The body is registered at module top level and the binding inside
55+
// `outer` becomes a reference to it, exactly like a top-level function.
56+
expect(out).toContain(
57+
'const serverFunction_1 = registerServerReference_1("outer.inner-' +
58+
hashOf(result) +
59+
'", async function inner() {'
60+
);
61+
expect(out).toContain("const inner = createServerReference_1(serverFunction_1);");
62+
expect(result.code).not.toMatch(/"use server"/);
63+
});
64+
65+
it("replaces the declaration with a proxy on the client", () => {
66+
const result = compile(source, { mode: "client" });
67+
expect(result.valid).toBe(true);
68+
const out = lines(result.code);
69+
expect(out).toContain(
70+
`const inner = createServerReference_1("outer.inner-${hashOf(result)}");`
71+
);
72+
// The server body is gone from the client build.
73+
expect(result.code).not.toMatch(/return 1/);
74+
expect(result.code).not.toMatch(/registerServerReference/);
75+
});
76+
77+
it("keeps the declaration callable before its source position", () => {
78+
// A function declaration is hoisted to the top of its scope. The bubbled
79+
// `const` lands at the top of the block, so a use above the declaration
80+
// still resolves after the rewrite.
81+
const code = [
82+
"export function outer() {",
83+
" const ref = inner;",
84+
" async function inner() {",
85+
' "use server";',
86+
" return 1;",
87+
" }",
88+
" return ref;",
89+
"}"
90+
].join("\n");
91+
const out = lines(compile(code).code);
92+
const declaration = out.indexOf("const inner = createServerReference_1(serverFunction_1);");
93+
const use = out.indexOf("const ref = inner;");
94+
expect(declaration).toBeGreaterThan(-1);
95+
expect(use).toBeGreaterThan(declaration);
96+
});
97+
98+
it("extracts through several levels of nesting", () => {
99+
const code = [
100+
"export function outer() {",
101+
" function mid() {",
102+
' async function inner() { "use server"; return 1; }',
103+
" return inner;",
104+
" }",
105+
" return mid;",
106+
"}"
107+
].join("\n");
108+
const result = compile(code);
109+
expect(result.functions.map(f => f.name)).toEqual(["outer.mid.inner"]);
110+
});
111+
112+
it("extracts a declaration inside a block inside a function", () => {
113+
const code = [
114+
"export function outer(flag) {",
115+
" if (flag) {",
116+
' async function inner() { "use server"; return 1; }',
117+
" return inner;",
118+
" }",
119+
"}"
120+
].join("\n");
121+
const result = compile(code);
122+
expect(result.functions.map(f => f.name)).toEqual(["outer.inner"]);
123+
});
124+
125+
it("rejects a nested declaration that captures an enclosing local", () => {
126+
// Extraction and validation agree: the same function that is now
127+
// extracted is the one whose captures were already being checked.
128+
const code = [
129+
"export function outer(db) {",
130+
' async function inner() { "use server"; return db.x; }',
131+
" return inner;",
132+
"}"
133+
].join("\n");
134+
expect(() => compile(code)).toThrow(/`db` is declared in an enclosing function/);
135+
});
136+
137+
it("leaves an unmarked nested declaration's body in place", () => {
138+
const code = [
139+
"export function outer() {",
140+
" function helper() { return 2; }",
141+
' const go = async () => { "use server"; return 1; };',
142+
" return [helper, go];",
143+
"}"
144+
].join("\n");
145+
const result = compile(code, { mode: "client" });
146+
expect(result.functions.map(f => f.name)).toEqual(["outer.go"]);
147+
expect(result.code).toMatch(/return 2/);
148+
});
149+
});
150+
151+
// The file hash is whatever the pass produced; the scheme itself is pinned
152+
// differentially in directives-id-scheme.test.js.
153+
function hashOf(result) {
154+
return result.functions[0].id.split("-")[1];
155+
}

‎packages/compiler/src/directives/transform.rs‎

Lines changed: 29 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -702,13 +702,36 @@ impl<'a> DirectivesTransform<'a> {
702702

703703
/// Babel's function-level pre-pass bubbles *every* function declaration to a
704704
/// `const` at the top of its enclosing block (so exports keep working and the
705-
/// directive transform only has to handle expression forms). Declarations
706-
/// nested inside another bubbled declaration are skipped, matching Babel's
707-
/// `tmp.skip()`.
705+
/// directive transform only has to handle expression forms).
706+
///
707+
/// Babel skipped the body of each bubbled declaration (`tmp.skip()`), so a
708+
/// declaration nested inside another function was never bubbled, never became
709+
/// an expression, and a `"use server"` directive on it was silently ignored,
710+
/// while the capture validator still treated it as a server function. This
711+
/// pass descends into bubbled bodies too, so nested declarations are
712+
/// extracted like every other marked function. Only files that extract at
713+
/// least one function keep the pass's output, so the extra bubbling never
714+
/// reaches a file without server functions.
708715
struct Bubbler<'ctx, 'a> {
709716
transform: &'ctx mut DirectivesTransform<'a>,
710717
}
711718

719+
impl<'ctx, 'a> Bubbler<'ctx, 'a> {
720+
/// Bubbles the declarations inside `function`'s body, then turns the
721+
/// declaration itself into `const name = function name() {}`.
722+
fn bubble_declaration(
723+
&mut self,
724+
mut function: oxc_allocator::Box<'a, oxc_ast::ast::Function<'a>>,
725+
) -> Statement<'a> {
726+
walk_mut::walk_function(
727+
self,
728+
&mut function,
729+
oxc_syntax::scope::ScopeFlags::Function,
730+
);
731+
self.transform.function_declaration_to_const(function)
732+
}
733+
}
734+
712735
impl<'a> VisitMut<'a> for Bubbler<'_, 'a> {
713736
fn visit_statements(&mut self, statements: &mut ArenaVec<'a, Statement<'a>>) {
714737
let ast = self.transform.ast();
@@ -718,7 +741,7 @@ impl<'a> VisitMut<'a> for Bubbler<'_, 'a> {
718741
for statement in old {
719742
match statement {
720743
Statement::FunctionDeclaration(function) if function.id.is_some() => {
721-
hoisted.push(self.transform.function_declaration_to_const(function));
744+
hoisted.push(self.bubble_declaration(function));
722745
}
723746
Statement::ExportDeclaration(export)
724747
if matches!(
@@ -731,7 +754,7 @@ impl<'a> VisitMut<'a> for Bubbler<'_, 'a> {
731754
unreachable!("shape checked above");
732755
};
733756
let name = function.id.as_ref().unwrap().name.to_string();
734-
hoisted.push(self.transform.function_declaration_to_const(function));
757+
hoisted.push(self.bubble_declaration(function));
735758
rest.push(
736759
self.transform
737760
.export_named_specifier_statement(&name, &name),
@@ -753,7 +776,7 @@ impl<'a> VisitMut<'a> for Bubbler<'_, 'a> {
753776
unreachable!("shape checked above");
754777
};
755778
let name = function.id.as_ref().unwrap().name.to_string();
756-
hoisted.push(self.transform.function_declaration_to_const(function));
779+
hoisted.push(self.bubble_declaration(function));
757780
export.declaration =
758781
ExportDefaultDeclarationKind::from(self.transform.identifier(&name));
759782
rest.push(Statement::ExportDefaultDeclaration(export));

0 commit comments

Comments
 (0)