Skip to content

Commit 5a641d8

Browse files
Sheraffclaude
andauthored
test: cover compiler output validity and edge cases for code splitting, Hydrate, server functions and the route generator (#8629)
* test(router-plugin, start-plugin-core): cover compiler output regressions Add engine-agnostic regression tests for compiler output found while reviewing the compiler migration (#8504). They only use the public compiler entry points and validate emitted code with Vite's Oxc transform/parser (TypeScript erased, parsed as a JS module with semantic checks), so they run unchanged against any compiler implementation. router-plugin: - every emitted code-splitter module stays valid for re-exported imports, partially exported destructuring and anonymous default exports - self-/mutually-referencing side effects stay in the reference module - namespace imports used by `import X = ns.X` and decorator placement before `export` are preserved - React Refresh hoisting keeps closures in scope, hoists the root route component, and declares hoisted components before use start-plugin-core: - self-referencing user code survives client and server compilation - nested and switch-case createServerFn keep provider modules valid - aliased createClientOnlyFn re-exports are transformed in SSR - Hydrate split modules: parent/fallback-only bindings are removed, text children render decoded entities, `'use client'` stays first Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * test: require hoisting and declared bindings in compiler regression tests - The React Refresh ordering test now requires the inline pendingComponent to be hoisted instead of passing when it stays inline, since main hoists it and React Refresh needs a top-level binding. - The self-referencing side-effect tests also assert that each binding the callbacks use is still declared. The module validator does not report references to undeclared names. The Start variant now validates the module. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * test(router-plugin, start-plugin-core, router-generator, react-start-rsc): cover compiler edge cases Engine-agnostic tests through public compiler entry points, passing on main. They cover: - code-splitter module state shared with exported functions, `var` declared inside top-level statements, long method chains, duplicate split keys, split options that read `Route`, route options declared in a variable, re-exports, type-only syntax, private class members, and namespace JSX tags - the code-splitter plugin pipeline: analysis cache keys and eviction, plugin-level `splitBehavior`, config `deleteNodes`, and the non-split HMR plugin for Solid and Vue - the route generator transform with parenthesized call parts, and byte-exact edits after a BOM or astral characters - the Start compiler: dev-mode server function ids, provider directives, handler name versioning, provider export removal, cross-module factory resolution, invalidation, and diagnostic locations - Hydrate children with block-bodied callbacks, self-closing boundaries, captures, split attributes, and the virtual module cache - import-protection exports, member-chain boundaries, source-mapped locations, and executed denied-import rewrites - RSC CSS transform import shapes and argument unwrapping Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * test(start-plugin-core): port Next.js server actions fixtures to createServerFn Translate the scenarios of Next.js's server-actions transform fixtures (crates/next-custom-transforms/tests/fixture/server-actions) to the createServerFn client, SSR caller and provider outputs: captured module bindings, shadowing, destructuring, handler forms, directives, export forms, non-ASCII names and client/server-only code side by side. The destructuring default and computed-key cases pass on main and fail with the Yuku compiler (#8504), which keeps every sibling of a live destructuring and with it a server-only import in the client output. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * test(router-plugin): port Next.js SSG and React Router route-chunk splitting scenarios Translate edge cases from Next.js's SSG transform fixtures and React Router's route-chunks / remove-exports tests into code-splitter coverage: imports used in JSX positions, shadowed names, transitive pruning of every declaration kind, destructurings and multi-declarator statements split across groups, mutually recursive shared helpers, nested-scope dependency analysis, helpers shared with the loader, top-level calls on imports and split chunk source maps. All scenarios already behave correctly; these tests pin them. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * test(start-plugin-core, router-plugin): port Qwik optimizer extraction edge cases Port capture and extraction scenarios from the Qwik optimizer test suite (QwikDev/qwik, packages/optimizer/core/src/test.rs) to the Hydrate split transform, server function extraction and route code splitting. All of them pass with both the Babel and the Yuku compiler. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * test(router-plugin, start-plugin-core): cover real-world compiler shapes Adds regression coverage derived from a differential audit of in-repo examples/e2e apps and open-source TanStack Router/Start apps: - split chunks import exported route-file bindings instead of copying them - declarations and imports only referenced from TypeScript types survive (classic JSX runtime React imports, side-effecting initializers) - TypeScript type and value exports sharing a name compile - file-level JSX pragmas stay in split chunks and Start compiler output - ambient declarations are not imported from the shared module - chained comparisons in plain JavaScript route files keep their operands - real-world route file names go through the code-splitter plugin pipeline Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * test(router-plugin, start-plugin-core): port React Compiler fixture shapes Wrap component bodies adapted from the React Compiler fixture corpus into route files and Start modules: - split route components and Hydrate chunks render like the original for labeled breaks, shadowing catch params and function names, destructuring defaults, getters/computed keys, hoisted functions, optional call chains, tagged templates and classes with static blocks/private fields - server function handlers that read a server-only import through unusual syntax positions keep it off the client - unused locals with side-effectful initializers (hook calls) in shared route modules and Hydrate chunks still run; these fail on the Yuku migration, which removes them Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * test: cover exported route variables in split chunks and JSX pragma forms - Split chunks import exported route-file variables (contexts, stores and caches built from private bindings) from the route module instead of redeclaring them. - The Start compiler keeps JSX pragmas in the Hydrate chunk, line-comment and license-header forms, classic `@jsx` with `@jsxFrag`, and after a `'use client'` directive. Both pass on main and on #8504 after its fixes. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * test(start-plugin-core): port SolidStart directive and Waku allowServer edge cases Translate SolidStart's "use server" directive compiler tests and helpers (type-only import specifiers, rejected server fn positions, captured this/arguments/super/private members, id stability and opacity, Hydrate closure captures) and Waku's allowServer transform tests (dependency pruning, aliasing, default exports, untouched look-alikes, zero-argument factories, trailing comments) into Start compiler coverage for React and Solid. The import-alias namespace test passes on main and fails on the Yuku compiler (#8504), which deletes the aliased namespace. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * test(router-plugin): port React Refresh and solid-refresh scenarios to route HMR Covers which route component shapes React Refresh registers after the HMR transforms (checked with Vite's Oxc React Refresh transform), hook signatures, @refresh reset, generated-name collisions, and the module shape solid-refresh expects (registrable components, @refresh reload/skip, top-level createContext). Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * test(router-plugin, start-plugin-core, react-start-rsc): port @vitejs/plugin-rsc transform edge cases Port scope, hoisting, export-shape, export * and directive scenarios from @vitejs/plugin-rsc's transform tests (vitejs/vite-plugin-react, MIT) to the Start compiler (server fn providers and callers, env-only functions, Hydrate chunks), the route code splitter and the RSC CSS transforms. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * test: port babel-dead-code-elimination and Turbopack tree-shaker scenarios Port dead-code-elimination scenarios (pcattori/babel-dead-code-elimination) and Turbopack tree-shaker analyzer fixtures (vercel/next.js) to the code splitter and the Start compiler: import specifier pruning, initially unused declarations and cycles, SCC removal, write-only bindings, nested patterns with rests and defaults, empty parameter patterns, var declarations nested in top-level statements, import attributes, typeof references, enum IIFEs, shared mutable state and statement order in the provider. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * test(router-plugin): share compiler regression test helpers The regression suites each re-implemented the same plumbing. Move it into `tests/regression-helpers.ts`: - `compileRouteModules` (reference, virtual chunks and shared module, with optional route HMR, Solid target or file name) and `expectValidModules`, previously copied into 12 files - `buildAndRun`, the Vite build-and-run harness copied into 5 files - `createCodeSplitterTransforms` and `transformWithRouteHmrPlugin`, which drive the bundler plugins the way a bundler does - `evaluateModule`, the JSX-to-text module evaluator copied into 3 files No test is added, removed or renamed. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * test(start-plugin-core): share compiler regression test helpers The regression suites each built their own `StartCompiler`, output compiler, Start runtime stubs and `<Hydrate>` chunk loader. Move them into `tests/regression-helpers.ts`: - `createStartCompiler`, `compileFor`, `compileCode` and `compileAll` (client, SSR caller and provider outputs, validated), previously built in 10 files - `importModule`, `callProvider`, `importSources` and `settle`, with one minimal Start runtime instead of four variants - `compileHydrate`, `getChunkParams`, `getChunkIds`, `loadChunk`, `evaluateModule` and `renderChunk`, previously copied into 6 files No test is added, removed or renamed. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * test(react-start-rsc): share the RSC CSS transform compile helper Both RSC CSS transform regression suites defined the same compile helper and a copy of the module validator; move the helper into `tests/regression-helpers.ts` and reuse start-plugin-core's validator. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * test(router-plugin): merge duplicated compiler regression tests Remove tests whose input shape and assertions another suite already covers, folding any unique assertion into the surviving test: - code-splitter-real-world: the two "split chunks share exported route-file bindings" compile checks duplicate code-splitter-exported-bindings (the built-app check stays); "file-level JSX pragmas" duplicates the @jsxImportSource cases of code-splitter-jsx-pragmas, which now also check that Oxc selects the pragma's JSX runtime for every split chunk. - ported-react-compiler-fixtures: "a catch parameter shadowing a module binding" duplicates the plugin-rsc "next to a catch parameter of the same name" case, which now names both sources. - ported-nextjs-ssg: "moves one declarator of a multi-declarator statement into the split chunk" duplicates the React Router "plain declarators" case, which now also asserts where each declarator is declared. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * test(start-plugin-core): merge duplicated compiler regression tests - The SolidStart "local types used by split children are not passed as props" Hydrate test duplicates the Qwik "local types used by the children are not captured as values" test; the Qwik test now also covers JSX type arguments and asserts that no type is passed as a prop. - start-compiler-edge-cases "does not duplicate a directive the module already has" becomes a case of the plugin-rsc "provider module directives" table, which also checks the prologue and module validity. - The single test of aliased-env-only-fns.test.ts moves to the "cross-module factory resolution" tests of start-compiler-edge-cases, where its output is also validated. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * test(router-generator): merge the parenthesized route call transform tests transform-parenthesized.test.ts duplicated the `transform` harness of transform-preservation.test.ts; move its tests there. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * test(router-plugin): keep covering configs without the router plugin Before the code-splitter transforms were shared, the real-world file-name test resolved a Vite config that did not list the router plugin, which covers the early return of the plugin-order check. Let the shared helper take the config's plugins and keep that case. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * test(router-plugin): regroup compiler regression tests by behaviour Dissolve the ported-* and code-splitter edge-case files into behaviour files (dead code, imports/exports, module state, pragmas, route options, scope), drop duplicate cases and vacuous assertions, and replace the five real Vite builds with one. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * test(start-plugin-core): regroup compiler regression tests by behaviour Dissolve the ported-* and start-compiler edge-case files into behaviour files (server fn caller dead code, declaration sites, exports and directives, handler scope, Hydrate captures, factories, user code kept), drop duplicate cases and vacuous assertions, and compile through a single harness. The RSC external-transform scope cases move into compiler.test.ts, replacing react-start-rsc's ported-vite-plugin-rsc.test.tsx. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * test(router-generator): move transform edge cases into transform.test.ts Merge the five parenthesized-call cases into one test next to the existing outer-parens test and fold the remaining preservation cases into transform.test.ts, reusing its makeNode helper. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * test(react-start-rsc): move RSC CSS transform edge cases into rscCssTransform.test.tsx Keep the cases with unique coverage (the @tanstack/react-start-rsc import source, transparent JSX wrappers, non-JSX arguments) next to the existing tests and drop the separate helper, which imported start-plugin-core tests. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * test: keep regression tests valid once known compiler bugs are fixed Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * test: share the build and React Refresh helpers Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * test(start-plugin-core): link Hydrate chunks to their parent however a fix imports it Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
1 parent 30fc108 commit 5a641d8

29 files changed

Lines changed: 6779 additions & 0 deletions

‎packages/react-start-rsc/tests/rscCssTransform.test.tsx‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,4 +161,55 @@ describe('RSC CSS compiler transforms', () => {
161161
detectKindsInCode(code, 'client', { compilerTransforms }),
162162
).toMatchInlineSnapshot(`Set {}`)
163163
})
164+
165+
test('rewrites render APIs imported from @tanstack/react-start-rsc', async () => {
166+
const code = await compileWithRscCssTransform({
167+
code: `
168+
import { renderServerComponent } from '@tanstack/react-start-rsc'
169+
170+
export const renderable = renderServerComponent(<Card />)
171+
`,
172+
})
173+
174+
expect(code).toContain(
175+
'__tanstackStartRscCss: import.meta.viteRsc.loadCss()',
176+
)
177+
})
178+
179+
test.each([
180+
{ wrapped: '(<Card />)', bare: '<Card />' },
181+
{ wrapped: '<Card /> as any', bare: '<Card />' },
182+
{ wrapped: '<Card />!', bare: '<Card />' },
183+
{ wrapped: '(<><Card /></>) satisfies unknown', bare: '<><Card /></>' },
184+
])(
185+
'streams $wrapped like the bare JSX it wraps',
186+
async ({ wrapped, bare }) => {
187+
const compileStream = (element: string) =>
188+
compileWithRscCssTransform({
189+
code: `
190+
import { renderToReadableStream } from '@tanstack/react-start/rsc'
191+
192+
export const stream = renderToReadableStream(${element})
193+
`,
194+
})
195+
196+
const bareCode = await compileStream(bare)
197+
expect(bareCode).toContain('import.meta.viteRsc.loadCss()')
198+
expect(await compileStream(wrapped)).toBe(bareCode)
199+
},
200+
)
201+
202+
test('does not stream JSX that is not the whole argument', async () => {
203+
const code = await compileWithRscCssTransform({
204+
code: `
205+
import { renderToReadableStream } from '@tanstack/react-start/rsc'
206+
207+
export const conditional = renderToReadableStream(flag ? <A /> : <B />)
208+
export const spread = renderToReadableStream(...args)
209+
`,
210+
})
211+
212+
expect(code).toContain('renderToReadableStream(...args)')
213+
expect(code).not.toContain('loadCss')
214+
})
164215
})

