Open History to see the last commit
1import { readFile, readdir } from 'node:fs/promises'
2import path from 'node:path'
3import { describe, expect, it } from 'vitest'
4import { parseAst } from '@tanstack/router-utils'
5β
6import {
7 buildDeclarationMap,
8 buildDependencyGraph,
9 collectIdentifiersFromNode,
10 collectLocalBindingsFromStatement,
11 collectModuleLevelRefsFromNode,
12 compileCodeSplitReferenceRoute,
13 compileCodeSplitSharedRoute,
14 compileCodeSplitVirtualRoute,
15 computeSharedBindings,
16 expandDestructuredDeclarations,
17 expandSharedDestructuredDeclarators,
18 expandTransitively,
19 removeBindingsDependingOnRoute,
20} from '../src/core/code-splitter/compilers'
21import { createIdentifier } from '@tanstack/router-utils'
22import { defaultCodeSplitGroupings } from '../src/core/constants'
23import { getFrameworkHmrCompilerPlugins } from '../src/core/code-splitter/plugins/framework-plugins'
24import { frameworks } from './constants'
25import { formatSnapshot } from './format-snapshot'
26import type { CodeSplitGroupings } from '../src/core/constants'
27β
28function getFrameworkDir(framework: string) {
29 const files = path.resolve(
30 __dirname,
31 `./code-splitter/test-files/${framework}`,
32 )
33 const snapshots = path.resolve(
34 __dirname,
35 `./code-splitter/snapshots/${framework}`,
36 )
37 return { files, snapshots }
38}
39β
40const testGroups: Array<{ name: string; groupings: CodeSplitGroupings }> = [
41 {
42 name: '1-default',
43 groupings: defaultCodeSplitGroupings,
44 },
45 {
46 name: '2-components-combined-loader-separate',
47 groupings: [
48 ['loader'],
49 ['component', 'pendingComponent', 'errorComponent', 'notFoundComponent'],
50 ],
51 },
52 {
53 name: '3-all-combined-errorComponent-separate',
54 groupings: [
55 ['loader', 'component', 'pendingComponent', 'notFoundComponent'],
56 ['errorComponent'],
57 ],
58 },
59]
60β
61describe('code-splitter works', () => {
62 describe.each(frameworks)('FRAMEWORK=%s', (framework) => {
63 describe.each(testGroups)(
64 'SPLIT_GROUP=$name',
65 async ({ groupings: grouping, name: groupName }) => {
66 const dirs = getFrameworkDir(framework)
67 const filenames = await readdir(dirs.files)
68β
69 it.each(filenames)(
70 `should compile "reference" for "%s"`,
71 async (filename) => {
72 const file = await readFile(path.join(dirs.files, filename))
73 const code = file.toString()
74β
75 const sharedBindings = computeSharedBindings({
76 code,
77 codeSplitGroupings: grouping,
78 })
79β
80 const compileResult = compileCodeSplitReferenceRoute({
81 code,
82 filename,
83 id: filename,
84 addHmr: false,
85 codeSplitGroupings: grouping,
86 targetFramework: framework,
87 sharedBindings:
88 sharedBindings.size > 0 ? sharedBindings : undefined,
89 })
90β
91 await expect(
92 await formatSnapshot(compileResult?.code || code, filename),
93 ).toMatchFileSnapshot(
94 path.join(dirs.snapshots, groupName, filename),
95 )
96 },
97 )
98β
99 it.each(filenames)(
100 `should compile "virtual" for "%s"`,
101 async (filename) => {
102 const file = await readFile(path.join(dirs.files, filename))
103 const code = file.toString()
104β
105 const sharedBindings = computeSharedBindings({
106 code,
107 codeSplitGroupings: grouping,
108 })
109β
110 for (const targets of grouping) {
111 const ident = createIdentifier(targets)
112β
113 const splitResult = compileCodeSplitVirtualRoute({
114 code,
115 filename: `${filename}?${ident}`,
116 splitTargets: targets,
117 sharedBindings:
118 sharedBindings.size > 0 ? sharedBindings : undefined,
119 })
120β
121 const snapshotFilename = path.join(
122 dirs.snapshots,
123 groupName,
124 `${filename.replace('.tsx', '')}@${ident}.tsx`,
125 )
126 await expect(
127 await formatSnapshot(splitResult.code, filename),
128 ).toMatchFileSnapshot(snapshotFilename)
129 }
130 },
131 )
132β
133 it.each(filenames)(
134 `should compile "shared" for "%s"`,
135 async (filename) => {
136 const file = await readFile(path.join(dirs.files, filename))
137 const code = file.toString()
138β
139 const sharedBindings = computeSharedBindings({
140 code,
141 codeSplitGroupings: grouping,
142 })
143β
144 const snapshotFilename = path.join(
145 dirs.snapshots,
146 groupName,
147 `${filename.replace('.tsx', '')}@shared.tsx`,
148 )
149β
150 if (sharedBindings.size === 0) {
151 // No shared module β snapshot should be empty string
152 await expect('').toMatchFileSnapshot(snapshotFilename)
153 return
154 }
155β
156 const sharedResult = compileCodeSplitSharedRoute({
157 code,
158 sharedBindings,
159 filename: `${filename}?tsr-shared=1`,
160 })
161β
162 await expect(
163 await formatSnapshot(sharedResult.code, filename),
164 ).toMatchFileSnapshot(snapshotFilename)
165 },
166 )
167 },
168 )
169 })
170})
171β
172describe('React Refresh virtual route compiler plugin', () => {
173 const splitComponentCases = [
174 { splitType: 'component', splitIdentifier: 'SplitComponent' },
175 {
176 splitType: 'pendingComponent',
177 splitIdentifier: 'SplitPendingComponent',
178 },
179 { splitType: 'errorComponent', splitIdentifier: 'SplitErrorComponent' },
180 ] as const
181β
182 function createRouteCode(splitType: string) {
183 return `
184import { createFileRoute } from '@tanstack/react-router'
185β
186export const Route = createFileRoute('/')({ ${splitType} })
187β
188function ${splitType}() {
189 return <div>lowercase function declaration</div>
190}
191`
192 }
193β
194 it.each(splitComponentCases)(
195 'renames a lowercase $splitType binding when HMR is enabled',
196 ({ splitType, splitIdentifier }) => {
197 const result = compileCodeSplitVirtualRoute({
198 code: createRouteCode(splitType),
199 filename: `lowercase-function-declaration.tsx?tsr-split=${splitType}`,
200 splitTargets: [splitType],
201 compilerPlugins: getFrameworkHmrCompilerPlugins({
202 targetFramework: 'react',
203 }),
204 })
205β
206 expect(result.code).toContain(`function ${splitIdentifier}()`)
207 expect(result.code).toContain(
208 `export { ${splitIdentifier} as ${splitType} }`,
209 )
210 },
211 )
212β
213 it.each(splitComponentCases)(
214 'keeps a lowercase $splitType binding when HMR is disabled',
215 ({ splitType }) => {
216 const result = compileCodeSplitVirtualRoute({
217 code: createRouteCode(splitType),
218 filename: `lowercase-function-declaration.tsx?tsr-split=${splitType}`,
219 splitTargets: [splitType],
220 })
221β
222 expect(result.code).toContain(`function ${splitType}()`)
223 expect(result.code).toContain(`export { ${splitType} }`)
224 },
225 )
226})
227β
228describe('computeSharedBindings fast paths', () => {
229 it('returns empty when only one split group is present (default groupings)', () => {
230 const code = `
231import { createFileRoute } from '@tanstack/react-router'
232const shared = 42
233export const Route = createFileRoute('/')({
234 component: () => shared,
235})
236`
237 const result = computeSharedBindings({
238 code,
239 codeSplitGroupings: defaultCodeSplitGroupings,
240 })
241 expect(result.size).toBe(0)
242 })
243β
244 it('returns empty when all split props are in the same group', () => {
245 const code = `
246import { createFileRoute } from '@tanstack/react-router'
247const shared = 42
248export const Route = createFileRoute('/')({
249 component: () => shared,
250 loader: () => shared,
251})
252`
253 const result = computeSharedBindings({
254 code,
255 codeSplitGroupings: [['component', 'loader']],
256 })
257 expect(result.size).toBe(0)
258 })
259β
260 it('returns empty when all route option values are undefined', () => {
261 const code = `
262import { createFileRoute } from '@tanstack/react-router'
263export const Route = createFileRoute('/')({
264 component: undefined,
265 errorComponent: undefined,
266 notFoundComponent: undefined,
267})
268`
269 const result = computeSharedBindings({
270 code,
271 codeSplitGroupings: defaultCodeSplitGroupings,
272 })
273 expect(result.size).toBe(0)
274 })
275β
276 it('returns empty when no local bindings exist (only imports + Route)', () => {
277 const code = `
278import { createFileRoute } from '@tanstack/react-router'
279export const Route = createFileRoute('/')({
280 component: () => <div>hello</div>,
281 errorComponent: () => <div>error</div>,
282})
283`
284 const result = computeSharedBindings({
285 code,
286 codeSplitGroupings: defaultCodeSplitGroupings,
287 })
288 expect(result.size).toBe(0)
289 })
290β
291 it('does not fast-path when there is a non-split and a split group', () => {
292 const code = `
293import { createFileRoute } from '@tanstack/react-router'
294const shared = 42
295export const Route = createFileRoute('/')({
296 component: () => shared,
297 beforeLoad: () => shared,
298})
299`
300 const result = computeSharedBindings({
301 code,
302 codeSplitGroupings: defaultCodeSplitGroupings,
303 })
304 expect(result).toContain('shared')
305 })
306})
307β
308// ============================================================================
309// LAYER 1: Algebraic Property Tests on Helper Functions
310//
311// These test that the pure graph/set functions obey mathematical contracts
312// independent of any particular route file.
313// ============================================================================
314β
315describe('expandTransitively', () => {
316 it('is idempotent β running twice yields the same result as once', () => {
317 // Graph: a -> b -> c, d -> b
318 const depGraph = new Map<string, Set<string>>([
319 ['a', new Set(['b'])],
320 ['b', new Set(['c'])],
321 ['c', new Set()],
322 ['d', new Set(['b'])],
323 ])
324β
325 const first = new Set(['a'])
326 expandTransitively(first, depGraph)
327 const afterFirst = new Set(first)
328β
329 expandTransitively(first, depGraph)
330 expect(first).toEqual(afterFirst)
331 })
332β
333 it('is monotone β larger initial set produces equal or larger result', () => {
334 const depGraph = new Map<string, Set<string>>([
335 ['a', new Set(['c'])],
336 ['b', new Set(['d'])],
337 ['c', new Set()],
338 ['d', new Set()],
339 ])
340β
341 const small = new Set(['a'])
342 expandTransitively(small, depGraph)
343β
344 const large = new Set(['a', 'b'])
345 expandTransitively(large, depGraph)
346β
347 for (const item of small) {
348 expect(large.has(item)).toBe(true)
349 }
350 })
351β
352 it('handles cycles without infinite loops', () => {
353 const depGraph = new Map<string, Set<string>>([
354 ['a', new Set(['b'])],
355 ['b', new Set(['c'])],
356 ['c', new Set(['a'])],
357 ])
358β
359 const set = new Set(['a'])
360 expandTransitively(set, depGraph)
361 expect(set).toEqual(new Set(['a', 'b', 'c']))
362 })
363β
364 it('is a no-op when there are no dependencies', () => {
365 const depGraph = new Map<string, Set<string>>([
366 ['a', new Set()],
367 ['b', new Set()],
368 ])
369β
370 const set = new Set(['a'])
371 expandTransitively(set, depGraph)
372 expect(set).toEqual(new Set(['a']))
373 })
374β
375 it('handles missing entries in the graph gracefully', () => {
376 const depGraph = new Map<string, Set<string>>()
377 const set = new Set(['unknown'])
378 expandTransitively(set, depGraph)
379 expect(set).toEqual(new Set(['unknown']))
380 })
381})
382β
383describe('buildDependencyGraph', () => {
384 it('result keys are a subset of localBindings', () => {
385 const code = `
386const a = 1
387const b = a + 1
388const c = 2
389`
390 const ast = parseAst({ code })
391 const declMap = buildDeclarationMap(ast)
392 const localBindings = new Set(['a', 'b', 'c'])
393 const graph = buildDependencyGraph(declMap, localBindings)
394β
395 for (const key of graph.keys()) {
396 expect(localBindings.has(key)).toBe(true)
397 }
398 })
399β
400 it('dependency values are also subsets of localBindings', () => {
401 const code = `
402import { external } from 'somewhere'
403const a = external
404const b = a + 1
405`
406 const ast = parseAst({ code })
407 const declMap = buildDeclarationMap(ast)
408 const localBindings = new Set(['a', 'b'])
409 const graph = buildDependencyGraph(declMap, localBindings)
410β
411 for (const deps of graph.values()) {
412 for (const dep of deps) {
413 expect(localBindings.has(dep)).toBe(true)
414 }
415 }
416 })
417β
418 it('captures direct references correctly', () => {
419 const code = `
420const x = 10
421const y = x + 1
422`
423 const ast = parseAst({ code })
424 const declMap = buildDeclarationMap(ast)
425 const localBindings = new Set(['x', 'y'])
426 const graph = buildDependencyGraph(declMap, localBindings)
427β
428 expect(graph.get('y')).toEqual(new Set(['x']))
429 expect(graph.get('x')?.size ?? 0).toBe(0)
430 })
431})
432β
433describe('removeBindingsDependingOnRoute', () => {
434 it('removes bindings that directly reference Route', () => {
435 const depGraph = new Map<string, Set<string>>([
436 ['helper', new Set(['Route'])],
437 ['standalone', new Set()],
438 ['Route', new Set()],
439 ])
440β
441 const shared = new Set(['helper', 'standalone'])
442 removeBindingsDependingOnRoute(shared, depGraph)
443β
444 expect(shared.has('helper')).toBe(false)
445 expect(shared.has('standalone')).toBe(true)
446 })
447β
448 it('removes bindings that transitively reference Route', () => {
449 const depGraph = new Map<string, Set<string>>([
450 ['a', new Set(['b'])],
451 ['b', new Set(['Route'])],
452 ['c', new Set()],
453 ['Route', new Set()],
454 ])
455β
456 const shared = new Set(['a', 'c'])
457 removeBindingsDependingOnRoute(shared, depGraph)
458β
459 expect(shared.has('a')).toBe(false)
460 expect(shared.has('c')).toBe(true)
461 })
462β
463 it('is a no-op when nothing depends on Route', () => {
464 const depGraph = new Map<string, Set<string>>([
465 ['a', new Set(['b'])],
466 ['b', new Set()],
467 ['Route', new Set()],
468 ])
469β
470 const shared = new Set(['a', 'b'])
471 const before = new Set(shared)
472 removeBindingsDependingOnRoute(shared, depGraph)
473β
474 expect(shared).toEqual(before)
475 })
476})
477β
478describe('expandDestructuredDeclarations', () => {
479 it('is idempotent', () => {
480 const code = `const { a, b } = fn()`
481 const ast = parseAst({ code })
482β
483 const shared = new Set(['a'])
484 expandDestructuredDeclarations(ast, shared)
485 const afterFirst = new Set(shared)
486β
487 expandDestructuredDeclarations(ast, shared)
488 expect(shared).toEqual(afterFirst)
489 })
490β
491 it('pulls all siblings when one destructured binding is shared', () => {
492 const code = `const { a, b, c } = fn()`
493 const ast = parseAst({ code })
494β
495 const shared = new Set(['b'])
496 expandDestructuredDeclarations(ast, shared)
497β
498 expect(shared).toEqual(new Set(['a', 'b', 'c']))
499 })
500β
501 it('does not affect non-destructured declarations', () => {
502 const code = `
503const x = 1
504const y = 2
505`
506 const ast = parseAst({ code })
507β
508 const shared = new Set(['x'])
509 expandDestructuredDeclarations(ast, shared)
510β
511 expect(shared).toEqual(new Set(['x']))
512 })
513})
514β
515describe('collectLocalBindingsFromStatement', () => {
516 it('collects variable declaration names', () => {
517 const code = `const x = 1`
518 const ast = parseAst({ code })
519 const bindings = new Set<string>()
520 collectLocalBindingsFromStatement(ast.program.body[0]!, bindings)
521 expect(bindings).toEqual(new Set(['x']))
522 })
523β
524 it('collects function declaration names', () => {
525 const code = `function foo() {}`
526 const ast = parseAst({ code })
527 const bindings = new Set<string>()
528 collectLocalBindingsFromStatement(ast.program.body[0]!, bindings)
529 expect(bindings).toEqual(new Set(['foo']))
530 })
531β
532 it('collects class declaration names', () => {
533 const code = `class MyClass {}`
534 const ast = parseAst({ code })
535 const bindings = new Set<string>()
536 collectLocalBindingsFromStatement(ast.program.body[0]!, bindings)
537 expect(bindings).toEqual(new Set(['MyClass']))
538 })
539β
540 it('collects exported declaration names', () => {
541 const code = `export const a = 1`
542 const ast = parseAst({ code })
543 const bindings = new Set<string>()
544 collectLocalBindingsFromStatement(ast.program.body[0]!, bindings)
545 expect(bindings).toEqual(new Set(['a']))
546 })
547β
548 it('collects destructured binding names', () => {
549 const code = `const { a, b } = obj`
550 const ast = parseAst({ code })
551 const bindings = new Set<string>()
552 collectLocalBindingsFromStatement(ast.program.body[0]!, bindings)
553 expect(bindings).toEqual(new Set(['a', 'b']))
554 })
555})
556β
557// ============================================================================
558// LAYER 2: Invariant Tests on computeSharedBindings
559//
560// These verify the core "contracts" of the shared bindings computation:
561// - Route is never extracted
562// - Results are always real local bindings
563// - Destructured cohesion holds
564// - Transitive dependencies are included
565// - Route-dependent bindings are excluded
566// ============================================================================
567β
568describe('computeSharedBindings invariants', () => {
569 const defaultGroupings = defaultCodeSplitGroupings
570β
571 function getLocalBindings(code: string): Set<string> {
572 const ast = parseAst({ code })
573 const bindings = new Set<string>()
574 for (const stmt of ast.program.body) {
575 collectLocalBindingsFromStatement(stmt, bindings)
576 }
577 bindings.delete('Route')
578 return bindings
579 }
580β
581 it('INVARIANT: Route is never in the shared set', () => {
582 const code = `
583import { createFileRoute } from '@tanstack/react-router'
584const shared = 42
585export const Route = createFileRoute('/')({
586 component: () => shared,
587 beforeLoad: () => shared,
588})
589`
590 const result = computeSharedBindings({
591 code,
592 codeSplitGroupings: defaultGroupings,
593 })
594 expect(result.has('Route')).toBe(false)
595 })
596β
597 it('INVARIANT: all results are actual local bindings from the source', () => {
598 const code = `
599import { createFileRoute } from '@tanstack/react-router'
600import { external } from 'somewhere'
601const config = { url: external, timeout: 5000 }
602const fetcher = (path) => fetch(config.url + path)
603export const Route = createFileRoute('/')({
604 loader: () => fetcher('/data'),
605 component: () => <div>{config.timeout}</div>,
606})
607`
608 const result = computeSharedBindings({
609 code,
610 codeSplitGroupings: defaultGroupings,
611 })
612 const localBindings = getLocalBindings(code)
613β
614 for (const name of result) {
615 expect(localBindings.has(name)).toBe(true)
616 }
617 })
618β
619 it('INVARIANT: imports are never in the shared set', () => {
620 const code = `
621import { createFileRoute } from '@tanstack/react-router'
622import { helper } from './utils'
623export const Route = createFileRoute('/')({
624 loader: () => helper(),
625 component: () => <div>{helper()}</div>,
626})
627`
628 const result = computeSharedBindings({
629 code,
630 codeSplitGroupings: defaultGroupings,
631 })
632 expect(result.has('helper')).toBe(false)
633 })
634β
635 it('INVARIANT: destructured siblings are either all shared or none shared', () => {
636 const code = `
637import { createFileRoute } from '@tanstack/react-router'
638const { a, b, c } = createHelpers()
639export const Route = createFileRoute('/')({
640 loader: () => a,
641 component: () => <div>{b}</div>,
642})
643`
644 const result = computeSharedBindings({
645 code,
646 codeSplitGroupings: defaultGroupings,
647 })
648β
649 // If any destructured sibling is shared, all must be
650 const siblings = ['a', 'b', 'c']
651 const sharedSiblings = siblings.filter((s) => result.has(s))
652 if (sharedSiblings.length > 0) {
653 expect(sharedSiblings.length).toBe(siblings.length)
654 }
655 })
656β
657 it('INVARIANT: transitive dependencies of shared bindings are also shared', () => {
658 const code = `
659import { createFileRoute } from '@tanstack/react-router'
660const BASE = 'https://api.example.com'
661const config = { url: BASE }
662const fetcher = () => fetch(config.url)
663export const Route = createFileRoute('/')({
664 loader: () => fetcher(),
665 component: () => <div>{config.url}</div>,
666})
667`
668 const result = computeSharedBindings({
669 code,
670 codeSplitGroupings: defaultGroupings,
671 })
672β
673 // If config is shared (referenced by both loader via fetcher and component directly),
674 // then BASE (which config depends on) should also be shared
675 if (result.has('config')) {
676 expect(result.has('BASE')).toBe(true)
677 }
678 })
679β
680 it('INVARIANT: bindings depending on Route are excluded from shared', () => {
681 const code = `
682import { createFileRoute } from '@tanstack/react-router'
683const HEADER = 'Page'
684function usePageTitle() {
685 return HEADER + ' - ' + Route.fullPath
686}
687export const Route = createFileRoute('/about')({
688 loader: () => usePageTitle(),
689 component: () => <div>{usePageTitle()}</div>,
690})
691`
692 const result = computeSharedBindings({
693 code,
694 codeSplitGroupings: defaultGroupings,
695 })
696β
697 // usePageTitle references Route, so it must NOT be shared
698 expect(result.has('usePageTitle')).toBe(false)
699 // HEADER is only referenced by usePageTitle which depends on Route,
700 // so HEADER should also not be shared (unless it has other references)
701 })
702β
703 it('INVARIANT: single-group-only bindings are never shared', () => {
704 const code = `
705import { createFileRoute } from '@tanstack/react-router'
706const loaderOnly = () => fetch('/api')
707const componentOnly = () => <span>hi</span>
708const shared = 42
709export const Route = createFileRoute('/')({
710 loader: () => { loaderOnly(); return shared },
711 component: () => <div>{componentOnly()} {shared}</div>,
712})
713`
714 const result = computeSharedBindings({
715 code,
716 codeSplitGroupings: defaultGroupings,
717 })
718β
719 // loaderOnly is only used by loader (non-split), should NOT be shared
720 expect(result.has('loaderOnly')).toBe(false)
721 // componentOnly is only used by component (split), should NOT be shared
722 expect(result.has('componentOnly')).toBe(false)
723 // shared IS used by both groups
724 expect(result.has('shared')).toBe(true)
725 })
726β
727 it('INVARIANT: empty result for unsplittable routes (createRootRoute)', () => {
728 const code = `
729import { createRootRoute } from '@tanstack/react-router'
730const shared = 42
731export const Route = createRootRoute({
732 component: () => <div>{shared}</div>,
733 beforeLoad: () => shared,
734})
735`
736 const result = computeSharedBindings({
737 code,
738 codeSplitGroupings: defaultGroupings,
739 })
740 expect(result.size).toBe(0)
741 })
742β
743 it('INVARIANT: result is stable across multiple calls with same input', () => {
744 const code = `
745import { createFileRoute } from '@tanstack/react-router'
746const shared = { name: 'test' }
747export const Route = createFileRoute('/')({
748 loader: () => shared.name,
749 component: () => <div>{shared.name}</div>,
750})
751`
752 const opts = { code, codeSplitGroupings: defaultGroupings }
753 const result1 = computeSharedBindings(opts)
754 const result2 = computeSharedBindings(opts)
755 const result3 = computeSharedBindings(opts)
756β
757 expect(result1).toEqual(result2)
758 expect(result2).toEqual(result3)
759 })
760})
761β
762// ============================================================================
763// LAYER 3: Small-Scope Exhaustive Tests
764//
765// Inspired by Alloy's "small scope hypothesis" β most bugs show up in small
766// counterexamples. We exhaustively test all combinations of:
767// - binding declaration types (const, function, class)
768// - route property configurations (loader+component, loader+errorComponent, etc.)
769// - split grouping configurations
770// ============================================================================
771β
772describe('small-scope exhaustive: computeSharedBindings', () => {
773 // Helper to generate a route file with specific binding configurations
774 function makeRouteCode(opts: {
775 bindings: Array<{ name: string; kind: 'const' | 'function' | 'class' }>
776 loaderRefs: Array<string>
777 componentRefs: Array<string>
778 errorComponentRefs?: Array<string>
779 beforeLoadRefs?: Array<string>
780 }): string {
781 const bindingDecls = opts.bindings
782 .map((b) => {
783 switch (b.kind) {
784 case 'const':
785 return `const ${b.name} = 42`
786 case 'function':
787 return `function ${b.name}() { return 42 }`
788 case 'class':
789 return `class ${b.name} { value = 42 }`
790 }
791 })
792 .join('\n')
793β
794 const loaderBody =
795 opts.loaderRefs.length > 0
796 ? opts.loaderRefs.map((r) => `${r}`).join('; ')
797 : '42'
798β
799 const componentBody =
800 opts.componentRefs.length > 0
801 ? opts.componentRefs.map((r) => `{${r}}`).join('')
802 : 'hello'
803β
804 const props: Array<string> = [
805 ` loader: () => { return ${loaderBody} }`,
806 ` component: () => <div>${componentBody}</div>`,
807 ]
808β
809 if (opts.errorComponentRefs) {
810 const body =
811 opts.errorComponentRefs.length > 0
812 ? opts.errorComponentRefs.map((r) => `{${r}}`).join('')
813 : 'error'
814 props.push(` errorComponent: () => <div>${body}</div>`)
815 }
816β
817 if (opts.beforeLoadRefs) {
818 const body =
819 opts.beforeLoadRefs.length > 0
820 ? opts.beforeLoadRefs.map((r) => `${r}`).join('; ')
821 : '42'
822 props.push(` beforeLoad: () => { return ${body} }`)
823 }
824β
825 return `
826import { createFileRoute } from '@tanstack/react-router'
827${bindingDecls}
828export const Route = createFileRoute('/')({
829${props.join(',\n')}
830})
831`
832 }
833β
834 // Exhaustively test 1-binding scenarios with all grouping configs
835 const groupingConfigs: Array<{
836 name: string
837 groupings: CodeSplitGroupings
838 }> = [
839 { name: 'default', groupings: defaultCodeSplitGroupings },
840 {
841 name: 'loader+components-combined',
842 groupings: [
843 ['loader'],
844 [
845 'component',
846 'pendingComponent',
847 'errorComponent',
848 'notFoundComponent',
849 ],
850 ],
851 },
852 ]
853β
854 const bindingKinds = ['const', 'function', 'class'] as const
855β
856 describe('single binding Γ all property combinations', () => {
857 // For each binding kind Γ each grouping Γ each reference pattern,
858 // verify invariants hold
859 for (const kind of bindingKinds) {
860 for (const { name: groupName, groupings } of groupingConfigs) {
861 // Pattern: binding used only by loader (non-split) β never shared
862 it(`${kind} used only by loader [${groupName}] β not shared`, () => {
863 const code = makeRouteCode({
864 bindings: [{ name: 'x', kind }],
865 loaderRefs: ['x'],
866 componentRefs: [],
867 })
868 const result = computeSharedBindings({
869 code,
870 codeSplitGroupings: groupings,
871 })
872 expect(result.has('x')).toBe(false)
873 })
874β
875 // Pattern: binding used only by component (split) β never shared
876 it(`${kind} used only by component [${groupName}] β not shared`, () => {
877 const code = makeRouteCode({
878 bindings: [{ name: 'x', kind }],
879 loaderRefs: [],
880 componentRefs: ['x'],
881 })
882 const result = computeSharedBindings({
883 code,
884 codeSplitGroupings: groupings,
885 })
886 expect(result.has('x')).toBe(false)
887 })
888β
889 // Pattern: binding used by both loader AND component β shared
890 it(`${kind} used by loader+component [${groupName}] β shared`, () => {
891 const code = makeRouteCode({
892 bindings: [{ name: 'x', kind }],
893 loaderRefs: ['x'],
894 componentRefs: ['x'],
895 })
896 const result = computeSharedBindings({
897 code,
898 codeSplitGroupings: groupings,
899 })
900 expect(result.has('x')).toBe(true)
901 })
902β
903 // Pattern: binding used by component AND beforeLoad (non-split) β shared
904 it(`${kind} used by component+beforeLoad [${groupName}] β shared`, () => {
905 const code = makeRouteCode({
906 bindings: [{ name: 'x', kind }],
907 loaderRefs: [],
908 componentRefs: ['x'],
909 beforeLoadRefs: ['x'],
910 })
911 const result = computeSharedBindings({
912 code,
913 codeSplitGroupings: groupings,
914 })
915 expect(result.has('x')).toBe(true)
916 })
917 }
918 }
919 })
920β
921 describe('two bindings Γ cross-group references', () => {
922 for (const { name: groupName, groupings } of groupingConfigs) {
923 // Both bindings in same group β neither shared
924 it(`both in loader only [${groupName}] β neither shared`, () => {
925 const code = makeRouteCode({
926 bindings: [
927 { name: 'a', kind: 'const' },
928 { name: 'b', kind: 'const' },
929 ],
930 loaderRefs: ['a', 'b'],
931 componentRefs: [],
932 })
933 const result = computeSharedBindings({
934 code,
935 codeSplitGroupings: groupings,
936 })
937 expect(result.has('a')).toBe(false)
938 expect(result.has('b')).toBe(false)
939 })
940β
941 // One binding per group β neither shared
942 it(`one per group, no overlap [${groupName}] β neither shared`, () => {
943 const code = makeRouteCode({
944 bindings: [
945 { name: 'a', kind: 'const' },
946 { name: 'b', kind: 'const' },
947 ],
948 loaderRefs: ['a'],
949 componentRefs: ['b'],
950 })
951 const result = computeSharedBindings({
952 code,
953 codeSplitGroupings: groupings,
954 })
955 expect(result.has('a')).toBe(false)
956 expect(result.has('b')).toBe(false)
957 })
958β
959 // Both in both groups β both shared
960 it(`both in both groups [${groupName}] β both shared`, () => {
961 const code = makeRouteCode({
962 bindings: [
963 { name: 'a', kind: 'const' },
964 { name: 'b', kind: 'const' },
965 ],
966 loaderRefs: ['a', 'b'],
967 componentRefs: ['a', 'b'],
968 })
969 const result = computeSharedBindings({
970 code,
971 codeSplitGroupings: groupings,
972 })
973 expect(result.has('a')).toBe(true)
974 expect(result.has('b')).toBe(true)
975 })
976β
977 // One shared, one not β exactly one shared
978 it(`one in both groups, one in one [${groupName}] β only cross-group is shared`, () => {
979 const code = makeRouteCode({
980 bindings: [
981 { name: 'a', kind: 'const' },
982 { name: 'b', kind: 'const' },
983 ],
984 loaderRefs: ['a'],
985 componentRefs: ['a', 'b'],
986 })
987 const result = computeSharedBindings({
988 code,
989 codeSplitGroupings: groupings,
990 })
991 expect(result.has('a')).toBe(true)
992 expect(result.has('b')).toBe(false)
993 })
994 }
995 })
996β
997 describe('transitive dependency chains', () => {
998 it('A depends on B, both used by different groups β both shared', () => {
999 const code = `
1000import { createFileRoute } from '@tanstack/react-router'
1001const BASE = 'https://api.example.com'
1002const config = { url: BASE }
1003export const Route = createFileRoute('/')({
1004 loader: () => config.url,
1005 component: () => <div>{config.url}</div>,
1006})
1007`
1008 const result = computeSharedBindings({
1009 code,
1010 codeSplitGroupings: defaultCodeSplitGroupings,
1011 })
1012 // config is directly used by both groups β shared
1013 expect(result.has('config')).toBe(true)
1014 // BASE is a dep of config β also shared
1015 expect(result.has('BASE')).toBe(true)
1016 })
1017β
1018 it('A depends on B depends on C, A used cross-group β all three shared', () => {
1019 const code = `
1020import { createFileRoute } from '@tanstack/react-router'
1021const c = 'deep'
1022const b = c + '-value'
1023const a = b + '-final'
1024export const Route = createFileRoute('/')({
1025 loader: () => a,
1026 component: () => <div>{a}</div>,
1027})
1028`
1029 const result = computeSharedBindings({
1030 code,
1031 codeSplitGroupings: defaultCodeSplitGroupings,
1032 })
1033 expect(result.has('a')).toBe(true)
1034 expect(result.has('b')).toBe(true)
1035 expect(result.has('c')).toBe(true)
1036 })
1037β
1038 it('diamond dependency: AβB, AβC, BβD, CβD β all shared when A is cross-group', () => {
1039 const code = `
1040import { createFileRoute } from '@tanstack/react-router'
1041const D = 42
1042const B = D + 1
1043const C = D + 2
1044const A = B + C
1045export const Route = createFileRoute('/')({
1046 loader: () => A,
1047 component: () => <div>{A}</div>,
1048})
1049`
1050 const result = computeSharedBindings({
1051 code,
1052 codeSplitGroupings: defaultCodeSplitGroupings,
1053 })
1054 expect(result.has('A')).toBe(true)
1055 expect(result.has('B')).toBe(true)
1056 expect(result.has('C')).toBe(true)
1057 expect(result.has('D')).toBe(true)
1058 })
1059 })
1060β
1061 describe('meta-invariant: all fixture files satisfy core contracts', () => {
1062 const sharedFixtures = [
1063 'shared-variable.tsx',
1064 'shared-class.tsx',
1065 'shared-function.tsx',
1066 'shared-exported.tsx',
1067 'shared-indirect-ref.tsx',
1068 'shared-none.tsx',
1069 'shared-destructured.tsx',
1070 'shared-destructured-export.tsx',
1071 'shared-imported-binding.tsx',
1072 'shared-jsx-component-ref.tsx',
1073 'shared-referencing-route.tsx',
1074 'shared-transitive.tsx',
1075 'shared-with-side-effect.tsx',
1076 ]
1077β
1078 // Run invariants across ALL existing test fixtures β like a conformance suite
1079 it.each(sharedFixtures)(
1080 'fixture "%s" satisfies: Route excluded, results β localBindings',
1081 async (filename) => {
1082 const file = await readFile(
1083 path.join(__dirname, `./code-splitter/test-files/react/${filename}`),
1084 )
1085 const code = file.toString()
1086β
1087 const result = computeSharedBindings({
1088 code,
1089 codeSplitGroupings: defaultCodeSplitGroupings,
1090 })
1091β
1092 // Contract 1: Route is never shared
1093 expect(result.has('Route')).toBe(false)
1094β
1095 // Contract 2: all results are real local bindings
1096 const ast = parseAst({ code })
1097 const localBindings = new Set<string>()
1098 for (const stmt of ast.program.body) {
1099 collectLocalBindingsFromStatement(stmt, localBindings)
1100 }
1101 localBindings.delete('Route')
1102β
1103 for (const name of result) {
1104 expect(localBindings.has(name)).toBe(true)
1105 }
1106β
1107 // Contract 3: result is deterministic
1108 const result2 = computeSharedBindings({
1109 code,
1110 codeSplitGroupings: defaultCodeSplitGroupings,
1111 })
1112 expect(result).toEqual(result2)
1113 },
1114 )
1115 })
1116})