Skip to content

Commit e968866

Browse files
committed
Merge remote-tracking branch 'origin/next' into mq-3837
2 parents 00dbc86 + 59fb244 commit e968866

7 files changed

Lines changed: 345 additions & 2 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@solidjs/babel-plugin": patch
3+
---
4+
5+
SSR `hoistProps` skips TypeScript type positions when collecting captures, so on authored TSX (types parsed, stripped later) a `typeof x` query or a type named like a value no longer captures that value, or forces the literal fallback when it is reassigned (#3828).
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@solidjs/compiler": patch
3+
---
4+
5+
SSR `hoistProps` no longer captures names in TypeScript type positions (type parameters, annotations, `as`/`satisfies` targets, type arguments, `typeof x` queries, local `type`/`interface` declarations, `implements`/`extends` heritage) as constructor arguments, which threw `ReferenceError` once the types were stripped (#3828). A `type` or `interface` that shares a value's name no longer makes that value count as redeclared, so its site still hoists.

‎packages/babel-plugin/src/ssr/props.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,20 @@ function insideRealFunction(path: NodePath, stop: NodePath): boolean {
156156
return false;
157157
}
158158

159+
/** Type positions are erased before the code runs: a name there (the `x` of
160+
* `typeof x`, or a type that shares a value's name) is not a value the
161+
* constructor can be handed. `TSType` covers `implements`/`extends` heritage. */
162+
function isTypePosition(path: NodePath): boolean {
163+
return (
164+
path.isTSType() ||
165+
path.isTSTypeAnnotation() ||
166+
path.isTSTypeParameterDeclaration() ||
167+
path.isTSTypeParameterInstantiation() ||
168+
path.isTSInterfaceDeclaration() ||
169+
path.isTSTypeAliasDeclaration()
170+
);
171+
}
172+
159173
/** Is `binding` initialized by the time the site constructs its props? The
160174
* getter read it lazily; the constructor reads it now. A parameter or a
161175
* hoisted function always is. Otherwise the declaration must precede the
@@ -241,6 +255,10 @@ function hoistSite(p: NodePath<t.ObjectExpression>, state: HoistState): void {
241255
if (q.node.meta.name === "new" && !insideRealFunction(q, m)) fallback = true;
242256
return;
243257
}
258+
if (isTypePosition(q)) {
259+
q.skip();
260+
return;
261+
}
244262
if (!q.isIdentifier()) return;
245263
const name = q.node.name;
246264
let write = false;
Lines changed: 243 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,243 @@
1+
// Shared by the Babel plugin and native compiler tests (#3828): a name in a
2+
// TypeScript type position is erased before the code runs, so an SSR props
3+
// constructor must never be handed it as a captured value. Each case lists,
4+
// per `new _P$(…)` in output order, the bindings passed as captures; the
5+
// output is then type-stripped and executed, and must agree with the
6+
// `hoistProps: false` literal form.
7+
const babel = require("@babel/core");
8+
const { stripTypeScriptTypes } = require("node:module");
9+
10+
const components = `const List = (p: any) => p.children;
11+
const Item = (p: any) => [p.v, p.w];
12+
`;
13+
14+
const cases = [
15+
{
16+
name: "type parameter in a nested arrow's parameter and return annotations",
17+
filename: "arrow.tsx",
18+
source: `${components}
19+
export const C = <Row,>(props: any) => (
20+
<List>
21+
<Item v={props.rows} w={(row: Row): Row => props.key(row)} />
22+
</List>
23+
);
24+
const [rows, key] = C({ rows: [1], key: (r: number) => r + 1 });
25+
__result = [rows, key(1)];`,
26+
captures: [["props"], ["props"]],
27+
result: [[1], 2]
28+
},
29+
{
30+
name: "type parameter of a function component in a function expression's annotations",
31+
filename: "function.tsx",
32+
source: `${components}
33+
function C<Row>(props: any) {
34+
return (
35+
<List>
36+
<Item
37+
v={props.v}
38+
w={function (this: unknown, row: Row): Row {
39+
return props.key(row);
40+
}}
41+
/>
42+
</List>
43+
);
44+
}
45+
const [v, w] = C({ v: 1, key: (r: number) => r * 3 });
46+
__result = [v, w(2)];`,
47+
captures: [["props"], ["props"]],
48+
result: [1, 6]
49+
},
50+
{
51+
name: "as, satisfies and non-null keep the value and drop the type",
52+
filename: "assertions.tsx",
53+
source: `${components}
54+
function C<Row>(props: any) {
55+
return <Item v={(props.v as Row)!} w={props.w satisfies Row} />;
56+
}
57+
__result = C({ v: 1, w: 2 });`,
58+
captures: [["props"]],
59+
result: [1, 2]
60+
},
61+
{
62+
name: "generic call and constructor type arguments",
63+
filename: "type-arguments.tsx",
64+
source: `${components}
65+
const id = <T,>(v: T) => v;
66+
function C<Row>(props: any) {
67+
return <Item v={id<Row>(props.v)} w={new Map<string, Row>([["k", props.w]]).get("k")} />;
68+
}
69+
__result = C({ v: 1, w: 2 });`,
70+
captures: [["props"]],
71+
result: [1, 2]
72+
},
73+
{
74+
name: "typeof a local value in a type captures neither it nor a reassigned one",
75+
filename: "typeof.tsx",
76+
source: `${components}
77+
function C(props: any) {
78+
let n = props.n;
79+
n++;
80+
const m = props.m;
81+
return <Item v={props.v as typeof n} w={props.w as typeof m} />;
82+
}
83+
__result = C({ n: 1, m: 2, v: 3, w: 4 });`,
84+
captures: [["props"]],
85+
result: [3, 4]
86+
},
87+
{
88+
name: "local type alias, interface heritage and class implements",
89+
filename: "declarations.tsx",
90+
source: `${components}
91+
function C(props: any) {
92+
type Row = { v: number };
93+
interface Keyed extends Row {
94+
k: number;
95+
}
96+
return (
97+
<Item
98+
v={(() => {
99+
interface Local extends Keyed {}
100+
class K implements Keyed {
101+
v = props.v;
102+
k = 0;
103+
}
104+
const local: Local = new K();
105+
return local.v;
106+
})()}
107+
w={props.w as Row}
108+
/>
109+
);
110+
}
111+
__result = C({ v: 1, w: 2 });`,
112+
captures: [["props"]],
113+
result: [1, 2]
114+
},
115+
{
116+
name: "type-only imports",
117+
filename: "imports.tsx",
118+
source: `import type { Row } from "./types";
119+
import { type Key } from "./types";
120+
${components}
121+
function C(props: any) {
122+
return <Item v={props.v as Row} w={props.w as Key} />;
123+
}
124+
__result = C({ v: 1, w: 2 });`,
125+
captures: [["props"]],
126+
result: [1, 2]
127+
},
128+
{
129+
name: "a name that is both a type and a value captures the value use",
130+
filename: "type-and-value.tsx",
131+
source: `${components}
132+
function C(props: any) {
133+
const Row = (v: number) => v * 2;
134+
type Row = ReturnType<typeof Row>;
135+
return <Item v={Row(props.v) as Row} w={props.w as Row} />;
136+
}
137+
__result = C({ v: 1, w: 2 });`,
138+
captures: [["Row", "props"]],
139+
result: [2, 2]
140+
},
141+
{
142+
name: "a type declared before a same-named value captures the value use",
143+
filename: "type-then-value.tsx",
144+
source: `${components}
145+
function C(props: any) {
146+
type Row = number;
147+
const Row = (v: number): Row => v * 2;
148+
return <Item v={Row(props.v) as Row} w={props.w as Row} />;
149+
}
150+
__result = C({ v: 1, w: 2 });`,
151+
captures: [["Row", "props"]],
152+
result: [2, 2]
153+
},
154+
{
155+
name: "a type parameter shadowing a value captures the value use",
156+
filename: "shadowed.tsx",
157+
source: `${components}
158+
function C(props: any) {
159+
const Row = props.factor;
160+
function Inner<Row>(p: any) {
161+
return <Item v={p.v as Row} w={p.w * Row} />;
162+
}
163+
return Inner(props);
164+
}
165+
__result = C({ factor: 3, v: 1, w: 2 });`,
166+
captures: [["p", "Row"]],
167+
result: [1, 6]
168+
}
169+
];
170+
171+
const ctorName = /^_P\$\d*$/;
172+
173+
/** Per `new _P$(…)` in output order, the arguments bound to `this[_m$…]`. */
174+
function captures(code) {
175+
const ast = babel.parseSync(code, {
176+
babelrc: false,
177+
configFile: false,
178+
sourceType: "module",
179+
parserOpts: { plugins: ["typescript"] }
180+
});
181+
const slots = new Map();
182+
const calls = [];
183+
babel.traverse(ast, {
184+
FunctionDeclaration(path) {
185+
const { id, params, body } = path.node;
186+
if (!id || !ctorName.test(id.name)) return;
187+
const names = params.map(param => param.name);
188+
const captured = [];
189+
for (const statement of body.body) {
190+
const e = statement.expression;
191+
if (
192+
e?.type === "AssignmentExpression" &&
193+
e.left.type === "MemberExpression" &&
194+
e.left.computed &&
195+
e.left.object.type === "ThisExpression" &&
196+
e.right.type === "Identifier"
197+
) {
198+
captured.push(names.indexOf(e.right.name));
199+
}
200+
}
201+
slots.set(id.name, captured);
202+
},
203+
NewExpression(path) {
204+
const { callee } = path.node;
205+
if (callee.type === "Identifier" && ctorName.test(callee.name)) calls.push(path.node);
206+
}
207+
});
208+
return calls.map(call =>
209+
slots.get(call.callee.name).map(index => {
210+
const arg = call.arguments[index];
211+
return arg.type === "Identifier" ? arg.name : arg.type;
212+
})
213+
);
214+
}
215+
216+
const runtime = {
217+
ssr: (t, ...v) => ({ t, v }),
218+
escape: v => v,
219+
mergeProps: (...sources) => Object.assign({}, ...sources),
220+
memo: fn => fn,
221+
createComponent: (Comp, props) => Comp(props)
222+
};
223+
224+
/** Strips the types the way the bundler does after the JSX transform, then runs the module body. */
225+
function run(code) {
226+
const body = stripTypeScriptTypes(code)
227+
.replace(/import \{ ([\w$]+) as ([\w$]+) \} from "r-server";/g, "const $2 = __rt.$1;")
228+
.replace(/^\s*import \{\s*\} from "[^"]+";$/gm, "")
229+
.replace(/^export /gm, "");
230+
return new Function("__rt", `let __result;\n${body}\nreturn __result;`)(runtime);
231+
}
232+
233+
/** `compile(source, filename, hoistProps)` returns the compiled code. */
234+
exports.assertCase = function assertCase(testCase, compile) {
235+
const hoisted = compile(testCase.source, testCase.filename, true);
236+
expect(captures(hoisted)).toEqual(testCase.captures);
237+
expect(run(hoisted)).toEqual(testCase.result);
238+
const literal = compile(testCase.source, testCase.filename, false);
239+
expect(captures(literal)).toEqual([]);
240+
expect(run(literal)).toEqual(testCase.result);
241+
};
242+
243+
exports.cases = cases;

‎packages/babel-plugin/test/ssr-props.spec.js‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,10 @@
33
// (`hoistProps: false`) — the fixtures only show the text.
44
const babel = require("@babel/core");
55
const plugin = require("../index");
6+
const {
7+
cases: typeCases,
8+
assertCase: assertTypeCase
9+
} = require("./__shared_fixtures__/ssrHoistPropsTypes/expected");
610

711
const options = {
812
moduleName: "r-server",
@@ -366,3 +370,19 @@ describe("SSR hoisted props", () => {
366370
expect(compiled).toMatch(/get value\(\)/);
367371
});
368372
});
373+
374+
// Authored TSX, parsed but not stripped — what the Vite plugin's Babel
375+
// backend hands the plugin; the bundler erases the types afterwards.
376+
describe("SSR hoisted props skip TypeScript type positions", () => {
377+
const compileTs = (source, filename, hoistProps) =>
378+
babel.transformSync(source, {
379+
configFile: false,
380+
babelrc: false,
381+
filename,
382+
parserOpts: { plugins: ["jsx", "typescript"] },
383+
plugins: [[plugin, { ...options, hoistProps }]]
384+
}).code;
385+
for (const testCase of typeCases) {
386+
test(testCase.name, () => assertTypeCase(testCase, compileTs));
387+
}
388+
});
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
const path = require("path");
2+
const { transform } = require("../index");
3+
const { cases, assertCase } = require(
4+
path.resolve(__dirname, "../../babel-plugin/test/__shared_fixtures__/ssrHoistPropsTypes/expected")
5+
);
6+
7+
function compile(source, filename, hoistProps) {
8+
return transform(source, {
9+
filename,
10+
generate: "ssr",
11+
moduleName: "r-server",
12+
requireImportSource: false,
13+
hoistProps
14+
}).code;
15+
}
16+
17+
describe("SSR hoisted props skip TypeScript type positions", () => {
18+
for (const testCase of cases) {
19+
test(testCase.name, () => assertCase(testCase, compile));
20+
}
21+
});

‎packages/compiler/src/ssr/props.rs‎

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -310,8 +310,25 @@ impl<'a> Planner<'_, 'a> {
310310

311311
/// Babel's `!binding.constant`: assigned anywhere, or declared twice.
312312
fn is_mutated(&self, symbol: SymbolId) -> bool {
313+
self.semantic.scoping().symbol_is_mutated(symbol)
314+
|| self.value_declarations(symbol).nth(1).is_some()
315+
}
316+
317+
/// The declarations of `symbol` that exist at runtime. A `type` or
318+
/// `interface` sharing a value's name joins the value's symbol as a
319+
/// redeclaration; Babel's binding is the value alone.
320+
fn value_declarations(&self, symbol: SymbolId) -> impl Iterator<Item = NodeId> + '_ {
313321
let scoping = self.semantic.scoping();
314-
scoping.symbol_is_mutated(symbol) || !scoping.symbol_redeclarations(symbol).is_empty()
322+
let redeclarations = scoping.symbol_redeclarations(symbol);
323+
let single = redeclarations
324+
.is_empty()
325+
.then(|| scoping.symbol_declaration(symbol));
326+
single.into_iter().chain(
327+
redeclarations
328+
.iter()
329+
.filter(|redeclaration| redeclaration.flags.intersects(SymbolFlags::Value))
330+
.map(|redeclaration| redeclaration.declaration),
331+
)
315332
}
316333