‎packages/router-generator/tests/transform.test.ts‎

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,35 @@ function makeNode(
1313
}
1414
}
1515

16+
function transformToNewRoute(source: string, node = makeNode()) {
17+
return transform({
18+
source,
19+
ctx: { target: 'react', routeId: '/new', lazy: false },
20+
node,
21+
})
22+
}
23+
1624
describe('transform', () => {
25+
it('reads and rewrites the route constructor, id and options through parentheses', () => {
26+
const node = makeNode()
27+
const result = transformToNewRoute(
28+
[
29+
"import { createLazyFileRoute } from '@tanstack/react-router'",
30+
"export const Route = (createLazyFileRoute)(('/old'))(({ component: Page, server: {} }))",
31+
].join('\n'),
32+
node,
33+
)
34+
35+
expect(result).toEqual({
36+
result: 'modified',
37+
output: [
38+
"import { createFileRoute } from '@tanstack/react-router'",
39+
"export const Route = (createFileRoute)(('/new'))(({ component: Page, server: {} }))",
40+
].join('\n'),
41+
})
42+
expect(node.createFileRouteProps).toEqual(new Set(['component', 'server']))
43+
})
44+
1745
it('updates parenthesized route calls without changing their surrounding source', () => {
1846
const result = transform({
1947
source:
@@ -535,4 +563,95 @@ describe('transform', () => {
535563
)
536564
expect(result.output).not.toContain('createLazyFileRoute')
537565
})
566+
567+
// The recorded option keys drive prerendering and server-only route pruning.
568+
it('records identifier and string-literal option keys, not computed or spread ones', () => {
569+
const node = makeNode()
570+
const result = transformToNewRoute(
571+
[
572+
"import { createFileRoute } from '@tanstack/react-router'",
573+
"export const Route = createFileRoute('/new')({ 'component': Page, [key]: load, ...rest, server: {} })",
574+
].join('\n'),
575+
node,
576+
)
577+
578+
expect(result).toEqual({ result: 'not-modified' })
579+
expect(node.createFileRouteProps).toEqual(new Set(['component', 'server']))
580+
})
581+
})
582+
583+
// The generator writes its output back over the user's route file, so every
584+
// byte outside the route id and the router import must survive unchanged.
585+
describe('transform preserves the rest of the route file', () => {
586+
it('edits the right spans after a BOM and astral characters', () => {
587+
const result = transformToNewRoute(
588+
[
589+
'\uFEFF// 😀',
590+
"import { createLazyFileRoute } from '@tanstack/react-router'",
591+
"import { createFileRoute } from '@tanstack/react-router'",
592+
"export const Route = createFileRoute(/* 🚀 */ '/old')({})",
593+
].join('\n'),
594+
)
595+
596+
expect(result).toEqual({
597+
result: 'modified',
598+
output: [
599+
'\uFEFF// 😀',
600+
"import { createFileRoute } from '@tanstack/react-router'",
601+
"export const Route = createFileRoute(/* 🚀 */ '/new')({})",
602+
].join('\n'),
603+
})
604+
})
605+
606+
it.each([
607+
{
608+
name: 'a default import',
609+
imports: "import Router from '@tanstack/react-router'",
610+
expected:
611+
"import Router, { createFileRoute } from '@tanstack/react-router'",
612+
},
613+
{
614+
name: 'an aliased import of the constructor',
615+
imports:
616+
"import { createFileRoute as cfr } from '@tanstack/react-router'",
617+
expected:
618+
"import { createFileRoute as cfr, createFileRoute } from '@tanstack/react-router'",
619+
},
620+
{
621+
// The constructor goes into the named import, never the namespace one.
622+
name: 'a namespace import',
623+
imports: [
624+
"import * as Router from '@tanstack/react-router'",
625+
"import { Link } from '@tanstack/react-router'",
626+
].join('\n'),
627+
expected: [
628+
"import * as Router from '@tanstack/react-router'",
629+
"import { Link, createFileRoute } from '@tanstack/react-router'",
630+
].join('\n'),
631+
},
632+
])('adds the missing constructor next to $name', ({ imports, expected }) => {
633+
const route = "export const Route = createFileRoute('/old')({})"
634+
635+
expect(transformToNewRoute(`${imports}\n${route}`)).toEqual({
636+
result: 'modified',
637+
output: `${expected}\n${route.replace('/old', '/new')}`,
638+
})
639+
})
640+
641+
it('updates only the Route declarator of a multi-declarator export', () => {
642+
const result = transformToNewRoute(
643+
[
644+
"import { createFileRoute } from '@tanstack/react-router'",
645+
"export const Route = createFileRoute('/old')({}), path = '/old'",
646+
].join('\n'),
647+
)
648+
649+
expect(result).toEqual({
650+
result: 'modified',
651+
output: [
652+
"import { createFileRoute } from '@tanstack/react-router'",
653+
"export const Route = createFileRoute('/new')({}), path = '/old'",
654+
].join('\n'),
655+
})
656+
})
538657
})

0 commit comments

Comments
 (0)