Open History to see the last commit
1import { describe, expect, it } from 'vitest'
2import {
3 compileRouteModules,
4 declarationOf,
5 evaluateModule,
6 expectValidModules,
7 head,
8 importSources,
9 importedNames,
10} from './regression-helpers'
11β
12const pageRoute = (body: string) => `${head}${body}
13export const Route = createFileRoute('/')({ component: Page })
14`
15β
16describe('a split component keeps the module bindings it reads', () => {
17 it.each([
18 {
19 // Source: @vitejs/plugin-rsc hoist/function-hoist-block.js
20 name: 'past a function declared in a nested block',
21 body: `const value = 'outer'
22function Page() {
23 const seen = value
24 {
25 function value() {}
26 }
27 return seen
28}`,
29 expected: 'outer',
30 },
31 {
32 // Source: @vitejs/plugin-rsc scope/param-default-var-hoisting.js
33 name: 'from a parameter default next to a var of the same name',
34 body: `const value = 'outer'
35function Page(props, seen = value) {
36 var value = 'inner'
37 return seen + ':' + value
38}`,
39 expected: 'outer:inner',
40 },
41 {
42 // Source: @vitejs/plugin-rsc scope/label.js
43 name: 'next to a label of the same name',
44 body: `const value = 'outer'
45function Page() {
46 value: for (const item of [1]) {
47 if (item) {
48 break value
49 }
50 }
51 return value
52}`,
53 expected: 'outer',
54 },
55 {
56 // Source: @vitejs/plugin-rsc hoist/catch-binding-shadow.js; React Compiler try-catch-* fixtures
57 name: 'next to a catch parameter of the same name',
58 body: `const err = { message: 'outer' }
59function Page() {
60 const readOuter = () => err.message
61 try {
62 throw new Error('inner')
63 } catch (err) {
64 return err.message + ':' + readOuter()
65 }
66}`,
67 expected: 'inner:outer',
68 },
69 {
70 // Source: @vitejs/plugin-rsc hoist/computed-destructuring-key-captures-outer-binding.js
71 name: 'through a computed destructuring key',
72 body: `const key = 'value'
73function Page() {
74 const { [key]: picked } = { value: 'picked' }
75 return picked
76}`,
77 expected: 'picked',
78 },
79 {
80 // Source: React Compiler destructure-*-default fixtures
81 name: 'from parameter destructuring defaults',
82 body: `const fallback = 'fb'
83function Page({ title = fallback, items: [first = fallback.toUpperCase()] = [] }) {
84 return <p>{title}{first}</p>
85}`,
86 expected: '<p>fbFB</p>',
87 },
88 {
89 // Source: React Compiler optional-call-chain-*.js
90 name: 'through optional call chains',
91 body: `const helpers = { format: (v) => '[' + v + ']' }
92function Page() {
93 return <p>{helpers?.format?.('a')}{helpers.missing?.(1) ?? '-'}</p>
94}`,
95 expected: '<p>[a]-</p>',
96 },
97 {
98 // Source: React Compiler tagged-template-literal.js
99 name: 'as a template tag',
100 body: `const tag = (strings, ...values) => strings.raw.join('|') + values.join(',')
101function Page() {
102 return <p>{tag\`a\${1}b\${2}c\`}</p>
103}`,
104 expected: '<p>a|b|c1,2</p>',
105 },
106 {
107 // Source: React Compiler class fixtures; @vitejs/plugin-rsc hoist/class-declaration-in-body.js
108 name: 'from the static block of a local class',
109 body: `const base = 2
110function Page() {
111 class Counter {
112 static start
113 static {
114 Counter.start = base * 2
115 }
116 #n = Counter.start
117 get n() {
118 return this.#n
119 }
120 }
121 return <p>{new Counter().n}</p>
122}`,
123 expected: '<p>4</p>',
124 },
125 ])('$name', async ({ body, expected }) => {
126 const { modules } = compileRouteModules(pageRoute(body))
127 await expectValidModules(modules)
128 const chunk = await evaluateModule(modules['virtual component']!)
129 expect(chunk.component!({})).toBe(expected)
130 })
131})
132β
133describe('names a route option declares itself do not reference module bindings', () => {
134 it.each([
135 {
136 // Source: Next.js ssg/getStaticProps/should-not-mix-up-bindings
137 name: 'locals and a named function expression in the split component',
138 options: `loader: () => [label, format()],
139 component: () => {
140 const label = 'local'
141 const obj = { a: function format(x: number) { return x } }
142 return <div>{label}{obj.a(1)}</div>
143 },`,
144 },
145 {
146 // Source: Next.js ssg/getServerSideProps/query-usage
147 name: 'a local in the loader',
148 options: `loader: () => {
149 const label = 'local'
150 return label
151 },
152 component: () => <div>{label}{format()}</div>,`,
153 },
154 {
155 // Source: Next.js ssg/getServerSideProps/query-usage
156 name: 'destructured parameters',
157 options: `loader: ({ label }: any) => [label, format()],
158 component: ({ format }: any) => <div>{format}{label}</div>,`,
159 },
160 {
161 // Source: Qwik optimizer test.rs should_not_auto_export_var_shadowed_in_{catch,do_while,switch,labeled_block}
162 name: 'block-scoped names in the split component',
163 options: `loader: () => [label, format()],
164 component: ({ kind }: any) => {
165 try { JSON.parse(kind) } catch (label) { console.log(label) }
166 let i = 0
167 do { const label = i; i += label + 1 } while (i < 3)
168 switch (kind) { case 'a': { const label = 'case'; console.log(label) } }
169 block: { const format = 'labeled'; if (format) break block }
170 return <p>{i}</p>
171 },`,
172 },
173 ])('$name', async ({ options }) => {
174 const { modules, sharedBindings } =
175 compileRouteModules(`${head}import { load } from './load'
176const label = load()
177function format() { return 'format' }
178export const Route = createFileRoute('/')({
179 ${options}
180})
181`)
182 // A name both options really read would be shared between them.
183 expect(sharedBindings).toEqual([])
184 await expectValidModules(modules)
185 })
186β
187 // Source: Next.js ssg/getStaticProps/should-not-remove-import-used-in-render
188 it('neither do intrinsic tag and attribute names, unlike component tags and JSX expressions', async () => {
189 const { modules, sharedBindings } =
190 compileRouteModules(`${head}import { A, B } from './ui'
191import { load } from './load'
192const a = load()
193const p = load()
194const label = load()
195export const Route = createFileRoute('/')({
196 loader: () => [a, p, label],
197 component: () => (
198 <p label="x" title={<A />}>
199 <a href="/">home</a>
200 <B.Deep.C />
201 </p>
202 ),
203})
204`)
205 expect(sharedBindings).toEqual([])
206 expect(importedNames(modules['virtual component']!, './ui')).toEqual([
207 'A',
208 'B',
209 ])
210 expect(importSources(modules.reference!)).not.toContain('./ui')
211 await expectValidModules(modules)
212 })
213β
214 // Source: React Router route-chunks-test.ts "computed object property"
215 it('neither do object keys, unlike computed keys', async () => {
216 const { modules, sharedBindings } =
217 compileRouteModules(`${head}import { load } from './load'
218const label = load()
219const kind = 'kind'
220export const Route = createFileRoute('/')({
221 loader: () => [label, kind],
222 component: () => {
223 const obj = { label: 1, [kind]: 2 }
224 return <div>{obj.label}</div>
225 },
226})
227`)
228 expect(sharedBindings).toEqual(['kind'])
229 await expectValidModules(modules)
230 })
231})
232β
233describe('imports read in nested positions follow the code that reads them', () => {
234 // Source: React Router route-chunks-test.ts "default argument", "destructured
235 // argument with default value", "for...of with destructuring and default
236 // value", "try catch" and "generator function"; Turbopack tree-shaker analyzer/typeof-1
237 it.each([
238 {
239 name: 'a default parameter',
240 helper: 'const read = (value = x) => value',
241 },
242 {
243 name: 'a destructuring default',
244 helper: 'const read = ([{ value }] = [{ value: x }]) => value',
245 },
246 {
247 name: 'a for-of destructuring default',
248 helper: `const read = () => {
249 for (const { value = x } of [{}]) {
250 return value
251 }
252}`,
253 },
254 {
255 name: 'a catch clause',
256 helper: `const read = () => {
257 try {
258 throw 0
259 } catch {
260 return x
261 }
262}`,
263 },
264 { name: 'a generator', helper: 'const read = function* () { yield x }' },
265 { name: 'a typeof operand', helper: 'const read = () => typeof x' },
266 ])('$name', async ({ helper }) => {
267 const { modules } = compileRouteModules(`${head}import { x } from './x'
268${helper}
269export const Route = createFileRoute('/')({
270 loader: () => 'data',
271 component: () => <p>{String(read())}</p>,
272})
273`)
274 expect(modules['virtual component']).toMatch(declarationOf('read'))
275 expect(importedNames(modules['virtual component']!, './x')).toEqual(['x'])
276 expect(importSources(modules.reference!)).not.toContain('./x')
277 await expectValidModules(modules)
278 })
279β
280 it.each([
281 {
282 // Source: @vitejs/plugin-rsc hoist/function-hoist-block.js
283 name: 'past a function declared in a nested block',
284 loader: `() => {
285 {
286 function store() {}
287 }
288 return store.value
289}`,
290 },
291 {
292 // Source: @vitejs/plugin-rsc scope/param-default-var-hoisting.js
293 name: 'from a parameter default next to a var of the same name',
294 loader: `(ctx, value = store.value) => {
295 var store = 'local'
296 return value
297}`,
298 },
299 {
300 // Source: @vitejs/plugin-rsc hoist/catch-binding-shadow.js
301 name: 'in a try block whose catch parameter shadows it',
302 loader: `() => {
303 try {
304 return store.value
305 } catch (store) {
306 return store
307 }
308}`,
309 },
310 ])('keeps an import the loader reads $name', async ({ loader }) => {
311 const { modules } =
312 compileRouteModules(`${head}import { store } from './store'
313function Page() {
314 return 'page'
315}
316export const Route = createFileRoute('/')({ loader: ${loader}, component: Page })
317`)
318 expect(importedNames(modules.reference!, './store')).toEqual(['store'])
319 await expectValidModules(modules)
320 })
321})
322β
323describe('plain JavaScript route files', () => {
324 // In JavaScript, `a < b > (c)` is two comparisons, not a call with a type
325 // argument, so `b` is a value the expression reads.
326 it('reads every operand of a chained comparison', () => {
327 const { sharedBindings } = compileRouteModules(
328 `${head}const a = 1, b = 2, c = 3
329const r = a < b > (c)
330export const Route = createFileRoute('/compare')({
331 loader: () => r,
332 component: () => <p>{String(r)}</p>,
333})
334`,
335 { filename: 'route.js' },
336 )
337 expect(sharedBindings).toEqual(['a', 'b', 'c', 'r'])
338 })
339})