317334
/// The SSR template emits `(_v$ = init, ssr(_tmpl$, _v$))` with `var _v$;`
@@ -345,7 +362,9 @@ impl<'a> Planner<'_, 'a> {
345362
/// declaration itself (`const x = <Comp a={x.y} />` reads `x` lazily today).
346363
fn declared_before(&self, symbol: SymbolId, site: Span) -> bool {
347364
let scoping = self.semantic.scoping();
348-
let declaration = scoping.symbol_declaration(symbol);
365+
let Some(declaration) = self.value_declarations(symbol).next() else {
366+
return false;
367+
};
349368
let kind = self.semantic.nodes().kind(declaration);
350369
if matches!(
351370
kind,
@@ -499,6 +518,18 @@ impl<'a> Visit<'a> for BodyScan<'_, '_, 'a> {
499518
fn visit_private_in_expression(&mut self, _it: &PrivateInExpression<'a>) {
500519
self.fallback = true;
501520
}
521+
522+
// Type positions are erased before the code runs: a name there (a type
523+
// parameter, a local `type`/`interface`, the `x` of `typeof x`) is not a
524+
// value the constructor can be handed. Semantic flags a type query's
525+
// reference `Read`, so these are skipped by position, not by flags.
526+
fn visit_ts_type(&mut self, _it: &TSType<'a>) {}
527+
fn visit_ts_type_annotation(&mut self, _it: &TSTypeAnnotation<'a>) {}
528+
fn visit_ts_type_parameter_declaration(&mut self, _it: &TSTypeParameterDeclaration<'a>) {}
529+
fn visit_ts_type_parameter_instantiation(&mut self, _it: &TSTypeParameterInstantiation<'a>) {}
530+
fn visit_ts_interface_declaration(&mut self, _it: &TSInterfaceDeclaration<'a>) {}
531+
fn visit_ts_type_alias_declaration(&mut self, _it: &TSTypeAliasDeclaration<'a>) {}
532+
fn visit_ts_class_implements(&mut self, _it: &TSClassImplements<'a>) {}
502533
}
503534

504535
// --- Phase 2: emit -------------------------------------------------------------

0 commit comments

Comments
 (0)