Open History to see the last commit
1import { describe, expect, it } from 'vitest'
2import {
3 buildAndRun,
4 compileRouteModules,
5 declarationOf,
6 expectValidModules,
7 head,
8 importSources,
9} from './regression-helpers'
10β
11/** How many times `pattern` occurs across all emitted modules. */
12function countAcrossModules(modules: Record<string, string>, pattern: RegExp) {
13 return Object.values(modules).reduce(
14 (count, code) =>
15 count + (code.match(new RegExp(pattern.source, 'g'))?.length ?? 0),
16 0,
17 )
18}
19β
20describe('split chunks keep the module state the route relies on', () => {
21 // Route files commonly export a store or helpers over private state next to
22 // the route and use them from the route component as well.
23 it('renders a split component using exported bindings over private state like the unsplit route', async () => {
24 const result = await buildAndRun(
25 `${head}const state = { count: 0 }
26export function increment() {
27 return ++state.count
28}
29let renders = 0
30export function getRenders() {
31 return renders
32}
33const initial = 0
34export const store = { count: initial }
35function Page() {
36 increment()
37 renders++
38 store.count++
39 return <p>{[state.count, getRenders(), store.count - initial].join('/')}</p>
40}
41export const Route = createFileRoute('/')({ component: Page })
42`,
43 `const component = entry.Route.options.component
44return [await entry.render(component), await entry.render(component), entry.store.count]`,
45 )
46 // Known limitation on main: the chunk gets its own copy of `state` and
47 // `renders`, so callers of the exported functions are not checked here.
48 // `store.count` is 2: the chunk mutated the store the route module exports
49 expect(result).toEqual(['<p>1/1/1</p>', '<p>2/2/2</p>', 2])
50 }, 30_000)
51β
52 // Source: Qwik optimizer test.rs
53 // should_keep_non_migrated_binding_from_shared_destructuring_declarator_with_default (+ _with_rest)
54 it('evaluates a destructuring split between the loader and the component once', async () => {
55 const { modules } =
56 compileRouteModules(`${head}import { makeConfig } from './config'
57const { a = 'A', ...b } = makeConfig()
58export const Route = createFileRoute('/')({
59 loader: () => a,
60 component: () => <div>{JSON.stringify(b)}</div>,
61})
62`)
63 expect(countAcrossModules(modules, /makeConfig\(\)/)).toBe(1)
64 await expectValidModules(modules)
65 })
66β
67 // Source: Qwik optimizer test.rs root_level_self_referential_qrl,
68 // example_self_referential_component_migration
69 it('declares mutually recursive components used by two lazy chunks once', async () => {
70 const { modules } =
71 compileRouteModules(`${head}function A({ depth }) { return depth ? <B depth={depth - 1} /> : <i>a</i> }
72function B({ depth }) { return <b><A depth={depth} /></b> }
73export const Route = createFileRoute('/')({
74 component: () => <A depth={1} />,
75 errorComponent: () => <B depth={0} />,
76})
77`)
78 expect(countAcrossModules(modules, /function A\b/)).toBe(1)
79 expect(countAcrossModules(modules, /function B\b/)).toBe(1)
80 await expectValidModules(modules)
81 })
82β
83 it('shares a class with a static block and private members', async () => {
84 const { modules, sharedBindings } =
85 compileRouteModules(`${head}class Counter {
86 static created = 0
87 static { Counter.created = 1 }
88 #n = 0
89 increment() { return ++this.#n }
90 static owns(value: object) { return #n in value }
91}
92const counter = new Counter()
93export const Route = createFileRoute('/')({
94 loader: () => counter.increment(),
95 component: () => <div>{String(Counter.owns(counter))}</div>,
96})
97`)
98 expect(sharedBindings).toEqual(['Counter', 'counter'])
99 expect(modules['virtual component']).not.toMatch(declarationOf('Counter'))
100 await expectValidModules(modules)
101 })
102β
103 // Source: Turbopack tree-shaker analyzer/nanoid, analyzer/let-bug-1
104 it('shares a let that a shared helper reassigns', async () => {
105 const { modules, sharedBindings } =
106 compileRouteModules(`${head}let pool: Array<number> = [], offset = 0
107const fill = () => { pool = [offset++] }
108export const Route = createFileRoute('/')({
109 loader: () => { fill(); return pool },
110 component: () => { fill(); return <p>{pool.join()}</p> },
111})
112`)
113 expect(sharedBindings).toEqual(['fill', 'offset', 'pool'])
114 expect(modules.reference).not.toMatch(declarationOf('pool'))
115 expect(modules['virtual component']).not.toMatch(declarationOf('pool'))
116 await expectValidModules(modules)
117 })
118})
119β
120describe('split chunks keep reassigned bindings next to their writers', () => {
121 // Source: React Router route-chunks-test.ts "reassignment"; babel-dead-code-elimination
122 // find-removable-bindings.test.ts "constant violations mark as external"
123 it('moves a binding that only the split component reassigns into its chunk', async () => {
124 const { modules, sharedBindings } =
125 compileRouteModules(`${head}import { next } from './next'
126let current = 'initial-marker'
127export const Route = createFileRoute('/')({
128 loader: () => 'data',
129 component: () => {
130 current = next
131 return <p>{current}</p>
132 },
133})
134`)
135 expect(sharedBindings).toEqual([])
136 expect(modules.reference).not.toContain('initial-marker')
137 expect(importSources(modules.reference!)).not.toContain('./next')
138 expect(modules['virtual component']).toMatch(declarationOf('current'))
139 expect(modules['virtual component']).toContain('initial-marker')
140 await expectValidModules(modules)
141 })
142β
143 // Source: Next.js ssg/getStaticProps/should-support-babel-style-memoized-function
144 it.each([
145 { name: 'the component', loader: `'data'`, shared: [] },
146 {
147 name: 'the loader and the component',
148 loader: 'fetchData()',
149 shared: ['fetchData'],
150 },
151 ])(
152 'keeps a self-reassigning function used by $name valid',
153 async ({ loader, shared }) => {
154 const { modules, sharedBindings } =
155 compileRouteModules(`${head}function fetchData() {
156 fetchData = function () {
157 return 'memoized'
158 }
159 return fetchData.apply(this, arguments as any)
160}
161export const Route = createFileRoute('/')({
162 loader: () => ${loader},
163 component: () => <div>{fetchData()}</div>,
164})
165`)
166 expect(sharedBindings).toEqual(shared)
167 const owner = shared.length
168 ? modules.shared!
169 : modules['virtual component']!
170 expect(owner).toMatch(declarationOf('fetchData'))
171 expect(owner).toContain('fetchData = function')
172 await expectValidModules(modules)
173 },
174 )
175})