From f1a4973d41dcd552b9663964b1b06e019c42b517 Mon Sep 17 00:00:00 2001 From: MoonBrillante <32852571+MoonBrillante@users.noreply.github.com> Date: Mon, 13 Apr 2026 23:29:07 +0200 Subject: [PATCH 001/604] fix(docs): correct server function name in example (#7173) --- docs/start/framework/react/guide/server-functions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/start/framework/react/guide/server-functions.md b/docs/start/framework/react/guide/server-functions.md index fb843a501c..3844b205ab 100644 --- a/docs/start/framework/react/guide/server-functions.md +++ b/docs/start/framework/react/guide/server-functions.md @@ -52,7 +52,7 @@ Call server functions from: ```tsx // In a route loader export const Route = createFileRoute('/posts')({ - loader: () => getPosts(), + loader: () => getServerPosts(), }) // In a component From c5ad32936f6adcca0c56474677b73b212498443b Mon Sep 17 00:00:00 2001 From: Manuel Schiller Date: Tue, 14 Apr 2026 00:48:18 +0200 Subject: [PATCH 002/604] fix react server exports for start and react-router (#7183) Co-authored-by: nx-cloud[bot] <71083854+nx-cloud[bot]@users.noreply.github.com> --- .changeset/neat-melons-worry.md | 7 +++ e2e/react-start/rsc/src/routeTree.gen.ts | 42 ++++++++++++++++ e2e/react-start/rsc/src/routes/__root.tsx | 16 ++++++ e2e/react-start/rsc/src/routes/index.tsx | 14 ++++++ .../rsc/src/routes/rsc-server-not-found.tsx | 50 +++++++++++++++++++ .../rsc/src/routes/rsc-server-redirect.tsx | 26 ++++++++++ .../rsc/tests/rsc-server-not-found.spec.ts | 47 +++++++++++++++++ .../rsc/tests/rsc-server-redirect.spec.ts | 27 ++++++++++ packages/react-router/package.json | 4 ++ packages/react-router/src/index.rsc.ts | 11 ++++ packages/react-router/vite.config.ts | 1 + 11 files changed, 245 insertions(+) create mode 100644 .changeset/neat-melons-worry.md create mode 100644 e2e/react-start/rsc/src/routes/rsc-server-not-found.tsx create mode 100644 e2e/react-start/rsc/src/routes/rsc-server-redirect.tsx create mode 100644 e2e/react-start/rsc/tests/rsc-server-not-found.spec.ts create mode 100644 e2e/react-start/rsc/tests/rsc-server-redirect.spec.ts create mode 100644 packages/react-router/src/index.rsc.ts diff --git a/.changeset/neat-melons-worry.md b/.changeset/neat-melons-worry.md new file mode 100644 index 0000000000..d9148ae10d --- /dev/null +++ b/.changeset/neat-melons-worry.md @@ -0,0 +1,7 @@ +--- +'@tanstack/react-router': patch +--- + +Fix React Server Component imports from `@tanstack/react-router` by adding a `react-server` root export that preserves the normal API surface while resolving `notFound` and `redirect` from a server-safe entry. + +This fixes RSC routes that throw `notFound()` or `redirect()` from server functions so they behave correctly during SSR and client navigation. diff --git a/e2e/react-start/rsc/src/routeTree.gen.ts b/e2e/react-start/rsc/src/routeTree.gen.ts index d5074d36e0..c06c950ea2 100644 --- a/e2e/react-start/rsc/src/routeTree.gen.ts +++ b/e2e/react-start/rsc/src/routeTree.gen.ts @@ -19,6 +19,8 @@ import { Route as RscSsrFalseRouteImport } from './routes/rsc-ssr-false' import { Route as RscSsrDataOnlyRouteImport } from './routes/rsc-ssr-data-only' import { Route as RscSlotsRouteImport } from './routes/rsc-slots' import { Route as RscSlotJsxArgsRouteImport } from './routes/rsc-slot-jsx-args' +import { Route as RscServerRedirectRouteImport } from './routes/rsc-server-redirect' +import { Route as RscServerNotFoundRouteImport } from './routes/rsc-server-not-found' import { Route as RscRequestHeadersRouteImport } from './routes/rsc-request-headers' import { Route as RscReactCacheRouteImport } from './routes/rsc-react-cache' import { Route as RscParallelRouteImport } from './routes/rsc-parallel' @@ -103,6 +105,16 @@ const RscSlotJsxArgsRoute = RscSlotJsxArgsRouteImport.update({ path: '/rsc-slot-jsx-args', getParentRoute: () => rootRouteImport, } as any) +const RscServerRedirectRoute = RscServerRedirectRouteImport.update({ + id: '/rsc-server-redirect', + path: '/rsc-server-redirect', + getParentRoute: () => rootRouteImport, +} as any) +const RscServerNotFoundRoute = RscServerNotFoundRouteImport.update({ + id: '/rsc-server-not-found', + path: '/rsc-server-not-found', + getParentRoute: () => rootRouteImport, +} as any) const RscRequestHeadersRoute = RscRequestHeadersRouteImport.update({ id: '/rsc-request-headers', path: '/rsc-request-headers', @@ -298,6 +310,8 @@ export interface FileRoutesByFullPath { '/rsc-parallel': typeof RscParallelRoute '/rsc-react-cache': typeof RscReactCacheRoute '/rsc-request-headers': typeof RscRequestHeadersRoute + '/rsc-server-not-found': typeof RscServerNotFoundRoute + '/rsc-server-redirect': typeof RscServerRedirectRoute '/rsc-slot-jsx-args': typeof RscSlotJsxArgsRoute '/rsc-slots': typeof RscSlotsRoute '/rsc-ssr-data-only': typeof RscSsrDataOnlyRoute @@ -343,6 +357,8 @@ export interface FileRoutesByTo { '/rsc-parallel': typeof RscParallelRoute '/rsc-react-cache': typeof RscReactCacheRoute '/rsc-request-headers': typeof RscRequestHeadersRoute + '/rsc-server-not-found': typeof RscServerNotFoundRoute + '/rsc-server-redirect': typeof RscServerRedirectRoute '/rsc-slot-jsx-args': typeof RscSlotJsxArgsRoute '/rsc-slots': typeof RscSlotsRoute '/rsc-ssr-data-only': typeof RscSsrDataOnlyRoute @@ -389,6 +405,8 @@ export interface FileRoutesById { '/rsc-parallel': typeof RscParallelRoute '/rsc-react-cache': typeof RscReactCacheRoute '/rsc-request-headers': typeof RscRequestHeadersRoute + '/rsc-server-not-found': typeof RscServerNotFoundRoute + '/rsc-server-redirect': typeof RscServerRedirectRoute '/rsc-slot-jsx-args': typeof RscSlotJsxArgsRoute '/rsc-slots': typeof RscSlotsRoute '/rsc-ssr-data-only': typeof RscSsrDataOnlyRoute @@ -436,6 +454,8 @@ export interface FileRouteTypes { | '/rsc-parallel' | '/rsc-react-cache' | '/rsc-request-headers' + | '/rsc-server-not-found' + | '/rsc-server-redirect' | '/rsc-slot-jsx-args' | '/rsc-slots' | '/rsc-ssr-data-only' @@ -481,6 +501,8 @@ export interface FileRouteTypes { | '/rsc-parallel' | '/rsc-react-cache' | '/rsc-request-headers' + | '/rsc-server-not-found' + | '/rsc-server-redirect' | '/rsc-slot-jsx-args' | '/rsc-slots' | '/rsc-ssr-data-only' @@ -526,6 +548,8 @@ export interface FileRouteTypes { | '/rsc-parallel' | '/rsc-react-cache' | '/rsc-request-headers' + | '/rsc-server-not-found' + | '/rsc-server-redirect' | '/rsc-slot-jsx-args' | '/rsc-slots' | '/rsc-ssr-data-only' @@ -572,6 +596,8 @@ export interface RootRouteChildren { RscParallelRoute: typeof RscParallelRoute RscReactCacheRoute: typeof RscReactCacheRoute RscRequestHeadersRoute: typeof RscRequestHeadersRoute + RscServerNotFoundRoute: typeof RscServerNotFoundRoute + RscServerRedirectRoute: typeof RscServerRedirectRoute RscSlotJsxArgsRoute: typeof RscSlotJsxArgsRoute RscSlotsRoute: typeof RscSlotsRoute RscSsrDataOnlyRoute: typeof RscSsrDataOnlyRoute @@ -661,6 +687,20 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof RscSlotJsxArgsRouteImport parentRoute: typeof rootRouteImport } + '/rsc-server-redirect': { + id: '/rsc-server-redirect' + path: '/rsc-server-redirect' + fullPath: '/rsc-server-redirect' + preLoaderRoute: typeof RscServerRedirectRouteImport + parentRoute: typeof rootRouteImport + } + '/rsc-server-not-found': { + id: '/rsc-server-not-found' + path: '/rsc-server-not-found' + fullPath: '/rsc-server-not-found' + preLoaderRoute: typeof RscServerNotFoundRouteImport + parentRoute: typeof rootRouteImport + } '/rsc-request-headers': { id: '/rsc-request-headers' path: '/rsc-request-headers' @@ -924,6 +964,8 @@ const rootRouteChildren: RootRouteChildren = { RscParallelRoute: RscParallelRoute, RscReactCacheRoute: RscReactCacheRoute, RscRequestHeadersRoute: RscRequestHeadersRoute, + RscServerNotFoundRoute: RscServerNotFoundRoute, + RscServerRedirectRoute: RscServerRedirectRoute, RscSlotJsxArgsRoute: RscSlotJsxArgsRoute, RscSlotsRoute: RscSlotsRoute, RscSsrDataOnlyRoute: RscSsrDataOnlyRoute, diff --git a/e2e/react-start/rsc/src/routes/__root.tsx b/e2e/react-start/rsc/src/routes/__root.tsx index ac169e7e94..9ebb559527 100644 --- a/e2e/react-start/rsc/src/routes/__root.tsx +++ b/e2e/react-start/rsc/src/routes/__root.tsx @@ -312,6 +312,22 @@ function RootComponent() { > Request Headers + + Server Not Found + + + Server Redirect + { + throw notFound() +}) + +export const Route = createFileRoute('/rsc-server-not-found')({ + loader: async () => { + await getMissingResource() + }, + component: RscServerNotFoundComponent, + notFoundComponent: RscServerNotFoundBoundary, +}) + +function RscServerNotFoundComponent() { + return ( +
+

+ RSC Server Not Found +

+
+ ) +} + +function RscServerNotFoundBoundary() { + return ( +
+

+ RSC Server Function Not Found +

+

+ The server function threw `notFound()` and the route-level not found + boundary rendered instead of crashing. +

+ + Back home + +
+ ) +} diff --git a/e2e/react-start/rsc/src/routes/rsc-server-redirect.tsx b/e2e/react-start/rsc/src/routes/rsc-server-redirect.tsx new file mode 100644 index 0000000000..a8e14f6c93 --- /dev/null +++ b/e2e/react-start/rsc/src/routes/rsc-server-redirect.tsx @@ -0,0 +1,26 @@ +import { createFileRoute, redirect } from '@tanstack/react-router' +import { createServerFn } from '@tanstack/react-start' +import { pageStyles } from '~/utils/styles' + +const redirectToBasic = createServerFn({ + method: 'GET', +}).handler(async () => { + throw redirect({ to: '/rsc-basic' }) +}) + +export const Route = createFileRoute('/rsc-server-redirect')({ + loader: async () => { + await redirectToBasic() + }, + component: RscServerRedirectComponent, +}) + +function RscServerRedirectComponent() { + return ( +
+

+ RSC Server Redirect +

+
+ ) +} diff --git a/e2e/react-start/rsc/tests/rsc-server-not-found.spec.ts b/e2e/react-start/rsc/tests/rsc-server-not-found.spec.ts new file mode 100644 index 0000000000..c760b40140 --- /dev/null +++ b/e2e/react-start/rsc/tests/rsc-server-not-found.spec.ts @@ -0,0 +1,47 @@ +import { expect } from '@playwright/test' +import { test } from '@tanstack/router-e2e-utils' + +test.describe('RSC Server Not Found Tests', () => { + test.use({ + whitelistErrors: [ + 'Failed to load resource: the server responded with a status of 404', + ], + }) + + test('SSR renders the route notFoundComponent when a server function throws notFound', async ({ + page, + }) => { + const response = await page.goto('/rsc-server-not-found') + await page.waitForURL('/rsc-server-not-found') + + expect(response?.status()).toBe(404) + + await expect( + page.getByTestId('rsc-server-not-found-boundary'), + ).toBeVisible() + await expect(page.getByTestId('rsc-server-not-found-heading')).toHaveText( + 'RSC Server Function Not Found', + ) + await expect( + page.getByTestId('rsc-server-not-found-message'), + ).toContainText('server function threw `notFound()`') + }) + + test('client navigation renders the route notFoundComponent when a server function throws notFound', async ({ + page, + }) => { + await page.goto('/') + await page.waitForURL('/') + await expect(page.getByTestId('app-hydrated')).toHaveText('hydrated') + + await page.getByTestId('nav-server-not-found').click() + await page.waitForURL('/rsc-server-not-found') + + await expect( + page.getByTestId('rsc-server-not-found-boundary'), + ).toBeVisible() + await expect(page.getByTestId('rsc-server-not-found-heading')).toHaveText( + 'RSC Server Function Not Found', + ) + }) +}) diff --git a/e2e/react-start/rsc/tests/rsc-server-redirect.spec.ts b/e2e/react-start/rsc/tests/rsc-server-redirect.spec.ts new file mode 100644 index 0000000000..da0a84fb94 --- /dev/null +++ b/e2e/react-start/rsc/tests/rsc-server-redirect.spec.ts @@ -0,0 +1,27 @@ +import { expect } from '@playwright/test' +import { test } from '@tanstack/router-e2e-utils' + +test.describe('RSC Server Redirect Tests', () => { + test('SSR follows route redirect when a server function throws redirect', async ({ + page, + }) => { + const response = await page.goto('/rsc-server-redirect') + await page.waitForURL('/rsc-basic') + + expect(response?.status()).toBe(200) + await expect(page.getByTestId('rsc-basic-content')).toBeVisible() + }) + + test('client navigation follows route redirect when a server function throws redirect', async ({ + page, + }) => { + await page.goto('/') + await page.waitForURL('/') + await expect(page.getByTestId('app-hydrated')).toHaveText('hydrated') + + await page.getByTestId('nav-server-redirect').click() + await page.waitForURL('/rsc-basic') + + await expect(page.getByTestId('rsc-basic-content')).toBeVisible() + }) +}) diff --git a/packages/react-router/package.json b/packages/react-router/package.json index 20eaf383bb..63e72a4944 100644 --- a/packages/react-router/package.json +++ b/packages/react-router/package.json @@ -48,6 +48,10 @@ "module": "dist/esm/index.js", "exports": { ".": { + "react-server": { + "types": "./dist/esm/index.rsc.d.ts", + "default": "./dist/esm/index.rsc.js" + }, "import": { "types": "./dist/esm/index.d.ts", "development": "./dist/esm/index.dev.js", diff --git a/packages/react-router/src/index.rsc.ts b/packages/react-router/src/index.rsc.ts new file mode 100644 index 0000000000..d5baf7e952 --- /dev/null +++ b/packages/react-router/src/index.rsc.ts @@ -0,0 +1,11 @@ +export * from './index' + +export { + notFound, + isNotFound, + redirect, + isRedirect, + rootRouteId, +} from '@tanstack/router-core' + +export type { NotFoundError } from '@tanstack/router-core' diff --git a/packages/react-router/vite.config.ts b/packages/react-router/vite.config.ts index f21400df28..0eb9e3c77e 100644 --- a/packages/react-router/vite.config.ts +++ b/packages/react-router/vite.config.ts @@ -28,6 +28,7 @@ export default mergeConfig( tsconfigPath: './tsconfig.build.json', entry: [ './src/index.tsx', + './src/index.rsc.ts', './src/index.dev.tsx', './src/ssr/client.ts', './src/ssr/server.ts', From c3d525924d0ae4f36140c97d63df187aa527728d Mon Sep 17 00:00:00 2001 From: Manuel Schiller Date: Tue, 14 Apr 2026 01:07:14 +0200 Subject: [PATCH 003/604] chore: stabilize tests (#7185) --- .../rsc/src/routes/rsc-ssr-false.tsx | 7 +- .../rsc/tests/rsc-ssr-false.spec.ts | 96 ++++++++++--------- 2 files changed, 57 insertions(+), 46 deletions(-) diff --git a/e2e/react-start/rsc/src/routes/rsc-ssr-false.tsx b/e2e/react-start/rsc/src/routes/rsc-ssr-false.tsx index c0df96d9b8..1f81248f87 100644 --- a/e2e/react-start/rsc/src/routes/rsc-ssr-false.tsx +++ b/e2e/react-start/rsc/src/routes/rsc-ssr-false.tsx @@ -298,6 +298,7 @@ function RscSsrFalseComponent() { const canvasRef = React.useRef(null) const hasMounted = React.useRef(false) + const isDrawingRef = React.useRef(false) const [isDrawing, setIsDrawing] = React.useState(false) const [brushSize, setBrushSize] = React.useState(tools.brushSizes[1]) // Initialize color from localStorage if available, otherwise use default @@ -362,6 +363,7 @@ function RscSsrFalseComponent() { const canvas = canvasRef.current if (!canvas) return + isDrawingRef.current = true setIsDrawing(true) const rect = canvas.getBoundingClientRect() const ctx = canvas.getContext('2d') @@ -372,7 +374,7 @@ function RscSsrFalseComponent() { } const draw = (e: React.MouseEvent) => { - if (!isDrawing) return + if (!isDrawingRef.current) return const canvas = canvasRef.current if (!canvas) return @@ -389,7 +391,8 @@ function RscSsrFalseComponent() { } const stopDrawing = () => { - if (isDrawing) { + if (isDrawingRef.current) { + isDrawingRef.current = false setStrokeCount((c) => { const newCount = c + 1 // Save stroke count to localStorage diff --git a/e2e/react-start/rsc/tests/rsc-ssr-false.spec.ts b/e2e/react-start/rsc/tests/rsc-ssr-false.spec.ts index 7c730dad8e..71490dd6b6 100644 --- a/e2e/react-start/rsc/tests/rsc-ssr-false.spec.ts +++ b/e2e/react-start/rsc/tests/rsc-ssr-false.spec.ts @@ -1,6 +1,11 @@ import { expect } from '@playwright/test' import { test } from '@tanstack/router-e2e-utils' +type Point = { + x: number + y: number +} + // This warning can occur during rapid navigation/hydration cycles and doesn't affect functionality // It's a React development mode warning about async state updates during mounting test.use({ @@ -20,6 +25,31 @@ test.describe('RSC SSR False Tests - Both loader and component on client', () => }) } + async function drawStroke(page: any, start: Point, end: Point) { + await page.getByTestId('drawing-canvas').evaluate( + ( + canvas: HTMLCanvasElement, + { start, end }: { start: Point; end: Point }, + ) => { + const rect = canvas.getBoundingClientRect() + + const createMouseEvent = (type: string, point: Point) => + new MouseEvent(type, { + bubbles: true, + cancelable: true, + clientX: rect.left + point.x, + clientY: rect.top + point.y, + }) + + canvas.dispatchEvent(createMouseEvent('mousedown', start)) + canvas.dispatchEvent(createMouseEvent('mousemove', start)) + canvas.dispatchEvent(createMouseEvent('mousemove', end)) + canvas.dispatchEvent(createMouseEvent('mouseup', end)) + }, + { start, end }, + ) + } + test('Page renders with RSC content after initial client load', async ({ page, }) => { @@ -117,33 +147,21 @@ test.describe('RSC SSR False Tests - Both loader and component on client', () => await expect(page.getByTestId('canvas-container')).toBeVisible() - const canvas = page.getByTestId('drawing-canvas') - const box = await canvas.boundingBox() - expect(box).not.toBeNull() - // Draw a stroke - await page.mouse.move(box!.x + 50, box!.y + 50) - await page.mouse.down() - await page.mouse.move(box!.x + 150, box!.y + 100) - await page.mouse.up() + await drawStroke(page, { x: 50, y: 50 }, { x: 150, y: 100 }) // Verify stroke count increased - const containerText = await page - .getByTestId('canvas-container') - .textContent() - expect(containerText).toContain('Strokes: 1') + await expect(page.getByTestId('canvas-container')).toContainText( + 'Strokes: 1', + ) // Draw another stroke - await page.mouse.move(box!.x + 100, box!.y + 30) - await page.mouse.down() - await page.mouse.move(box!.x + 200, box!.y + 80) - await page.mouse.up() + await drawStroke(page, { x: 100, y: 30 }, { x: 200, y: 80 }) // Verify stroke count increased again - const containerText2 = await page - .getByTestId('canvas-container') - .textContent() - expect(containerText2).toContain('Strokes: 2') + await expect(page.getByTestId('canvas-container')).toContainText( + 'Strokes: 2', + ) }) test('Clear canvas button works', async ({ page }) => { @@ -153,26 +171,21 @@ test.describe('RSC SSR False Tests - Both loader and component on client', () => await expect(page.getByTestId('canvas-container')).toBeVisible() - const canvas = page.getByTestId('drawing-canvas') - const box = await canvas.boundingBox() - expect(box).not.toBeNull() - // Draw a stroke - await page.mouse.move(box!.x + 50, box!.y + 50) - await page.mouse.down() - await page.mouse.move(box!.x + 150, box!.y + 100) - await page.mouse.up() + await drawStroke(page, { x: 50, y: 50 }, { x: 150, y: 100 }) // Verify stroke was recorded - let containerText = await page.getByTestId('canvas-container').textContent() - expect(containerText).toContain('Strokes: 1') + await expect(page.getByTestId('canvas-container')).toContainText( + 'Strokes: 1', + ) // Clear canvas await page.getByTestId('clear-canvas-btn').click() // Verify stroke count reset - containerText = await page.getByTestId('canvas-container').textContent() - expect(containerText).toContain('Strokes: 0') + await expect(page.getByTestId('canvas-container')).toContainText( + 'Strokes: 0', + ) }) test('Save controls are visible and functional', async ({ page }) => { @@ -313,18 +326,12 @@ test.describe('RSC SSR False Tests - Both loader and component on client', () => await page.getByTestId('clear-canvas-btn').click() // Draw something - const canvas = page.getByTestId('drawing-canvas') - const box = await canvas.boundingBox() - expect(box).not.toBeNull() - - await page.mouse.move(box!.x + 50, box!.y + 50) - await page.mouse.down() - await page.mouse.move(box!.x + 150, box!.y + 100) - await page.mouse.up() + await drawStroke(page, { x: 50, y: 50 }, { x: 150, y: 100 }) // Verify stroke was counted - let containerText = await page.getByTestId('canvas-container').textContent() - expect(containerText).toContain('Strokes: 1') + await expect(page.getByTestId('canvas-container')).toContainText( + 'Strokes: 1', + ) // Reload page await page.reload() @@ -340,7 +347,8 @@ test.describe('RSC SSR False Tests - Both loader and component on client', () => ) // Verify stroke count was also restored - containerText = await page.getByTestId('canvas-container').textContent() - expect(containerText).toContain('Strokes: 1') + await expect(page.getByTestId('canvas-container')).toContainText( + 'Strokes: 1', + ) }) }) From 73cd5699ac470d566fb06982f15a9862d25ca5c7 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Mon, 13 Apr 2026 23:09:50 +0000 Subject: [PATCH 004/604] ci: changeset release --- .changeset/neat-melons-worry.md | 7 ------- .../react/authenticated-routes-firebase/package.json | 2 +- examples/react/authenticated-routes/package.json | 2 +- .../react/basic-default-search-params/package.json | 2 +- examples/react/basic-devtools-panel/package.json | 2 +- examples/react/basic-file-based/package.json | 2 +- examples/react/basic-non-nested-devtools/package.json | 2 +- .../react/basic-react-query-file-based/package.json | 2 +- examples/react/basic-react-query/package.json | 2 +- examples/react/basic-ssr-file-based/package.json | 2 +- .../react/basic-ssr-streaming-file-based/package.json | 2 +- examples/react/basic-virtual-file-based/package.json | 2 +- .../react/basic-virtual-inside-file-based/package.json | 2 +- examples/react/basic/package.json | 2 +- examples/react/deferred-data/package.json | 2 +- examples/react/i18n-paraglide/package.json | 2 +- examples/react/kitchen-sink-file-based/package.json | 2 +- .../kitchen-sink-react-query-file-based/package.json | 2 +- examples/react/kitchen-sink-react-query/package.json | 2 +- examples/react/kitchen-sink/package.json | 2 +- examples/react/large-file-based/package.json | 2 +- examples/react/location-masking/package.json | 2 +- examples/react/navigation-blocking/package.json | 2 +- .../react/quickstart-esbuild-file-based/package.json | 2 +- examples/react/quickstart-file-based/package.json | 2 +- .../react/quickstart-rspack-file-based/package.json | 2 +- .../react/quickstart-webpack-file-based/package.json | 2 +- examples/react/quickstart/package.json | 2 +- .../react/router-monorepo-react-query/package.json | 2 +- .../packages/router/package.json | 2 +- .../react/router-monorepo-simple-lazy/package.json | 2 +- .../packages/router/package.json | 2 +- examples/react/router-monorepo-simple/package.json | 2 +- .../packages/router/package.json | 2 +- examples/react/scroll-restoration/package.json | 2 +- examples/react/search-validator-adapters/package.json | 2 +- examples/react/start-bare/package.json | 4 ++-- examples/react/start-basic-auth/package.json | 4 ++-- examples/react/start-basic-authjs/package.json | 4 ++-- examples/react/start-basic-cloudflare/package.json | 4 ++-- examples/react/start-basic-react-query/package.json | 4 ++-- examples/react/start-basic-static/package.json | 4 ++-- examples/react/start-basic/package.json | 4 ++-- examples/react/start-bun/package.json | 4 ++-- examples/react/start-clerk-basic/package.json | 4 ++-- examples/react/start-convex-trellaux/package.json | 4 ++-- examples/react/start-counter/package.json | 4 ++-- examples/react/start-i18n-paraglide/package.json | 4 ++-- examples/react/start-large/package.json | 4 ++-- examples/react/start-material-ui/package.json | 4 ++-- examples/react/start-rscs/package.json | 4 ++-- .../package.json | 4 ++-- examples/react/start-supabase-basic/package.json | 4 ++-- examples/react/start-tailwind-v4/package.json | 4 ++-- examples/react/start-trellaux/package.json | 4 ++-- examples/react/start-workos/package.json | 4 ++-- examples/react/view-transitions/package.json | 2 +- examples/react/with-framer-motion/package.json | 2 +- examples/react/with-trpc-react-query/package.json | 2 +- examples/react/with-trpc/package.json | 2 +- packages/react-router/CHANGELOG.md | 8 ++++++++ packages/react-router/package.json | 2 +- packages/react-start-client/CHANGELOG.md | 7 +++++++ packages/react-start-client/package.json | 2 +- packages/react-start-rsc/CHANGELOG.md | 8 ++++++++ packages/react-start-rsc/package.json | 2 +- packages/react-start-server/CHANGELOG.md | 7 +++++++ packages/react-start-server/package.json | 2 +- packages/react-start/CHANGELOG.md | 10 ++++++++++ packages/react-start/package.json | 2 +- 70 files changed, 124 insertions(+), 91 deletions(-) delete mode 100644 .changeset/neat-melons-worry.md diff --git a/.changeset/neat-melons-worry.md b/.changeset/neat-melons-worry.md deleted file mode 100644 index d9148ae10d..0000000000 --- a/.changeset/neat-melons-worry.md +++ /dev/null @@ -1,7 +0,0 @@ ---- -'@tanstack/react-router': patch ---- - -Fix React Server Component imports from `@tanstack/react-router` by adding a `react-server` root export that preserves the normal API surface while resolving `notFound` and `redirect` from a server-safe entry. - -This fixes RSC routes that throw `notFound()` or `redirect()` from server functions so they behave correctly during SSR and client navigation. diff --git a/examples/react/authenticated-routes-firebase/package.json b/examples/react/authenticated-routes-firebase/package.json index bf4a82d319..0456cfc1e1 100644 --- a/examples/react/authenticated-routes-firebase/package.json +++ b/examples/react/authenticated-routes-firebase/package.json @@ -10,7 +10,7 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", "@tanstack/router-plugin": "^1.167.21", "firebase": "^11.4.0", diff --git a/examples/react/authenticated-routes/package.json b/examples/react/authenticated-routes/package.json index 7e58cbb842..86d7d48927 100644 --- a/examples/react/authenticated-routes/package.json +++ b/examples/react/authenticated-routes/package.json @@ -10,7 +10,7 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", "@tanstack/router-plugin": "^1.167.21", "react": "^19.0.0", diff --git a/examples/react/basic-default-search-params/package.json b/examples/react/basic-default-search-params/package.json index 75ec36fc6d..91d5a9193e 100644 --- a/examples/react/basic-default-search-params/package.json +++ b/examples/react/basic-default-search-params/package.json @@ -11,7 +11,7 @@ "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/react-query": "^5.90.0", - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/examples/react/basic-devtools-panel/package.json b/examples/react/basic-devtools-panel/package.json index 117d935373..7344200aa3 100644 --- a/examples/react/basic-devtools-panel/package.json +++ b/examples/react/basic-devtools-panel/package.json @@ -11,7 +11,7 @@ "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/react-query-devtools": "^5.67.2", - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/examples/react/basic-file-based/package.json b/examples/react/basic-file-based/package.json index 0f8fc59389..f6f34943e7 100644 --- a/examples/react/basic-file-based/package.json +++ b/examples/react/basic-file-based/package.json @@ -10,7 +10,7 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", "@tanstack/router-plugin": "^1.167.21", "react": "^19.0.0", diff --git a/examples/react/basic-non-nested-devtools/package.json b/examples/react/basic-non-nested-devtools/package.json index 38fc1e65e0..0ffbda985e 100644 --- a/examples/react/basic-non-nested-devtools/package.json +++ b/examples/react/basic-non-nested-devtools/package.json @@ -10,7 +10,7 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/examples/react/basic-react-query-file-based/package.json b/examples/react/basic-react-query-file-based/package.json index 1b944d8874..7207e32aef 100644 --- a/examples/react/basic-react-query-file-based/package.json +++ b/examples/react/basic-react-query-file-based/package.json @@ -12,7 +12,7 @@ "@tailwindcss/vite": "^4.2.2", "@tanstack/react-query": "^5.90.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", "@tanstack/router-plugin": "^1.167.21", "react": "^19.0.0", diff --git a/examples/react/basic-react-query/package.json b/examples/react/basic-react-query/package.json index 8828bf5504..5d7a929042 100644 --- a/examples/react/basic-react-query/package.json +++ b/examples/react/basic-react-query/package.json @@ -12,7 +12,7 @@ "@tailwindcss/vite": "^4.2.2", "@tanstack/react-query": "^5.90.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/examples/react/basic-ssr-file-based/package.json b/examples/react/basic-ssr-file-based/package.json index 609205f9d5..d51fbc4736 100644 --- a/examples/react/basic-ssr-file-based/package.json +++ b/examples/react/basic-ssr-file-based/package.json @@ -11,7 +11,7 @@ "debug": "node --inspect-brk server" }, "dependencies": { - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/router-plugin": "^1.167.21", "compression": "^1.8.0", "express": "^4.21.2", diff --git a/examples/react/basic-ssr-streaming-file-based/package.json b/examples/react/basic-ssr-streaming-file-based/package.json index 3608c414ec..5540b2e42c 100644 --- a/examples/react/basic-ssr-streaming-file-based/package.json +++ b/examples/react/basic-ssr-streaming-file-based/package.json @@ -11,7 +11,7 @@ "debug": "node --inspect-brk server" }, "dependencies": { - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/router-plugin": "^1.167.21", "compression": "^1.8.0", "express": "^4.21.2", diff --git a/examples/react/basic-virtual-file-based/package.json b/examples/react/basic-virtual-file-based/package.json index ceca586ffb..45e0d27a76 100644 --- a/examples/react/basic-virtual-file-based/package.json +++ b/examples/react/basic-virtual-file-based/package.json @@ -10,7 +10,7 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", "@tanstack/router-plugin": "^1.167.21", "@tanstack/virtual-file-routes": "^1.161.7", diff --git a/examples/react/basic-virtual-inside-file-based/package.json b/examples/react/basic-virtual-inside-file-based/package.json index 303c676733..5aeed96944 100644 --- a/examples/react/basic-virtual-inside-file-based/package.json +++ b/examples/react/basic-virtual-inside-file-based/package.json @@ -10,7 +10,7 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", "@tanstack/router-plugin": "^1.167.21", "@tanstack/virtual-file-routes": "^1.161.7", diff --git a/examples/react/basic/package.json b/examples/react/basic/package.json index 375567f985..0ab9ff9881 100644 --- a/examples/react/basic/package.json +++ b/examples/react/basic/package.json @@ -10,7 +10,7 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/examples/react/deferred-data/package.json b/examples/react/deferred-data/package.json index 9bc10a545b..19e831f895 100644 --- a/examples/react/deferred-data/package.json +++ b/examples/react/deferred-data/package.json @@ -10,7 +10,7 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/examples/react/i18n-paraglide/package.json b/examples/react/i18n-paraglide/package.json index 8955206b22..296303cd57 100644 --- a/examples/react/i18n-paraglide/package.json +++ b/examples/react/i18n-paraglide/package.json @@ -11,7 +11,7 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/router-plugin": "^1.167.21", "react": "^19.1.1", "react-dom": "^19.1.1", diff --git a/examples/react/kitchen-sink-file-based/package.json b/examples/react/kitchen-sink-file-based/package.json index 285b38db03..2cf8273ec1 100644 --- a/examples/react/kitchen-sink-file-based/package.json +++ b/examples/react/kitchen-sink-file-based/package.json @@ -10,7 +10,7 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", "@tanstack/router-plugin": "^1.167.21", "immer": "^10.1.1", diff --git a/examples/react/kitchen-sink-react-query-file-based/package.json b/examples/react/kitchen-sink-react-query-file-based/package.json index dc65d9d237..828a9dde2b 100644 --- a/examples/react/kitchen-sink-react-query-file-based/package.json +++ b/examples/react/kitchen-sink-react-query-file-based/package.json @@ -12,7 +12,7 @@ "@tailwindcss/vite": "^4.2.2", "@tanstack/react-query": "^5.90.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", "@tanstack/router-plugin": "^1.167.21", "immer": "^10.1.1", diff --git a/examples/react/kitchen-sink-react-query/package.json b/examples/react/kitchen-sink-react-query/package.json index 4199dfe898..4ff3efec99 100644 --- a/examples/react/kitchen-sink-react-query/package.json +++ b/examples/react/kitchen-sink-react-query/package.json @@ -12,7 +12,7 @@ "@tailwindcss/vite": "^4.2.2", "@tanstack/react-query": "^5.90.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", "immer": "^10.1.1", "react": "^19.0.0", diff --git a/examples/react/kitchen-sink/package.json b/examples/react/kitchen-sink/package.json index 0dd8a670d8..32b949f66c 100644 --- a/examples/react/kitchen-sink/package.json +++ b/examples/react/kitchen-sink/package.json @@ -10,7 +10,7 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", "immer": "^10.1.1", "react": "^19.0.0", diff --git a/examples/react/large-file-based/package.json b/examples/react/large-file-based/package.json index b8cebbbd55..24d4823f82 100644 --- a/examples/react/large-file-based/package.json +++ b/examples/react/large-file-based/package.json @@ -13,7 +13,7 @@ "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/react-query": "^5.90.0", - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", "@tanstack/router-plugin": "^1.167.21", "react": "^19.0.0", diff --git a/examples/react/location-masking/package.json b/examples/react/location-masking/package.json index 19cb49e2c5..8cee80755b 100644 --- a/examples/react/location-masking/package.json +++ b/examples/react/location-masking/package.json @@ -12,7 +12,7 @@ "@radix-ui/react-dialog": "^1.1.6", "@tailwindcss/vite": "^4.2.2", "@tanstack/react-query": "^5.90.0", - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/examples/react/navigation-blocking/package.json b/examples/react/navigation-blocking/package.json index 5cbbdc2050..9f892491d5 100644 --- a/examples/react/navigation-blocking/package.json +++ b/examples/react/navigation-blocking/package.json @@ -11,7 +11,7 @@ "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/react-query": "^5.90.0", - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/examples/react/quickstart-esbuild-file-based/package.json b/examples/react/quickstart-esbuild-file-based/package.json index 86349db26d..fa387f2c92 100644 --- a/examples/react/quickstart-esbuild-file-based/package.json +++ b/examples/react/quickstart-esbuild-file-based/package.json @@ -9,7 +9,7 @@ "start": "dev" }, "dependencies": { - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", "@tanstack/router-plugin": "^1.167.21", "react": "^19.0.0", diff --git a/examples/react/quickstart-file-based/package.json b/examples/react/quickstart-file-based/package.json index a2121273a0..59eaf5f8f2 100644 --- a/examples/react/quickstart-file-based/package.json +++ b/examples/react/quickstart-file-based/package.json @@ -10,7 +10,7 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", "@tanstack/router-plugin": "^1.167.21", "react": "^19.0.0", diff --git a/examples/react/quickstart-rspack-file-based/package.json b/examples/react/quickstart-rspack-file-based/package.json index 22fad57fa4..5d49798039 100644 --- a/examples/react/quickstart-rspack-file-based/package.json +++ b/examples/react/quickstart-rspack-file-based/package.json @@ -9,7 +9,7 @@ }, "dependencies": { "@tailwindcss/postcss": "^4.2.2", - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", "postcss": "^8.5.1", "react": "^19.0.0", diff --git a/examples/react/quickstart-webpack-file-based/package.json b/examples/react/quickstart-webpack-file-based/package.json index 3608c1938c..8e05c4b735 100644 --- a/examples/react/quickstart-webpack-file-based/package.json +++ b/examples/react/quickstart-webpack-file-based/package.json @@ -7,7 +7,7 @@ "build": "webpack build && tsc --noEmit" }, "dependencies": { - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", "react": "^19.0.0", "react-dom": "^19.0.0" diff --git a/examples/react/quickstart/package.json b/examples/react/quickstart/package.json index 5feff28c3e..ebd6039f95 100644 --- a/examples/react/quickstart/package.json +++ b/examples/react/quickstart/package.json @@ -10,7 +10,7 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/examples/react/router-monorepo-react-query/package.json b/examples/react/router-monorepo-react-query/package.json index efcdef4714..04d766e11f 100644 --- a/examples/react/router-monorepo-react-query/package.json +++ b/examples/react/router-monorepo-react-query/package.json @@ -12,7 +12,7 @@ "dependencies": { "@tanstack/react-query": "^5.90.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", "@tanstack/router-plugin": "^1.167.21", "react": "^19.0.0", diff --git a/examples/react/router-monorepo-react-query/packages/router/package.json b/examples/react/router-monorepo-react-query/packages/router/package.json index 84b49eb7d5..8a6f053860 100644 --- a/examples/react/router-monorepo-react-query/packages/router/package.json +++ b/examples/react/router-monorepo-react-query/packages/router/package.json @@ -10,7 +10,7 @@ "dependencies": { "@tanstack/history": "^1.161.6", "@tanstack/react-query": "^5.90.0", - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/router-plugin": "^1.167.21", "@router-mono-react-query/post-query": "workspace:*", "redaxios": "^0.5.1", diff --git a/examples/react/router-monorepo-simple-lazy/package.json b/examples/react/router-monorepo-simple-lazy/package.json index 86b1c0c3f3..6a532044e1 100644 --- a/examples/react/router-monorepo-simple-lazy/package.json +++ b/examples/react/router-monorepo-simple-lazy/package.json @@ -8,7 +8,7 @@ "dev": "pnpm router build && pnpm post-feature build && pnpm app dev" }, "dependencies": { - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", "@tanstack/router-plugin": "^1.167.21", "react": "^19.0.0", diff --git a/examples/react/router-monorepo-simple-lazy/packages/router/package.json b/examples/react/router-monorepo-simple-lazy/packages/router/package.json index bfca5b4c20..f562cae132 100644 --- a/examples/react/router-monorepo-simple-lazy/packages/router/package.json +++ b/examples/react/router-monorepo-simple-lazy/packages/router/package.json @@ -9,7 +9,7 @@ "types": "./dist/index.d.ts", "dependencies": { "@tanstack/history": "^1.161.6", - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/router-plugin": "^1.167.21", "redaxios": "^0.5.1", "zod": "^3.24.2", diff --git a/examples/react/router-monorepo-simple/package.json b/examples/react/router-monorepo-simple/package.json index f9d0232b86..bb98b26229 100644 --- a/examples/react/router-monorepo-simple/package.json +++ b/examples/react/router-monorepo-simple/package.json @@ -8,7 +8,7 @@ "dev": "pnpm router build && pnpm post-feature build && pnpm app dev" }, "dependencies": { - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", "@tanstack/router-plugin": "^1.167.21", "react": "^19.0.0", diff --git a/examples/react/router-monorepo-simple/packages/router/package.json b/examples/react/router-monorepo-simple/packages/router/package.json index c2dd4dc537..f341ff292d 100644 --- a/examples/react/router-monorepo-simple/packages/router/package.json +++ b/examples/react/router-monorepo-simple/packages/router/package.json @@ -9,7 +9,7 @@ "types": "./dist/index.d.ts", "dependencies": { "@tanstack/history": "^1.161.6", - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/router-plugin": "^1.167.21", "redaxios": "^0.5.1", "zod": "^3.24.2", diff --git a/examples/react/scroll-restoration/package.json b/examples/react/scroll-restoration/package.json index 9f962d7159..ad832e4212 100644 --- a/examples/react/scroll-restoration/package.json +++ b/examples/react/scroll-restoration/package.json @@ -10,7 +10,7 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", "@tanstack/react-virtual": "^3.13.0", "react": "^19.0.0", diff --git a/examples/react/search-validator-adapters/package.json b/examples/react/search-validator-adapters/package.json index e1f6e57fc2..0ec04c2bda 100644 --- a/examples/react/search-validator-adapters/package.json +++ b/examples/react/search-validator-adapters/package.json @@ -13,7 +13,7 @@ "@tailwindcss/vite": "^4.2.2", "@tanstack/arktype-adapter": "^1.166.9", "@tanstack/react-query": "^5.90.0", - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", "@tanstack/router-plugin": "^1.167.21", "@tanstack/valibot-adapter": "^1.166.9", diff --git a/examples/react/start-bare/package.json b/examples/react/start-bare/package.json index 87f7bf2063..a81924b66a 100644 --- a/examples/react/start-bare/package.json +++ b/examples/react/start-bare/package.json @@ -10,9 +10,9 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/react-start": "^1.167.37", + "@tanstack/react-start": "^1.167.38", "react": "^19.0.0", "react-dom": "^19.0.0", "zod": "^3.24.2" diff --git a/examples/react/start-basic-auth/package.json b/examples/react/start-basic-auth/package.json index aec045f530..bcc6cd6b62 100644 --- a/examples/react/start-basic-auth/package.json +++ b/examples/react/start-basic-auth/package.json @@ -14,9 +14,9 @@ "@libsql/client": "^0.15.15", "@prisma/adapter-libsql": "^7.0.0", "@prisma/client": "^7.0.0", - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/react-start": "^1.167.37", + "@tanstack/react-start": "^1.167.38", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/start-basic-authjs/package.json b/examples/react/start-basic-authjs/package.json index 989ff0efb9..4d1b8bcb1f 100644 --- a/examples/react/start-basic-authjs/package.json +++ b/examples/react/start-basic-authjs/package.json @@ -11,9 +11,9 @@ }, "dependencies": { "@auth/core": "^0.41.1", - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/react-start": "^1.167.37", + "@tanstack/react-start": "^1.167.38", "start-authjs": "^1.0.0", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/examples/react/start-basic-cloudflare/package.json b/examples/react/start-basic-cloudflare/package.json index dee60f02ad..a070999c48 100644 --- a/examples/react/start-basic-cloudflare/package.json +++ b/examples/react/start-basic-cloudflare/package.json @@ -12,9 +12,9 @@ "postinstall": "npm run cf-typegen" }, "dependencies": { - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/react-start": "^1.167.37", + "@tanstack/react-start": "^1.167.38", "react": "^19.0.0", "react-dom": "^19.0.0" }, diff --git a/examples/react/start-basic-react-query/package.json b/examples/react/start-basic-react-query/package.json index 03fd4c744d..535b0c45bc 100644 --- a/examples/react/start-basic-react-query/package.json +++ b/examples/react/start-basic-react-query/package.json @@ -12,10 +12,10 @@ "dependencies": { "@tanstack/react-query": "^5.90.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", "@tanstack/react-router-ssr-query": "^1.166.11", - "@tanstack/react-start": "^1.167.37", + "@tanstack/react-start": "^1.167.38", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/start-basic-static/package.json b/examples/react/start-basic-static/package.json index 8b0800f955..f161c29a68 100644 --- a/examples/react/start-basic-static/package.json +++ b/examples/react/start-basic-static/package.json @@ -10,9 +10,9 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/react-start": "^1.167.37", + "@tanstack/react-start": "^1.167.38", "@tanstack/start-static-server-functions": "^1.166.32", "@vitejs/plugin-react": "^6.0.1", "react": "^19.0.0", diff --git a/examples/react/start-basic/package.json b/examples/react/start-basic/package.json index 484caebb72..070371ad27 100644 --- a/examples/react/start-basic/package.json +++ b/examples/react/start-basic/package.json @@ -10,9 +10,9 @@ "start": "node .output/server/index.mjs" }, "dependencies": { - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/react-start": "^1.167.37", + "@tanstack/react-start": "^1.167.38", "react": "^19.0.0", "react-dom": "^19.0.0", "tailwind-merge": "^2.6.0", diff --git a/examples/react/start-bun/package.json b/examples/react/start-bun/package.json index 699d70398d..f07689d86c 100644 --- a/examples/react/start-bun/package.json +++ b/examples/react/start-bun/package.json @@ -15,10 +15,10 @@ "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/react-devtools": "^0.7.0", - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", "@tanstack/react-router-ssr-query": "^1.166.11", - "@tanstack/react-start": "^1.167.37", + "@tanstack/react-start": "^1.167.38", "@tanstack/router-plugin": "^1.167.21", "react": "^19.1.1", "react-dom": "^19.1.1", diff --git a/examples/react/start-clerk-basic/package.json b/examples/react/start-clerk-basic/package.json index 4e52cf32cc..9b2fc88aa8 100644 --- a/examples/react/start-clerk-basic/package.json +++ b/examples/react/start-clerk-basic/package.json @@ -11,9 +11,9 @@ }, "dependencies": { "@clerk/tanstack-react-start": "^0.27.14", - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/react-start": "^1.167.37", + "@tanstack/react-start": "^1.167.38", "@vitejs/plugin-react": "^6.0.1", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/examples/react/start-convex-trellaux/package.json b/examples/react/start-convex-trellaux/package.json index 64e3090906..df9433ff25 100644 --- a/examples/react/start-convex-trellaux/package.json +++ b/examples/react/start-convex-trellaux/package.json @@ -15,10 +15,10 @@ "@convex-dev/react-query": "0.0.0-alpha.8", "@tanstack/react-query": "^5.90.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", "@tanstack/react-router-ssr-query": "^1.166.11", - "@tanstack/react-start": "^1.167.37", + "@tanstack/react-start": "^1.167.38", "concurrently": "^8.2.2", "convex": "^1.19.0", "ky": "^1.7.4", diff --git a/examples/react/start-counter/package.json b/examples/react/start-counter/package.json index 70b19e3a1f..af43c954a3 100644 --- a/examples/react/start-counter/package.json +++ b/examples/react/start-counter/package.json @@ -10,9 +10,9 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/react-start": "^1.167.37", + "@tanstack/react-start": "^1.167.38", "react": "^19.0.0", "react-dom": "^19.0.0" }, diff --git a/examples/react/start-i18n-paraglide/package.json b/examples/react/start-i18n-paraglide/package.json index 485e021384..f4e6745e0c 100644 --- a/examples/react/start-i18n-paraglide/package.json +++ b/examples/react/start-i18n-paraglide/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tanstack/react-devtools": "^0.7.0", - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/react-start": "^1.167.37", + "@tanstack/react-start": "^1.167.38", "react": "^19.1.1", "react-dom": "^19.1.1" }, diff --git a/examples/react/start-large/package.json b/examples/react/start-large/package.json index 1cc318a050..9fa036446a 100644 --- a/examples/react/start-large/package.json +++ b/examples/react/start-large/package.json @@ -13,9 +13,9 @@ }, "dependencies": { "@tanstack/react-query": "^5.90.0", - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/react-start": "^1.167.37", + "@tanstack/react-start": "^1.167.38", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/start-material-ui/package.json b/examples/react/start-material-ui/package.json index 12b5b9e59e..4552ea9adb 100644 --- a/examples/react/start-material-ui/package.json +++ b/examples/react/start-material-ui/package.json @@ -15,8 +15,8 @@ "@emotion/styled": "11.14.0", "@fontsource-variable/roboto": "5.2.5", "@mui/material": "6.4.7", - "@tanstack/react-router": "^1.168.19", - "@tanstack/react-start": "^1.167.37", + "@tanstack/react-router": "^1.168.20", + "@tanstack/react-start": "^1.167.38", "@tanstack/react-router-devtools": "^1.166.13", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/examples/react/start-rscs/package.json b/examples/react/start-rscs/package.json index 347414f630..06f7fd13ee 100644 --- a/examples/react/start-rscs/package.json +++ b/examples/react/start-rscs/package.json @@ -10,9 +10,9 @@ "start": "node .output/server/index.mjs" }, "dependencies": { - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/react-start": "^1.167.37", + "@tanstack/react-start": "^1.167.38", "dexie": "^4.0.10", "react": "^19.2.0", "react-dom": "^19.2.0", diff --git a/examples/react/start-streaming-data-from-server-functions/package.json b/examples/react/start-streaming-data-from-server-functions/package.json index b21f0bf164..7a6d255786 100644 --- a/examples/react/start-streaming-data-from-server-functions/package.json +++ b/examples/react/start-streaming-data-from-server-functions/package.json @@ -10,9 +10,9 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/react-start": "^1.167.37", + "@tanstack/react-start": "^1.167.38", "react": "^19.0.0", "react-dom": "^19.0.0", "zod": "^3.24.2" diff --git a/examples/react/start-supabase-basic/package.json b/examples/react/start-supabase-basic/package.json index 43f0866afc..83214b09f7 100644 --- a/examples/react/start-supabase-basic/package.json +++ b/examples/react/start-supabase-basic/package.json @@ -15,9 +15,9 @@ "dependencies": { "@supabase/ssr": "^0.5.2", "@supabase/supabase-js": "^2.48.1", - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/react-start": "^1.167.37", + "@tanstack/react-start": "^1.167.38", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1" diff --git a/examples/react/start-tailwind-v4/package.json b/examples/react/start-tailwind-v4/package.json index 5c10526e65..10a555f5b1 100644 --- a/examples/react/start-tailwind-v4/package.json +++ b/examples/react/start-tailwind-v4/package.json @@ -10,9 +10,9 @@ "start": "node .output/server/index.mjs" }, "dependencies": { - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/react-start": "^1.167.37", + "@tanstack/react-start": "^1.167.38", "react": "^19.0.0", "react-dom": "^19.0.0", "tailwind-merge": "^2.6.0", diff --git a/examples/react/start-trellaux/package.json b/examples/react/start-trellaux/package.json index b6d0d9a7bc..65ba4cadab 100644 --- a/examples/react/start-trellaux/package.json +++ b/examples/react/start-trellaux/package.json @@ -12,10 +12,10 @@ "dependencies": { "@tanstack/react-query": "^5.90.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", "@tanstack/react-router-ssr-query": "^1.166.11", - "@tanstack/react-start": "^1.167.37", + "@tanstack/react-start": "^1.167.38", "ky": "^1.7.4", "msw": "^2.7.0", "react": "^19.0.0", diff --git a/examples/react/start-workos/package.json b/examples/react/start-workos/package.json index c16fe1c297..f7dd8b07a1 100644 --- a/examples/react/start-workos/package.json +++ b/examples/react/start-workos/package.json @@ -14,9 +14,9 @@ "license": "MIT", "dependencies": { "@radix-ui/themes": "^3.3.0", - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/react-start": "^1.167.37", + "@tanstack/react-start": "^1.167.38", "@workos/authkit-tanstack-react-start": "^0.5.0", "react": "^19.0.0", "react-dom": "^19.0.0" diff --git a/examples/react/view-transitions/package.json b/examples/react/view-transitions/package.json index 6db44f06e5..6ff81fc850 100644 --- a/examples/react/view-transitions/package.json +++ b/examples/react/view-transitions/package.json @@ -10,7 +10,7 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", "@tanstack/router-plugin": "^1.167.21", "react": "^19.0.0", diff --git a/examples/react/with-framer-motion/package.json b/examples/react/with-framer-motion/package.json index cbf1aabbb5..ee57fc7bb7 100644 --- a/examples/react/with-framer-motion/package.json +++ b/examples/react/with-framer-motion/package.json @@ -10,7 +10,7 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", "framer-motion": "^11.18.2", "react": "^19.0.0", diff --git a/examples/react/with-trpc-react-query/package.json b/examples/react/with-trpc-react-query/package.json index c459ea6327..a2d52a8d24 100644 --- a/examples/react/with-trpc-react-query/package.json +++ b/examples/react/with-trpc-react-query/package.json @@ -13,7 +13,7 @@ "@tailwindcss/vite": "^4.2.2", "@tanstack/react-query": "^5.90.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", "@tanstack/router-plugin": "^1.167.21", "@trpc/client": "^11.4.3", diff --git a/examples/react/with-trpc/package.json b/examples/react/with-trpc/package.json index 130417397d..3f08e1bce0 100644 --- a/examples/react/with-trpc/package.json +++ b/examples/react/with-trpc/package.json @@ -11,7 +11,7 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.168.19", + "@tanstack/react-router": "^1.168.20", "@tanstack/react-router-devtools": "^1.166.13", "@tanstack/router-plugin": "^1.167.21", "@trpc/client": "^11.4.3", diff --git a/packages/react-router/CHANGELOG.md b/packages/react-router/CHANGELOG.md index 743eeafac2..c55152e20e 100644 --- a/packages/react-router/CHANGELOG.md +++ b/packages/react-router/CHANGELOG.md @@ -1,5 +1,13 @@ # @tanstack/react-router +## 1.168.20 + +### Patch Changes + +- Fix React Server Component imports from `@tanstack/react-router` by adding a `react-server` root export that preserves the normal API surface while resolving `notFound` and `redirect` from a server-safe entry. ([#7183](https://github.com/TanStack/router/pull/7183)) + + This fixes RSC routes that throw `notFound()` or `redirect()` from server functions so they behave correctly during SSR and client navigation. + ## 1.168.19 ### Patch Changes diff --git a/packages/react-router/package.json b/packages/react-router/package.json index 63e72a4944..d7906f3706 100644 --- a/packages/react-router/package.json +++ b/packages/react-router/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/react-router", - "version": "1.168.19", + "version": "1.168.20", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", diff --git a/packages/react-start-client/CHANGELOG.md b/packages/react-start-client/CHANGELOG.md index 4551669a4e..8bcf917855 100644 --- a/packages/react-start-client/CHANGELOG.md +++ b/packages/react-start-client/CHANGELOG.md @@ -1,5 +1,12 @@ # @tanstack/react-start-client +## 1.166.37 + +### Patch Changes + +- Updated dependencies [[`c5ad329`](https://github.com/TanStack/router/commit/c5ad32936f6adcca0c56474677b73b212498443b)]: + - @tanstack/react-router@1.168.20 + ## 1.166.36 ### Patch Changes diff --git a/packages/react-start-client/package.json b/packages/react-start-client/package.json index 4f7f9793df..9bc353e84b 100644 --- a/packages/react-start-client/package.json +++ b/packages/react-start-client/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/react-start-client", - "version": "1.166.36", + "version": "1.166.37", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", diff --git a/packages/react-start-rsc/CHANGELOG.md b/packages/react-start-rsc/CHANGELOG.md index 73cbb16267..964f286d45 100644 --- a/packages/react-start-rsc/CHANGELOG.md +++ b/packages/react-start-rsc/CHANGELOG.md @@ -1,5 +1,13 @@ # @tanstack/react-start-rsc +## 0.0.17 + +### Patch Changes + +- Updated dependencies [[`c5ad329`](https://github.com/TanStack/router/commit/c5ad32936f6adcca0c56474677b73b212498443b)]: + - @tanstack/react-router@1.168.20 + - @tanstack/react-start-server@1.166.38 + ## 0.0.16 ### Patch Changes diff --git a/packages/react-start-rsc/package.json b/packages/react-start-rsc/package.json index 6f7fabad38..f7b74bcca2 100644 --- a/packages/react-start-rsc/package.json +++ b/packages/react-start-rsc/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/react-start-rsc", - "version": "0.0.16", + "version": "0.0.17", "description": "React Server Components support for TanStack Start", "author": "Tanner Linsley", "license": "MIT", diff --git a/packages/react-start-server/CHANGELOG.md b/packages/react-start-server/CHANGELOG.md index 22ca9e84e2..c2857d4720 100644 --- a/packages/react-start-server/CHANGELOG.md +++ b/packages/react-start-server/CHANGELOG.md @@ -1,5 +1,12 @@ # @tanstack/react-start-server +## 1.166.38 + +### Patch Changes + +- Updated dependencies [[`c5ad329`](https://github.com/TanStack/router/commit/c5ad32936f6adcca0c56474677b73b212498443b)]: + - @tanstack/react-router@1.168.20 + ## 1.166.37 ### Patch Changes diff --git a/packages/react-start-server/package.json b/packages/react-start-server/package.json index a7872a04c0..94ba850cbb 100644 --- a/packages/react-start-server/package.json +++ b/packages/react-start-server/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/react-start-server", - "version": "1.166.37", + "version": "1.166.38", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", diff --git a/packages/react-start/CHANGELOG.md b/packages/react-start/CHANGELOG.md index 30fea2c69e..641a360b69 100644 --- a/packages/react-start/CHANGELOG.md +++ b/packages/react-start/CHANGELOG.md @@ -1,5 +1,15 @@ # @tanstack/react-start +## 1.167.38 + +### Patch Changes + +- Updated dependencies [[`c5ad329`](https://github.com/TanStack/router/commit/c5ad32936f6adcca0c56474677b73b212498443b)]: + - @tanstack/react-router@1.168.20 + - @tanstack/react-start-client@1.166.37 + - @tanstack/react-start-rsc@0.0.17 + - @tanstack/react-start-server@1.166.38 + ## 1.167.37 ### Patch Changes diff --git a/packages/react-start/package.json b/packages/react-start/package.json index 89ff815773..a3a76cd78f 100644 --- a/packages/react-start/package.json +++ b/packages/react-start/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/react-start", - "version": "1.167.37", + "version": "1.167.38", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", From 16f6892d6b7ceadf606677c5a40e743f29163aa6 Mon Sep 17 00:00:00 2001 From: Manuel Schiller Date: Tue, 14 Apr 2026 01:16:42 +0200 Subject: [PATCH 005/604] fix(router-core): avoid intermediate success state for async notFound (#7184) --- .changeset/clean-wombats-sleep.md | 7 ++ packages/react-router/tests/router.test.tsx | 82 +++++++++++++++++++++ packages/router-core/src/load-matches.ts | 8 +- 3 files changed, 94 insertions(+), 3 deletions(-) create mode 100644 .changeset/clean-wombats-sleep.md diff --git a/.changeset/clean-wombats-sleep.md b/.changeset/clean-wombats-sleep.md new file mode 100644 index 0000000000..913586cced --- /dev/null +++ b/.changeset/clean-wombats-sleep.md @@ -0,0 +1,7 @@ +--- +'@tanstack/router-core': patch +--- + +Fix async loaders that throw or return `notFound()` so they do not briefly mark the match as `success` before the final not-found boundary is resolved. + +This prevents route components from rendering with missing loader data during navigation when React observes the intermediate match state before not-found finalization completes. diff --git a/packages/react-router/tests/router.test.tsx b/packages/react-router/tests/router.test.tsx index 99a6e36d53..cf3b1c11fe 100644 --- a/packages/react-router/tests/router.test.tsx +++ b/packages/react-router/tests/router.test.tsx @@ -1525,6 +1525,88 @@ describe('invalidate', () => { ).toBeInTheDocument() expect(screen.queryByTestId('loader-route')).not.toBeInTheDocument() }) + + it('does not render the route component while async loader notFound is waiting for later matches to settle', async () => { + const history = createMemoryHistory({ + initialEntries: ['/parent/child/grandchild'], + }) + + const createControlledPromise = () => { + let resolve!: () => void + const promise = new Promise((r) => { + resolve = r + }) + + return { promise, resolve } + } + + const grandchildLoader = createControlledPromise() + + const rootRoute = createRootRoute({ + component: () => , + notFoundComponent: () => ( +
Root Not Found
+ ), + }) + + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + component: () => , + notFoundComponent: () => ( +
Parent Not Found
+ ), + }) + + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: async () => { + await Promise.resolve() + throw notFound() + }, + component: () => ( +
+ Child component should not render +
+ ), + }) + + const grandchildRoute = createRoute({ + getParentRoute: () => childRoute, + path: '/grandchild', + loader: () => grandchildLoader.promise, + component: () =>
Grandchild
, + }) + + const router = createRouter({ + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([childRoute.addChildren([grandchildRoute])]), + ]), + history, + defaultPendingMs: 0, + defaultPendingComponent: () => ( +
Loading...
+ ), + }) + + render() + + await waitFor(() => { + expect(router.state.location.pathname).toBe('/parent/child/grandchild') + expect(router.state.matches[0]?.routeId).toBe(rootRoute.id) + expect(router.state.matches[1]?.routeId).toBe(parentRoute.id) + expect(router.state.matches[2]?.routeId).toBe(childRoute.id) + }) + + expect(screen.queryByTestId('child-component')).not.toBeInTheDocument() + expect(screen.queryByTestId('parent-not-found')).not.toBeInTheDocument() + + grandchildLoader.resolve() + + expect(await screen.findByTestId('parent-not-found')).toBeInTheDocument() + expect(screen.queryByTestId('child-component')).not.toBeInTheDocument() + }) }) describe('search params in URL', () => { diff --git a/packages/router-core/src/load-matches.ts b/packages/router-core/src/load-matches.ts index a06715de43..275fd70c60 100644 --- a/packages/router-core/src/load-matches.ts +++ b/packages/router-core/src/load-matches.ts @@ -136,9 +136,11 @@ const handleRedirectAndNotFound = ( ...prev, status: isRedirect(err) ? 'redirected' - : prev.status === 'pending' - ? 'success' - : prev.status, + : isNotFound(err) + ? 'notFound' + : prev.status === 'pending' + ? 'success' + : prev.status, context: buildMatchContext(inner, match.index), isFetching: false, error: err, From 26680c95a9e3f7ef766450c99cb6d378e6f358b6 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Mon, 13 Apr 2026 23:30:55 +0000 Subject: [PATCH 006/604] ci: changeset release --- .changeset/clean-wombats-sleep.md | 7 -- .../package.json | 4 +- .../react/authenticated-routes/package.json | 4 +- .../basic-default-search-params/package.json | 2 +- .../react/basic-devtools-panel/package.json | 2 +- examples/react/basic-file-based/package.json | 4 +- .../basic-non-nested-devtools/package.json | 2 +- .../basic-react-query-file-based/package.json | 4 +- examples/react/basic-react-query/package.json | 2 +- .../react/basic-ssr-file-based/package.json | 4 +- .../package.json | 4 +- .../basic-virtual-file-based/package.json | 4 +- .../package.json | 4 +- examples/react/basic/package.json | 2 +- examples/react/deferred-data/package.json | 2 +- examples/react/i18n-paraglide/package.json | 4 +- .../kitchen-sink-file-based/package.json | 4 +- .../package.json | 4 +- .../kitchen-sink-react-query/package.json | 2 +- examples/react/kitchen-sink/package.json | 2 +- examples/react/large-file-based/package.json | 4 +- examples/react/location-masking/package.json | 2 +- .../react/navigation-blocking/package.json | 2 +- .../package.json | 4 +- .../react/quickstart-file-based/package.json | 4 +- .../quickstart-rspack-file-based/package.json | 4 +- .../package.json | 4 +- examples/react/quickstart/package.json | 2 +- .../router-monorepo-react-query/package.json | 4 +- .../packages/router/package.json | 4 +- .../router-monorepo-simple-lazy/package.json | 4 +- .../packages/router/package.json | 4 +- .../react/router-monorepo-simple/package.json | 4 +- .../packages/router/package.json | 4 +- .../react/scroll-restoration/package.json | 2 +- .../search-validator-adapters/package.json | 4 +- examples/react/start-bare/package.json | 4 +- examples/react/start-basic-auth/package.json | 4 +- .../react/start-basic-authjs/package.json | 4 +- .../react/start-basic-cloudflare/package.json | 4 +- .../start-basic-react-query/package.json | 4 +- .../react/start-basic-static/package.json | 6 +- examples/react/start-basic/package.json | 4 +- examples/react/start-bun/package.json | 6 +- examples/react/start-clerk-basic/package.json | 4 +- .../react/start-convex-trellaux/package.json | 4 +- examples/react/start-counter/package.json | 4 +- .../react/start-i18n-paraglide/package.json | 4 +- examples/react/start-large/package.json | 4 +- examples/react/start-material-ui/package.json | 4 +- examples/react/start-rscs/package.json | 4 +- .../package.json | 4 +- .../react/start-supabase-basic/package.json | 4 +- examples/react/start-tailwind-v4/package.json | 4 +- examples/react/start-trellaux/package.json | 4 +- examples/react/start-workos/package.json | 4 +- examples/react/view-transitions/package.json | 4 +- .../react/with-framer-motion/package.json | 2 +- .../react/with-trpc-react-query/package.json | 4 +- examples/react/with-trpc/package.json | 4 +- .../package.json | 4 +- .../solid/authenticated-routes/package.json | 4 +- .../basic-default-search-params/package.json | 2 +- .../solid/basic-devtools-panel/package.json | 2 +- examples/solid/basic-file-based/package.json | 4 +- .../basic-non-nested-devtools/package.json | 2 +- .../basic-solid-query-file-based/package.json | 4 +- examples/solid/basic-solid-query/package.json | 4 +- .../solid/basic-ssr-file-based/package.json | 4 +- .../package.json | 4 +- .../basic-virtual-file-based/package.json | 4 +- .../package.json | 4 +- examples/solid/basic/package.json | 2 +- examples/solid/deferred-data/package.json | 2 +- examples/solid/i18n-paraglide/package.json | 4 +- .../kitchen-sink-file-based/package.json | 4 +- .../package.json | 4 +- .../kitchen-sink-solid-query/package.json | 2 +- examples/solid/kitchen-sink/package.json | 2 +- examples/solid/large-file-based/package.json | 4 +- examples/solid/location-masking/package.json | 2 +- .../solid/navigation-blocking/package.json | 2 +- .../package.json | 4 +- .../solid/quickstart-file-based/package.json | 4 +- .../quickstart-rspack-file-based/package.json | 4 +- .../package.json | 4 +- examples/solid/quickstart/package.json | 2 +- .../router-monorepo-simple-lazy/package.json | 4 +- .../packages/router/package.json | 4 +- .../solid/router-monorepo-simple/package.json | 4 +- .../packages/router/package.json | 4 +- .../router-monorepo-solid-query/package.json | 4 +- .../packages/router/package.json | 4 +- .../solid/scroll-restoration/package.json | 2 +- .../search-validator-adapters/package.json | 4 +- examples/solid/start-basic-auth/package.json | 4 +- .../solid/start-basic-authjs/package.json | 4 +- .../solid/start-basic-cloudflare/package.json | 4 +- .../solid/start-basic-netlify/package.json | 4 +- examples/solid/start-basic-nitro/package.json | 4 +- .../start-basic-solid-query/package.json | 4 +- .../solid/start-basic-static/package.json | 6 +- examples/solid/start-basic/package.json | 4 +- examples/solid/start-bun/package.json | 6 +- .../start-convex-better-auth/package.json | 4 +- examples/solid/start-counter/package.json | 4 +- .../solid/start-i18n-paraglide/package.json | 4 +- examples/solid/start-large/package.json | 4 +- .../package.json | 4 +- .../solid/start-supabase-basic/package.json | 4 +- examples/solid/start-tailwind-v4/package.json | 4 +- examples/solid/view-transitions/package.json | 4 +- .../solid/with-framer-motion/package.json | 2 +- examples/solid/with-trpc/package.json | 4 +- .../vue/basic-file-based-jsx/package.json | 4 +- .../vue/basic-file-based-sfc/package.json | 4 +- examples/vue/basic/package.json | 2 +- packages/react-router/CHANGELOG.md | 7 ++ packages/react-router/package.json | 2 +- packages/react-start-client/CHANGELOG.md | 9 ++ packages/react-start-client/package.json | 2 +- packages/react-start-rsc/CHANGELOG.md | 13 +++ packages/react-start-rsc/package.json | 2 +- packages/react-start-server/CHANGELOG.md | 10 ++ packages/react-start-server/package.json | 2 +- packages/react-start/CHANGELOG.md | 13 +++ packages/react-start/package.json | 2 +- packages/router-cli/CHANGELOG.md | 7 ++ packages/router-cli/package.json | 2 +- packages/router-core/CHANGELOG.md | 8 ++ packages/router-core/package.json | 2 +- packages/router-generator/CHANGELOG.md | 7 ++ packages/router-generator/package.json | 2 +- packages/router-plugin/CHANGELOG.md | 9 ++ packages/router-plugin/package.json | 2 +- packages/router-vite-plugin/CHANGELOG.md | 7 ++ packages/router-vite-plugin/package.json | 2 +- packages/solid-router/CHANGELOG.md | 7 ++ packages/solid-router/package.json | 2 +- packages/solid-start-client/CHANGELOG.md | 9 ++ packages/solid-start-client/package.json | 2 +- packages/solid-start-server/CHANGELOG.md | 10 ++ packages/solid-start-server/package.json | 2 +- packages/solid-start/CHANGELOG.md | 12 +++ packages/solid-start/package.json | 2 +- packages/start-client-core/CHANGELOG.md | 8 ++ packages/start-client-core/package.json | 2 +- packages/start-plugin-core/CHANGELOG.md | 11 ++ packages/start-plugin-core/package.json | 2 +- packages/start-server-core/CHANGELOG.md | 9 ++ packages/start-server-core/package.json | 2 +- .../CHANGELOG.md | 9 ++ .../package.json | 2 +- packages/start-storage-context/CHANGELOG.md | 7 ++ packages/start-storage-context/package.json | 2 +- packages/vue-router/CHANGELOG.md | 7 ++ packages/vue-router/package.json | 2 +- packages/vue-start-client/CHANGELOG.md | 9 ++ packages/vue-start-client/package.json | 2 +- packages/vue-start-server/CHANGELOG.md | 10 ++ packages/vue-start-server/package.json | 2 +- packages/vue-start/CHANGELOG.md | 12 +++ packages/vue-start/package.json | 2 +- pnpm-lock.yaml | 102 +++++++++--------- 164 files changed, 494 insertions(+), 291 deletions(-) delete mode 100644 .changeset/clean-wombats-sleep.md diff --git a/.changeset/clean-wombats-sleep.md b/.changeset/clean-wombats-sleep.md deleted file mode 100644 index 913586cced..0000000000 --- a/.changeset/clean-wombats-sleep.md +++ /dev/null @@ -1,7 +0,0 @@ ---- -'@tanstack/router-core': patch ---- - -Fix async loaders that throw or return `notFound()` so they do not briefly mark the match as `success` before the final not-found boundary is resolved. - -This prevents route components from rendering with missing loader data during navigation when React observes the intermediate match state before not-found finalization completes. diff --git a/examples/react/authenticated-routes-firebase/package.json b/examples/react/authenticated-routes-firebase/package.json index 0456cfc1e1..facf4375ca 100644 --- a/examples/react/authenticated-routes-firebase/package.json +++ b/examples/react/authenticated-routes-firebase/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/router-plugin": "^1.167.22", "firebase": "^11.4.0", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/examples/react/authenticated-routes/package.json b/examples/react/authenticated-routes/package.json index 86d7d48927..a31eaae0d3 100644 --- a/examples/react/authenticated-routes/package.json +++ b/examples/react/authenticated-routes/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/router-plugin": "^1.167.22", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/basic-default-search-params/package.json b/examples/react/basic-default-search-params/package.json index 91d5a9193e..d6ded91ca0 100644 --- a/examples/react/basic-default-search-params/package.json +++ b/examples/react/basic-default-search-params/package.json @@ -11,7 +11,7 @@ "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/react-query": "^5.90.0", - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/examples/react/basic-devtools-panel/package.json b/examples/react/basic-devtools-panel/package.json index 7344200aa3..3f6522a1f8 100644 --- a/examples/react/basic-devtools-panel/package.json +++ b/examples/react/basic-devtools-panel/package.json @@ -11,7 +11,7 @@ "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/react-query-devtools": "^5.67.2", - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/examples/react/basic-file-based/package.json b/examples/react/basic-file-based/package.json index f6f34943e7..23c6a17f0b 100644 --- a/examples/react/basic-file-based/package.json +++ b/examples/react/basic-file-based/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/router-plugin": "^1.167.22", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/basic-non-nested-devtools/package.json b/examples/react/basic-non-nested-devtools/package.json index 0ffbda985e..6e7a55e574 100644 --- a/examples/react/basic-non-nested-devtools/package.json +++ b/examples/react/basic-non-nested-devtools/package.json @@ -10,7 +10,7 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/examples/react/basic-react-query-file-based/package.json b/examples/react/basic-react-query-file-based/package.json index 7207e32aef..35d08f13b4 100644 --- a/examples/react/basic-react-query-file-based/package.json +++ b/examples/react/basic-react-query-file-based/package.json @@ -12,9 +12,9 @@ "@tailwindcss/vite": "^4.2.2", "@tanstack/react-query": "^5.90.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/router-plugin": "^1.167.22", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/basic-react-query/package.json b/examples/react/basic-react-query/package.json index 5d7a929042..fea5acc299 100644 --- a/examples/react/basic-react-query/package.json +++ b/examples/react/basic-react-query/package.json @@ -12,7 +12,7 @@ "@tailwindcss/vite": "^4.2.2", "@tanstack/react-query": "^5.90.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/examples/react/basic-ssr-file-based/package.json b/examples/react/basic-ssr-file-based/package.json index d51fbc4736..26e2bb0f2b 100644 --- a/examples/react/basic-ssr-file-based/package.json +++ b/examples/react/basic-ssr-file-based/package.json @@ -11,8 +11,8 @@ "debug": "node --inspect-brk server" }, "dependencies": { - "@tanstack/react-router": "^1.168.20", - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/react-router": "^1.168.21", + "@tanstack/router-plugin": "^1.167.22", "compression": "^1.8.0", "express": "^4.21.2", "get-port": "^7.1.0", diff --git a/examples/react/basic-ssr-streaming-file-based/package.json b/examples/react/basic-ssr-streaming-file-based/package.json index 5540b2e42c..6a8ac9eb66 100644 --- a/examples/react/basic-ssr-streaming-file-based/package.json +++ b/examples/react/basic-ssr-streaming-file-based/package.json @@ -11,8 +11,8 @@ "debug": "node --inspect-brk server" }, "dependencies": { - "@tanstack/react-router": "^1.168.20", - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/react-router": "^1.168.21", + "@tanstack/router-plugin": "^1.167.22", "compression": "^1.8.0", "express": "^4.21.2", "get-port": "^7.1.0", diff --git a/examples/react/basic-virtual-file-based/package.json b/examples/react/basic-virtual-file-based/package.json index 45e0d27a76..71f484b817 100644 --- a/examples/react/basic-virtual-file-based/package.json +++ b/examples/react/basic-virtual-file-based/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/router-plugin": "^1.167.22", "@tanstack/virtual-file-routes": "^1.161.7", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/examples/react/basic-virtual-inside-file-based/package.json b/examples/react/basic-virtual-inside-file-based/package.json index 5aeed96944..f82823ba4c 100644 --- a/examples/react/basic-virtual-inside-file-based/package.json +++ b/examples/react/basic-virtual-inside-file-based/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/router-plugin": "^1.167.22", "@tanstack/virtual-file-routes": "^1.161.7", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/examples/react/basic/package.json b/examples/react/basic/package.json index 0ab9ff9881..535dcfccfa 100644 --- a/examples/react/basic/package.json +++ b/examples/react/basic/package.json @@ -10,7 +10,7 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/examples/react/deferred-data/package.json b/examples/react/deferred-data/package.json index 19e831f895..a9fa47017b 100644 --- a/examples/react/deferred-data/package.json +++ b/examples/react/deferred-data/package.json @@ -10,7 +10,7 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/examples/react/i18n-paraglide/package.json b/examples/react/i18n-paraglide/package.json index 296303cd57..19f38c3504 100644 --- a/examples/react/i18n-paraglide/package.json +++ b/examples/react/i18n-paraglide/package.json @@ -11,8 +11,8 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.168.20", - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/react-router": "^1.168.21", + "@tanstack/router-plugin": "^1.167.22", "react": "^19.1.1", "react-dom": "^19.1.1", "tailwindcss": "^4.2.2" diff --git a/examples/react/kitchen-sink-file-based/package.json b/examples/react/kitchen-sink-file-based/package.json index 2cf8273ec1..bef7c136fe 100644 --- a/examples/react/kitchen-sink-file-based/package.json +++ b/examples/react/kitchen-sink-file-based/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/router-plugin": "^1.167.22", "immer": "^10.1.1", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/examples/react/kitchen-sink-react-query-file-based/package.json b/examples/react/kitchen-sink-react-query-file-based/package.json index 828a9dde2b..feda3e971f 100644 --- a/examples/react/kitchen-sink-react-query-file-based/package.json +++ b/examples/react/kitchen-sink-react-query-file-based/package.json @@ -12,9 +12,9 @@ "@tailwindcss/vite": "^4.2.2", "@tanstack/react-query": "^5.90.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/router-plugin": "^1.167.22", "immer": "^10.1.1", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/examples/react/kitchen-sink-react-query/package.json b/examples/react/kitchen-sink-react-query/package.json index 4ff3efec99..4477207b2a 100644 --- a/examples/react/kitchen-sink-react-query/package.json +++ b/examples/react/kitchen-sink-react-query/package.json @@ -12,7 +12,7 @@ "@tailwindcss/vite": "^4.2.2", "@tanstack/react-query": "^5.90.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", "immer": "^10.1.1", "react": "^19.0.0", diff --git a/examples/react/kitchen-sink/package.json b/examples/react/kitchen-sink/package.json index 32b949f66c..eabdbafea5 100644 --- a/examples/react/kitchen-sink/package.json +++ b/examples/react/kitchen-sink/package.json @@ -10,7 +10,7 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", "immer": "^10.1.1", "react": "^19.0.0", diff --git a/examples/react/large-file-based/package.json b/examples/react/large-file-based/package.json index 24d4823f82..a8729db0bf 100644 --- a/examples/react/large-file-based/package.json +++ b/examples/react/large-file-based/package.json @@ -13,9 +13,9 @@ "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/react-query": "^5.90.0", - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/router-plugin": "^1.167.22", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/location-masking/package.json b/examples/react/location-masking/package.json index 8cee80755b..ba5883595b 100644 --- a/examples/react/location-masking/package.json +++ b/examples/react/location-masking/package.json @@ -12,7 +12,7 @@ "@radix-ui/react-dialog": "^1.1.6", "@tailwindcss/vite": "^4.2.2", "@tanstack/react-query": "^5.90.0", - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/examples/react/navigation-blocking/package.json b/examples/react/navigation-blocking/package.json index 9f892491d5..27d967ac47 100644 --- a/examples/react/navigation-blocking/package.json +++ b/examples/react/navigation-blocking/package.json @@ -11,7 +11,7 @@ "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/react-query": "^5.90.0", - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/examples/react/quickstart-esbuild-file-based/package.json b/examples/react/quickstart-esbuild-file-based/package.json index fa387f2c92..545be4c638 100644 --- a/examples/react/quickstart-esbuild-file-based/package.json +++ b/examples/react/quickstart-esbuild-file-based/package.json @@ -9,9 +9,9 @@ "start": "dev" }, "dependencies": { - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/router-plugin": "^1.167.22", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/quickstart-file-based/package.json b/examples/react/quickstart-file-based/package.json index 59eaf5f8f2..50a28c8812 100644 --- a/examples/react/quickstart-file-based/package.json +++ b/examples/react/quickstart-file-based/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/router-plugin": "^1.167.22", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/quickstart-rspack-file-based/package.json b/examples/react/quickstart-rspack-file-based/package.json index 5d49798039..91b3fba7a7 100644 --- a/examples/react/quickstart-rspack-file-based/package.json +++ b/examples/react/quickstart-rspack-file-based/package.json @@ -9,7 +9,7 @@ }, "dependencies": { "@tailwindcss/postcss": "^4.2.2", - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", "postcss": "^8.5.1", "react": "^19.0.0", @@ -19,7 +19,7 @@ "devDependencies": { "@rsbuild/core": "^1.2.4", "@rsbuild/plugin-react": "^1.1.0", - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/router-plugin": "^1.167.22", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "typescript": "^6.0.2" diff --git a/examples/react/quickstart-webpack-file-based/package.json b/examples/react/quickstart-webpack-file-based/package.json index 8e05c4b735..9bd1a457f4 100644 --- a/examples/react/quickstart-webpack-file-based/package.json +++ b/examples/react/quickstart-webpack-file-based/package.json @@ -7,14 +7,14 @@ "build": "webpack build && tsc --noEmit" }, "dependencies": { - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", "react": "^19.0.0", "react-dom": "^19.0.0" }, "devDependencies": { "@swc/core": "^1.10.15", - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/router-plugin": "^1.167.22", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "html-webpack-plugin": "^5.6.3", diff --git a/examples/react/quickstart/package.json b/examples/react/quickstart/package.json index ebd6039f95..225459a87b 100644 --- a/examples/react/quickstart/package.json +++ b/examples/react/quickstart/package.json @@ -10,7 +10,7 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/examples/react/router-monorepo-react-query/package.json b/examples/react/router-monorepo-react-query/package.json index 04d766e11f..d0eb8c4ebe 100644 --- a/examples/react/router-monorepo-react-query/package.json +++ b/examples/react/router-monorepo-react-query/package.json @@ -12,9 +12,9 @@ "dependencies": { "@tanstack/react-query": "^5.90.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/router-plugin": "^1.167.22", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1" diff --git a/examples/react/router-monorepo-react-query/packages/router/package.json b/examples/react/router-monorepo-react-query/packages/router/package.json index 8a6f053860..e7c2e56901 100644 --- a/examples/react/router-monorepo-react-query/packages/router/package.json +++ b/examples/react/router-monorepo-react-query/packages/router/package.json @@ -10,8 +10,8 @@ "dependencies": { "@tanstack/history": "^1.161.6", "@tanstack/react-query": "^5.90.0", - "@tanstack/react-router": "^1.168.20", - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/react-router": "^1.168.21", + "@tanstack/router-plugin": "^1.167.22", "@router-mono-react-query/post-query": "workspace:*", "redaxios": "^0.5.1", "zod": "^3.24.2", diff --git a/examples/react/router-monorepo-simple-lazy/package.json b/examples/react/router-monorepo-simple-lazy/package.json index 6a532044e1..336aa0e709 100644 --- a/examples/react/router-monorepo-simple-lazy/package.json +++ b/examples/react/router-monorepo-simple-lazy/package.json @@ -8,9 +8,9 @@ "dev": "pnpm router build && pnpm post-feature build && pnpm app dev" }, "dependencies": { - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/router-plugin": "^1.167.22", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1" diff --git a/examples/react/router-monorepo-simple-lazy/packages/router/package.json b/examples/react/router-monorepo-simple-lazy/packages/router/package.json index f562cae132..442910b1c6 100644 --- a/examples/react/router-monorepo-simple-lazy/packages/router/package.json +++ b/examples/react/router-monorepo-simple-lazy/packages/router/package.json @@ -9,8 +9,8 @@ "types": "./dist/index.d.ts", "dependencies": { "@tanstack/history": "^1.161.6", - "@tanstack/react-router": "^1.168.20", - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/react-router": "^1.168.21", + "@tanstack/router-plugin": "^1.167.22", "redaxios": "^0.5.1", "zod": "^3.24.2", "react": "^19.0.0", diff --git a/examples/react/router-monorepo-simple/package.json b/examples/react/router-monorepo-simple/package.json index bb98b26229..fc19956da7 100644 --- a/examples/react/router-monorepo-simple/package.json +++ b/examples/react/router-monorepo-simple/package.json @@ -8,9 +8,9 @@ "dev": "pnpm router build && pnpm post-feature build && pnpm app dev" }, "dependencies": { - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/router-plugin": "^1.167.22", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1" diff --git a/examples/react/router-monorepo-simple/packages/router/package.json b/examples/react/router-monorepo-simple/packages/router/package.json index f341ff292d..f41803bd47 100644 --- a/examples/react/router-monorepo-simple/packages/router/package.json +++ b/examples/react/router-monorepo-simple/packages/router/package.json @@ -9,8 +9,8 @@ "types": "./dist/index.d.ts", "dependencies": { "@tanstack/history": "^1.161.6", - "@tanstack/react-router": "^1.168.20", - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/react-router": "^1.168.21", + "@tanstack/router-plugin": "^1.167.22", "redaxios": "^0.5.1", "zod": "^3.24.2", "react": "^19.0.0", diff --git a/examples/react/scroll-restoration/package.json b/examples/react/scroll-restoration/package.json index ad832e4212..263adaee7c 100644 --- a/examples/react/scroll-restoration/package.json +++ b/examples/react/scroll-restoration/package.json @@ -10,7 +10,7 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", "@tanstack/react-virtual": "^3.13.0", "react": "^19.0.0", diff --git a/examples/react/search-validator-adapters/package.json b/examples/react/search-validator-adapters/package.json index 0ec04c2bda..2ca164c57a 100644 --- a/examples/react/search-validator-adapters/package.json +++ b/examples/react/search-validator-adapters/package.json @@ -13,9 +13,9 @@ "@tailwindcss/vite": "^4.2.2", "@tanstack/arktype-adapter": "^1.166.9", "@tanstack/react-query": "^5.90.0", - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/router-plugin": "^1.167.22", "@tanstack/valibot-adapter": "^1.166.9", "@tanstack/zod-adapter": "^1.166.9", "arktype": "^2.1.7", diff --git a/examples/react/start-bare/package.json b/examples/react/start-bare/package.json index a81924b66a..669f5c6083 100644 --- a/examples/react/start-bare/package.json +++ b/examples/react/start-bare/package.json @@ -10,9 +10,9 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/react-start": "^1.167.38", + "@tanstack/react-start": "^1.167.39", "react": "^19.0.0", "react-dom": "^19.0.0", "zod": "^3.24.2" diff --git a/examples/react/start-basic-auth/package.json b/examples/react/start-basic-auth/package.json index bcc6cd6b62..00580e9d49 100644 --- a/examples/react/start-basic-auth/package.json +++ b/examples/react/start-basic-auth/package.json @@ -14,9 +14,9 @@ "@libsql/client": "^0.15.15", "@prisma/adapter-libsql": "^7.0.0", "@prisma/client": "^7.0.0", - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/react-start": "^1.167.38", + "@tanstack/react-start": "^1.167.39", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/start-basic-authjs/package.json b/examples/react/start-basic-authjs/package.json index 4d1b8bcb1f..ab8373dd00 100644 --- a/examples/react/start-basic-authjs/package.json +++ b/examples/react/start-basic-authjs/package.json @@ -11,9 +11,9 @@ }, "dependencies": { "@auth/core": "^0.41.1", - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/react-start": "^1.167.38", + "@tanstack/react-start": "^1.167.39", "start-authjs": "^1.0.0", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/examples/react/start-basic-cloudflare/package.json b/examples/react/start-basic-cloudflare/package.json index a070999c48..cfd4abfb28 100644 --- a/examples/react/start-basic-cloudflare/package.json +++ b/examples/react/start-basic-cloudflare/package.json @@ -12,9 +12,9 @@ "postinstall": "npm run cf-typegen" }, "dependencies": { - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/react-start": "^1.167.38", + "@tanstack/react-start": "^1.167.39", "react": "^19.0.0", "react-dom": "^19.0.0" }, diff --git a/examples/react/start-basic-react-query/package.json b/examples/react/start-basic-react-query/package.json index 535b0c45bc..1ba3bcd430 100644 --- a/examples/react/start-basic-react-query/package.json +++ b/examples/react/start-basic-react-query/package.json @@ -12,10 +12,10 @@ "dependencies": { "@tanstack/react-query": "^5.90.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", "@tanstack/react-router-ssr-query": "^1.166.11", - "@tanstack/react-start": "^1.167.38", + "@tanstack/react-start": "^1.167.39", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/start-basic-static/package.json b/examples/react/start-basic-static/package.json index f161c29a68..d597ccbec3 100644 --- a/examples/react/start-basic-static/package.json +++ b/examples/react/start-basic-static/package.json @@ -10,10 +10,10 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/react-start": "^1.167.38", - "@tanstack/start-static-server-functions": "^1.166.32", + "@tanstack/react-start": "^1.167.39", + "@tanstack/start-static-server-functions": "^1.166.33", "@vitejs/plugin-react": "^6.0.1", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/examples/react/start-basic/package.json b/examples/react/start-basic/package.json index 070371ad27..c6602579a7 100644 --- a/examples/react/start-basic/package.json +++ b/examples/react/start-basic/package.json @@ -10,9 +10,9 @@ "start": "node .output/server/index.mjs" }, "dependencies": { - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/react-start": "^1.167.38", + "@tanstack/react-start": "^1.167.39", "react": "^19.0.0", "react-dom": "^19.0.0", "tailwind-merge": "^2.6.0", diff --git a/examples/react/start-bun/package.json b/examples/react/start-bun/package.json index f07689d86c..75d54b1395 100644 --- a/examples/react/start-bun/package.json +++ b/examples/react/start-bun/package.json @@ -15,11 +15,11 @@ "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/react-devtools": "^0.7.0", - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", "@tanstack/react-router-ssr-query": "^1.166.11", - "@tanstack/react-start": "^1.167.38", - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/react-start": "^1.167.39", + "@tanstack/router-plugin": "^1.167.22", "react": "^19.1.1", "react-dom": "^19.1.1", "tailwindcss": "^4.2.2" diff --git a/examples/react/start-clerk-basic/package.json b/examples/react/start-clerk-basic/package.json index 9b2fc88aa8..c50e47d21a 100644 --- a/examples/react/start-clerk-basic/package.json +++ b/examples/react/start-clerk-basic/package.json @@ -11,9 +11,9 @@ }, "dependencies": { "@clerk/tanstack-react-start": "^0.27.14", - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/react-start": "^1.167.38", + "@tanstack/react-start": "^1.167.39", "@vitejs/plugin-react": "^6.0.1", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/examples/react/start-convex-trellaux/package.json b/examples/react/start-convex-trellaux/package.json index df9433ff25..4f5c29321f 100644 --- a/examples/react/start-convex-trellaux/package.json +++ b/examples/react/start-convex-trellaux/package.json @@ -15,10 +15,10 @@ "@convex-dev/react-query": "0.0.0-alpha.8", "@tanstack/react-query": "^5.90.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", "@tanstack/react-router-ssr-query": "^1.166.11", - "@tanstack/react-start": "^1.167.38", + "@tanstack/react-start": "^1.167.39", "concurrently": "^8.2.2", "convex": "^1.19.0", "ky": "^1.7.4", diff --git a/examples/react/start-counter/package.json b/examples/react/start-counter/package.json index af43c954a3..28e4475de6 100644 --- a/examples/react/start-counter/package.json +++ b/examples/react/start-counter/package.json @@ -10,9 +10,9 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/react-start": "^1.167.38", + "@tanstack/react-start": "^1.167.39", "react": "^19.0.0", "react-dom": "^19.0.0" }, diff --git a/examples/react/start-i18n-paraglide/package.json b/examples/react/start-i18n-paraglide/package.json index f4e6745e0c..a4614e0aad 100644 --- a/examples/react/start-i18n-paraglide/package.json +++ b/examples/react/start-i18n-paraglide/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tanstack/react-devtools": "^0.7.0", - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/react-start": "^1.167.38", + "@tanstack/react-start": "^1.167.39", "react": "^19.1.1", "react-dom": "^19.1.1" }, diff --git a/examples/react/start-large/package.json b/examples/react/start-large/package.json index 9fa036446a..08e4836965 100644 --- a/examples/react/start-large/package.json +++ b/examples/react/start-large/package.json @@ -13,9 +13,9 @@ }, "dependencies": { "@tanstack/react-query": "^5.90.0", - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/react-start": "^1.167.38", + "@tanstack/react-start": "^1.167.39", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/start-material-ui/package.json b/examples/react/start-material-ui/package.json index 4552ea9adb..0be46b068c 100644 --- a/examples/react/start-material-ui/package.json +++ b/examples/react/start-material-ui/package.json @@ -15,8 +15,8 @@ "@emotion/styled": "11.14.0", "@fontsource-variable/roboto": "5.2.5", "@mui/material": "6.4.7", - "@tanstack/react-router": "^1.168.20", - "@tanstack/react-start": "^1.167.38", + "@tanstack/react-router": "^1.168.21", + "@tanstack/react-start": "^1.167.39", "@tanstack/react-router-devtools": "^1.166.13", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/examples/react/start-rscs/package.json b/examples/react/start-rscs/package.json index 06f7fd13ee..c9eb7877b5 100644 --- a/examples/react/start-rscs/package.json +++ b/examples/react/start-rscs/package.json @@ -10,9 +10,9 @@ "start": "node .output/server/index.mjs" }, "dependencies": { - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/react-start": "^1.167.38", + "@tanstack/react-start": "^1.167.39", "dexie": "^4.0.10", "react": "^19.2.0", "react-dom": "^19.2.0", diff --git a/examples/react/start-streaming-data-from-server-functions/package.json b/examples/react/start-streaming-data-from-server-functions/package.json index 7a6d255786..4a106fbc81 100644 --- a/examples/react/start-streaming-data-from-server-functions/package.json +++ b/examples/react/start-streaming-data-from-server-functions/package.json @@ -10,9 +10,9 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/react-start": "^1.167.38", + "@tanstack/react-start": "^1.167.39", "react": "^19.0.0", "react-dom": "^19.0.0", "zod": "^3.24.2" diff --git a/examples/react/start-supabase-basic/package.json b/examples/react/start-supabase-basic/package.json index 83214b09f7..0aba4ea790 100644 --- a/examples/react/start-supabase-basic/package.json +++ b/examples/react/start-supabase-basic/package.json @@ -15,9 +15,9 @@ "dependencies": { "@supabase/ssr": "^0.5.2", "@supabase/supabase-js": "^2.48.1", - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/react-start": "^1.167.38", + "@tanstack/react-start": "^1.167.39", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1" diff --git a/examples/react/start-tailwind-v4/package.json b/examples/react/start-tailwind-v4/package.json index 10a555f5b1..d847260c9e 100644 --- a/examples/react/start-tailwind-v4/package.json +++ b/examples/react/start-tailwind-v4/package.json @@ -10,9 +10,9 @@ "start": "node .output/server/index.mjs" }, "dependencies": { - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/react-start": "^1.167.38", + "@tanstack/react-start": "^1.167.39", "react": "^19.0.0", "react-dom": "^19.0.0", "tailwind-merge": "^2.6.0", diff --git a/examples/react/start-trellaux/package.json b/examples/react/start-trellaux/package.json index 65ba4cadab..7cbb88f088 100644 --- a/examples/react/start-trellaux/package.json +++ b/examples/react/start-trellaux/package.json @@ -12,10 +12,10 @@ "dependencies": { "@tanstack/react-query": "^5.90.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", "@tanstack/react-router-ssr-query": "^1.166.11", - "@tanstack/react-start": "^1.167.38", + "@tanstack/react-start": "^1.167.39", "ky": "^1.7.4", "msw": "^2.7.0", "react": "^19.0.0", diff --git a/examples/react/start-workos/package.json b/examples/react/start-workos/package.json index f7dd8b07a1..c12b35b59b 100644 --- a/examples/react/start-workos/package.json +++ b/examples/react/start-workos/package.json @@ -14,9 +14,9 @@ "license": "MIT", "dependencies": { "@radix-ui/themes": "^3.3.0", - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/react-start": "^1.167.38", + "@tanstack/react-start": "^1.167.39", "@workos/authkit-tanstack-react-start": "^0.5.0", "react": "^19.0.0", "react-dom": "^19.0.0" diff --git a/examples/react/view-transitions/package.json b/examples/react/view-transitions/package.json index 6ff81fc850..db60215b6e 100644 --- a/examples/react/view-transitions/package.json +++ b/examples/react/view-transitions/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/router-plugin": "^1.167.22", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/with-framer-motion/package.json b/examples/react/with-framer-motion/package.json index ee57fc7bb7..f15baa4620 100644 --- a/examples/react/with-framer-motion/package.json +++ b/examples/react/with-framer-motion/package.json @@ -10,7 +10,7 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", "framer-motion": "^11.18.2", "react": "^19.0.0", diff --git a/examples/react/with-trpc-react-query/package.json b/examples/react/with-trpc-react-query/package.json index a2d52a8d24..3928dfdd4c 100644 --- a/examples/react/with-trpc-react-query/package.json +++ b/examples/react/with-trpc-react-query/package.json @@ -13,9 +13,9 @@ "@tailwindcss/vite": "^4.2.2", "@tanstack/react-query": "^5.90.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/router-plugin": "^1.167.22", "@trpc/client": "^11.4.3", "@trpc/server": "^11.4.3", "@trpc/tanstack-react-query": "^11.4.3", diff --git a/examples/react/with-trpc/package.json b/examples/react/with-trpc/package.json index 3f08e1bce0..0308dcc73b 100644 --- a/examples/react/with-trpc/package.json +++ b/examples/react/with-trpc/package.json @@ -11,9 +11,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.168.20", + "@tanstack/react-router": "^1.168.21", "@tanstack/react-router-devtools": "^1.166.13", - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/router-plugin": "^1.167.22", "@trpc/client": "^11.4.3", "@trpc/server": "^11.4.3", "express": "^4.21.2", diff --git a/examples/solid/authenticated-routes-firebase/package.json b/examples/solid/authenticated-routes-firebase/package.json index 79173e2e1c..3da798cdd4 100644 --- a/examples/solid/authenticated-routes-firebase/package.json +++ b/examples/solid/authenticated-routes-firebase/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/router-plugin": "^1.167.22", "firebase": "^11.4.0", "solid-js": "^1.9.10", "redaxios": "^0.5.1", diff --git a/examples/solid/authenticated-routes/package.json b/examples/solid/authenticated-routes/package.json index ba33f948a9..9d9881cf87 100644 --- a/examples/solid/authenticated-routes/package.json +++ b/examples/solid/authenticated-routes/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/router-plugin": "^1.167.22", "solid-js": "^1.9.10", "redaxios": "^0.5.1", "tailwindcss": "^4.2.2", diff --git a/examples/solid/basic-default-search-params/package.json b/examples/solid/basic-default-search-params/package.json index 5689f2fd6d..90151f8754 100644 --- a/examples/solid/basic-default-search-params/package.json +++ b/examples/solid/basic-default-search-params/package.json @@ -11,7 +11,7 @@ "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/solid-query": "^5.90.9", - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", "solid-js": "^1.9.10", "redaxios": "^0.5.1", diff --git a/examples/solid/basic-devtools-panel/package.json b/examples/solid/basic-devtools-panel/package.json index 981fe44258..902accf836 100644 --- a/examples/solid/basic-devtools-panel/package.json +++ b/examples/solid/basic-devtools-panel/package.json @@ -10,7 +10,7 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", "redaxios": "^0.5.1", "solid-js": "^1.9.10", diff --git a/examples/solid/basic-file-based/package.json b/examples/solid/basic-file-based/package.json index fd4d2cfefa..e4af9403af 100644 --- a/examples/solid/basic-file-based/package.json +++ b/examples/solid/basic-file-based/package.json @@ -10,7 +10,7 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", "redaxios": "^0.5.1", "solid-js": "^1.9.10", @@ -18,7 +18,7 @@ "zod": "^3.24.2" }, "devDependencies": { - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/router-plugin": "^1.167.22", "typescript": "^6.0.2", "vite": "^8.0.0", "vite-plugin-solid": "^2.11.11" diff --git a/examples/solid/basic-non-nested-devtools/package.json b/examples/solid/basic-non-nested-devtools/package.json index ab60dda517..501686857a 100644 --- a/examples/solid/basic-non-nested-devtools/package.json +++ b/examples/solid/basic-non-nested-devtools/package.json @@ -10,7 +10,7 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", "redaxios": "^0.5.1", "solid-js": "^1.9.10", diff --git a/examples/solid/basic-solid-query-file-based/package.json b/examples/solid/basic-solid-query-file-based/package.json index b88006a66e..b886f7d0bf 100644 --- a/examples/solid/basic-solid-query-file-based/package.json +++ b/examples/solid/basic-solid-query-file-based/package.json @@ -13,7 +13,7 @@ "@tailwindcss/vite": "^4.2.2", "@tanstack/solid-query": "^5.90.9", "@tanstack/solid-query-devtools": "^5.90.0", - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", "redaxios": "^0.5.1", "solid-js": "^1.9.10", @@ -21,7 +21,7 @@ "zod": "^3.24.2" }, "devDependencies": { - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/router-plugin": "^1.167.22", "typescript": "^6.0.2", "vite": "^8.0.0", "vite-plugin-solid": "^2.11.11" diff --git a/examples/solid/basic-solid-query/package.json b/examples/solid/basic-solid-query/package.json index 6a72187576..20d79164a8 100644 --- a/examples/solid/basic-solid-query/package.json +++ b/examples/solid/basic-solid-query/package.json @@ -12,14 +12,14 @@ "@tailwindcss/vite": "^4.2.2", "@tanstack/solid-query": "^5.90.9", "@tanstack/solid-query-devtools": "^5.90.0", - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", "redaxios": "^0.5.1", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2" }, "devDependencies": { - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/router-plugin": "^1.167.22", "typescript": "^6.0.2", "vite": "^8.0.0", "vite-plugin-solid": "^2.11.11" diff --git a/examples/solid/basic-ssr-file-based/package.json b/examples/solid/basic-ssr-file-based/package.json index 2e8dfc3375..82091ddb3a 100644 --- a/examples/solid/basic-ssr-file-based/package.json +++ b/examples/solid/basic-ssr-file-based/package.json @@ -11,8 +11,8 @@ "debug": "node --inspect-brk server" }, "dependencies": { - "@tanstack/solid-router": "^1.168.18", - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/solid-router": "^1.168.19", + "@tanstack/router-plugin": "^1.167.22", "compression": "^1.8.0", "express": "^4.21.2", "get-port": "^7.1.0", diff --git a/examples/solid/basic-ssr-streaming-file-based/package.json b/examples/solid/basic-ssr-streaming-file-based/package.json index ec4bbbf424..4ddfdaee05 100644 --- a/examples/solid/basic-ssr-streaming-file-based/package.json +++ b/examples/solid/basic-ssr-streaming-file-based/package.json @@ -12,7 +12,7 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", "compression": "^1.8.0", "express": "^4.21.2", @@ -24,7 +24,7 @@ "zod": "^3.24.2" }, "devDependencies": { - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/router-plugin": "^1.167.22", "@types/express": "^4.17.23", "typescript": "^6.0.2", "vite": "^8.0.0", diff --git a/examples/solid/basic-virtual-file-based/package.json b/examples/solid/basic-virtual-file-based/package.json index 58e91fe92d..bf3ec3b3cb 100644 --- a/examples/solid/basic-virtual-file-based/package.json +++ b/examples/solid/basic-virtual-file-based/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/router-plugin": "^1.167.22", "@tanstack/virtual-file-routes": "^1.161.7", "solid-js": "^1.9.10", "redaxios": "^0.5.1", diff --git a/examples/solid/basic-virtual-inside-file-based/package.json b/examples/solid/basic-virtual-inside-file-based/package.json index daa2154b73..714f7c0642 100644 --- a/examples/solid/basic-virtual-inside-file-based/package.json +++ b/examples/solid/basic-virtual-inside-file-based/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/router-plugin": "^1.167.22", "@tanstack/virtual-file-routes": "^1.161.7", "solid-js": "^1.9.10", "redaxios": "^0.5.1", diff --git a/examples/solid/basic/package.json b/examples/solid/basic/package.json index 5615debeaf..4c141199cc 100644 --- a/examples/solid/basic/package.json +++ b/examples/solid/basic/package.json @@ -10,7 +10,7 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", "redaxios": "^0.5.1", "solid-js": "^1.9.10", diff --git a/examples/solid/deferred-data/package.json b/examples/solid/deferred-data/package.json index 874e067a6c..68f68b669f 100644 --- a/examples/solid/deferred-data/package.json +++ b/examples/solid/deferred-data/package.json @@ -10,7 +10,7 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", "solid-js": "^1.9.10", "redaxios": "^0.5.1", diff --git a/examples/solid/i18n-paraglide/package.json b/examples/solid/i18n-paraglide/package.json index 2eee1dc9d1..9481b1d13c 100644 --- a/examples/solid/i18n-paraglide/package.json +++ b/examples/solid/i18n-paraglide/package.json @@ -11,8 +11,8 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.168.18", - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/solid-router": "^1.168.19", + "@tanstack/router-plugin": "^1.167.22", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2" }, diff --git a/examples/solid/kitchen-sink-file-based/package.json b/examples/solid/kitchen-sink-file-based/package.json index 1246d85944..49765faa05 100644 --- a/examples/solid/kitchen-sink-file-based/package.json +++ b/examples/solid/kitchen-sink-file-based/package.json @@ -10,7 +10,7 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", "immer": "^10.1.1", "redaxios": "^0.5.1", @@ -19,7 +19,7 @@ "zod": "^3.24.2" }, "devDependencies": { - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/router-plugin": "^1.167.22", "typescript": "^6.0.2", "vite": "^8.0.0", "vite-plugin-solid": "^2.11.11" diff --git a/examples/solid/kitchen-sink-solid-query-file-based/package.json b/examples/solid/kitchen-sink-solid-query-file-based/package.json index a93186ee7a..618679015d 100644 --- a/examples/solid/kitchen-sink-solid-query-file-based/package.json +++ b/examples/solid/kitchen-sink-solid-query-file-based/package.json @@ -10,10 +10,10 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/router-plugin": "^1.167.22", "@tanstack/solid-query": "^5.90.9", "@tanstack/solid-query-devtools": "^5.90.0", - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", "immer": "^10.1.1", "redaxios": "^0.5.1", diff --git a/examples/solid/kitchen-sink-solid-query/package.json b/examples/solid/kitchen-sink-solid-query/package.json index c12e9afba3..292aaaf962 100644 --- a/examples/solid/kitchen-sink-solid-query/package.json +++ b/examples/solid/kitchen-sink-solid-query/package.json @@ -12,7 +12,7 @@ "@tailwindcss/vite": "^4.2.2", "@tanstack/solid-query": "^5.90.9", "@tanstack/solid-query-devtools": "^5.90.0", - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", "immer": "^10.1.1", "redaxios": "^0.5.1", diff --git a/examples/solid/kitchen-sink/package.json b/examples/solid/kitchen-sink/package.json index 2aa7329eb3..0434ce62f8 100644 --- a/examples/solid/kitchen-sink/package.json +++ b/examples/solid/kitchen-sink/package.json @@ -10,7 +10,7 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", "immer": "^10.1.1", "solid-js": "^1.9.10", diff --git a/examples/solid/large-file-based/package.json b/examples/solid/large-file-based/package.json index e221cb20d9..3f8b6ea9de 100644 --- a/examples/solid/large-file-based/package.json +++ b/examples/solid/large-file-based/package.json @@ -13,9 +13,9 @@ "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/solid-query": "^5.90.9", - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/router-plugin": "^1.167.22", "solid-js": "^1.9.10", "redaxios": "^0.5.1", "tailwindcss": "^4.2.2", diff --git a/examples/solid/location-masking/package.json b/examples/solid/location-masking/package.json index 4a7f2f2ba0..127a65e821 100644 --- a/examples/solid/location-masking/package.json +++ b/examples/solid/location-masking/package.json @@ -11,7 +11,7 @@ "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/solid-query": "^5.90.9", - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", "solid-js": "^1.9.10", "redaxios": "^0.5.1", diff --git a/examples/solid/navigation-blocking/package.json b/examples/solid/navigation-blocking/package.json index 88ac0d9908..98b7116b3f 100644 --- a/examples/solid/navigation-blocking/package.json +++ b/examples/solid/navigation-blocking/package.json @@ -11,7 +11,7 @@ "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/solid-query": "^5.90.9", - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", "solid-js": "^1.9.10", "redaxios": "^0.5.1", diff --git a/examples/solid/quickstart-esbuild-file-based/package.json b/examples/solid/quickstart-esbuild-file-based/package.json index 794bedc713..bd784f4da7 100644 --- a/examples/solid/quickstart-esbuild-file-based/package.json +++ b/examples/solid/quickstart-esbuild-file-based/package.json @@ -9,8 +9,8 @@ "start": "dev" }, "dependencies": { - "@tanstack/router-plugin": "^1.167.21", - "@tanstack/solid-router": "^1.168.18", + "@tanstack/router-plugin": "^1.167.22", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", "redaxios": "^0.5.1", "solid-js": "^1.9.10", diff --git a/examples/solid/quickstart-file-based/package.json b/examples/solid/quickstart-file-based/package.json index 769fb6789d..c55c05db6a 100644 --- a/examples/solid/quickstart-file-based/package.json +++ b/examples/solid/quickstart-file-based/package.json @@ -10,7 +10,7 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", "redaxios": "^0.5.1", "solid-js": "^1.9.10", @@ -18,7 +18,7 @@ "zod": "^3.24.2" }, "devDependencies": { - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/router-plugin": "^1.167.22", "typescript": "^6.0.2", "vite": "^8.0.0", "vite-plugin-solid": "^2.11.11" diff --git a/examples/solid/quickstart-rspack-file-based/package.json b/examples/solid/quickstart-rspack-file-based/package.json index 6e8db5f1ea..9129f3f1f6 100644 --- a/examples/solid/quickstart-rspack-file-based/package.json +++ b/examples/solid/quickstart-rspack-file-based/package.json @@ -9,7 +9,7 @@ }, "dependencies": { "@tailwindcss/postcss": "^4.2.2", - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", "postcss": "^8.5.1", "solid-js": "^1.9.10", @@ -19,7 +19,7 @@ "@rsbuild/core": "^1.2.4", "@rsbuild/plugin-babel": "^1.0.6", "@rsbuild/plugin-solid": "^1.0.6", - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/router-plugin": "^1.167.22", "typescript": "^6.0.2" } } diff --git a/examples/solid/quickstart-webpack-file-based/package.json b/examples/solid/quickstart-webpack-file-based/package.json index 37b7bfbffa..5ba9293e4a 100644 --- a/examples/solid/quickstart-webpack-file-based/package.json +++ b/examples/solid/quickstart-webpack-file-based/package.json @@ -7,7 +7,7 @@ "build": "webpack build && tsc --noEmit" }, "dependencies": { - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2" @@ -15,7 +15,7 @@ "devDependencies": { "@babel/core": "^7.28.5", "@babel/preset-typescript": "^7.27.1", - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/router-plugin": "^1.167.22", "babel-loader": "^10.0.0", "babel-preset-solid": "^1.9.10", "css-loader": "^7.1.2", diff --git a/examples/solid/quickstart/package.json b/examples/solid/quickstart/package.json index f34499d6f9..7f61c0d701 100644 --- a/examples/solid/quickstart/package.json +++ b/examples/solid/quickstart/package.json @@ -10,7 +10,7 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2" diff --git a/examples/solid/router-monorepo-simple-lazy/package.json b/examples/solid/router-monorepo-simple-lazy/package.json index d46016eee2..2e59740694 100644 --- a/examples/solid/router-monorepo-simple-lazy/package.json +++ b/examples/solid/router-monorepo-simple-lazy/package.json @@ -8,9 +8,9 @@ "dev": "pnpm router build && pnpm post-feature build && pnpm app dev" }, "dependencies": { - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/router-plugin": "^1.167.22", "solid-js": "^1.9.10", "redaxios": "^0.5.1" }, diff --git a/examples/solid/router-monorepo-simple-lazy/packages/router/package.json b/examples/solid/router-monorepo-simple-lazy/packages/router/package.json index d60bfde079..0179b9772b 100644 --- a/examples/solid/router-monorepo-simple-lazy/packages/router/package.json +++ b/examples/solid/router-monorepo-simple-lazy/packages/router/package.json @@ -9,8 +9,8 @@ "types": "./dist/index.d.ts", "dependencies": { "@tanstack/history": "^1.161.6", - "@tanstack/solid-router": "^1.168.18", - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/solid-router": "^1.168.19", + "@tanstack/router-plugin": "^1.167.22", "redaxios": "^0.5.1", "zod": "^3.24.2", "solid-js": "^1.9.10" diff --git a/examples/solid/router-monorepo-simple/package.json b/examples/solid/router-monorepo-simple/package.json index 9181d0e1b9..fa6d0446cf 100644 --- a/examples/solid/router-monorepo-simple/package.json +++ b/examples/solid/router-monorepo-simple/package.json @@ -8,9 +8,9 @@ "dev": "pnpm router build && pnpm post-feature build && pnpm app dev" }, "dependencies": { - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/router-plugin": "^1.167.22", "solid-js": "^1.9.10", "redaxios": "^0.5.1" }, diff --git a/examples/solid/router-monorepo-simple/packages/router/package.json b/examples/solid/router-monorepo-simple/packages/router/package.json index 515dc95671..e5dc734412 100644 --- a/examples/solid/router-monorepo-simple/packages/router/package.json +++ b/examples/solid/router-monorepo-simple/packages/router/package.json @@ -9,8 +9,8 @@ "types": "./dist/index.d.ts", "dependencies": { "@tanstack/history": "^1.161.6", - "@tanstack/solid-router": "^1.168.18", - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/solid-router": "^1.168.19", + "@tanstack/router-plugin": "^1.167.22", "redaxios": "^0.5.1", "zod": "^3.24.2", "solid-js": "^1.9.10" diff --git a/examples/solid/router-monorepo-solid-query/package.json b/examples/solid/router-monorepo-solid-query/package.json index bdf32feacb..44fe0904bd 100644 --- a/examples/solid/router-monorepo-solid-query/package.json +++ b/examples/solid/router-monorepo-solid-query/package.json @@ -12,9 +12,9 @@ "dependencies": { "@tanstack/solid-query": "^5.90.9", "@tanstack/solid-query-devtools": "^5.90.0", - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/router-plugin": "^1.167.22", "solid-js": "^1.9.10", "redaxios": "^0.5.1" }, diff --git a/examples/solid/router-monorepo-solid-query/packages/router/package.json b/examples/solid/router-monorepo-solid-query/packages/router/package.json index db7adf2e44..97ea1eafd2 100644 --- a/examples/solid/router-monorepo-solid-query/packages/router/package.json +++ b/examples/solid/router-monorepo-solid-query/packages/router/package.json @@ -10,8 +10,8 @@ "dependencies": { "@tanstack/history": "^1.161.6", "@tanstack/solid-query": "^5.90.9", - "@tanstack/solid-router": "^1.168.18", - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/solid-router": "^1.168.19", + "@tanstack/router-plugin": "^1.167.22", "@router-solid-mono-solid-query/post-query": "workspace:*", "redaxios": "^0.5.1", "zod": "^3.24.2", diff --git a/examples/solid/scroll-restoration/package.json b/examples/solid/scroll-restoration/package.json index d1362e1c2b..f481e5d962 100644 --- a/examples/solid/scroll-restoration/package.json +++ b/examples/solid/scroll-restoration/package.json @@ -10,7 +10,7 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", "@tanstack/solid-virtual": "^3.13.0", "solid-js": "^1.9.10", diff --git a/examples/solid/search-validator-adapters/package.json b/examples/solid/search-validator-adapters/package.json index 23d8d2b442..dde7ba1232 100644 --- a/examples/solid/search-validator-adapters/package.json +++ b/examples/solid/search-validator-adapters/package.json @@ -13,9 +13,9 @@ "@tailwindcss/vite": "^4.2.2", "@tanstack/arktype-adapter": "^1.166.9", "@tanstack/solid-query": "^5.90.9", - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/router-plugin": "^1.167.22", "@tanstack/valibot-adapter": "^1.166.9", "@tanstack/zod-adapter": "^1.166.9", "arktype": "^2.1.7", diff --git a/examples/solid/start-basic-auth/package.json b/examples/solid/start-basic-auth/package.json index e71b5744f2..461a81252e 100644 --- a/examples/solid/start-basic-auth/package.json +++ b/examples/solid/start-basic-auth/package.json @@ -14,9 +14,9 @@ "@libsql/client": "^0.15.15", "@prisma/adapter-libsql": "^7.0.0", "@prisma/client": "^7.0.0", - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", - "@tanstack/solid-start": "^1.167.34", + "@tanstack/solid-start": "^1.167.35", "redaxios": "^0.5.1", "solid-js": "^1.9.10", "tailwind-merge": "^2.6.0" diff --git a/examples/solid/start-basic-authjs/package.json b/examples/solid/start-basic-authjs/package.json index 031692919f..f61d817535 100644 --- a/examples/solid/start-basic-authjs/package.json +++ b/examples/solid/start-basic-authjs/package.json @@ -11,9 +11,9 @@ }, "dependencies": { "@auth/core": "^0.41.1", - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", - "@tanstack/solid-start": "^1.167.34", + "@tanstack/solid-start": "^1.167.35", "start-authjs": "^1.0.0", "solid-js": "^1.9.10", "tailwind-merge": "^2.6.0" diff --git a/examples/solid/start-basic-cloudflare/package.json b/examples/solid/start-basic-cloudflare/package.json index d0f2ebde8d..00386e7fe2 100644 --- a/examples/solid/start-basic-cloudflare/package.json +++ b/examples/solid/start-basic-cloudflare/package.json @@ -12,9 +12,9 @@ "postinstall": "npm run cf-typegen" }, "dependencies": { - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", - "@tanstack/solid-start": "^1.167.34", + "@tanstack/solid-start": "^1.167.35", "solid-js": "^1.9.10" }, "devDependencies": { diff --git a/examples/solid/start-basic-netlify/package.json b/examples/solid/start-basic-netlify/package.json index aa83717084..ec0425c1b3 100644 --- a/examples/solid/start-basic-netlify/package.json +++ b/examples/solid/start-basic-netlify/package.json @@ -9,9 +9,9 @@ "preview": "vite preview" }, "dependencies": { - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", - "@tanstack/solid-start": "^1.167.34", + "@tanstack/solid-start": "^1.167.35", "solid-js": "^1.9.10" }, "devDependencies": { diff --git a/examples/solid/start-basic-nitro/package.json b/examples/solid/start-basic-nitro/package.json index 8de48b7cde..be2168c8f8 100644 --- a/examples/solid/start-basic-nitro/package.json +++ b/examples/solid/start-basic-nitro/package.json @@ -9,9 +9,9 @@ "preview": "vite preview" }, "dependencies": { - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", - "@tanstack/solid-start": "^1.167.34", + "@tanstack/solid-start": "^1.167.35", "solid-js": "^1.9.10" }, "devDependencies": { diff --git a/examples/solid/start-basic-solid-query/package.json b/examples/solid/start-basic-solid-query/package.json index 7738b189e7..e03ded709f 100644 --- a/examples/solid/start-basic-solid-query/package.json +++ b/examples/solid/start-basic-solid-query/package.json @@ -12,10 +12,10 @@ "dependencies": { "@tanstack/solid-query": "^5.90.9", "@tanstack/solid-query-devtools": "^5.90.0", - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", "@tanstack/solid-router-ssr-query": "^1.166.11", - "@tanstack/solid-start": "^1.167.34", + "@tanstack/solid-start": "^1.167.35", "redaxios": "^0.5.1", "solid-js": "^1.9.10", "tailwind-merge": "^2.6.0" diff --git a/examples/solid/start-basic-static/package.json b/examples/solid/start-basic-static/package.json index 4c871e6006..bd4450f8fd 100644 --- a/examples/solid/start-basic-static/package.json +++ b/examples/solid/start-basic-static/package.json @@ -10,10 +10,10 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", - "@tanstack/solid-start": "^1.167.34", - "@tanstack/start-static-server-functions": "^1.166.32", + "@tanstack/solid-start": "^1.167.35", + "@tanstack/start-static-server-functions": "^1.166.33", "solid-js": "^1.9.10", "redaxios": "^0.5.1", "tailwind-merge": "^2.6.0" diff --git a/examples/solid/start-basic/package.json b/examples/solid/start-basic/package.json index e4b98daaa5..087e2ecb87 100644 --- a/examples/solid/start-basic/package.json +++ b/examples/solid/start-basic/package.json @@ -10,9 +10,9 @@ "start": "node .output/server/index.mjs" }, "dependencies": { - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", - "@tanstack/solid-start": "^1.167.34", + "@tanstack/solid-start": "^1.167.35", "redaxios": "^0.5.1", "solid-js": "^1.9.10", "tailwind-merge": "^2.6.0" diff --git a/examples/solid/start-bun/package.json b/examples/solid/start-bun/package.json index 4367a7921b..80e91cc982 100644 --- a/examples/solid/start-bun/package.json +++ b/examples/solid/start-bun/package.json @@ -15,11 +15,11 @@ "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/solid-devtools": "^0.7.0", - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", "@tanstack/solid-router-ssr-query": "^1.166.11", - "@tanstack/solid-start": "^1.167.34", - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/solid-start": "^1.167.35", + "@tanstack/router-plugin": "^1.167.22", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2" }, diff --git a/examples/solid/start-convex-better-auth/package.json b/examples/solid/start-convex-better-auth/package.json index 27e3212279..a9cb204b9e 100644 --- a/examples/solid/start-convex-better-auth/package.json +++ b/examples/solid/start-convex-better-auth/package.json @@ -13,9 +13,9 @@ "dependencies": { "@convex-dev/better-auth": "^0.9.7", "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", - "@tanstack/solid-start": "^1.167.34", + "@tanstack/solid-start": "^1.167.35", "better-auth": "^1.3.27", "clsx": "^2.1.1", "convex": "^1.28.2", diff --git a/examples/solid/start-counter/package.json b/examples/solid/start-counter/package.json index ce50e3a801..35b43b49b5 100644 --- a/examples/solid/start-counter/package.json +++ b/examples/solid/start-counter/package.json @@ -10,9 +10,9 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", - "@tanstack/solid-start": "^1.167.34", + "@tanstack/solid-start": "^1.167.35", "solid-js": "^1.9.10", "redaxios": "^0.5.1", "tailwind-merge": "^2.6.0", diff --git a/examples/solid/start-i18n-paraglide/package.json b/examples/solid/start-i18n-paraglide/package.json index bbccbc8a65..9700ad95ab 100644 --- a/examples/solid/start-i18n-paraglide/package.json +++ b/examples/solid/start-i18n-paraglide/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tanstack/solid-devtools": "^0.7.0", - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", - "@tanstack/solid-start": "^1.167.34", + "@tanstack/solid-start": "^1.167.35", "solid-js": "^1.9.10" }, "devDependencies": { diff --git a/examples/solid/start-large/package.json b/examples/solid/start-large/package.json index 26d9b6495f..60351bf889 100644 --- a/examples/solid/start-large/package.json +++ b/examples/solid/start-large/package.json @@ -13,9 +13,9 @@ }, "dependencies": { "@tanstack/solid-query": "^5.90.9", - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", - "@tanstack/solid-start": "^1.167.34", + "@tanstack/solid-start": "^1.167.35", "solid-js": "^1.9.10", "redaxios": "^0.5.1", "tailwind-merge": "^2.6.0", diff --git a/examples/solid/start-streaming-data-from-server-functions/package.json b/examples/solid/start-streaming-data-from-server-functions/package.json index 3d8319fd74..240ecad611 100644 --- a/examples/solid/start-streaming-data-from-server-functions/package.json +++ b/examples/solid/start-streaming-data-from-server-functions/package.json @@ -10,9 +10,9 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", - "@tanstack/solid-start": "^1.167.34", + "@tanstack/solid-start": "^1.167.35", "solid-js": "^1.9.10", "zod": "^3.24.2" }, diff --git a/examples/solid/start-supabase-basic/package.json b/examples/solid/start-supabase-basic/package.json index 5d3a30082b..9cdd3e1c88 100644 --- a/examples/solid/start-supabase-basic/package.json +++ b/examples/solid/start-supabase-basic/package.json @@ -14,9 +14,9 @@ "dependencies": { "@supabase/ssr": "^0.5.2", "@supabase/supabase-js": "^2.48.1", - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", - "@tanstack/solid-start": "^1.167.34", + "@tanstack/solid-start": "^1.167.35", "solid-js": "^1.9.9", "redaxios": "^0.5.1" }, diff --git a/examples/solid/start-tailwind-v4/package.json b/examples/solid/start-tailwind-v4/package.json index 32661acd59..4beecdd00e 100644 --- a/examples/solid/start-tailwind-v4/package.json +++ b/examples/solid/start-tailwind-v4/package.json @@ -10,9 +10,9 @@ "start": "node .output/server/index.mjs" }, "dependencies": { - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", - "@tanstack/solid-start": "^1.167.34", + "@tanstack/solid-start": "^1.167.35", "solid-js": "^1.9.10", "tailwind-merge": "^2.6.0", "zod": "^3.24.2" diff --git a/examples/solid/view-transitions/package.json b/examples/solid/view-transitions/package.json index c6d401aaf5..3c42422f4b 100644 --- a/examples/solid/view-transitions/package.json +++ b/examples/solid/view-transitions/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/router-plugin": "^1.167.22", "solid-js": "^1.9.10", "redaxios": "^0.5.1", "tailwindcss": "^4.2.2", diff --git a/examples/solid/with-framer-motion/package.json b/examples/solid/with-framer-motion/package.json index 41ccc0dddc..db77023373 100644 --- a/examples/solid/with-framer-motion/package.json +++ b/examples/solid/with-framer-motion/package.json @@ -10,7 +10,7 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", "redaxios": "^0.5.1", "solid-js": "^1.9.10", diff --git a/examples/solid/with-trpc/package.json b/examples/solid/with-trpc/package.json index fba91f39b9..833dbca872 100644 --- a/examples/solid/with-trpc/package.json +++ b/examples/solid/with-trpc/package.json @@ -11,9 +11,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.168.18", + "@tanstack/solid-router": "^1.168.19", "@tanstack/solid-router-devtools": "^1.166.13", - "@tanstack/router-plugin": "^1.167.21", + "@tanstack/router-plugin": "^1.167.22", "@trpc/client": "^11.4.3", "@trpc/server": "^11.4.3", "express": "^4.21.2", diff --git a/examples/vue/basic-file-based-jsx/package.json b/examples/vue/basic-file-based-jsx/package.json index bfc10ad3e8..0ec172de06 100644 --- a/examples/vue/basic-file-based-jsx/package.json +++ b/examples/vue/basic-file-based-jsx/package.json @@ -10,8 +10,8 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/router-plugin": "^1.167.21", - "@tanstack/vue-router": "^1.168.18", + "@tanstack/router-plugin": "^1.167.22", + "@tanstack/vue-router": "^1.168.19", "@tanstack/vue-router-devtools": "^1.166.13", "@tanstack/zod-adapter": "^1.166.9", "redaxios": "^0.5.1", diff --git a/examples/vue/basic-file-based-sfc/package.json b/examples/vue/basic-file-based-sfc/package.json index aeac1c2b0d..b9da55a299 100644 --- a/examples/vue/basic-file-based-sfc/package.json +++ b/examples/vue/basic-file-based-sfc/package.json @@ -10,8 +10,8 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/router-plugin": "^1.167.21", - "@tanstack/vue-router": "^1.168.18", + "@tanstack/router-plugin": "^1.167.22", + "@tanstack/vue-router": "^1.168.19", "@tanstack/vue-router-devtools": "^1.166.13", "@tanstack/zod-adapter": "^1.166.9", "redaxios": "^0.5.1", diff --git a/examples/vue/basic/package.json b/examples/vue/basic/package.json index fc6eeb4993..adca570e49 100644 --- a/examples/vue/basic/package.json +++ b/examples/vue/basic/package.json @@ -9,7 +9,7 @@ "start": "vite" }, "dependencies": { - "@tanstack/vue-router": "^1.168.18", + "@tanstack/vue-router": "^1.168.19", "@tanstack/vue-router-devtools": "^1.166.13", "redaxios": "^0.5.1", "vue": "^3.5.13", diff --git a/packages/react-router/CHANGELOG.md b/packages/react-router/CHANGELOG.md index c55152e20e..2a9dd79694 100644 --- a/packages/react-router/CHANGELOG.md +++ b/packages/react-router/CHANGELOG.md @@ -1,5 +1,12 @@ # @tanstack/react-router +## 1.168.21 + +### Patch Changes + +- Updated dependencies [[`16f6892`](https://github.com/TanStack/router/commit/16f6892d6b7ceadf606677c5a40e743f29163aa6)]: + - @tanstack/router-core@1.168.15 + ## 1.168.20 ### Patch Changes diff --git a/packages/react-router/package.json b/packages/react-router/package.json index d7906f3706..8f7a0abf2b 100644 --- a/packages/react-router/package.json +++ b/packages/react-router/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/react-router", - "version": "1.168.20", + "version": "1.168.21", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", diff --git a/packages/react-start-client/CHANGELOG.md b/packages/react-start-client/CHANGELOG.md index 8bcf917855..c4a85b8995 100644 --- a/packages/react-start-client/CHANGELOG.md +++ b/packages/react-start-client/CHANGELOG.md @@ -1,5 +1,14 @@ # @tanstack/react-start-client +## 1.166.38 + +### Patch Changes + +- Updated dependencies [[`16f6892`](https://github.com/TanStack/router/commit/16f6892d6b7ceadf606677c5a40e743f29163aa6)]: + - @tanstack/router-core@1.168.15 + - @tanstack/react-router@1.168.21 + - @tanstack/start-client-core@1.167.17 + ## 1.166.37 ### Patch Changes diff --git a/packages/react-start-client/package.json b/packages/react-start-client/package.json index 9bc353e84b..2285410ddc 100644 --- a/packages/react-start-client/package.json +++ b/packages/react-start-client/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/react-start-client", - "version": "1.166.37", + "version": "1.166.38", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", diff --git a/packages/react-start-rsc/CHANGELOG.md b/packages/react-start-rsc/CHANGELOG.md index 964f286d45..439347f49d 100644 --- a/packages/react-start-rsc/CHANGELOG.md +++ b/packages/react-start-rsc/CHANGELOG.md @@ -1,5 +1,18 @@ # @tanstack/react-start-rsc +## 0.0.18 + +### Patch Changes + +- Updated dependencies [[`16f6892`](https://github.com/TanStack/router/commit/16f6892d6b7ceadf606677c5a40e743f29163aa6)]: + - @tanstack/router-core@1.168.15 + - @tanstack/react-router@1.168.21 + - @tanstack/react-start-server@1.166.39 + - @tanstack/start-client-core@1.167.17 + - @tanstack/start-plugin-core@1.167.34 + - @tanstack/start-server-core@1.167.19 + - @tanstack/start-storage-context@1.166.29 + ## 0.0.17 ### Patch Changes diff --git a/packages/react-start-rsc/package.json b/packages/react-start-rsc/package.json index f7b74bcca2..73005a2431 100644 --- a/packages/react-start-rsc/package.json +++ b/packages/react-start-rsc/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/react-start-rsc", - "version": "0.0.17", + "version": "0.0.18", "description": "React Server Components support for TanStack Start", "author": "Tanner Linsley", "license": "MIT", diff --git a/packages/react-start-server/CHANGELOG.md b/packages/react-start-server/CHANGELOG.md index c2857d4720..94630de683 100644 --- a/packages/react-start-server/CHANGELOG.md +++ b/packages/react-start-server/CHANGELOG.md @@ -1,5 +1,15 @@ # @tanstack/react-start-server +## 1.166.39 + +### Patch Changes + +- Updated dependencies [[`16f6892`](https://github.com/TanStack/router/commit/16f6892d6b7ceadf606677c5a40e743f29163aa6)]: + - @tanstack/router-core@1.168.15 + - @tanstack/react-router@1.168.21 + - @tanstack/start-client-core@1.167.17 + - @tanstack/start-server-core@1.167.19 + ## 1.166.38 ### Patch Changes diff --git a/packages/react-start-server/package.json b/packages/react-start-server/package.json index 94ba850cbb..c5d554d026 100644 --- a/packages/react-start-server/package.json +++ b/packages/react-start-server/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/react-start-server", - "version": "1.166.38", + "version": "1.166.39", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", diff --git a/packages/react-start/CHANGELOG.md b/packages/react-start/CHANGELOG.md index 641a360b69..6f66220cec 100644 --- a/packages/react-start/CHANGELOG.md +++ b/packages/react-start/CHANGELOG.md @@ -1,5 +1,18 @@ # @tanstack/react-start +## 1.167.39 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/react-router@1.168.21 + - @tanstack/react-start-client@1.166.38 + - @tanstack/react-start-rsc@0.0.18 + - @tanstack/react-start-server@1.166.39 + - @tanstack/start-client-core@1.167.17 + - @tanstack/start-plugin-core@1.167.34 + - @tanstack/start-server-core@1.167.19 + ## 1.167.38 ### Patch Changes diff --git a/packages/react-start/package.json b/packages/react-start/package.json index a3a76cd78f..e531aa199e 100644 --- a/packages/react-start/package.json +++ b/packages/react-start/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/react-start", - "version": "1.167.38", + "version": "1.167.39", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", diff --git a/packages/router-cli/CHANGELOG.md b/packages/router-cli/CHANGELOG.md index f2b40aa762..da3731691c 100644 --- a/packages/router-cli/CHANGELOG.md +++ b/packages/router-cli/CHANGELOG.md @@ -1,5 +1,12 @@ # @tanstack/router-cli +## 1.166.33 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.166.32 + ## 1.166.32 ### Patch Changes diff --git a/packages/router-cli/package.json b/packages/router-cli/package.json index a90ea8e289..c8baf996bb 100644 --- a/packages/router-cli/package.json +++ b/packages/router-cli/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/router-cli", - "version": "1.166.32", + "version": "1.166.33", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", diff --git a/packages/router-core/CHANGELOG.md b/packages/router-core/CHANGELOG.md index 7b95a4c75d..5fecaef60b 100644 --- a/packages/router-core/CHANGELOG.md +++ b/packages/router-core/CHANGELOG.md @@ -1,5 +1,13 @@ # @tanstack/router-core +## 1.168.15 + +### Patch Changes + +- Fix async loaders that throw or return `notFound()` so they do not briefly mark the match as `success` before the final not-found boundary is resolved. ([#7184](https://github.com/TanStack/router/pull/7184)) + + This prevents route components from rendering with missing loader data during navigation when React observes the intermediate match state before not-found finalization completes. + ## 1.168.14 ### Patch Changes diff --git a/packages/router-core/package.json b/packages/router-core/package.json index 923fa0af20..779fe17d47 100644 --- a/packages/router-core/package.json +++ b/packages/router-core/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/router-core", - "version": "1.168.14", + "version": "1.168.15", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", diff --git a/packages/router-generator/CHANGELOG.md b/packages/router-generator/CHANGELOG.md index 4dd96ce6cd..6a773de36c 100644 --- a/packages/router-generator/CHANGELOG.md +++ b/packages/router-generator/CHANGELOG.md @@ -1,5 +1,12 @@ # @tanstack/router-generator +## 1.166.32 + +### Patch Changes + +- Updated dependencies [[`16f6892`](https://github.com/TanStack/router/commit/16f6892d6b7ceadf606677c5a40e743f29163aa6)]: + - @tanstack/router-core@1.168.15 + ## 1.166.31 ### Patch Changes diff --git a/packages/router-generator/package.json b/packages/router-generator/package.json index c74e3090fb..f74026597a 100644 --- a/packages/router-generator/package.json +++ b/packages/router-generator/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/router-generator", - "version": "1.166.31", + "version": "1.166.32", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", diff --git a/packages/router-plugin/CHANGELOG.md b/packages/router-plugin/CHANGELOG.md index ddfd5f61bd..d15e6062d7 100644 --- a/packages/router-plugin/CHANGELOG.md +++ b/packages/router-plugin/CHANGELOG.md @@ -1,5 +1,14 @@ # @tanstack/router-plugin +## 1.167.22 + +### Patch Changes + +- Updated dependencies [[`16f6892`](https://github.com/TanStack/router/commit/16f6892d6b7ceadf606677c5a40e743f29163aa6)]: + - @tanstack/router-core@1.168.15 + - @tanstack/react-router@1.168.21 + - @tanstack/router-generator@1.166.32 + ## 1.167.21 ### Patch Changes diff --git a/packages/router-plugin/package.json b/packages/router-plugin/package.json index d1aa1992f4..847d422ade 100644 --- a/packages/router-plugin/package.json +++ b/packages/router-plugin/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/router-plugin", - "version": "1.167.21", + "version": "1.167.22", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", diff --git a/packages/router-vite-plugin/CHANGELOG.md b/packages/router-vite-plugin/CHANGELOG.md index ad37b5d3f5..4dd045cdca 100644 --- a/packages/router-vite-plugin/CHANGELOG.md +++ b/packages/router-vite-plugin/CHANGELOG.md @@ -1,5 +1,12 @@ # @tanstack/router-vite-plugin +## 1.166.37 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-plugin@1.167.22 + ## 1.166.36 ### Patch Changes diff --git a/packages/router-vite-plugin/package.json b/packages/router-vite-plugin/package.json index 6b133a5b33..c5dafff49d 100644 --- a/packages/router-vite-plugin/package.json +++ b/packages/router-vite-plugin/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/router-vite-plugin", - "version": "1.166.36", + "version": "1.166.37", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", diff --git a/packages/solid-router/CHANGELOG.md b/packages/solid-router/CHANGELOG.md index 0f713f4a19..adae20df2e 100644 --- a/packages/solid-router/CHANGELOG.md +++ b/packages/solid-router/CHANGELOG.md @@ -1,5 +1,12 @@ # @tanstack/solid-router +## 1.168.19 + +### Patch Changes + +- Updated dependencies [[`16f6892`](https://github.com/TanStack/router/commit/16f6892d6b7ceadf606677c5a40e743f29163aa6)]: + - @tanstack/router-core@1.168.15 + ## 1.168.18 ### Patch Changes diff --git a/packages/solid-router/package.json b/packages/solid-router/package.json index d2f2f4c636..2c08cc516c 100644 --- a/packages/solid-router/package.json +++ b/packages/solid-router/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/solid-router", - "version": "1.168.18", + "version": "1.168.19", "description": "Modern and scalable routing for Solid applications", "author": "Tanner Linsley", "license": "MIT", diff --git a/packages/solid-start-client/CHANGELOG.md b/packages/solid-start-client/CHANGELOG.md index e44ec41178..08913d70fe 100644 --- a/packages/solid-start-client/CHANGELOG.md +++ b/packages/solid-start-client/CHANGELOG.md @@ -1,5 +1,14 @@ # @tanstack/solid-start-client +## 1.166.35 + +### Patch Changes + +- Updated dependencies [[`16f6892`](https://github.com/TanStack/router/commit/16f6892d6b7ceadf606677c5a40e743f29163aa6)]: + - @tanstack/router-core@1.168.15 + - @tanstack/solid-router@1.168.19 + - @tanstack/start-client-core@1.167.17 + ## 1.166.34 ### Patch Changes diff --git a/packages/solid-start-client/package.json b/packages/solid-start-client/package.json index dc6afbfe5a..fc634fdbb3 100644 --- a/packages/solid-start-client/package.json +++ b/packages/solid-start-client/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/solid-start-client", - "version": "1.166.34", + "version": "1.166.35", "description": "Modern and scalable routing for Solid applications", "author": "Tanner Linsley", "license": "MIT", diff --git a/packages/solid-start-server/CHANGELOG.md b/packages/solid-start-server/CHANGELOG.md index 69c650dcbe..e4bc56a0eb 100644 --- a/packages/solid-start-server/CHANGELOG.md +++ b/packages/solid-start-server/CHANGELOG.md @@ -1,5 +1,15 @@ # @tanstack/solid-start-server +## 1.166.36 + +### Patch Changes + +- Updated dependencies [[`16f6892`](https://github.com/TanStack/router/commit/16f6892d6b7ceadf606677c5a40e743f29163aa6)]: + - @tanstack/router-core@1.168.15 + - @tanstack/solid-router@1.168.19 + - @tanstack/start-client-core@1.167.17 + - @tanstack/start-server-core@1.167.19 + ## 1.166.35 ### Patch Changes diff --git a/packages/solid-start-server/package.json b/packages/solid-start-server/package.json index b4fe2ac02a..2de2f26e03 100644 --- a/packages/solid-start-server/package.json +++ b/packages/solid-start-server/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/solid-start-server", - "version": "1.166.35", + "version": "1.166.36", "description": "Modern and scalable routing for Solid applications", "author": "Tanner Linsley", "license": "MIT", diff --git a/packages/solid-start/CHANGELOG.md b/packages/solid-start/CHANGELOG.md index 61a4e8e6b5..f2ed87da71 100644 --- a/packages/solid-start/CHANGELOG.md +++ b/packages/solid-start/CHANGELOG.md @@ -1,5 +1,17 @@ # @tanstack/solid-start +## 1.167.35 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/solid-router@1.168.19 + - @tanstack/solid-start-client@1.166.35 + - @tanstack/solid-start-server@1.166.36 + - @tanstack/start-client-core@1.167.17 + - @tanstack/start-plugin-core@1.167.34 + - @tanstack/start-server-core@1.167.19 + ## 1.167.34 ### Patch Changes diff --git a/packages/solid-start/package.json b/packages/solid-start/package.json index 25c2958d8c..9823910bd1 100644 --- a/packages/solid-start/package.json +++ b/packages/solid-start/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/solid-start", - "version": "1.167.34", + "version": "1.167.35", "description": "Modern and scalable routing for Solid applications", "author": "Tanner Linsley", "license": "MIT", diff --git a/packages/start-client-core/CHANGELOG.md b/packages/start-client-core/CHANGELOG.md index 13d6d8b91a..cfbb33e86a 100644 --- a/packages/start-client-core/CHANGELOG.md +++ b/packages/start-client-core/CHANGELOG.md @@ -1,5 +1,13 @@ # @tanstack/start-client-core +## 1.167.17 + +### Patch Changes + +- Updated dependencies [[`16f6892`](https://github.com/TanStack/router/commit/16f6892d6b7ceadf606677c5a40e743f29163aa6)]: + - @tanstack/router-core@1.168.15 + - @tanstack/start-storage-context@1.166.29 + ## 1.167.16 ### Patch Changes diff --git a/packages/start-client-core/package.json b/packages/start-client-core/package.json index 2ae70cc25a..39ce827da2 100644 --- a/packages/start-client-core/package.json +++ b/packages/start-client-core/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/start-client-core", - "version": "1.167.16", + "version": "1.167.17", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", diff --git a/packages/start-plugin-core/CHANGELOG.md b/packages/start-plugin-core/CHANGELOG.md index 8c37fe2c87..cea13e5b95 100644 --- a/packages/start-plugin-core/CHANGELOG.md +++ b/packages/start-plugin-core/CHANGELOG.md @@ -1,5 +1,16 @@ # @tanstack/start-plugin-core +## 1.167.34 + +### Patch Changes + +- Updated dependencies [[`16f6892`](https://github.com/TanStack/router/commit/16f6892d6b7ceadf606677c5a40e743f29163aa6)]: + - @tanstack/router-core@1.168.15 + - @tanstack/router-generator@1.166.32 + - @tanstack/router-plugin@1.167.22 + - @tanstack/start-client-core@1.167.17 + - @tanstack/start-server-core@1.167.19 + ## 1.167.33 ### Patch Changes diff --git a/packages/start-plugin-core/package.json b/packages/start-plugin-core/package.json index b42e418224..46c33a14c2 100644 --- a/packages/start-plugin-core/package.json +++ b/packages/start-plugin-core/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/start-plugin-core", - "version": "1.167.33", + "version": "1.167.34", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", diff --git a/packages/start-server-core/CHANGELOG.md b/packages/start-server-core/CHANGELOG.md index 97ead206d2..fd7506dd57 100644 --- a/packages/start-server-core/CHANGELOG.md +++ b/packages/start-server-core/CHANGELOG.md @@ -1,5 +1,14 @@ # @tanstack/start-server-core +## 1.167.19 + +### Patch Changes + +- Updated dependencies [[`16f6892`](https://github.com/TanStack/router/commit/16f6892d6b7ceadf606677c5a40e743f29163aa6)]: + - @tanstack/router-core@1.168.15 + - @tanstack/start-client-core@1.167.17 + - @tanstack/start-storage-context@1.166.29 + ## 1.167.18 ### Patch Changes diff --git a/packages/start-server-core/package.json b/packages/start-server-core/package.json index 77c7ace7c2..9fa626652b 100644 --- a/packages/start-server-core/package.json +++ b/packages/start-server-core/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/start-server-core", - "version": "1.167.18", + "version": "1.167.19", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", diff --git a/packages/start-static-server-functions/CHANGELOG.md b/packages/start-static-server-functions/CHANGELOG.md index e7cd4a9762..319c21bfe3 100644 --- a/packages/start-static-server-functions/CHANGELOG.md +++ b/packages/start-static-server-functions/CHANGELOG.md @@ -1,5 +1,14 @@ # @tanstack/start-static-server-functions +## 1.166.33 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/start-client-core@1.167.17 + - @tanstack/react-start@1.167.39 + - @tanstack/solid-start@1.167.35 + ## 1.166.32 ### Patch Changes diff --git a/packages/start-static-server-functions/package.json b/packages/start-static-server-functions/package.json index 91fd78fc40..3a521e8258 100644 --- a/packages/start-static-server-functions/package.json +++ b/packages/start-static-server-functions/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/start-static-server-functions", - "version": "1.166.32", + "version": "1.166.33", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", diff --git a/packages/start-storage-context/CHANGELOG.md b/packages/start-storage-context/CHANGELOG.md index b8cfbdb4eb..1590207314 100644 --- a/packages/start-storage-context/CHANGELOG.md +++ b/packages/start-storage-context/CHANGELOG.md @@ -1,5 +1,12 @@ # @tanstack/start-storage-context +## 1.166.29 + +### Patch Changes + +- Updated dependencies [[`16f6892`](https://github.com/TanStack/router/commit/16f6892d6b7ceadf606677c5a40e743f29163aa6)]: + - @tanstack/router-core@1.168.15 + ## 1.166.28 ### Patch Changes diff --git a/packages/start-storage-context/package.json b/packages/start-storage-context/package.json index 265a4c3296..31b7117c8f 100644 --- a/packages/start-storage-context/package.json +++ b/packages/start-storage-context/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/start-storage-context", - "version": "1.166.28", + "version": "1.166.29", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", diff --git a/packages/vue-router/CHANGELOG.md b/packages/vue-router/CHANGELOG.md index f5a3d30531..1ce2c54612 100644 --- a/packages/vue-router/CHANGELOG.md +++ b/packages/vue-router/CHANGELOG.md @@ -1,5 +1,12 @@ # @tanstack/vue-router +## 1.168.19 + +### Patch Changes + +- Updated dependencies [[`16f6892`](https://github.com/TanStack/router/commit/16f6892d6b7ceadf606677c5a40e743f29163aa6)]: + - @tanstack/router-core@1.168.15 + ## 1.168.18 ### Patch Changes diff --git a/packages/vue-router/package.json b/packages/vue-router/package.json index 88a48c1f84..94a4f7d74b 100644 --- a/packages/vue-router/package.json +++ b/packages/vue-router/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/vue-router", - "version": "1.168.18", + "version": "1.168.19", "description": "Modern and scalable routing for Vue applications", "author": "Tanner Linsley", "license": "MIT", diff --git a/packages/vue-start-client/CHANGELOG.md b/packages/vue-start-client/CHANGELOG.md index c818b39ba3..51061ec6e2 100644 --- a/packages/vue-start-client/CHANGELOG.md +++ b/packages/vue-start-client/CHANGELOG.md @@ -1,5 +1,14 @@ # @tanstack/vue-start-client +## 1.166.35 + +### Patch Changes + +- Updated dependencies [[`16f6892`](https://github.com/TanStack/router/commit/16f6892d6b7ceadf606677c5a40e743f29163aa6)]: + - @tanstack/router-core@1.168.15 + - @tanstack/start-client-core@1.167.17 + - @tanstack/vue-router@1.168.19 + ## 1.166.34 ### Patch Changes diff --git a/packages/vue-start-client/package.json b/packages/vue-start-client/package.json index ef40699f00..eaf9060e01 100644 --- a/packages/vue-start-client/package.json +++ b/packages/vue-start-client/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/vue-start-client", - "version": "1.166.34", + "version": "1.166.35", "description": "Modern and scalable routing for Vue applications", "author": "Tanner Linsley", "license": "MIT", diff --git a/packages/vue-start-server/CHANGELOG.md b/packages/vue-start-server/CHANGELOG.md index 7a366aa06a..f9de3ec8b0 100644 --- a/packages/vue-start-server/CHANGELOG.md +++ b/packages/vue-start-server/CHANGELOG.md @@ -1,5 +1,15 @@ # @tanstack/vue-start-server +## 1.166.36 + +### Patch Changes + +- Updated dependencies [[`16f6892`](https://github.com/TanStack/router/commit/16f6892d6b7ceadf606677c5a40e743f29163aa6)]: + - @tanstack/router-core@1.168.15 + - @tanstack/start-client-core@1.167.17 + - @tanstack/start-server-core@1.167.19 + - @tanstack/vue-router@1.168.19 + ## 1.166.35 ### Patch Changes diff --git a/packages/vue-start-server/package.json b/packages/vue-start-server/package.json index 1f837cf579..8056ea4282 100644 --- a/packages/vue-start-server/package.json +++ b/packages/vue-start-server/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/vue-start-server", - "version": "1.166.35", + "version": "1.166.36", "description": "Modern and scalable routing for Vue applications", "author": "Tanner Linsley", "license": "MIT", diff --git a/packages/vue-start/CHANGELOG.md b/packages/vue-start/CHANGELOG.md index b4aaae45a9..ce97a89793 100644 --- a/packages/vue-start/CHANGELOG.md +++ b/packages/vue-start/CHANGELOG.md @@ -1,5 +1,17 @@ # @tanstack/vue-start +## 1.167.35 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/start-client-core@1.167.17 + - @tanstack/start-plugin-core@1.167.34 + - @tanstack/start-server-core@1.167.19 + - @tanstack/vue-router@1.168.19 + - @tanstack/vue-start-client@1.166.35 + - @tanstack/vue-start-server@1.166.36 + ## 1.167.34 ### Patch Changes diff --git a/packages/vue-start/package.json b/packages/vue-start/package.json index d6d9cd0e80..30ed515962 100644 --- a/packages/vue-start/package.json +++ b/packages/vue-start/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/vue-start", - "version": "1.167.34", + "version": "1.167.35", "description": "Modern and scalable routing for Vue applications", "author": "Tanner Linsley", "license": "MIT", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f8c38ee3c5..9afc7270ff 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -9815,7 +9815,7 @@ importers: specifier: workspace:* version: link:../../../packages/router-plugin '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -9852,7 +9852,7 @@ importers: specifier: workspace:* version: link:../../../packages/router-plugin '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -9892,7 +9892,7 @@ importers: specifier: ^4.2.2 version: 4.2.2(vite@8.0.0(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.6.1)(sass-embedded@1.97.2)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.8.1)) '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -9932,7 +9932,7 @@ importers: specifier: ^5.90.9 version: 5.90.9(solid-js@1.9.10) '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -9966,7 +9966,7 @@ importers: specifier: ^4.2.2 version: 4.2.2(vite@8.0.0(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.6.1)(sass-embedded@1.97.2)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.8.1)) '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -9997,7 +9997,7 @@ importers: specifier: ^4.2.2 version: 4.2.2(vite@8.0.0(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.6.1)(sass-embedded@1.97.2)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.8.1)) '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -10034,7 +10034,7 @@ importers: specifier: ^4.2.2 version: 4.2.2(vite@8.0.0(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.6.1)(sass-embedded@1.97.2)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.8.1)) '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -10077,7 +10077,7 @@ importers: specifier: ^5.90.0 version: 5.90.4(@tanstack/solid-query@5.90.9(solid-js@1.9.10))(solid-js@1.9.10) '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -10117,7 +10117,7 @@ importers: specifier: ^5.90.0 version: 5.90.4(@tanstack/solid-query@5.90.9(solid-js@1.9.10))(solid-js@1.9.10) '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -10154,7 +10154,7 @@ importers: specifier: workspace:* version: link:../../../packages/router-plugin '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router compression: specifier: ^1.8.0 @@ -10194,7 +10194,7 @@ importers: specifier: ^4.2.2 version: 4.2.2(vite@8.0.0(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.6.1)(sass-embedded@1.97.2)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.8.1)) '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -10249,7 +10249,7 @@ importers: specifier: workspace:* version: link:../../../packages/router-plugin '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -10289,7 +10289,7 @@ importers: specifier: workspace:* version: link:../../../packages/router-plugin '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -10326,7 +10326,7 @@ importers: specifier: ^4.2.2 version: 4.2.2(vite@8.0.0(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.6.1)(sass-embedded@1.97.2)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.8.1)) '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -10363,7 +10363,7 @@ importers: specifier: workspace:* version: link:../../../packages/router-plugin '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router solid-js: specifier: 1.9.10 @@ -10394,7 +10394,7 @@ importers: specifier: ^4.2.2 version: 4.2.2(vite@8.0.0(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.6.1)(sass-embedded@1.97.2)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.8.1)) '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -10431,7 +10431,7 @@ importers: specifier: ^4.2.2 version: 4.2.2(vite@8.0.0(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.6.1)(sass-embedded@1.97.2)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.8.1)) '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -10477,7 +10477,7 @@ importers: specifier: ^5.90.0 version: 5.90.4(@tanstack/solid-query@5.90.9(solid-js@1.9.10))(solid-js@1.9.10) '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -10523,7 +10523,7 @@ importers: specifier: ^5.90.0 version: 5.90.4(@tanstack/solid-query@5.90.9(solid-js@1.9.10))(solid-js@1.9.10) '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -10566,7 +10566,7 @@ importers: specifier: ^5.90.9 version: 5.90.9(solid-js@1.9.10) '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -10603,7 +10603,7 @@ importers: specifier: ^5.90.9 version: 5.90.9(solid-js@1.9.10) '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -10637,7 +10637,7 @@ importers: specifier: ^5.90.9 version: 5.90.9(solid-js@1.9.10) '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -10668,7 +10668,7 @@ importers: specifier: ^4.2.2 version: 4.2.2(vite@8.0.0(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.6.1)(sass-embedded@1.97.2)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.8.1)) '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -10696,7 +10696,7 @@ importers: specifier: workspace:* version: link:../../../packages/router-plugin '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -10727,7 +10727,7 @@ importers: specifier: ^4.2.2 version: 4.2.2(vite@8.0.0(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.6.1)(sass-embedded@1.97.2)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.8.1)) '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -10764,7 +10764,7 @@ importers: specifier: ^4.2.2 version: 4.2.2 '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -10798,7 +10798,7 @@ importers: examples/solid/quickstart-webpack-file-based: dependencies: '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -10859,7 +10859,7 @@ importers: specifier: workspace:* version: link:../../../packages/router-plugin '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -10893,7 +10893,7 @@ importers: specifier: workspace:* version: link:../../../packages/router-plugin '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -10933,7 +10933,7 @@ importers: specifier: ^5.90.0 version: 5.90.4(@tanstack/solid-query@5.90.9(solid-js@1.9.10))(solid-js@1.9.10) '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -10967,7 +10967,7 @@ importers: specifier: ^4.2.2 version: 4.2.2(vite@8.0.0(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.6.1)(sass-embedded@1.97.2)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.8.1)) '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -11007,7 +11007,7 @@ importers: specifier: ^5.90.9 version: 5.90.9(solid-js@1.9.10) '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -11053,7 +11053,7 @@ importers: examples/solid/start-basic: dependencies: '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -11105,7 +11105,7 @@ importers: specifier: ^7.0.0 version: 7.0.0(prisma@7.0.0(@types/react@19.2.9)(magicast@0.3.5)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)(typescript@6.0.2))(typescript@6.0.2) '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -11154,7 +11154,7 @@ importers: specifier: ^0.41.1 version: 0.41.1 '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -11194,7 +11194,7 @@ importers: examples/solid/start-basic-cloudflare: dependencies: '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -11234,7 +11234,7 @@ importers: examples/solid/start-basic-netlify: dependencies: '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -11271,7 +11271,7 @@ importers: examples/solid/start-basic-nitro: dependencies: '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -11314,7 +11314,7 @@ importers: specifier: ^5.90.0 version: 5.90.4(@tanstack/solid-query@5.90.9(solid-js@1.9.10))(solid-js@1.9.10) '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -11357,7 +11357,7 @@ importers: examples/solid/start-basic-static: dependencies: '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -11409,7 +11409,7 @@ importers: specifier: ^0.7.0 version: 0.7.14(csstype@3.2.3)(solid-js@1.9.10) '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -11473,7 +11473,7 @@ importers: specifier: ^4.2.2 version: 4.2.2(vite@8.0.0(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.6.1)(sass-embedded@1.97.2)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.8.1)) '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -11528,7 +11528,7 @@ importers: examples/solid/start-counter: dependencies: '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -11571,7 +11571,7 @@ importers: specifier: ^0.7.0 version: 0.7.14(csstype@3.2.3)(solid-js@1.9.10) '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -11611,7 +11611,7 @@ importers: specifier: ^5.90.9 version: 5.90.9(solid-js@1.9.10) '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -11654,7 +11654,7 @@ importers: examples/solid/start-streaming-data-from-server-functions: dependencies: '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -11691,7 +11691,7 @@ importers: specifier: ^2.48.1 version: 2.48.1 '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -11728,7 +11728,7 @@ importers: examples/solid/start-tailwind-v4: dependencies: '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -11774,7 +11774,7 @@ importers: specifier: workspace:* version: link:../../../packages/router-plugin '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -11808,7 +11808,7 @@ importers: specifier: ^4.2.2 version: 4.2.2(vite@8.0.0(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.6.1)(sass-embedded@1.97.2)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.8.1)) '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ @@ -11848,7 +11848,7 @@ importers: specifier: workspace:* version: link:../../../packages/router-plugin '@tanstack/solid-router': - specifier: ^1.168.18 + specifier: ^1.168.19 version: link:../../../packages/solid-router '@tanstack/solid-router-devtools': specifier: workspace:^ From 8caa20223e876129afa3ee51881fb3aefe5dc065 Mon Sep 17 00:00:00 2001 From: Coding Cossack <108333654+CodingCossack@users.noreply.github.com> Date: Tue, 14 Apr 2026 00:33:37 +0100 Subject: [PATCH 007/604] Add a React Start server-components skill (#7181) Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com> --- .../skills/_artifacts/domain_map.yaml | 59 ++++++++ .../skills/_artifacts/skill_spec.md | 25 +++- .../skills/_artifacts/skill_tree.yaml | 19 +++ .../react-start/skills/react-start/SKILL.md | 2 + .../react-start/server-components/SKILL.md | 127 ++++++++++++++++ .../server-components/docs/architecture.md | 84 +++++++++++ .../docs/caching-refresh-ssr.md | 137 +++++++++++++++++ .../docs/composite-components.md | 115 ++++++++++++++ .../docs/current-api-notes.md | 74 +++++++++ .../docs/debugging-review.md | 141 ++++++++++++++++++ .../server-components/docs/sources.md | 39 +++++ .../examples/01-renderable-route-loader.tsx | 28 ++++ .../examples/02-composite-slots.tsx | 124 +++++++++++++++ .../examples/03-query-owned-rsc.tsx | 97 ++++++++++++ .../examples/04-selective-ssr-data-only.tsx | 72 +++++++++ .../examples/05-ssr-false-browser-loader.tsx | 40 +++++ .../06-low-level-flight-api-route.tsx | 40 +++++ 17 files changed, 1215 insertions(+), 8 deletions(-) create mode 100644 packages/react-start/skills/react-start/server-components/SKILL.md create mode 100644 packages/react-start/skills/react-start/server-components/docs/architecture.md create mode 100644 packages/react-start/skills/react-start/server-components/docs/caching-refresh-ssr.md create mode 100644 packages/react-start/skills/react-start/server-components/docs/composite-components.md create mode 100644 packages/react-start/skills/react-start/server-components/docs/current-api-notes.md create mode 100644 packages/react-start/skills/react-start/server-components/docs/debugging-review.md create mode 100644 packages/react-start/skills/react-start/server-components/docs/sources.md create mode 100644 packages/react-start/skills/react-start/server-components/examples/01-renderable-route-loader.tsx create mode 100644 packages/react-start/skills/react-start/server-components/examples/02-composite-slots.tsx create mode 100644 packages/react-start/skills/react-start/server-components/examples/03-query-owned-rsc.tsx create mode 100644 packages/react-start/skills/react-start/server-components/examples/04-selective-ssr-data-only.tsx create mode 100644 packages/react-start/skills/react-start/server-components/examples/05-ssr-false-browser-loader.tsx create mode 100644 packages/react-start/skills/react-start/server-components/examples/06-low-level-flight-api-route.tsx diff --git a/packages/react-start/skills/_artifacts/domain_map.yaml b/packages/react-start/skills/_artifacts/domain_map.yaml index b5e84d4dfb..271b1fe746 100644 --- a/packages/react-start/skills/_artifacts/domain_map.yaml +++ b/packages/react-start/skills/_artifacts/domain_map.yaml @@ -444,6 +444,65 @@ skills: priority: MEDIUM status: active + - name: 'Server Components' + slug: 'server-components' + domain: 'deployment-and-rendering' + description: >- + Implement and debug TanStack Start React Server Components with + renderServerComponent, createCompositeComponent, low-level + Flight streaming APIs, Router vs Query cache ownership, refresh + paths, and selective SSR modes. + type: sub-skill + packages: + - '@tanstack/react-start' + - '@tanstack/react-start-rsc' + covers: + - renderServerComponent + - createCompositeComponent + - CompositeComponent + - renderToReadableStream + - createFromReadableStream + - createFromFetch + - Router-owned RSC caching + - Query-owned RSC caching + - Refresh ownership (router.invalidate, invalidateQueries, refetchQueries) + - "Selective SSR modes (ssr: 'data-only', ssr: false)" + - 'structuralSharing: false for Query-cached RSC values' + tasks: + - 'Implement route-owned React Server Components' + - 'Choose between renderServerComponent and createCompositeComponent' + - 'Debug stale RSC data and invalidation' + - 'Migrate Next App Router RSC patterns to TanStack Start' + failure_modes: + - mistake: 'Using renderServerComponent when the UI needs slots' + mechanism: >- + renderServerComponent returns a renderable value and does + not support client-provided children, render props, or + component props. Use createCompositeComponent and render it + with CompositeComponent when the server output must accept + slots. + source: 'docs/start/framework/react/guide/server-components.md' + priority: HIGH + status: active + + - mistake: 'Omitting structuralSharing: false for Query-cached RSC values' + mechanism: >- + Query-cached RSC values must disable structural sharing. + Otherwise the cache may try to merge Flight payloads across + fetches, which can cause errors. + source: 'docs/start/framework/react/guide/server-components.md' + priority: HIGH + status: active + + - mistake: 'Copying stale renderRsc or .validator examples into current code' + mechanism: >- + Older snippets may use renderRsc or .validator(...). + Normalize them to renderServerComponent and + .inputValidator(...) before using them in current code. + source: 'docs/start/framework/react/guide/server-functions.md' + priority: MEDIUM + status: active + tensions: - name: 'Isomorphic defaults vs server-only expectations' skills: ['execution-model', 'server-functions'] diff --git a/packages/react-start/skills/_artifacts/skill_spec.md b/packages/react-start/skills/_artifacts/skill_spec.md index 11b6843bb0..ce016f4e03 100644 --- a/packages/react-start/skills/_artifacts/skill_spec.md +++ b/packages/react-start/skills/_artifacts/skill_spec.md @@ -4,14 +4,14 @@ TanStack Start is a full-stack React framework built on TanStack Router and Vite ## Domains -| Domain | Description | Skills | -| ------------------------ | ------------------------------------------------------------- | ---------------- | -| Project Setup | Scaffolding, Vite plugin, router factory, root route, entries | start-setup | -| Server Functions | Type-safe RPCs with createServerFn, validation, streaming | server-functions | -| Middleware and Context | Request/function middleware, context, global middleware | middleware | -| Execution Model | Isomorphic defaults, environment boundaries, env vars | execution-model | -| Server Routes | API endpoints, HTTP handlers, handler middleware | server-routes | -| Deployment and Rendering | Hosting, selective SSR, prerendering, SEO | deployment | +| Domain | Description | Skills | +| ------------------------ | ------------------------------------------------------------- | ----------------------------- | +| Project Setup | Scaffolding, Vite plugin, router factory, root route, entries | start-setup | +| Server Functions | Type-safe RPCs with createServerFn, validation, streaming | server-functions | +| Middleware and Context | Request/function middleware, context, global middleware | middleware | +| Execution Model | Isomorphic defaults, environment boundaries, env vars | execution-model | +| Server Routes | API endpoints, HTTP handlers, handler middleware | server-routes | +| Deployment and Rendering | Hosting, selective SSR, prerendering, SEO | deployment, server-components | ## Skill Inventory @@ -23,6 +23,7 @@ TanStack Start is a full-stack React framework built on TanStack Router and Vite | execution-model | core | execution-model | Isomorphic defaults, environment functions, env vars | 4 | | server-routes | core | server-routes | server property, HTTP handlers, createHandlers | 2 | | deployment | core | deployment-and-rendering | Hosting, SSR modes, prerendering, SEO | 3 | +| server-components | sub-skill | deployment-and-rendering | React Server Components, cache ownership, selective SSR | 3 | | react-start | framework | project-setup | React bindings, useServerFn, full setup | 3 | | migrate-from-nextjs | lifecycle | project-setup | Next.js App Router migration checklist | 3 | @@ -77,6 +78,14 @@ TanStack Start is a full-stack React framework built on TanStack Router and Vite | 2 | Bun deployment with React 18 | MEDIUM | docs/guide/hosting | | 3 | Child route loosening parent SSR config | MEDIUM | docs/guide/selective-ssr | +### server-components (3 failure modes) + +| # | Mistake | Priority | Source | +| --- | ------------------------------------------------------------- | -------- | ---------------------------- | +| 1 | Using renderServerComponent when the UI needs slots | HIGH | docs/guide/server-components | +| 2 | Omitting structuralSharing: false for Query-cached RSC values | HIGH | docs/guide/server-components | +| 3 | Copying stale renderRsc or .validator examples | MEDIUM | docs/guide/server-functions | + ## Tensions | Tension | Skills | Agent implication | diff --git a/packages/react-start/skills/_artifacts/skill_tree.yaml b/packages/react-start/skills/_artifacts/skill_tree.yaml index cf743b067c..f896955132 100644 --- a/packages/react-start/skills/_artifacts/skill_tree.yaml +++ b/packages/react-start/skills/_artifacts/skill_tree.yaml @@ -137,6 +137,25 @@ skills: - 'TanStack/router:packages/react-start/src' - 'TanStack/router:docs/start/framework/react/build-from-scratch.md' + - name: 'Server Components' + slug: 'react-start/server-components' + type: 'sub-skill' + domain: 'deployment-and-rendering' + path: 'skills/react-start/server-components/SKILL.md' + package: 'packages/react-start' + description: >- + Implement, review, debug, and refactor TanStack Start React + Server Components in React 19 apps. + requires: + - 'react-start' + - 'start-core/server-functions' + - 'start-core/execution-model' + sources: + - 'TanStack/router:docs/start/framework/react/guide/server-components.md' + - 'TanStack/router:docs/start/framework/react/guide/server-functions.md' + - 'TanStack/router:docs/start/framework/react/guide/execution-model.md' + - 'TanStack/router:docs/router/guide/data-loading.md' + # ── Lifecycle Skills ──────────────────────────────────────────── - name: 'Migrate from Next.js' slug: 'lifecycle/migrate-from-nextjs' diff --git a/packages/react-start/skills/react-start/SKILL.md b/packages/react-start/skills/react-start/SKILL.md index e3067e9e05..2f3d569a55 100644 --- a/packages/react-start/skills/react-start/SKILL.md +++ b/packages/react-start/skills/react-start/SKILL.md @@ -22,6 +22,8 @@ This skill builds on start-core. Read [start-core](../../../start-client-core/sk This skill covers the React-specific bindings, setup, and patterns for TanStack Start. +For React Server Components patterns, see [react-start/server-components](./server-components/SKILL.md). + > **CRITICAL**: All code is ISOMORPHIC by default. Loaders run on BOTH server and client. Use `createServerFn` for server-only logic. > **CRITICAL**: Do not confuse `@tanstack/react-start` with Next.js or Remix. They are completely different frameworks with different APIs. diff --git a/packages/react-start/skills/react-start/server-components/SKILL.md b/packages/react-start/skills/react-start/server-components/SKILL.md new file mode 100644 index 0000000000..271113df3c --- /dev/null +++ b/packages/react-start/skills/react-start/server-components/SKILL.md @@ -0,0 +1,127 @@ +--- +name: react-start/server-components +description: >- + Implement, review, debug, and refactor TanStack Start React Server + Components in React 19 apps. Use when tasks mention + @tanstack/react-start/rsc, renderServerComponent, + createCompositeComponent, CompositeComponent, + renderToReadableStream, createFromReadableStream, createFromFetch, + Composite Components, React Flight streams, loader or query owned + RSC caching, router.invalidate, structuralSharing: false, + selective SSR, stale names like renderRsc or .validator, or + migration from Next App Router RSC patterns. Do not use for + generic SSR or non-TanStack RSC frameworks except brief + comparison. +type: sub-skill +library: tanstack-start +library_version: '1.166.2' +requires: + - react-start + - start-core/server-functions + - start-core/execution-model +sources: + - TanStack/router:docs/start/framework/react/guide/server-components.md + - TanStack/router:docs/start/framework/react/guide/server-functions.md + - TanStack/router:docs/start/framework/react/guide/execution-model.md + - TanStack/router:docs/router/guide/data-loading.md +--- + +# TanStack Start React Server Components + +Treat TanStack Start RSCs as fetchable React Flight payloads, not as a framework-owned server tree. Start from data ownership and cache ownership, then choose the smallest RSC primitive that fits. + +## When this skill is active + +1. Inspect `vite.config.*` for `tanstackStart({ rsc: { enabled: true } })`, `rsc()`, and `viteReact()`. +2. Inspect route files for `loader`, `loaderDeps`, `staleTime`, `ssr`, and `errorComponent`. +3. Inspect server boundaries: `createServerFn`, `createServerOnlyFn`, `.server.*`, and imports from `@tanstack/react-start/server`. +4. Identify the cache owner: Router loader cache, TanStack Query, or HTTP/server cache. +5. Identify the refresh path: `router.invalidate()`, `invalidateQueries`, `refetchQueries`, or GET cache headers. + +## Hard invariants + +- Route loaders are isomorphic. Do not put DB access, secrets, or Node-only APIs directly in a loader. If the loader itself must use browser APIs, make that route `ssr: false`. +- `renderServerComponent(...)` returns a renderable fragment. It does not support slots. +- `createCompositeComponent(...)` is for server-rendered UI that must accept client-provided `children`, render props, or component props. +- Query-cached RSC values require `structuralSharing: false`. +- Slot payloads are opaque on the server. Do not inspect, map, or clone `props.children`. +- Render-prop and component-slot arguments must stay Flight-serializable. +- Current server function validation API is `.inputValidator(...)`. Older snippets may still show `.validator(...)`; normalize them. +- TanStack custom serialization does not apply inside RSCs yet. Stay inside native Flight-supported values. + +## Decide three things immediately + +### 1) Transport / composition primitive + +- No client slots needed -> `renderServerComponent` +- Client interactivity must be inserted inside server-rendered markup -> `createCompositeComponent` + `` +- Need custom Flight streaming, API routes, or non-standard transport -> `renderToReadableStream`, `createFromReadableStream`, `createFromFetch` + +### 2) Cache owner + +- Route-shaped data keyed by pathname, params, or search -> Router cache +- Independent key space, background refetch, or non-route ownership -> TanStack Query +- Cross-request reuse on server or CDN -> GET `createServerFn` + response cache headers and/or external server cache + +### 3) Refresh owner + +- Router-owned RSC -> `router.invalidate()` +- Query-owned RSC -> `queryClient.invalidateQueries(...)` or `refetchQueries(...)` +- Mixed Router + Query -> invalidate both deliberately; do not assume one refreshes the other + +## Pattern chooser + +- Simple server fragment in a route loader -> `renderServerComponent` +- Interactive slot inside server markup -> `createCompositeComponent` +- Route component needs browser APIs but loader can still prefetch on the server -> `ssr: 'data-only'` +- Loader itself needs browser APIs -> `ssr: false` +- Route cache key must include search params -> `loaderDeps` +- Query-managed RSC -> `useSuspenseQuery` + SSR `ensureQueryData` +- Multiple independent RSCs -> separate server functions + `Promise.all` +- Multiple RSCs sharing data or invalidating together -> one server function returning many renderables or sources +- Need isolated widget failures or staggered reveal -> return promises from the loader and resolve with `use()` inside Suspense + +## Slot choice + +- `children`: free-form composition, no server-to-client data flow +- render props: the server must pass serializable data into client-rendered UI +- component props: reusable client slot with a stable typed prop surface +- If you are about to use `Children.map`, `cloneElement`, or inspect `children` on the server, stop and convert it to a render prop + +## Review / refactor checklist + +- Is the chosen primitive the smallest one that fits? +- Does the loader own the RSC, or should Query own it? +- Are route cache keys complete (`params` + minimal `loaderDeps`)? +- Is invalidation hitting the real cache owner? +- Are query options using `structuralSharing: false` for any RSC value? +- Are mutations explicit `createServerFn({ method: 'POST' })` calls instead of hidden server actions? +- Are server-only imports kept inside server functions or server-only boundaries? +- Are examples using current names (`renderServerComponent`, `.inputValidator`) instead of stale ones? + +## Debug fast + +- Setup, exports, or stale docs mismatch -> `docs/current-api-notes.md` +- Composite Component design or slot bug -> `docs/composite-components.md` +- Stale data, refetching, loader keys, Query vs Router ownership, or SSR mode -> `docs/caching-refresh-ssr.md` +- Review, refactor, import leaks, error boundaries, or serialization bugs -> `docs/debugging-review.md` +- Architecture and Next/App Router translation -> `docs/architecture.md` + +## Copy-paste patterns + +- `examples/01-renderable-route-loader.tsx` +- `examples/02-composite-slots.tsx` +- `examples/03-query-owned-rsc.tsx` +- `examples/04-selective-ssr-data-only.tsx` +- `examples/05-ssr-false-browser-loader.tsx` +- `examples/06-low-level-flight-api-route.tsx` + +## Default implementation sequence + +1. Keep server-only work inside `createServerFn` or `createServerOnlyFn` +2. Return an RSC from the server function +3. Consume it through the route loader unless Query has a clear ownership advantage +4. Add the smallest cache policy that satisfies freshness requirements +5. Wire invalidation exactly once at the real cache owner +6. Escalate to Composite Components only when the client must fill slots +7. Escalate to low-level Flight APIs only when high-level helpers cannot express the transport diff --git a/packages/react-start/skills/react-start/server-components/docs/architecture.md b/packages/react-start/skills/react-start/server-components/docs/architecture.md new file mode 100644 index 0000000000..f416b832ad --- /dev/null +++ b/packages/react-start/skills/react-start/server-components/docs/architecture.md @@ -0,0 +1,84 @@ +# Architecture and mental model + +## Core model + +TanStack Start treats React Server Components as plain React Flight data: + +- create them on the server +- return them from a server function or API route +- decode and render them during SSR or on the client +- cache them with whatever already owns the data flow + +That matters because the framework is not asking you to move the whole UI tree to the server. RSCs are opt-in fragments that fit into existing Router and Query workflows. + +## Boundary model + +The fastest way to get TanStack Start RSC wrong is to think “loader = server”. + +Use these boundaries instead: + +- `createServerFn`: explicit RPC boundary; safe to call from client code because the client gets an RPC stub +- `createServerOnlyFn`: utility that must never run on the client +- route `loader`: orchestration layer that runs on the server for the initial SSR request and in the browser on client navigation unless the route is `ssr: false` + +Practical rule: loaders decide _when_ to fetch. Server functions decide _what_ must stay on the server. + +## What still works inside RSCs + +Do not over-correct and assume RSCs are a stripped-down universe. + +- TanStack Router `Link` works inside server components +- CSS Modules and global CSS imports work inside server components +- `React.cache` works for request-scoped memoization inside server components + +Use those directly when they simplify the tree. + +## When RSCs actually pay off + +Use TanStack Start RSCs when one or more of these are true: + +- a region is heavy to render but mostly static once delivered +- a server-only dependency should never enter the client bundle +- data fetching and render logic want to live together +- you want progressively streamed HTML for part of the route +- the result can be cached better as a fragment than as an entire page + +Do not force RSCs into highly interactive, state-dense client surfaces unless they materially reduce bundle size or remove awkward client/server sync. + +## Choosing tree ownership + +Think in terms of ownership: + +- client-owned UI: plain client components, Query, SPA patterns +- route-owned RSC: route loader fetches a fragment and Router cache owns freshness +- query-owned RSC: Query owns the fragment because its lifecycle is not route-shaped +- mixed ownership: the route owns coarse navigation state, Query owns sub-fragments + +The wrong smell is accidental double ownership: one RSC is fetched in a loader, then also separately cached in Query, then only one side is invalidated. + +## Composite Components in one sentence + +A Composite Component is a server-rendered fragment with placeholders the client fills later. + +That makes it the replacement for “I need server-rendered markup here, but I still need client interactivity in the middle of it.” + +The client can wrap, nest, reorder, and interleave those fragments instead of accepting a single framework-owned server tree. + +## Next App Router translation + +Use this mapping when someone is thinking in Next terms: + +- Next “server-first tree” -> Start “isomorphic-first app with opt-in RSC fragments” +- Next `'use client'` boundary -> Start Composite Component slot boundary +- Next server actions -> Start explicit `createServerFn({ method: 'POST' })` +- Next framework cache semantics -> Start Router cache, Query cache, and HTTP cache you control directly + +The useful mental shift is this: in TanStack Start, RSC is a transport and composition primitive, not the center of gravity for the whole app. + +## High-value heuristics + +- If the fragment never accepts client content, demote it to `renderServerComponent`. +- If a route-scoped RSC never needs independent refetching, keep it in the loader cache. +- If a fragment is reused across routes or refreshed independently, consider Query ownership. +- If several fragments always share data and invalidate together, bundle them in one server function. +- If one slow fragment blocks everything, stop awaiting it in the loader and defer it. diff --git a/packages/react-start/skills/react-start/server-components/docs/caching-refresh-ssr.md b/packages/react-start/skills/react-start/server-components/docs/caching-refresh-ssr.md new file mode 100644 index 0000000000..6619f78942 --- /dev/null +++ b/packages/react-start/skills/react-start/server-components/docs/caching-refresh-ssr.md @@ -0,0 +1,137 @@ +# Caching, refresh, SSR modes, and loading patterns + +## Pick one cache owner first + +### Router cache + +Use Router when the RSC is route-shaped and keyed by URL state. + +Relevant facts: + +- Router loader cache keys are based on pathname and params, plus anything you add through `loaderDeps` +- default navigation `staleTime` is `0` +- default preload freshness is `30s` +- default stale reload mode is background stale-while-revalidate +- `router.invalidate()` reloads active loaders immediately and marks cached routes stale + +Use Router ownership when the fragment naturally belongs to the route and should track navigation. + +### TanStack Query + +Use Query when the fragment has its own lifecycle. + +Typical reasons: + +- reuse across routes +- background refetching independent of navigation +- manual query invalidation +- non-route ownership + +Hard rule: + +```tsx +structuralSharing: false +``` + +Without that, Query may try to merge RSC values across fetches. + +### HTTP / server cache + +Use GET server functions and response headers when you want cross-request reuse: + +- CDN caching +- edge caching +- reverse proxies +- shared server caches + +Set headers in a GET `createServerFn` via `setResponseHeaders(...)`. + +## Router-owned RSC pattern + +Use a server function to return the RSC, then fetch it in the route loader. + +Tune Router with: + +- `staleTime` when revisits should stay fresh for a window +- `loaderDeps` when search params affect the fragment +- `staleReloadMode: 'blocking'` when showing stale data during reload is unacceptable + +`loaderDeps` rule: include only values the loader actually uses. Returning the whole search object causes noisy invalidation. + +## Query-owned RSC pattern + +Use Query when you want explicit cache keys and background fetch behavior. + +Recommended shape: + +```tsx +const postQueryOptions = (postId: string) => ({ + queryKey: ['post-rsc', postId], + structuralSharing: false, + queryFn: () => getPostRsc({ data: { postId } }), + staleTime: 5 * 60 * 1000, +}) +``` + +For SSR reuse, prefetch in the route loader: + +```tsx +await context.queryClient.ensureQueryData(postQueryOptions(params.postId)) +``` + +Then read it with `useSuspenseQuery` in the component. + +## Refresh rules + +- loader-owned fragment changed -> `router.invalidate()` +- query-owned fragment changed -> `queryClient.invalidateQueries(...)` +- shared route and query state -> refresh both if both are authoritative +- CDN or response-header cache involved -> make sure the mutation path also busts or bypasses server-side cache + +Do not “spray” invalidation everywhere. Decide who owns freshness, then target that owner. + +## Selective SSR modes + +### `ssr: 'data-only'` + +Use when: + +- the route component needs browser APIs +- the loader can still fetch the RSC on the server for first paint +- you want server-fetched fragment data ready before the client component mounts + +This is often the right shape for responsive charts, viewport-dependent layout wrappers, or widgets that need `window` but still benefit from server-rendered content. + +### `ssr: false` + +Use when the loader itself depends on browser APIs such as: + +- `localStorage` +- `window` +- browser-only client state + +In this mode, both the loader and component run in the browser. The loader can still call a server function that returns an RSC. + +## Loading patterns + +### Independent fragments -> parallel + +If the fragments do not share data, fetch them with separate server functions and `Promise.all`. + +### Shared data or shared invalidation -> bundle + +If several fragments always share a fetch or invalidate together, return them from one server function. This reduces round trips and keeps ownership aligned. + +### One slow fragment should not block everything -> defer + +Return promises from the loader instead of awaiting them. Resolve them with `use()` inside Suspense. This also lets you isolate failures with a local ErrorBoundary instead of the route error boundary. + +### Large or unbounded lists -> async generators + +Use async generators when items should arrive incrementally and total size or per-item latency is unpredictable. + +## Request-scoped memoization + +`React.cache` works inside server components. Use it when several async server components in one request need the same expensive fetch or computation. + +That is request-scoped deduplication, not a cross-request cache. diff --git a/packages/react-start/skills/react-start/server-components/docs/composite-components.md b/packages/react-start/skills/react-start/server-components/docs/composite-components.md new file mode 100644 index 0000000000..738e07c632 --- /dev/null +++ b/packages/react-start/skills/react-start/server-components/docs/composite-components.md @@ -0,0 +1,115 @@ +# Composite Components and slot composition + +## The real mechanism + +Inside `createCompositeComponent`, slot props are placeholders, not real client elements. + +Server-side behavior: + +- reading `props.children` records “there will be children here” +- calling `props.renderSomething(args)` records “call this slot with these args later” +- reading a component prop like `props.AddToCart` records “render this client component here with these props later” + +Client-side behavior: + +- `` replaces those placeholders with the real props you passed at render time + +This is why slots are powerful and why some React habits stop working. + +## Choose the slot type by data flow + +### `children` + +Use when: + +- the server only needs a hole for client content +- no server data needs to flow into the slotted content +- free-form composition matters more than a rigid interface + +Do not use when the server must inject IDs, permissions, pricing, or derived data into the child content. + +### render props + +Use when: + +- the server must pass data into the client-rendered content +- the data is serializable +- you want the call site to stay flexible + +This is usually the best default when the server owns the data and the client owns the interactive control. + +### component props + +Use when: + +- you have a reusable client component +- the prop contract is stable +- you want the server to decide where it renders and which typed props it receives + +This is a good fit for buttons, menus, controls, widgets, and repeated productized patterns. + +## Rules that matter + +- `renderServerComponent` does not support slots +- do not use `React.Children.map`, `cloneElement`, or child inspection on the server +- render-prop arguments and component-slot props must be Flight-serializable +- keep slot contracts narrow; pass IDs and plain data, not giant objects by default + +## The most common anti-pattern + +Bad instinct: + +```tsx +createCompositeComponent((props: { children?: React.ReactNode }) => ( +
+ {React.Children.map(props.children, (child) => + React.cloneElement(child, { extra: 'prop' }), + )} +
+)) +``` + +Correct rewrite: + +```tsx +createCompositeComponent<{ + renderItem?: (data: { extra: string }) => React.ReactNode +}>((props) =>
{props.renderItem?.({ extra: 'prop' })}
) +``` + +Server-side slot content is opaque. If the server needs to add data, make the data explicit. + +## Good slot contracts + +Prefer contracts like: + +- `renderActions?: ({ postId, authorId }) => ReactNode` +- `AddToCart?: ComponentType<{ productId: string; price: number }>` +- `children?: ReactNode` + +Avoid contracts like: + +- `renderAnything?: (data: EntirePostRecordFromDB) => ReactNode` +- `children` plus child inspection and mutation +- opaque callbacks that expect non-serializable classes or functions from the server + +## Composition patterns that age well + +### Shell + actions + +The server renders an article, card, or panel and exposes one `renderActions` slot for buttons, menus, or controls. + +### Shell + body children + +The server renders stable framing UI and accepts `children` for optional interactive regions like comments, drawers, or editors. + +### Stable control slot + +The server accepts a component prop such as `AddToCart`, `UserMenu`, or `RowActions` and supplies clean typed props to it. + +## Refactor heuristics + +- No slot use anywhere -> replace the Composite Component with `renderServerComponent` +- Slot exists only to pass data -> prefer a render prop over `children` +- Repeated render-prop call sites with the same component -> promote to a component prop +- Giant slot arg object -> shrink it to the smallest serializable payload that the client really needs diff --git a/packages/react-start/skills/react-start/server-components/docs/current-api-notes.md b/packages/react-start/skills/react-start/server-components/docs/current-api-notes.md new file mode 100644 index 0000000000..a6ca6fee5e --- /dev/null +++ b/packages/react-start/skills/react-start/server-components/docs/current-api-notes.md @@ -0,0 +1,74 @@ +# Current API notes and stale example corrections + +Validated against official TanStack Start, TanStack Router, TanStack blog, and Vite docs on 2026-04-13. + +## Current setup shape + +Use the current RSC setup: + +- React 19+ +- Vite 7+ +- `@vitejs/plugin-rsc` +- `tanstackStart({ rsc: { enabled: true } })` +- `rsc()` +- `viteReact()` + +## Current high-level APIs + +Prefer: + +- `renderServerComponent` +- `createCompositeComponent` +- `CompositeComponent` + +Use low-level APIs only for custom transport: + +- `renderToReadableStream` +- `createFromReadableStream` +- `createFromFetch` + +## Current validation API + +Use `.inputValidator(...)` on `createServerFn`. + +Important because some current RSC docs snippets still show the older `.validator(...)` spelling. Normalize those examples before copying them into real code. + +## Current constraints + +- RSC support is still experimental +- TanStack custom serialization is not available inside RSCs yet +- slot args must stay Flight-serializable +- `structuralSharing: false` is mandatory for Query-cached RSC values + +## Stale example traps to avoid + +### Old `renderRsc` examples + +You may still find older official repo examples using `renderRsc` and older config shapes. Do not cargo-cult them into new code. Normalize to the current docs and current `@tanstack/react-start/rsc` APIs. + +### Old validation snippets + +If you see `.validator(z.object(...))` in an RSC example, rewrite it to `.inputValidator(z.object(...))` to match the current server function API. + +### Old Vite config shapes + +If an example enables Start but does not also install and register `@vitejs/plugin-rsc`, treat it as stale for current TanStack Start RSC setup. + +## Maintenance rule + +When docs, examples, and repo snippets disagree: + +1. prefer the current TanStack Start docs +2. prefer the current TanStack blog announcement over older repo samples +3. cross-check with current Server Functions and Execution Model docs +4. then normalize all local examples to one coherent modern API surface + +## Official source list + +- TanStack Start Server Components docs +- TanStack Start Server Functions docs +- TanStack Start Execution Model docs +- TanStack Start Import Protection docs +- TanStack Router Data Loading docs +- TanStack blog: React Server Components Your Way +- Vite docs for `@vitejs/plugin-rsc` diff --git a/packages/react-start/skills/react-start/server-components/docs/debugging-review.md b/packages/react-start/skills/react-start/server-components/docs/debugging-review.md new file mode 100644 index 0000000000..68580a9674 --- /dev/null +++ b/packages/react-start/skills/react-start/server-components/docs/debugging-review.md @@ -0,0 +1,141 @@ +# Debugging and review guide + +## Triage by failure stage + +### 1. Setup / build failure + +Likely causes: + +- `@vitejs/plugin-rsc` missing +- RSC not enabled in `tanstackStart({ rsc: { enabled: true } })` +- stale example using old exports +- wrong React or Vite baseline + +Checks: + +- inspect `vite.config.*` +- inspect imports from `@tanstack/react-start/rsc` +- normalize to `renderServerComponent`, `createCompositeComponent`, `CompositeComponent`, `.inputValidator(...)` + +### 2. Wrong environment failure + +Symptoms: + +- DB or secret access explodes on client navigation +- `window` or `localStorage` explodes during SSR +- import protection complaints about server-only code + +Likely causes: + +- server-only logic placed directly in an isomorphic loader +- browser-only logic used in SSR route/component +- helper referencing `.server` imports outside a recognized server boundary + +Fixes: + +- move server-only work into `createServerFn` or `createServerOnlyFn` +- use `ssr: 'data-only'` when only the component needs browser APIs +- use `ssr: false` when the loader itself needs browser APIs +- keep server-only imports inside server-only callbacks or files + +## Composition / slot bugs + +Symptoms: + +- child content disappears or cannot be modified +- `Children.map` or `cloneElement` does nothing useful +- component prop slot receives unusable data +- Composite Component seems heavier than necessary + +Likely causes: + +- trying to inspect server-side slot placeholders +- non-serializable slot args +- using a Composite Component for a fragment that has no slots + +Fixes: + +- replace child inspection with a render prop +- narrow slot args to serializable values +- demote slotless composites to `renderServerComponent` + +## Cache / staleness bugs + +Symptoms: + +- stale UI after mutation +- route revisits do not refresh when expected +- route refreshes too often +- Query errors or weird object merging on RSC values + +Likely causes: + +- invalidating the wrong cache owner +- missing or oversized `loaderDeps` +- missing `structuralSharing: false` +- `staleTime` / `staleReloadMode` mismatch with desired UX + +Checks: + +- decide whether Router or Query owns the fragment +- inspect `loaderDeps` for only the params actually used +- verify Query key includes all real inputs +- verify `structuralSharing: false` +- use `router.invalidate()` only when the loader owns freshness + +## Error boundary surprises + +Rule: + +- awaited loader failure -> route `errorComponent` +- deferred promise failure -> local ErrorBoundary around the deferred read + +If a single failing widget should not take down the route, stop awaiting it in the loader. + +## Serialization bugs + +Symptoms: + +- odd runtime decode failures +- slot args rejected or malformed +- custom serializer assumptions fail + +Likely causes: + +- passing classes, functions, Maps/Sets with custom serialization expectations, or other non-Flight-friendly values +- relying on TanStack custom serialization inside RSCs + +Fixes: + +- reduce payloads to primitives, Dates, plain objects, arrays, and React elements where appropriate +- pass IDs, not rich server objects, unless they are plain and intentionally serialized + +## Import protection and bundling gotchas + +- static imports of server functions are safe; the client build gets RPC stubs +- dynamic imports of server functions can cause bundler issues +- dev-mode import protection warnings can be informational because there is no tree-shaking; build output is the authoritative check + +## Code review checklist + +- correct primitive: renderable vs composite vs low-level stream +- loader is orchestration, not secret storage +- `loaderDeps` only covers actual inputs +- Query-owned RSC uses `structuralSharing: false` +- invalidation targets the real cache owner +- mutations are explicit `POST` server functions +- slot contracts are narrow and serializable +- stale examples normalized to current APIs +- route-level vs component-level error handling matches the UX requirement + +## Simplify-first recovery path + +When a bug is tangled across Query, Router, Composite Components, and SSR modes: + +1. collapse to one route-owned `renderServerComponent` +2. verify the server function and loader path +3. reintroduce Query only if you need independent ownership +4. reintroduce Composite Components only if you need slots +5. reintroduce deferred loading only if you need staggered reveal or isolated failures + +This sequence removes entire classes of bugs instead of trying to patch all of them at once. diff --git a/packages/react-start/skills/react-start/server-components/docs/sources.md b/packages/react-start/skills/react-start/server-components/docs/sources.md new file mode 100644 index 0000000000..fc1546ef84 --- /dev/null +++ b/packages/react-start/skills/react-start/server-components/docs/sources.md @@ -0,0 +1,39 @@ +# Official sources + +Validated on 2026-04-13. + +## TanStack Start + +- Server Components guide + https://tanstack.com/start/latest/docs/framework/react/guide/server-components + +- Server Functions guide + https://tanstack.com/start/latest/docs/framework/react/guide/server-functions + +- Execution Model guide + https://tanstack.com/start/latest/docs/framework/react/guide/execution-model + +- Import Protection guide + https://tanstack.com/start/latest/docs/framework/react/guide/import-protection + +## TanStack Router + +- Data Loading guide + https://tanstack.com/router/latest/docs/framework/react/guide/data-loading + +## TanStack blog + +- React Server Components Your Way + https://tanstack.com/blog/react-server-components + +## Vite + +- `@vitejs/plugin-rsc` documentation / discovery entry point + https://vite.dev/plugins/ + +## Notes on drift observed during validation + +- Current RSC docs and blog use `renderServerComponent`, `createCompositeComponent`, `CompositeComponent`, and low-level Flight APIs from `@tanstack/react-start/rsc`. +- Current Server Functions docs use `.inputValidator(...)`. +- Some current RSC docs snippets still show older `.validator(...)`. +- Older official repo examples may still show `renderRsc` and older config shapes. Prefer the current docs above. diff --git a/packages/react-start/skills/react-start/server-components/examples/01-renderable-route-loader.tsx b/packages/react-start/skills/react-start/server-components/examples/01-renderable-route-loader.tsx new file mode 100644 index 0000000000..eb4a308abb --- /dev/null +++ b/packages/react-start/skills/react-start/server-components/examples/01-renderable-route-loader.tsx @@ -0,0 +1,28 @@ +// Current TanStack Start RSC pattern. +// Replace route paths and data sources with your own app code. + +import { createFileRoute } from '@tanstack/react-router' +import { createServerFn } from '@tanstack/react-start' +import { renderServerComponent } from '@tanstack/react-start/rsc' + +function Greeting() { + return

Hello from TanStack Start RSC

+} + +const getGreeting = createServerFn({ method: 'GET' }).handler(async () => { + const Renderable = await renderServerComponent() + return { Renderable } +}) + +export const Route = createFileRoute('/hello')({ + loader: async () => { + const { Renderable } = await getGreeting() + return { Greeting: Renderable } + }, + component: HelloPage, +}) + +function HelloPage() { + const { Greeting } = Route.useLoaderData() + return <>{Greeting} +} diff --git a/packages/react-start/skills/react-start/server-components/examples/02-composite-slots.tsx b/packages/react-start/skills/react-start/server-components/examples/02-composite-slots.tsx new file mode 100644 index 0000000000..5bf1d77414 --- /dev/null +++ b/packages/react-start/skills/react-start/server-components/examples/02-composite-slots.tsx @@ -0,0 +1,124 @@ +// Composite Component patterns: +// - children slot for free-form composition +// - render-prop slot when the server must pass data into client UI +// - component prop slot for reusable typed interactive controls + +import type { ComponentType, ReactNode } from 'react' +import { createFileRoute } from '@tanstack/react-router' +import { createServerFn } from '@tanstack/react-start' +import { + CompositeComponent, + createCompositeComponent, +} from '@tanstack/react-start/rsc' +import { z } from 'zod' + +// Replace with your own server-only data layer +declare const db: { + posts: { + findById(postId: string): Promise<{ + id: string + authorId: string + title: string + body: string + }> + } + products: { + findById(productId: string): Promise<{ + id: string + name: string + price: number + }> + } +} + +const getPostCard = createServerFn({ method: 'GET' }) + .inputValidator(z.object({ postId: z.string() })) + .handler(async ({ data }) => { + const post = await db.posts.findById(data.postId) + + const src = await createCompositeComponent<{ + children?: ReactNode + renderActions?: (args: { postId: string; authorId: string }) => ReactNode + }>((props) => ( +
+

{post.title}

+

{post.body}

+ +
+ {props.renderActions?.({ + postId: post.id, + authorId: post.authorId, + })} +
+ +
{props.children}
+
+ )) + + return { src } + }) + +export const Route = createFileRoute('/posts/$postId')({ + loader: async ({ params }) => + getPostCard({ data: { postId: params.postId } }), + component: PostPage, +}) + +function PostPage() { + const { src } = Route.useLoaderData() + + return ( + ( + + )} + > + + + ) +} + +function Comments() { + return
Interactive comments go here
+} + +function PostActions(props: { postId: string; authorId: string }) { + return ( + + ) +} + +// Component-prop slot variant +const getProductCard = createServerFn({ method: 'GET' }) + .inputValidator(z.object({ productId: z.string() })) + .handler(async ({ data }) => { + const product = await db.products.findById(data.productId) + + const src = await createCompositeComponent<{ + AddToCart?: ComponentType<{ productId: string; price: number }> + }>((props) => ( +
+

{product.name}

+ {props.AddToCart ? ( + + ) : null} +
+ )) + + return { src } + }) + +function AddToCartButton(props: { productId: string; price: number }) { + return ( + + ) +} + +// Example usage somewhere else: +// const { src } = await getProductCard({ data: { productId: 'p-1' } }) +// diff --git a/packages/react-start/skills/react-start/server-components/examples/03-query-owned-rsc.tsx b/packages/react-start/skills/react-start/server-components/examples/03-query-owned-rsc.tsx new file mode 100644 index 0000000000..0b5c7c895a --- /dev/null +++ b/packages/react-start/skills/react-start/server-components/examples/03-query-owned-rsc.tsx @@ -0,0 +1,97 @@ +// Query-owned RSC pattern. +// Assumes your router context provides a queryClient for SSR prefetch. + +import type { ReactNode } from 'react' +import { createFileRoute } from '@tanstack/react-router' +import { createServerFn } from '@tanstack/react-start' +import { + CompositeComponent, + createCompositeComponent, +} from '@tanstack/react-start/rsc' +import { useQueryClient, useSuspenseQuery } from '@tanstack/react-query' +import { z } from 'zod' + +// Replace with your own data layer +declare const db: { + posts: { + findById(postId: string): Promise<{ + id: string + title: string + body: string + }> + update( + postId: string, + patch: { title?: string; body?: string }, + ): Promise + } +} + +const getPostRsc = createServerFn({ method: 'GET' }) + .inputValidator(z.object({ postId: z.string() })) + .handler(async ({ data }) => { + const post = await db.posts.findById(data.postId) + + const src = await createCompositeComponent<{ + renderActions?: (args: { postId: string }) => ReactNode + }>((props) => ( +
+

{post.title}

+

{post.body}

+
{props.renderActions?.({ postId: post.id })}
+
+ )) + + return { src } + }) + +const updatePost = createServerFn({ method: 'POST' }) + .inputValidator( + z.object({ + postId: z.string(), + title: z.string().optional(), + body: z.string().optional(), + }), + ) + .handler(async ({ data }) => { + await db.posts.update(data.postId, { + title: data.title, + body: data.body, + }) + }) + +const postQueryOptions = (postId: string) => ({ + queryKey: ['post-rsc', postId], + structuralSharing: false, + queryFn: () => getPostRsc({ data: { postId } }), + staleTime: 5 * 60 * 1000, +}) + +export const Route = createFileRoute('/posts/$postId')({ + loader: async ({ context, params }) => { + await context.queryClient.ensureQueryData(postQueryOptions(params.postId)) + }, + component: PostPage, +}) + +function PostPage() { + const { postId } = Route.useParams() + const queryClient = useQueryClient() + + const { data } = useSuspenseQuery(postQueryOptions(postId)) + + const handleRename = async () => { + await updatePost({ data: { postId, title: 'Updated title' } }) + await queryClient.invalidateQueries({ queryKey: ['post-rsc', postId] }) + } + + return ( + ( + + )} + /> + ) +} diff --git a/packages/react-start/skills/react-start/server-components/examples/04-selective-ssr-data-only.tsx b/packages/react-start/skills/react-start/server-components/examples/04-selective-ssr-data-only.tsx new file mode 100644 index 0000000000..a068c3c001 --- /dev/null +++ b/packages/react-start/skills/react-start/server-components/examples/04-selective-ssr-data-only.tsx @@ -0,0 +1,72 @@ +// Selective SSR: the loader fetches the RSC on the server, +// but the route component renders on the client because it needs browser APIs. + +import * as React from 'react' +import type { ReactNode } from 'react' +import { createFileRoute } from '@tanstack/react-router' +import { createServerFn } from '@tanstack/react-start' +import { + CompositeComponent, + createCompositeComponent, +} from '@tanstack/react-start/rsc' + +// Replace with your own server-side data source +declare function getDashboardStats(): Promise<{ + series: Array<{ x: number; y: number }> + totalUsers: number +}> + +const getDashboard = createServerFn({ method: 'GET' }).handler(async () => { + const stats = await getDashboardStats() + + const src = await createCompositeComponent<{ + renderChart?: (args: { + series: Array<{ x: number; y: number }> + }) => ReactNode + }>((props) => ( +
+

Users: {stats.totalUsers}

+ {props.renderChart?.({ series: stats.series })} +
+ )) + + return { src } +}) + +export const Route = createFileRoute('/dashboard')({ + ssr: 'data-only', + loader: async () => ({ + Dashboard: await getDashboard(), + }), + component: DashboardPage, +}) + +function DashboardPage() { + const { Dashboard } = Route.useLoaderData() + const [width, setWidth] = React.useState(0) + + React.useEffect(() => { + setWidth(window.innerWidth) + }, []) + + return ( + ( + + )} + /> + ) +} + +// Replace with your real chart component +function ResponsiveChart(props: { + data: Array<{ x: number; y: number }> + width: number +}) { + return ( +
+      {JSON.stringify({ width: props.width, points: props.data.length })}
+    
+ ) +} diff --git a/packages/react-start/skills/react-start/server-components/examples/05-ssr-false-browser-loader.tsx b/packages/react-start/skills/react-start/server-components/examples/05-ssr-false-browser-loader.tsx new file mode 100644 index 0000000000..fa5b4aae55 --- /dev/null +++ b/packages/react-start/skills/react-start/server-components/examples/05-ssr-false-browser-loader.tsx @@ -0,0 +1,40 @@ +// Browser-owned loader pattern. +// Use when the loader itself needs browser APIs such as localStorage. + +import { createFileRoute } from '@tanstack/react-router' +import { createServerFn } from '@tanstack/react-start' +import { renderServerComponent } from '@tanstack/react-start/rsc' +import { z } from 'zod' + +const getDrawingTools = createServerFn({ method: 'POST' }) + .inputValidator(z.object({ savedState: z.string().nullable() })) + .handler(async ({ data }) => { + const Tools = await renderServerComponent( + , + ) + + return { Tools } + }) + +export const Route = createFileRoute('/canvas')({ + ssr: false, + loader: async () => { + const savedState = localStorage.getItem('canvas-state') + return getDrawingTools({ data: { savedState } }) + }, + component: CanvasPage, +}) + +function CanvasPage() { + const { Tools } = Route.useLoaderData() + return <>{Tools} +} + +function ToolPalette(props: { savedState: string | null }) { + return ( +
+

Canvas tools

+
{props.savedState ?? 'no saved state'}
+
+ ) +} diff --git a/packages/react-start/skills/react-start/server-components/examples/06-low-level-flight-api-route.tsx b/packages/react-start/skills/react-start/server-components/examples/06-low-level-flight-api-route.tsx new file mode 100644 index 0000000000..17415d00a8 --- /dev/null +++ b/packages/react-start/skills/react-start/server-components/examples/06-low-level-flight-api-route.tsx @@ -0,0 +1,40 @@ +// Low-level Flight stream APIs. +// Prefer high-level helpers unless you need a custom transport. + +import { createAPIFileRoute } from '@tanstack/react-start/api' +import { createServerFn } from '@tanstack/react-start' +import { + createFromFetch, + renderToReadableStream, +} from '@tanstack/react-start/rsc' +import { useSuspenseQuery } from '@tanstack/react-query' + +const getFlightStream = createServerFn({ method: 'GET' }).handler(async () => { + return renderToReadableStream(
Server rendered content
) +}) + +export const APIRoute = createAPIFileRoute('/api/rsc')({ + GET: async () => { + const stream = await getFlightStream() + + return new Response(stream, { + headers: { + 'Content-Type': 'text/x-component', + }, + }) + }, +}) + +const rscQueryOptions = () => ({ + queryKey: ['api-rsc'], + structuralSharing: false, + queryFn: async () => { + const Renderable = await createFromFetch(fetch('/api/rsc')) + return { Renderable } + }, +}) + +export function ApiBackedRscWidget() { + const { data } = useSuspenseQuery(rscQueryOptions()) + return <>{data.Renderable} +} From df611998cb69e3010e88e2afd5d2bcc50cfd8f23 Mon Sep 17 00:00:00 2001 From: Nicolas Beaussart Date: Tue, 14 Apr 2026 13:17:12 +0200 Subject: [PATCH 008/604] chore: add sharding for playwright tests (#7187) * add sharding * fix dependnancy * fix playwright shard port reuse * full bust * throw more runners into this run * try to throw money at it and see the effect * tune --- .nx/workflows/dynamic-changesets.yaml | 6 +- e2e/react-start/rsc/package.json | 7 +- e2e/react-start/rsc/playwright.config.ts | 16 +- .../rsc/tests/setup/global.setup.ts | 2 +- .../rsc/tests/setup/global.teardown.ts | 2 +- nx.json | 11 +- package.json | 5 +- pnpm-lock.yaml | 648 ++++++++++++------ scripts/nx/playwright-plugin.md | 151 ++++ scripts/nx/playwright-plugin.ts | 130 ++++ 10 files changed, 751 insertions(+), 227 deletions(-) create mode 100644 scripts/nx/playwright-plugin.md create mode 100644 scripts/nx/playwright-plugin.ts diff --git a/.nx/workflows/dynamic-changesets.yaml b/.nx/workflows/dynamic-changesets.yaml index d3536f3ba7..786111053d 100644 --- a/.nx/workflows/dynamic-changesets.yaml +++ b/.nx/workflows/dynamic-changesets.yaml @@ -1,4 +1,4 @@ distribute-on: - small-changeset: 3 linux-medium-js - medium-changeset: 6 linux-medium-js - large-changeset: 10 linux-medium-js + small-changeset: 4 linux-medium-js + medium-changeset: 8 linux-medium-js + large-changeset: 14 linux-medium-js diff --git a/e2e/react-start/rsc/package.json b/e2e/react-start/rsc/package.json index 5c57315f05..eec6e1581d 100644 --- a/e2e/react-start/rsc/package.json +++ b/e2e/react-start/rsc/package.json @@ -9,7 +9,12 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e-full": "pnpm build && sh -c 'rm -f \"port-${E2E_PORT_KEY:-$npm_package_name}.txt\" \"port-${E2E_PORT_KEY:-$npm_package_name}-external.txt\"' && playwright test --project=chromium" + }, + "nx": { + "metadata": { + "playwrightShards": 6 + } }, "dependencies": { "@tanstack/react-router": "workspace:^", diff --git a/e2e/react-start/rsc/playwright.config.ts b/e2e/react-start/rsc/playwright.config.ts index ec873aadb1..b6c13c0798 100644 --- a/e2e/react-start/rsc/playwright.config.ts +++ b/e2e/react-start/rsc/playwright.config.ts @@ -1,8 +1,20 @@ +import fs from 'node:fs' import { defineConfig, devices } from '@playwright/test' import { getTestServerPort } from '@tanstack/router-e2e-utils' import packageJson from './package.json' with { type: 'json' } -const PORT = await getTestServerPort(packageJson.name) +const e2ePortKey = process.env.E2E_PORT_KEY ?? packageJson.name + +if (process.env.TEST_WORKER_INDEX === undefined) { + for (const portFile of [ + `port-${e2ePortKey}.txt`, + `port-${e2ePortKey}-external.txt`, + ]) { + fs.rmSync(portFile, { force: true }) + } +} + +const PORT = await getTestServerPort(e2ePortKey) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -18,7 +30,7 @@ export default defineConfig({ }, webServer: { - command: `PORT=${PORT} pnpm build && PORT=${PORT} pnpm start`, + command: `PORT=${PORT} pnpm start`, url: baseURL, reuseExistingServer: !process.env.CI, stdout: 'pipe', diff --git a/e2e/react-start/rsc/tests/setup/global.setup.ts b/e2e/react-start/rsc/tests/setup/global.setup.ts index 3593d10ab9..3def5f6941 100644 --- a/e2e/react-start/rsc/tests/setup/global.setup.ts +++ b/e2e/react-start/rsc/tests/setup/global.setup.ts @@ -2,5 +2,5 @@ import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' import packageJson from '../../package.json' with { type: 'json' } export default async function setup() { - await e2eStartDummyServer(packageJson.name) + await e2eStartDummyServer(process.env.E2E_PORT_KEY ?? packageJson.name) } diff --git a/e2e/react-start/rsc/tests/setup/global.teardown.ts b/e2e/react-start/rsc/tests/setup/global.teardown.ts index 62fd79911c..a9ad1445f7 100644 --- a/e2e/react-start/rsc/tests/setup/global.teardown.ts +++ b/e2e/react-start/rsc/tests/setup/global.teardown.ts @@ -2,5 +2,5 @@ import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' import packageJson from '../../package.json' with { type: 'json' } export default async function teardown() { - await e2eStopDummyServer(packageJson.name) + await e2eStopDummyServer(process.env.E2E_PORT_KEY ?? packageJson.name) } diff --git a/nx.json b/nx.json index 797ac91658..88eb404453 100644 --- a/nx.json +++ b/nx.json @@ -42,7 +42,7 @@ }, "test:e2e": { "cache": true, - "dependsOn": ["^build"], + "dependsOn": ["^build", "test:e2e--*"], "inputs": ["default", "^production"] }, "test:e2e:nitro": { @@ -76,5 +76,12 @@ "dependsOn": ["build"], "inputs": ["production"] } - } + }, + "plugins": [ + { + "name": "Playwright Sharding Plugin", + "plugin": "./scripts/nx/playwright-plugin.ts" + } + ], + "analytics": true } diff --git a/package.json b/package.json index 8905e44f74..3abe245fa8 100644 --- a/package.json +++ b/package.json @@ -48,8 +48,11 @@ "@arethetypeswrong/cli": "^0.18.2", "@changesets/cli": "^2.30.0", "@eslint-react/eslint-plugin": "^1.26.2", + "@nx/devkit": "22.6.5", "@playwright/test": "^1.57.0", "@svitejs/changesets-changelog-github-compact": "^1.2.0", + "@swc-node/core": "^1.14.1", + "@swc-node/register": "^1.11.1", "@tanstack/eslint-config": "0.4.0", "@tanstack/query-core": "^5.90.19", "@tanstack/react-query": "^5.90.19", @@ -64,7 +67,7 @@ "eslint-plugin-unused-imports": "^4.1.4", "jsdom": "^25.0.1", "markdown-link-extractor": "^4.0.3", - "nx": "22.5.1", + "nx": "22.6.5", "prettier": "^3.8.0", "publint": "^0.3.16", "react": "^19.2.3", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9afc7270ff..262710a585 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -71,12 +71,21 @@ importers: '@eslint-react/eslint-plugin': specifier: ^1.26.2 version: 1.26.2(eslint@9.22.0(jiti@2.6.1))(ts-api-utils@2.4.0(typescript@6.0.2))(typescript@6.0.2) + '@nx/devkit': + specifier: 22.6.5 + version: 22.6.5(nx@22.6.5(@swc-node/register@1.11.1(@emnapi/core@1.9.2)(@emnapi/runtime@1.9.2)(@swc/core@1.10.15(@swc/helpers@0.5.15))(@swc/types@0.1.17)(typescript@6.0.2))(@swc/core@1.10.15(@swc/helpers@0.5.15))) '@playwright/test': specifier: ^1.57.0 version: 1.58.0 '@svitejs/changesets-changelog-github-compact': specifier: ^1.2.0 version: 1.2.0(encoding@0.1.13) + '@swc-node/core': + specifier: ^1.14.1 + version: 1.14.1(@swc/core@1.10.15(@swc/helpers@0.5.15))(@swc/types@0.1.17) + '@swc-node/register': + specifier: ^1.11.1 + version: 1.11.1(@emnapi/core@1.9.2)(@emnapi/runtime@1.9.2)(@swc/core@1.10.15(@swc/helpers@0.5.15))(@swc/types@0.1.17)(typescript@6.0.2) '@tanstack/eslint-config': specifier: 0.4.0 version: 0.4.0(@typescript-eslint/utils@8.57.1(eslint@9.22.0(jiti@2.6.1))(typescript@6.0.2))(eslint-import-resolver-node@0.3.9)(eslint@9.22.0(jiti@2.6.1))(typescript@6.0.2) @@ -120,8 +129,8 @@ importers: specifier: ^4.0.3 version: 4.0.3 nx: - specifier: 22.5.1 - version: 22.5.1 + specifier: 22.6.5 + version: 22.6.5(@swc-node/register@1.11.1(@emnapi/core@1.9.2)(@emnapi/runtime@1.9.2)(@swc/core@1.10.15(@swc/helpers@0.5.15))(@swc/types@0.1.17)(typescript@6.0.2))(@swc/core@1.10.15(@swc/helpers@0.5.15)) prettier: specifier: ^3.8.0 version: 3.8.1 @@ -385,7 +394,7 @@ importers: version: 5.9.2 vitest: specifier: ^3.2.4 - version: 3.2.4(@types/debug@4.1.12)(@types/node@25.0.9)(@vitest/browser@4.0.18(msw@2.7.0(@types/node@25.0.9)(typescript@6.0.2))(vite@8.0.0(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.6.1)(sass-embedded@1.97.2)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.8.1))(vitest@4.0.18))(@vitest/ui@4.0.18)(esbuild@0.27.4)(jiti@2.6.1)(jsdom@27.0.0(postcss@8.5.8))(msw@2.7.0(@types/node@25.0.9)(typescript@5.9.2))(sass-embedded@1.97.2)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.8.1) + version: 3.2.4(@types/debug@4.1.12)(@types/node@25.0.9)(@vitest/browser@4.0.18(msw@2.7.0(@types/node@25.0.9)(typescript@6.0.2))(vite@8.0.0(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.6.1)(sass-embedded@1.97.2)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.8.1))(vitest@4.0.18))(@vitest/ui@4.0.18(vitest@4.0.18))(esbuild@0.27.4)(jiti@2.6.1)(jsdom@27.0.0(postcss@8.5.8))(msw@2.7.0(@types/node@25.0.9)(typescript@5.9.2))(sass-embedded@1.97.2)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.8.1) e2e/react-router/basepath-file-based: dependencies: @@ -5446,7 +5455,7 @@ importers: version: 1.0.6(@rsbuild/core@1.2.4) '@rsbuild/plugin-vue': specifier: ^1.2.2 - version: 1.2.2(@rsbuild/core@1.2.4)(esbuild@0.27.4)(vue@3.5.25(typescript@6.0.2)) + version: 1.2.2(@rsbuild/core@1.2.4)(@swc/core@1.10.15(@swc/helpers@0.5.15))(esbuild@0.27.4)(vue@3.5.25(typescript@6.0.2)) '@rsbuild/plugin-vue-jsx': specifier: ^1.1.1 version: 1.1.1(@babel/core@7.29.0)(@rsbuild/core@1.2.4) @@ -5501,7 +5510,7 @@ importers: version: 1.0.6(@rsbuild/core@1.2.4) '@rsbuild/plugin-vue': specifier: ^1.2.2 - version: 1.2.2(@rsbuild/core@1.2.4)(esbuild@0.27.4)(vue@3.5.25(typescript@6.0.2)) + version: 1.2.2(@rsbuild/core@1.2.4)(@swc/core@1.10.15(@swc/helpers@0.5.15))(esbuild@0.27.4)(vue@3.5.25(typescript@6.0.2)) '@rsbuild/plugin-vue-jsx': specifier: ^1.1.1 version: 1.1.1(@babel/core@7.29.0)(@rsbuild/core@1.2.4) @@ -8945,7 +8954,7 @@ importers: version: 8.0.0(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.6.1)(sass-embedded@1.97.2)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.8.1) vitest: specifier: ^3.2.4 - version: 3.2.4(@types/debug@4.1.12)(@types/node@25.0.9)(@vitest/browser@4.0.18(msw@2.7.0(@types/node@25.0.9)(typescript@6.0.2))(vite@8.0.0(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.6.1)(sass-embedded@1.97.2)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.8.1))(vitest@4.0.18))(@vitest/ui@4.0.18)(esbuild@0.27.4)(jiti@2.6.1)(jsdom@27.0.0(postcss@8.5.8))(msw@2.7.0(@types/node@25.0.9)(typescript@6.0.2))(sass-embedded@1.97.2)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.8.1) + version: 3.2.4(@types/debug@4.1.12)(@types/node@25.0.9)(@vitest/browser@4.0.18(msw@2.7.0(@types/node@25.0.9)(typescript@6.0.2))(vite@8.0.0(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.6.1)(sass-embedded@1.97.2)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.8.1))(vitest@4.0.18))(@vitest/ui@4.0.18(vitest@4.0.18))(esbuild@0.27.4)(jiti@2.6.1)(jsdom@27.0.0(postcss@8.5.8))(msw@2.7.0(@types/node@25.0.9)(typescript@6.0.2))(sass-embedded@1.97.2)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.8.1) web-vitals: specifier: ^5.1.0 version: 5.1.0 @@ -10845,7 +10854,7 @@ importers: version: 6.0.2 webpack: specifier: ^5.97.1 - version: 5.97.1(esbuild@0.27.4)(webpack-cli@5.1.4) + version: 5.97.1(@swc/core@1.10.15(@swc/helpers@0.5.15))(esbuild@0.27.4)(webpack-cli@5.1.4) webpack-cli: specifier: ^5.1.4 version: 5.1.4(webpack-dev-server@5.2.0)(webpack@5.97.1) @@ -11459,7 +11468,7 @@ importers: version: 2.11.11(@testing-library/jest-dom@6.6.3)(solid-js@1.9.10)(vite@8.0.0(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.6.1)(sass-embedded@1.97.2)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.8.1)) vitest: specifier: ^3.2.4 - version: 3.2.4(@types/debug@4.1.12)(@types/node@25.0.9)(@vitest/browser@4.0.18(msw@2.7.0(@types/node@25.0.9)(typescript@6.0.2))(vite@8.0.0(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.6.1)(sass-embedded@1.97.2)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.8.1))(vitest@4.0.18))(@vitest/ui@4.0.18)(esbuild@0.27.4)(jiti@2.6.1)(jsdom@27.0.0(postcss@8.5.8))(msw@2.7.0(@types/node@25.0.9)(typescript@6.0.2))(sass-embedded@1.97.2)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.8.1) + version: 3.2.4(@types/debug@4.1.12)(@types/node@25.0.9)(@vitest/browser@4.0.18(msw@2.7.0(@types/node@25.0.9)(typescript@6.0.2))(vite@8.0.0(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.6.1)(sass-embedded@1.97.2)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.8.1))(vitest@4.0.18))(@vitest/ui@4.0.18(vitest@4.0.18))(esbuild@0.27.4)(jiti@2.6.1)(jsdom@27.0.0(postcss@8.5.8))(msw@2.7.0(@types/node@25.0.9)(typescript@6.0.2))(sass-embedded@1.97.2)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.8.1) web-vitals: specifier: ^5.1.0 version: 5.1.0 @@ -12569,7 +12578,7 @@ importers: version: 2.11.11(@testing-library/jest-dom@6.6.3)(solid-js@1.9.10)(vite@8.0.0(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.6.1)(sass-embedded@1.97.2)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.8.1)) webpack: specifier: '>=5.92.0' - version: 5.97.1(esbuild@0.27.4) + version: 5.97.1(@swc/core@1.10.15(@swc/helpers@0.5.15))(esbuild@0.27.4) zod: specifier: ^3.24.2 version: 3.25.57 @@ -15711,14 +15720,6 @@ packages: '@ioredis/commands@1.5.0': resolution: {integrity: sha512-eUgLqrMf8nJkZxT24JvVRrQya1vZkQh8BBeYNwGDqa5I0VUi8ACx7uFvAaLxintokpTenkK6DASvo/bvNbBGow==} - '@isaacs/balanced-match@4.0.1': - resolution: {integrity: sha512-yzMTt9lEb8Gv7zRioUilSglI0c0smZ9k5D65677DLWLtWJaXIS3CqcGyUFByYKlnUj6TkjLVs54fBl6+TiGQDQ==} - engines: {node: 20 || >=22} - - '@isaacs/brace-expansion@5.0.0': - resolution: {integrity: sha512-ZT55BDLV0yv0RBm2czMiZ+SqCGO7AvmOM3G/w2xhVPH+te0aKgFjmBvGlL1dH+ql2tgGO3MVrbb3jCKyvpgnxA==} - engines: {node: 20 || >=22} - '@isaacs/cliui@8.0.2': resolution: {integrity: sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==} engines: {node: '>=12'} @@ -16212,53 +16213,58 @@ packages: '@nothing-but/utils@0.17.0': resolution: {integrity: sha512-TuCHcHLOqDL0SnaAxACfuRHBNRgNJcNn9X0GiH5H3YSDBVquCr3qEIG3FOQAuMyZCbu9w8nk2CHhOsn7IvhIwQ==} - '@nx/nx-darwin-arm64@22.5.1': - resolution: {integrity: sha512-DuvOwhXPO6l9W7/zM4/BaAbGTIXFyHVcbbCD1c7HfgZ3VfJPmcE7H4+TuQH0cigHHtpg/eGqV100NQbd7N4zwg==} + '@nx/devkit@22.6.5': + resolution: {integrity: sha512-9kvAI+kk2pfEXLqS8OyjI9XvWmp+Gdn7jPfxDAz8BOqxMyPy3p5hYl+jc4TIsLOWunAFl8azqrcYsHzEpaWCIA==} + peerDependencies: + nx: '>= 21 <= 23 || ^22.0.0-0' + + '@nx/nx-darwin-arm64@22.6.5': + resolution: {integrity: sha512-qT77Omkg5xQuL2+pDbneX2tI+XW5ZeayMylu7UUgK8OhTrAkJLKjpuYRH4xT5XBipxbDtlxmO3aLS3Ib1pKzJQ==} cpu: [arm64] os: [darwin] - '@nx/nx-darwin-x64@22.5.1': - resolution: {integrity: sha512-81Lb7+rp3Qltpgy33Kc1qxk+8IWqZLhqvdLdRFSVV1FN1pPSJDFKyPjCn9oMpRryNPSJ8DgZDpfIaVVyP85rUw==} + '@nx/nx-darwin-x64@22.6.5': + resolution: {integrity: sha512-9jICxb7vfJ56y/7Yuh3b/n1QJqWxO9xnXKYEs6SO8xPoW/KomVckILGc1C6RQSs6/3ixVJC7k1Dh1wm5tKPFrg==} cpu: [x64] os: [darwin] - '@nx/nx-freebsd-x64@22.5.1': - resolution: {integrity: sha512-Ig8yQN3lSz9R+Zf3NQWcvEnIzwDX4NSeaFtEliPnC3OHlQXGNXbOUfkExa0U0UUgyxa4rgnCgefmwuc12H9q2Q==} + '@nx/nx-freebsd-x64@22.6.5': + resolution: {integrity: sha512-6B1wEKpqz5dI3AGMqttAVnA6M3DB/besAtuGyQiymK9ROlta1iuWgCcIYwcCQyhLn2Rx7vqj447KKcgCa8HlVw==} cpu: [x64] os: [freebsd] - '@nx/nx-linux-arm-gnueabihf@22.5.1': - resolution: {integrity: sha512-C7tGoLnR9MjKLJsLMF2VsKcDChPiygAsw6dSVgU4B650H7sBWmkEHM/QjvyRvkcZuoQBDamS/eVs/UaJu9wNhA==} + '@nx/nx-linux-arm-gnueabihf@22.6.5': + resolution: {integrity: sha512-xV50B8mnDPboct7JkAHftajI02s+8FszA8WTzhore+YGR+lEKHTLpucwGEaQuMlSdLplH7pQix4B4uK5pcMhZw==} cpu: [arm] os: [linux] - '@nx/nx-linux-arm64-gnu@22.5.1': - resolution: {integrity: sha512-GNxei+lwhzhrO9m+nNkibgxLhbkYKyFXPSRpOKLwv9VavNzJn5UmLfKJyhjNQPBOSYuNhiVPbU1Ja/qOBcozYw==} + '@nx/nx-linux-arm64-gnu@22.6.5': + resolution: {integrity: sha512-2JkWuMGj+HpW6oPAvU5VdAx1afTnEbiM10Y3YOrl3fipWV4BiP5VDx762QTrfCraP4hl6yqTgvTe7F9xaby+jQ==} cpu: [arm64] os: [linux] - '@nx/nx-linux-arm64-musl@22.5.1': - resolution: {integrity: sha512-VDJtdJP2nCgS8ommbfWFAKjoZCE51VH7tZyIfh8RFI5fxwoB3Pk6d6f6cmNHI/1t98YI3V7Onuf3Y9KBkYtyfQ==} + '@nx/nx-linux-arm64-musl@22.6.5': + resolution: {integrity: sha512-Z/zMqFClnEyqDXouJKEPoWVhMQIif5F0YuECWBYjd3ZLwQsXGTItoh+6Wm3XF/nGMA2uLOHyTq/X7iFXQY3RzA==} cpu: [arm64] os: [linux] - '@nx/nx-linux-x64-gnu@22.5.1': - resolution: {integrity: sha512-BZ/i+KTplEJmE8ZHKgPGD513Zl86DuSGyRAvbDZ7Qf19Tei7Of6vxW+ypvVDIwmDbyXfe13u54M5gDt8iiqFGQ==} + '@nx/nx-linux-x64-gnu@22.6.5': + resolution: {integrity: sha512-FlotSyqNnaXSn0K+yWw+hRdYBwusABrPgKLyixfJIYRzsy+xPKN6pON6vZfqGwzuWF/9mEGReRz+iM8PiW0XSg==} cpu: [x64] os: [linux] - '@nx/nx-linux-x64-musl@22.5.1': - resolution: {integrity: sha512-e0VdiV6fe88Dbhill2gUjYAD9jMhHjYsafGOPR+/uaGMAYPoI1jKur6uPGY+ik6fvwvDFFl0VT2+HACKVn7RoA==} + '@nx/nx-linux-x64-musl@22.6.5': + resolution: {integrity: sha512-RVOe2qcwhoIx6mxQURPjUfAW5SEOmT2gdhewvdcvX9ICq1hj5B2VarmkhTg0qroO7xiyqOqwq26mCzoV2I3NgQ==} cpu: [x64] os: [linux] - '@nx/nx-win32-arm64-msvc@22.5.1': - resolution: {integrity: sha512-3vWZO9y7uHKeyepcU55pE8VQTKGome3mLdicvx1TCoKKl0cA3bTR341Jdo2Zl4Waa2ENk7pGQbLWRQ3ZkaA92A==} + '@nx/nx-win32-arm64-msvc@22.6.5': + resolution: {integrity: sha512-ZqurqI8VuYnsr2Kn4K4t+Gx6j/BZdf6qz/6Tv4A7XQQ6oNYVQgTqoNEFj+CCkVaIe6aIdCWpousFLqs+ZgBqYQ==} cpu: [arm64] os: [win32] - '@nx/nx-win32-x64-msvc@22.5.1': - resolution: {integrity: sha512-4e5LduuhpBx96JgD1J3fHUGCwC+/lL+tvXp3UVtjh/AOdINGsyI+scinT3uaI9vcB5GKBcybTxbBZzwcH50w9g==} + '@nx/nx-win32-x64-msvc@22.6.5': + resolution: {integrity: sha512-i2QFBJIuaYg9BHxrrnBV4O7W9rVL2k0pSIdk/rRp3EYJEU93iUng+qbZiY9wh1xvmXuUCE2G7TRd+8/SG/RFKg==} cpu: [x64] os: [win32] @@ -16419,6 +16425,106 @@ packages: '@oxc-project/types@0.124.0': resolution: {integrity: sha512-VBFWMTBvHxS11Z5Lvlr3IWgrwhMTXV+Md+EQF0Xf60+wAdsGFTBx7X7K/hP4pi8N7dcm1RvcHwDxZ16Qx8keUg==} + '@oxc-resolver/binding-android-arm-eabi@11.19.1': + resolution: {integrity: sha512-aUs47y+xyXHUKlbhqHUjBABjvycq6YSD7bpxSW7vplUmdzAlJ93yXY6ZR0c1o1x5A/QKbENCvs3+NlY8IpIVzg==} + cpu: [arm] + os: [android] + + '@oxc-resolver/binding-android-arm64@11.19.1': + resolution: {integrity: sha512-oolbkRX+m7Pq2LNjr/kKgYeC7bRDMVTWPgxBGMjSpZi/+UskVo4jsMU3MLheZV55jL6c3rNelPl4oD60ggYmqA==} + cpu: [arm64] + os: [android] + + '@oxc-resolver/binding-darwin-arm64@11.19.1': + resolution: {integrity: sha512-nUC6d2i3R5B12sUW4O646qD5cnMXf2oBGPLIIeaRfU9doJRORAbE2SGv4eW6rMqhD+G7nf2Y8TTJTLiiO3Q/dQ==} + cpu: [arm64] + os: [darwin] + + '@oxc-resolver/binding-darwin-x64@11.19.1': + resolution: {integrity: sha512-cV50vE5+uAgNcFa3QY1JOeKDSkM/9ReIcc/9wn4TavhW/itkDGrXhw9jaKnkQnGbjJ198Yh5nbX/Gr2mr4Z5jQ==} + cpu: [x64] + os: [darwin] + + '@oxc-resolver/binding-freebsd-x64@11.19.1': + resolution: {integrity: sha512-xZOQiYGFxtk48PBKff+Zwoym7ScPAIVp4c14lfLxizO2LTTTJe5sx9vQNGrBymrf/vatSPNMD4FgsaaRigPkqw==} + cpu: [x64] + os: [freebsd] + + '@oxc-resolver/binding-linux-arm-gnueabihf@11.19.1': + resolution: {integrity: sha512-lXZYWAC6kaGe/ky2su94e9jN9t6M0/6c+GrSlCqL//XO1cxi5lpAhnJYdyrKfm0ZEr/c7RNyAx3P7FSBcBd5+A==} + cpu: [arm] + os: [linux] + + '@oxc-resolver/binding-linux-arm-musleabihf@11.19.1': + resolution: {integrity: sha512-veG1kKsuK5+t2IsO9q0DErYVSw2azvCVvWHnfTOS73WE0STdLLB7Q1bB9WR+yHPQM76ASkFyRbogWo1GR1+WbQ==} + cpu: [arm] + os: [linux] + + '@oxc-resolver/binding-linux-arm64-gnu@11.19.1': + resolution: {integrity: sha512-heV2+jmXyYnUrpUXSPugqWDRpnsQcDm2AX4wzTuvgdlZfoNYO0O3W2AVpJYaDn9AG4JdM6Kxom8+foE7/BcSig==} + cpu: [arm64] + os: [linux] + + '@oxc-resolver/binding-linux-arm64-musl@11.19.1': + resolution: {integrity: sha512-jvo2Pjs1c9KPxMuMPIeQsgu0mOJF9rEb3y3TdpsrqwxRM+AN6/nDDwv45n5ZrUnQMsdBy5gIabioMKnQfWo9ew==} + cpu: [arm64] + os: [linux] + + '@oxc-resolver/binding-linux-ppc64-gnu@11.19.1': + resolution: {integrity: sha512-vLmdNxWCdN7Uo5suays6A/+ywBby2PWBBPXctWPg5V0+eVuzsJxgAn6MMB4mPlshskYbppjpN2Zg83ArHze9gQ==} + cpu: [ppc64] + os: [linux] + + '@oxc-resolver/binding-linux-riscv64-gnu@11.19.1': + resolution: {integrity: sha512-/b+WgR+VTSBxzgOhDO7TlMXC1ufPIMR6Vj1zN+/x+MnyXGW7prTLzU9eW85Aj7Th7CCEG9ArCbTeqxCzFWdg2w==} + cpu: [riscv64] + os: [linux] + + '@oxc-resolver/binding-linux-riscv64-musl@11.19.1': + resolution: {integrity: sha512-YlRdeWb9j42p29ROh+h4eg/OQ3dTJlpHSa+84pUM9+p6i3djtPz1q55yLJhgW9XfDch7FN1pQ/Vd6YP+xfRIuw==} + cpu: [riscv64] + os: [linux] + + '@oxc-resolver/binding-linux-s390x-gnu@11.19.1': + resolution: {integrity: sha512-EDpafVOQWF8/MJynsjOGFThcqhRHy417sRyLfQmeiamJ8qVhSKAn2Dn2VVKUGCjVB9C46VGjhNo7nOPUi1x6uA==} + cpu: [s390x] + os: [linux] + + '@oxc-resolver/binding-linux-x64-gnu@11.19.1': + resolution: {integrity: sha512-NxjZe+rqWhr+RT8/Ik+5ptA3oz7tUw361Wa5RWQXKnfqwSSHdHyrw6IdcTfYuml9dM856AlKWZIUXDmA9kkiBQ==} + cpu: [x64] + os: [linux] + + '@oxc-resolver/binding-linux-x64-musl@11.19.1': + resolution: {integrity: sha512-cM/hQwsO3ReJg5kR+SpI69DMfvNCp+A/eVR4b4YClE5bVZwz8rh2Nh05InhwI5HR/9cArbEkzMjcKgTHS6UaNw==} + cpu: [x64] + os: [linux] + + '@oxc-resolver/binding-openharmony-arm64@11.19.1': + resolution: {integrity: sha512-QF080IowFB0+9Rh6RcD19bdgh49BpQHUW5TajG1qvWHvmrQznTZZjYlgE2ltLXyKY+qs4F/v5xuX1XS7Is+3qA==} + cpu: [arm64] + os: [openharmony] + + '@oxc-resolver/binding-wasm32-wasi@11.19.1': + resolution: {integrity: sha512-w8UCKhX826cP/ZLokXDS6+milN8y4X7zidsAttEdWlVoamTNf6lhBJldaWr3ukTDiye7s4HRcuPEPOXNC432Vg==} + engines: {node: '>=14.0.0'} + cpu: [wasm32] + + '@oxc-resolver/binding-win32-arm64-msvc@11.19.1': + resolution: {integrity: sha512-nJ4AsUVZrVKwnU/QRdzPCCrO0TrabBqgJ8pJhXITdZGYOV28TIYystV1VFLbQ7DtAcaBHpocT5/ZJnF78YJPtQ==} + cpu: [arm64] + os: [win32] + + '@oxc-resolver/binding-win32-ia32-msvc@11.19.1': + resolution: {integrity: sha512-EW+ND5q2Tl+a3pH81l1QbfgbF3HmqgwLfDfVithRFheac8OTcnbXt/JxqD2GbDkb7xYEqy1zNaVFRr3oeG8npA==} + cpu: [ia32] + os: [win32] + + '@oxc-resolver/binding-win32-x64-msvc@11.19.1': + resolution: {integrity: sha512-6hIU3RQu45B+VNTY4Ru8ppFwjVS/S5qwYyGhBotmjxfEKk41I2DlGtRfGJndZ5+6lneE2pwloqunlOyZuX/XAw==} + cpu: [x64] + os: [win32] + '@oxc-transform/binding-android-arm-eabi@0.110.0': resolution: {integrity: sha512-sE9dxvqqAax1YYJ3t7j+h5ZSI9jl6dYuDfngl6ieZUrIy5P89/8JKVgAzgp8o3wQSo7ndpJvYsi1K4ZqrmbP7w==} engines: {node: ^20.19.0 || >=22.12.0} @@ -18351,6 +18457,22 @@ packages: resolution: {integrity: sha512-08eKiDAjj4zLug1taXSIJ0kGL5cawjVCyJkBb6EWSg5fEPX6L+Wtr0CH2If4j5KYylz85iaZiFlUItvgJvll5g==} engines: {node: ^14.13.1 || ^16.0.0 || >=18} + '@swc-node/core@1.14.1': + resolution: {integrity: sha512-jrt5GUaZUU6cmMS+WTJEvGvaB6j1YNKPHPzC2PUi2BjaFbtxURHj6641Az6xN7b665hNniAIdvjxWcRml5yCnw==} + engines: {node: '>= 10'} + peerDependencies: + '@swc/core': '>= 1.13.3' + '@swc/types': '>= 0.1' + + '@swc-node/register@1.11.1': + resolution: {integrity: sha512-VQ0hJ5jX31TVv/fhZx4xJRzd8pwn6VvzYd2tGOHHr2TfXGCBixZoqdPDXTiEoJLCTS2MmvBf6zyQZZ0M8aGQCQ==} + peerDependencies: + '@swc/core': '>= 1.4.13' + typescript: '>= 4.3' + + '@swc-node/sourcemap-support@0.6.1': + resolution: {integrity: sha512-ovltDVH5QpdHXZkW138vG4+dgcNsxfwxHVoV6BtmTbz2KKl1A8ZSlbdtxzzfNjCjbpayda8Us9eMtcHobm38dA==} + '@swc/core-darwin-arm64@1.10.15': resolution: {integrity: sha512-zFdZ6/yHqMCPk7OhLFqHy/MQ1EqJhcZMpNHd1gXYT7VRU3FaqvvKETrUlG3VYl65McPC7AhMRfXPyJ0JO/jARQ==} engines: {node: '>=10'} @@ -19909,6 +20031,9 @@ packages: axios@1.13.2: resolution: {integrity: sha512-VPk9ebNqPcy5lRGuSlKx752IlDatOjT9paPlm8A7yOuW2Fbvp4X3JznJtT4f0GzGLLiWE9W8onz51SqLYwzGaA==} + axios@1.15.0: + resolution: {integrity: sha512-wWyJDlAatxk30ZJer+GeCWS209sA42X+N5jU2jy6oHTp7ufw8uzUTVFBX9+wTfAlhiJXGS0Bq7X6efruWjuK9Q==} + b4a@1.6.7: resolution: {integrity: sha512-OnAYlL5b7LEkALw87fUVafQw5rVR9RjwGd4KUwNQ6DrrNmaVaUCgLipfVlzrPQ4tWOR9P0IXGNOx50jYCCdSJg==} @@ -20983,9 +21108,9 @@ packages: effect@3.18.4: resolution: {integrity: sha512-b1LXQJLe9D11wfnOKAk3PKxuqYshQ0Heez+y5pnkd3jLj1yx9QhM72zZ9uUrOQyNvrs2GZZd/3maL0ZV18YuDA==} - ejs@3.1.10: - resolution: {integrity: sha512-UeJmFfOrAQS8OJWPZ4qtgHyWExa088/MtK5UEyoJGFH67cDEXkZSviOiKRCZ4Xij0zxI3JECgYs3oKx+AizQBA==} - engines: {node: '>=0.10.0'} + ejs@5.0.1: + resolution: {integrity: sha512-COqBPFMxuPTPspXl2DkVYaDS3HtrD1GpzOGkNTJ1IYkifq/r9h8SVEFrjA3D9/VJGOEoMQcrlhpntcSUrM8k6A==} + engines: {node: '>=0.12.18'} hasBin: true electron-to-chromium@1.5.267: @@ -21561,9 +21686,6 @@ packages: file-uri-to-path@1.0.0: resolution: {integrity: sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==} - filelist@1.0.6: - resolution: {integrity: sha512-5giy2PkLYY1cP39p17Ech+2xlpTRL9HLspOfEgm0L6CwBXBTgsK5ou0JtzYuepxkaQ/tvhCFIJ5uXo0OrM2DxA==} - fill-range@7.1.1: resolution: {integrity: sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==} engines: {node: '>=8'} @@ -21636,6 +21758,15 @@ packages: debug: optional: true + follow-redirects@1.16.0: + resolution: {integrity: sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==} + engines: {node: '>=4.0'} + peerDependencies: + debug: '*' + peerDependenciesMeta: + debug: + optional: true + for-each@0.3.5: resolution: {integrity: sha512-dKx12eRCVIzqCxFGplyFKJMPvLEWgmNtUrpTiJIR5u97zEhRG8ySrtboPHZXx7daLxQVrl643cTzbab2tkQjxg==} engines: {node: '>= 0.4'} @@ -22435,11 +22566,6 @@ packages: jackspeak@3.4.3: resolution: {integrity: sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==} - jake@10.9.4: - resolution: {integrity: sha512-wpHYzhxiVQL+IV05BLE2Xn34zW1S223hvjtqk0+gsPrwd/8JNLXJgZZM/iPFsYc1xyphF+6M6EvdE5E9MBGkDA==} - engines: {node: '>=10'} - hasBin: true - jest-diff@30.0.5: resolution: {integrity: sha512-1UIqE9PoEKaHcIKvq2vbibrCog4Y8G0zmOxgQUVEiTqwR5hJVMCoDsN1vFvI5JvwD37hjueZ1C4l2FyGnfpE0A==} engines: {node: ^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0} @@ -23014,10 +23140,6 @@ packages: resolution: {integrity: sha512-ethXTt3SGGR+95gudmqJ1eNhRO7eGEGIgYA9vnPatK4/etz2MEVDno5GMCibdMTuBMyElzIlgxMna3K94XDIDQ==} engines: {node: 20 || >=22} - minimatch@10.1.1: - resolution: {integrity: sha512-enIvLvRAFZYXJzkCYG5RKmPfrFArdLv+R+lbQ53BmIMLIry74bjKzX6iHAm8WYamJkhSSEabrWN5D97XnKObjQ==} - engines: {node: 20 || >=22} - minimatch@10.2.4: resolution: {integrity: sha512-oRjTw/97aTBN0RHbYCdtF1MQfvusSIBQM0IZEgzl6426+8jSC0nF1a/GmnVLpfB9yyr6g6FTqWqiZVbxrtaCIg==} engines: {node: 18 || 20 || >=22} @@ -23288,9 +23410,6 @@ packages: resolution: {integrity: sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==} hasBin: true - node-machine-id@1.1.12: - resolution: {integrity: sha512-QNABxbrPa3qEIfrE6GOJ7BYIuignnJw7iQ2YPbc3Nla1HzRJjXzZOiikfF8m7eAMfichLt3M4VgLOetqgDmgGQ==} - node-mock-http@1.0.4: resolution: {integrity: sha512-8DY+kFsDkNXy1sJglUfuODx1/opAGJGyrTuFqEoN90oRc2Vk0ZbD4K2qmKXBBEhZQzdKHIVfEJpDU8Ak2NJEvQ==} @@ -23344,12 +23463,12 @@ packages: nwsapi@2.2.16: resolution: {integrity: sha512-F1I/bimDpj3ncaNDhfyMWuFqmQDBwDB0Fogc2qpL3BWvkQteFD/8BzWuIRl83rq0DXfm8SGt/HFhLXZyljTXcQ==} - nx@22.5.1: - resolution: {integrity: sha512-KIQqOSdoshkav9JuoH/+Vp42niA5MTRtACupe+q8CaB7bHiLsWr5nctQVC7ul3NauAmsoqNWH7t5CIi8KgrPIQ==} + nx@22.6.5: + resolution: {integrity: sha512-VRKhDAt684dXNSz9MNjE7MekkCfQF41P2PSx5jEWQjDEP1Z4jFZbyeygWs5ZyOroG7/n0MoWAJTe6ftvIcBOAg==} hasBin: true peerDependencies: - '@swc-node/register': 1.11.1 - '@swc/core': 1.15.8 + '@swc-node/register': ^1.11.1 + '@swc/core': ^1.15.8 peerDependenciesMeta: '@swc-node/register': optional: true @@ -23464,6 +23583,9 @@ packages: resolution: {integrity: sha512-KWGTzPo83QmGrXC4ml83PM9HDwUPtZFfasiclUvTV4i3/0j7xRRqINVkrL77CbQnoWura3CMxkRofjQKVDuhBw==} engines: {node: ^20.19.0 || >=22.12.0} + oxc-resolver@11.19.1: + resolution: {integrity: sha512-qE/CIg/spwrTBFt5aKmwe3ifeDdLfA2NESN30E42X/lII5ClF8V7Wt6WIJhcGZjp0/Q+nQ+9vgxGk//xZNX2hg==} + oxc-transform@0.110.0: resolution: {integrity: sha512-/fymQNzzUoKZweH0nC5yvbI2eR0yWYusT9TEKDYVgOgYrf9Qmdez9lUFyvxKR9ycx+PTHi/reIOzqf3wkShQsw==} engines: {node: ^20.19.0 || >=22.12.0} @@ -23685,6 +23807,10 @@ packages: resolution: {integrity: sha512-0GNPNzHXBKw6U/InGe79A3Crzyk9bcSyObF9/Gfo9DLEf5qj5RF50RSjsu0W1rZ6ZqRGdzDFCRBQvi9/rSGPtA==} hasBin: true + pirates@4.0.7: + resolution: {integrity: sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==} + engines: {node: '>= 6'} + pixelmatch@7.1.0: resolution: {integrity: sha512-1wrVzJ2STrpmONHKBy228LM1b84msXDUoAzVEl0R8Mz4Ce6EPr+IVtxm8+yvrqLYMHswREkjYFaMxnyGnaY3Ng==} hasBin: true @@ -23913,6 +24039,10 @@ packages: proxy-from-env@1.1.0: resolution: {integrity: sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==} + proxy-from-env@2.1.0: + resolution: {integrity: sha512-cJ+oHTW1VAEa8cJslgmUZrc+sjRKgAKl3Zyse6+PV38hZe/V6Z14TbCuXcan9F9ghlz4QrFr2c92TNF82UkYHA==} + engines: {node: '>=10'} + psl@1.15.0: resolution: {integrity: sha512-JZd3gMVBAVQkSs6HdNZo9Sdo0LNcQeMNP3CozBJb3JYC/QUYZTnKxP+f8oWRX4rHP5EurWxqAHTSwUCjlNKa1w==} @@ -24683,6 +24813,10 @@ packages: smob@1.5.0: resolution: {integrity: sha512-g6T+p7QO8npa+/hNx9ohv1E5pVCmWrVCUzUXJyLdMmftX6ER0oiWY/w9knEonLpnOp6b6FenKnMfR8gqwWdwig==} + smol-toml@1.6.1: + resolution: {integrity: sha512-dWUG8F5sIIARXih1DTaQAX4SsiTXhInKf1buxdY9DIg4ZYPZK5nGM1VRIYmEbDbsHt7USo99xSLFu5Q1IqTmsg==} + engines: {node: '>= 18'} + sockjs@0.3.24: resolution: {integrity: sha512-GJgLTZ7vYb/JtPSSZ10hsOYIvEYsjbNU+zPdIHcUaWVNUEPivzxku31865sSSud0Da0W4lEeOPlmw93zLQchuQ==} @@ -27354,30 +27488,30 @@ snapshots: dependencies: '@emnapi/wasi-threads': 1.1.0 tslib: 2.8.1 + optional: true '@emnapi/core@1.9.2': dependencies: '@emnapi/wasi-threads': 1.2.1 tslib: 2.8.1 - optional: true '@emnapi/runtime@1.7.1': dependencies: tslib: 2.8.1 + optional: true '@emnapi/runtime@1.9.2': dependencies: tslib: 2.8.1 - optional: true '@emnapi/wasi-threads@1.1.0': dependencies: tslib: 2.8.1 + optional: true '@emnapi/wasi-threads@1.2.1': dependencies: tslib: 2.8.1 - optional: true '@emotion/babel-plugin@11.13.5': dependencies: @@ -28720,12 +28854,6 @@ snapshots: '@ioredis/commands@1.5.0': {} - '@isaacs/balanced-match@4.0.1': {} - - '@isaacs/brace-expansion@5.0.0': - dependencies: - '@isaacs/balanced-match': 4.0.1 - '@isaacs/cliui@8.0.2': dependencies: string-width: 5.1.2 @@ -29148,8 +29276,8 @@ snapshots: '@napi-rs/wasm-runtime@0.2.4': dependencies: - '@emnapi/core': 1.7.1 - '@emnapi/runtime': 1.7.1 + '@emnapi/core': 1.9.2 + '@emnapi/runtime': 1.9.2 '@tybys/wasm-util': 0.9.0 '@napi-rs/wasm-runtime@1.1.1': @@ -29517,34 +29645,45 @@ snapshots: '@nothing-but/utils@0.17.0': {} - '@nx/nx-darwin-arm64@22.5.1': + '@nx/devkit@22.6.5(nx@22.6.5(@swc-node/register@1.11.1(@emnapi/core@1.9.2)(@emnapi/runtime@1.9.2)(@swc/core@1.10.15(@swc/helpers@0.5.15))(@swc/types@0.1.17)(typescript@6.0.2))(@swc/core@1.10.15(@swc/helpers@0.5.15)))': + dependencies: + '@zkochan/js-yaml': 0.0.7 + ejs: 5.0.1 + enquirer: 2.3.6 + minimatch: 10.2.4 + nx: 22.6.5(@swc-node/register@1.11.1(@emnapi/core@1.9.2)(@emnapi/runtime@1.9.2)(@swc/core@1.10.15(@swc/helpers@0.5.15))(@swc/types@0.1.17)(typescript@6.0.2))(@swc/core@1.10.15(@swc/helpers@0.5.15)) + semver: 7.7.3 + tslib: 2.8.1 + yargs-parser: 21.1.1 + + '@nx/nx-darwin-arm64@22.6.5': optional: true - '@nx/nx-darwin-x64@22.5.1': + '@nx/nx-darwin-x64@22.6.5': optional: true - '@nx/nx-freebsd-x64@22.5.1': + '@nx/nx-freebsd-x64@22.6.5': optional: true - '@nx/nx-linux-arm-gnueabihf@22.5.1': + '@nx/nx-linux-arm-gnueabihf@22.6.5': optional: true - '@nx/nx-linux-arm64-gnu@22.5.1': + '@nx/nx-linux-arm64-gnu@22.6.5': optional: true - '@nx/nx-linux-arm64-musl@22.5.1': + '@nx/nx-linux-arm64-musl@22.6.5': optional: true - '@nx/nx-linux-x64-gnu@22.5.1': + '@nx/nx-linux-x64-gnu@22.6.5': optional: true - '@nx/nx-linux-x64-musl@22.5.1': + '@nx/nx-linux-x64-musl@22.6.5': optional: true - '@nx/nx-win32-arm64-msvc@22.5.1': + '@nx/nx-win32-arm64-msvc@22.6.5': optional: true - '@nx/nx-win32-x64-msvc@22.5.1': + '@nx/nx-win32-x64-msvc@22.6.5': optional: true '@one-ini/wasm@0.1.1': {} @@ -29643,6 +29782,71 @@ snapshots: '@oxc-project/types@0.124.0': {} + '@oxc-resolver/binding-android-arm-eabi@11.19.1': + optional: true + + '@oxc-resolver/binding-android-arm64@11.19.1': + optional: true + + '@oxc-resolver/binding-darwin-arm64@11.19.1': + optional: true + + '@oxc-resolver/binding-darwin-x64@11.19.1': + optional: true + + '@oxc-resolver/binding-freebsd-x64@11.19.1': + optional: true + + '@oxc-resolver/binding-linux-arm-gnueabihf@11.19.1': + optional: true + + '@oxc-resolver/binding-linux-arm-musleabihf@11.19.1': + optional: true + + '@oxc-resolver/binding-linux-arm64-gnu@11.19.1': + optional: true + + '@oxc-resolver/binding-linux-arm64-musl@11.19.1': + optional: true + + '@oxc-resolver/binding-linux-ppc64-gnu@11.19.1': + optional: true + + '@oxc-resolver/binding-linux-riscv64-gnu@11.19.1': + optional: true + + '@oxc-resolver/binding-linux-riscv64-musl@11.19.1': + optional: true + + '@oxc-resolver/binding-linux-s390x-gnu@11.19.1': + optional: true + + '@oxc-resolver/binding-linux-x64-gnu@11.19.1': + optional: true + + '@oxc-resolver/binding-linux-x64-musl@11.19.1': + optional: true + + '@oxc-resolver/binding-openharmony-arm64@11.19.1': + optional: true + + '@oxc-resolver/binding-wasm32-wasi@11.19.1(@emnapi/core@1.9.2)(@emnapi/runtime@1.9.2)': + dependencies: + '@napi-rs/wasm-runtime': 1.1.3(@emnapi/core@1.9.2)(@emnapi/runtime@1.9.2) + transitivePeerDependencies: + - '@emnapi/core' + - '@emnapi/runtime' + optional: true + + '@oxc-resolver/binding-win32-arm64-msvc@11.19.1': + optional: true + + '@oxc-resolver/binding-win32-ia32-msvc@11.19.1': + optional: true + + '@oxc-resolver/binding-win32-x64-msvc@11.19.1': + optional: true + '@oxc-transform/binding-android-arm-eabi@0.110.0': optional: true @@ -31038,11 +31242,11 @@ snapshots: - '@babel/core' - supports-color - '@rsbuild/plugin-vue@1.2.2(@rsbuild/core@1.2.4)(esbuild@0.27.4)(vue@3.5.25(typescript@6.0.2))': + '@rsbuild/plugin-vue@1.2.2(@rsbuild/core@1.2.4)(@swc/core@1.10.15(@swc/helpers@0.5.15))(esbuild@0.27.4)(vue@3.5.25(typescript@6.0.2))': dependencies: '@rsbuild/core': 1.2.4 - rspack-vue-loader: 17.4.4(vue@3.5.25(typescript@6.0.2))(webpack@5.104.0(esbuild@0.27.4)) - webpack: 5.104.0(esbuild@0.27.4) + rspack-vue-loader: 17.4.4(vue@3.5.25(typescript@6.0.2))(webpack@5.104.0(@swc/core@1.10.15(@swc/helpers@0.5.15))(esbuild@0.27.4)) + webpack: 5.104.0(@swc/core@1.10.15(@swc/helpers@0.5.15))(esbuild@0.27.4) transitivePeerDependencies: - '@swc/core' - '@vue/compiler-sfc' @@ -31564,6 +31768,33 @@ snapshots: transitivePeerDependencies: - encoding + '@swc-node/core@1.14.1(@swc/core@1.10.15(@swc/helpers@0.5.15))(@swc/types@0.1.17)': + dependencies: + '@swc/core': 1.10.15(@swc/helpers@0.5.15) + '@swc/types': 0.1.17 + + '@swc-node/register@1.11.1(@emnapi/core@1.9.2)(@emnapi/runtime@1.9.2)(@swc/core@1.10.15(@swc/helpers@0.5.15))(@swc/types@0.1.17)(typescript@6.0.2)': + dependencies: + '@swc-node/core': 1.14.1(@swc/core@1.10.15(@swc/helpers@0.5.15))(@swc/types@0.1.17) + '@swc-node/sourcemap-support': 0.6.1 + '@swc/core': 1.10.15(@swc/helpers@0.5.15) + colorette: 2.0.20 + debug: 4.4.3 + oxc-resolver: 11.19.1(@emnapi/core@1.9.2)(@emnapi/runtime@1.9.2) + pirates: 4.0.7 + tslib: 2.8.1 + typescript: 6.0.2 + transitivePeerDependencies: + - '@emnapi/core' + - '@emnapi/runtime' + - '@swc/types' + - supports-color + + '@swc-node/sourcemap-support@0.6.1': + dependencies: + source-map-support: 0.5.21 + tslib: 2.8.1 + '@swc/core-darwin-arm64@1.10.15': optional: true @@ -33100,7 +33331,7 @@ snapshots: sirv: 3.0.2 tinyglobby: 0.2.15 tinyrainbow: 3.0.3 - vitest: 4.0.18(@types/node@25.0.9)(@vitest/ui@4.0.18)(esbuild@0.27.4)(jiti@2.6.1)(jsdom@27.0.0(postcss@8.5.8))(msw@2.7.0(@types/node@25.0.9)(typescript@6.0.2))(sass-embedded@1.97.2)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.8.1) + vitest: 4.0.18(@types/node@25.0.9)(@vitest/ui@4.0.18)(esbuild@0.27.4)(jiti@2.6.1)(jsdom@25.0.1)(msw@2.7.0(@types/node@25.0.9)(typescript@6.0.2))(sass-embedded@1.97.2)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.8.1) '@vitest/utils@3.2.4': dependencies: @@ -33776,6 +34007,14 @@ snapshots: transitivePeerDependencies: - debug + axios@1.15.0: + dependencies: + follow-redirects: 1.16.0 + form-data: 4.0.5 + proxy-from-env: 2.1.0 + transitivePeerDependencies: + - debug + b4a@1.6.7: {} babel-dead-code-elimination@1.0.12: @@ -33791,7 +34030,7 @@ snapshots: dependencies: '@babel/core': 7.28.5 find-up: 5.0.0 - webpack: 5.97.1(esbuild@0.27.4)(webpack-cli@5.1.4) + webpack: 5.97.1(@swc/core@1.10.15(@swc/helpers@0.5.15))(esbuild@0.27.4)(webpack-cli@5.1.4) babel-plugin-jsx-dom-expressions@0.40.3(@babel/core@7.28.5): dependencies: @@ -34507,7 +34746,7 @@ snapshots: semver: 7.7.3 optionalDependencies: '@rspack/core': 1.2.2(@swc/helpers@0.5.15) - webpack: 5.97.1(esbuild@0.27.4)(webpack-cli@5.1.4) + webpack: 5.97.1(@swc/core@1.10.15(@swc/helpers@0.5.15))(esbuild@0.27.4)(webpack-cli@5.1.4) css-select@4.3.0: dependencies: @@ -34871,9 +35110,7 @@ snapshots: '@standard-schema/spec': 1.0.0 fast-check: 3.23.2 - ejs@3.1.10: - dependencies: - jake: 10.9.4 + ejs@5.0.1: {} electron-to-chromium@1.5.267: {} @@ -35749,10 +35986,6 @@ snapshots: file-uri-to-path@1.0.0: {} - filelist@1.0.6: - dependencies: - minimatch: 5.1.6 - fill-range@7.1.1: dependencies: to-regex-range: 5.0.1 @@ -35863,6 +36096,8 @@ snapshots: optionalDependencies: debug: 4.4.3 + follow-redirects@1.16.0: {} + for-each@0.3.5: dependencies: is-callable: 1.2.7 @@ -36025,7 +36260,7 @@ snapshots: glob@13.0.0: dependencies: - minimatch: 10.1.1 + minimatch: 10.2.4 minipass: 7.1.2 path-scurry: 2.0.0 @@ -36651,12 +36886,6 @@ snapshots: optionalDependencies: '@pkgjs/parseargs': 0.11.0 - jake@10.9.4: - dependencies: - async: 3.2.6 - filelist: 1.0.6 - picocolors: 1.1.1 - jest-diff@30.0.5: dependencies: '@jest/diff-sequences': 30.0.1 @@ -37227,10 +37456,6 @@ snapshots: dependencies: brace-expansion: 2.0.1 - minimatch@10.1.1: - dependencies: - '@isaacs/brace-expansion': 5.0.0 - minimatch@10.2.4: dependencies: brace-expansion: 5.0.4 @@ -37686,8 +37911,6 @@ snapshots: node-gyp-build@4.8.4: {} - node-machine-id@1.1.12: {} - node-mock-http@1.0.4: {} node-releases@2.0.19: {} @@ -37734,19 +37957,19 @@ snapshots: nwsapi@2.2.16: {} - nx@22.5.1: + nx@22.6.5(@swc-node/register@1.11.1(@emnapi/core@1.9.2)(@emnapi/runtime@1.9.2)(@swc/core@1.10.15(@swc/helpers@0.5.15))(@swc/types@0.1.17)(typescript@6.0.2))(@swc/core@1.10.15(@swc/helpers@0.5.15)): dependencies: '@napi-rs/wasm-runtime': 0.2.4 '@yarnpkg/lockfile': 1.1.0 '@yarnpkg/parsers': 3.0.2 '@zkochan/js-yaml': 0.0.7 - axios: 1.13.2 + axios: 1.15.0 cli-cursor: 3.1.0 cli-spinners: 2.6.1 cliui: 8.0.1 dotenv: 16.4.7 dotenv-expand: 11.0.7 - ejs: 3.1.10 + ejs: 5.0.1 enquirer: 2.3.6 figures: 3.2.0 flat: 5.0.2 @@ -37755,14 +37978,14 @@ snapshots: jest-diff: 30.0.5 jsonc-parser: 3.2.0 lines-and-columns: 2.0.3 - minimatch: 10.1.1 - node-machine-id: 1.1.12 + minimatch: 10.2.4 npm-run-path: 4.0.1 open: 8.4.2 ora: 5.3.0 picocolors: 1.1.1 resolve.exports: 2.0.3 semver: 7.7.3 + smol-toml: 1.6.1 string-width: 4.2.3 tar-stream: 2.2.0 tmp: 0.2.3 @@ -37773,16 +37996,18 @@ snapshots: yargs: 17.7.2 yargs-parser: 21.1.1 optionalDependencies: - '@nx/nx-darwin-arm64': 22.5.1 - '@nx/nx-darwin-x64': 22.5.1 - '@nx/nx-freebsd-x64': 22.5.1 - '@nx/nx-linux-arm-gnueabihf': 22.5.1 - '@nx/nx-linux-arm64-gnu': 22.5.1 - '@nx/nx-linux-arm64-musl': 22.5.1 - '@nx/nx-linux-x64-gnu': 22.5.1 - '@nx/nx-linux-x64-musl': 22.5.1 - '@nx/nx-win32-arm64-msvc': 22.5.1 - '@nx/nx-win32-x64-msvc': 22.5.1 + '@nx/nx-darwin-arm64': 22.6.5 + '@nx/nx-darwin-x64': 22.6.5 + '@nx/nx-freebsd-x64': 22.6.5 + '@nx/nx-linux-arm-gnueabihf': 22.6.5 + '@nx/nx-linux-arm64-gnu': 22.6.5 + '@nx/nx-linux-arm64-musl': 22.6.5 + '@nx/nx-linux-x64-gnu': 22.6.5 + '@nx/nx-linux-x64-musl': 22.6.5 + '@nx/nx-win32-arm64-msvc': 22.6.5 + '@nx/nx-win32-x64-msvc': 22.6.5 + '@swc-node/register': 1.11.1(@emnapi/core@1.9.2)(@emnapi/runtime@1.9.2)(@swc/core@1.10.15(@swc/helpers@0.5.15))(@swc/types@0.1.17)(typescript@6.0.2) + '@swc/core': 1.10.15(@swc/helpers@0.5.15) transitivePeerDependencies: - debug @@ -37926,6 +38151,32 @@ snapshots: '@oxc-minify/binding-win32-ia32-msvc': 0.110.0 '@oxc-minify/binding-win32-x64-msvc': 0.110.0 + oxc-resolver@11.19.1(@emnapi/core@1.9.2)(@emnapi/runtime@1.9.2): + optionalDependencies: + '@oxc-resolver/binding-android-arm-eabi': 11.19.1 + '@oxc-resolver/binding-android-arm64': 11.19.1 + '@oxc-resolver/binding-darwin-arm64': 11.19.1 + '@oxc-resolver/binding-darwin-x64': 11.19.1 + '@oxc-resolver/binding-freebsd-x64': 11.19.1 + '@oxc-resolver/binding-linux-arm-gnueabihf': 11.19.1 + '@oxc-resolver/binding-linux-arm-musleabihf': 11.19.1 + '@oxc-resolver/binding-linux-arm64-gnu': 11.19.1 + '@oxc-resolver/binding-linux-arm64-musl': 11.19.1 + '@oxc-resolver/binding-linux-ppc64-gnu': 11.19.1 + '@oxc-resolver/binding-linux-riscv64-gnu': 11.19.1 + '@oxc-resolver/binding-linux-riscv64-musl': 11.19.1 + '@oxc-resolver/binding-linux-s390x-gnu': 11.19.1 + '@oxc-resolver/binding-linux-x64-gnu': 11.19.1 + '@oxc-resolver/binding-linux-x64-musl': 11.19.1 + '@oxc-resolver/binding-openharmony-arm64': 11.19.1 + '@oxc-resolver/binding-wasm32-wasi': 11.19.1(@emnapi/core@1.9.2)(@emnapi/runtime@1.9.2) + '@oxc-resolver/binding-win32-arm64-msvc': 11.19.1 + '@oxc-resolver/binding-win32-ia32-msvc': 11.19.1 + '@oxc-resolver/binding-win32-x64-msvc': 11.19.1 + transitivePeerDependencies: + - '@emnapi/core' + - '@emnapi/runtime' + oxc-transform@0.110.0: optionalDependencies: '@oxc-transform/binding-android-arm-eabi': 0.110.0 @@ -38148,6 +38399,8 @@ snapshots: sonic-boom: 4.2.0 thread-stream: 4.0.0 + pirates@4.0.7: {} + pixelmatch@7.1.0: dependencies: pngjs: 7.0.0 @@ -38188,7 +38441,7 @@ snapshots: semver: 7.7.3 optionalDependencies: '@rspack/core': 1.2.2(@swc/helpers@0.5.15) - webpack: 5.97.1(esbuild@0.27.4)(webpack-cli@5.1.4) + webpack: 5.97.1(@swc/core@1.10.15(@swc/helpers@0.5.15))(esbuild@0.27.4)(webpack-cli@5.1.4) transitivePeerDependencies: - typescript @@ -38396,6 +38649,8 @@ snapshots: proxy-from-env@1.1.0: {} + proxy-from-env@2.1.0: {} + psl@1.15.0: dependencies: punycode: 2.3.1 @@ -38893,11 +39148,11 @@ snapshots: rrweb-cssom@0.8.0: {} - rspack-vue-loader@17.4.4(vue@3.5.25(typescript@6.0.2))(webpack@5.104.0(esbuild@0.27.4)): + rspack-vue-loader@17.4.4(vue@3.5.25(typescript@6.0.2))(webpack@5.104.0(@swc/core@1.10.15(@swc/helpers@0.5.15))(esbuild@0.27.4)): dependencies: chalk: 4.1.2 watchpack: 2.4.2 - webpack: 5.104.0(esbuild@0.27.4) + webpack: 5.104.0(@swc/core@1.10.15(@swc/helpers@0.5.15))(esbuild@0.27.4) optionalDependencies: vue: 3.5.25(typescript@6.0.2) @@ -39328,6 +39583,8 @@ snapshots: smob@1.5.0: {} + smol-toml@1.6.1: {} + sockjs@0.3.24: dependencies: faye-websocket: 0.11.4 @@ -39527,7 +39784,7 @@ snapshots: style-loader@4.0.0(webpack@5.97.1): dependencies: - webpack: 5.97.1(esbuild@0.27.4)(webpack-cli@5.1.4) + webpack: 5.97.1(@swc/core@1.10.15(@swc/helpers@0.5.15))(esbuild@0.27.4)(webpack-cli@5.1.4) style-to-object@1.0.8: dependencies: @@ -39623,6 +39880,18 @@ snapshots: term-size@2.2.1: {} + terser-webpack-plugin@5.3.11(@swc/core@1.10.15(@swc/helpers@0.5.15))(esbuild@0.27.4)(webpack@5.97.1(@swc/core@1.10.15(@swc/helpers@0.5.15))(esbuild@0.27.4)): + dependencies: + '@jridgewell/trace-mapping': 0.3.31 + jest-worker: 27.5.1 + schema-utils: 4.3.0 + serialize-javascript: 6.0.2 + terser: 5.37.0 + webpack: 5.97.1(@swc/core@1.10.15(@swc/helpers@0.5.15))(esbuild@0.27.4) + optionalDependencies: + '@swc/core': 1.10.15(@swc/helpers@0.5.15) + esbuild: 0.27.4 + terser-webpack-plugin@5.3.11(@swc/core@1.10.15(@swc/helpers@0.5.15))(esbuild@0.27.4)(webpack@5.97.1): dependencies: '@jridgewell/trace-mapping': 0.3.31 @@ -39635,37 +39904,16 @@ snapshots: '@swc/core': 1.10.15(@swc/helpers@0.5.15) esbuild: 0.27.4 - terser-webpack-plugin@5.3.11(esbuild@0.27.4)(webpack@5.97.1(esbuild@0.27.4)): - dependencies: - '@jridgewell/trace-mapping': 0.3.31 - jest-worker: 27.5.1 - schema-utils: 4.3.0 - serialize-javascript: 6.0.2 - terser: 5.37.0 - webpack: 5.97.1(esbuild@0.27.4) - optionalDependencies: - esbuild: 0.27.4 - - terser-webpack-plugin@5.3.11(esbuild@0.27.4)(webpack@5.97.1): - dependencies: - '@jridgewell/trace-mapping': 0.3.31 - jest-worker: 27.5.1 - schema-utils: 4.3.0 - serialize-javascript: 6.0.2 - terser: 5.37.0 - webpack: 5.97.1(esbuild@0.27.4)(webpack-cli@5.1.4) - optionalDependencies: - esbuild: 0.27.4 - - terser-webpack-plugin@5.3.16(esbuild@0.27.4)(webpack@5.104.0(esbuild@0.27.4)): + terser-webpack-plugin@5.3.16(@swc/core@1.10.15(@swc/helpers@0.5.15))(esbuild@0.27.4)(webpack@5.104.0(@swc/core@1.10.15(@swc/helpers@0.5.15))(esbuild@0.27.4)): dependencies: '@jridgewell/trace-mapping': 0.3.31 jest-worker: 27.5.1 schema-utils: 4.3.3 serialize-javascript: 6.0.2 terser: 5.37.0 - webpack: 5.104.0(esbuild@0.27.4) + webpack: 5.104.0(@swc/core@1.10.15(@swc/helpers@0.5.15))(esbuild@0.27.4) optionalDependencies: + '@swc/core': 1.10.15(@swc/helpers@0.5.15) esbuild: 0.27.4 terser@5.37.0: @@ -39811,7 +40059,7 @@ snapshots: ts-declaration-location@1.0.5(typescript@6.0.2): dependencies: - minimatch: 10.1.1 + minimatch: 10.2.4 typescript: 6.0.2 ts-declaration-location@1.0.7(typescript@6.0.2): @@ -40324,7 +40572,7 @@ snapshots: optionalDependencies: vite: 8.0.0(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.6.1)(sass-embedded@1.97.2)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.8.1) - vitest@3.2.4(@types/debug@4.1.12)(@types/node@25.0.9)(@vitest/browser@4.0.18(msw@2.7.0(@types/node@25.0.9)(typescript@6.0.2))(vite@8.0.0(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.6.1)(sass-embedded@1.97.2)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.8.1))(vitest@4.0.18))(@vitest/ui@4.0.18)(esbuild@0.27.4)(jiti@2.6.1)(jsdom@27.0.0(postcss@8.5.8))(msw@2.7.0(@types/node@25.0.9)(typescript@5.9.2))(sass-embedded@1.97.2)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.8.1): + vitest@3.2.4(@types/debug@4.1.12)(@types/node@25.0.9)(@vitest/browser@4.0.18(msw@2.7.0(@types/node@25.0.9)(typescript@6.0.2))(vite@8.0.0(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.6.1)(sass-embedded@1.97.2)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.8.1))(vitest@4.0.18))(@vitest/ui@4.0.18(vitest@4.0.18))(esbuild@0.27.4)(jiti@2.6.1)(jsdom@27.0.0(postcss@8.5.8))(msw@2.7.0(@types/node@25.0.9)(typescript@5.9.2))(sass-embedded@1.97.2)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.8.1): dependencies: '@types/chai': 5.2.2 '@vitest/expect': 3.2.4 @@ -40370,7 +40618,7 @@ snapshots: - tsx - yaml - vitest@3.2.4(@types/debug@4.1.12)(@types/node@25.0.9)(@vitest/browser@4.0.18(msw@2.7.0(@types/node@25.0.9)(typescript@6.0.2))(vite@8.0.0(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.6.1)(sass-embedded@1.97.2)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.8.1))(vitest@4.0.18))(@vitest/ui@4.0.18)(esbuild@0.27.4)(jiti@2.6.1)(jsdom@27.0.0(postcss@8.5.8))(msw@2.7.0(@types/node@25.0.9)(typescript@6.0.2))(sass-embedded@1.97.2)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.8.1): + vitest@3.2.4(@types/debug@4.1.12)(@types/node@25.0.9)(@vitest/browser@4.0.18(msw@2.7.0(@types/node@25.0.9)(typescript@6.0.2))(vite@8.0.0(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.6.1)(sass-embedded@1.97.2)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.8.1))(vitest@4.0.18))(@vitest/ui@4.0.18(vitest@4.0.18))(esbuild@0.27.4)(jiti@2.6.1)(jsdom@27.0.0(postcss@8.5.8))(msw@2.7.0(@types/node@25.0.9)(typescript@6.0.2))(sass-embedded@1.97.2)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.8.1): dependencies: '@types/chai': 5.2.2 '@vitest/expect': 3.2.4 @@ -40715,7 +40963,7 @@ snapshots: webpack-virtual-modules@0.6.2: {} - webpack@5.104.0(esbuild@0.27.4): + webpack@5.104.0(@swc/core@1.10.15(@swc/helpers@0.5.15))(esbuild@0.27.4): dependencies: '@types/eslint-scope': 3.7.7 '@types/estree': 1.0.8 @@ -40739,7 +40987,7 @@ snapshots: neo-async: 2.6.2 schema-utils: 4.3.3 tapable: 2.3.0 - terser-webpack-plugin: 5.3.16(esbuild@0.27.4)(webpack@5.104.0(esbuild@0.27.4)) + terser-webpack-plugin: 5.3.16(@swc/core@1.10.15(@swc/helpers@0.5.15))(esbuild@0.27.4)(webpack@5.104.0(@swc/core@1.10.15(@swc/helpers@0.5.15))(esbuild@0.27.4)) watchpack: 2.4.4 webpack-sources: 3.3.3 transitivePeerDependencies: @@ -40747,6 +40995,36 @@ snapshots: - esbuild - uglify-js + webpack@5.97.1(@swc/core@1.10.15(@swc/helpers@0.5.15))(esbuild@0.27.4): + dependencies: + '@types/eslint-scope': 3.7.7 + '@types/estree': 1.0.7 + '@webassemblyjs/ast': 1.14.1 + '@webassemblyjs/wasm-edit': 1.14.1 + '@webassemblyjs/wasm-parser': 1.14.1 + acorn: 8.14.1 + browserslist: 4.24.4 + chrome-trace-event: 1.0.4 + enhanced-resolve: 5.18.1 + es-module-lexer: 1.6.0 + eslint-scope: 5.1.1 + events: 3.3.0 + glob-to-regexp: 0.4.1 + graceful-fs: 4.2.11 + json-parse-even-better-errors: 2.3.1 + loader-runner: 4.3.0 + mime-types: 2.1.35 + neo-async: 2.6.2 + schema-utils: 3.3.0 + tapable: 2.2.1 + terser-webpack-plugin: 5.3.11(@swc/core@1.10.15(@swc/helpers@0.5.15))(esbuild@0.27.4)(webpack@5.97.1(@swc/core@1.10.15(@swc/helpers@0.5.15))(esbuild@0.27.4)) + watchpack: 2.4.2 + webpack-sources: 3.2.3 + transitivePeerDependencies: + - '@swc/core' + - esbuild + - uglify-js + webpack@5.97.1(@swc/core@1.10.15(@swc/helpers@0.5.15))(esbuild@0.27.4)(webpack-cli@5.1.4): dependencies: '@types/eslint-scope': 3.7.7 @@ -40779,68 +41057,6 @@ snapshots: - esbuild - uglify-js - webpack@5.97.1(esbuild@0.27.4): - dependencies: - '@types/eslint-scope': 3.7.7 - '@types/estree': 1.0.7 - '@webassemblyjs/ast': 1.14.1 - '@webassemblyjs/wasm-edit': 1.14.1 - '@webassemblyjs/wasm-parser': 1.14.1 - acorn: 8.14.1 - browserslist: 4.24.4 - chrome-trace-event: 1.0.4 - enhanced-resolve: 5.18.1 - es-module-lexer: 1.6.0 - eslint-scope: 5.1.1 - events: 3.3.0 - glob-to-regexp: 0.4.1 - graceful-fs: 4.2.11 - json-parse-even-better-errors: 2.3.1 - loader-runner: 4.3.0 - mime-types: 2.1.35 - neo-async: 2.6.2 - schema-utils: 3.3.0 - tapable: 2.2.1 - terser-webpack-plugin: 5.3.11(esbuild@0.27.4)(webpack@5.97.1(esbuild@0.27.4)) - watchpack: 2.4.2 - webpack-sources: 3.2.3 - transitivePeerDependencies: - - '@swc/core' - - esbuild - - uglify-js - - webpack@5.97.1(esbuild@0.27.4)(webpack-cli@5.1.4): - dependencies: - '@types/eslint-scope': 3.7.7 - '@types/estree': 1.0.7 - '@webassemblyjs/ast': 1.14.1 - '@webassemblyjs/wasm-edit': 1.14.1 - '@webassemblyjs/wasm-parser': 1.14.1 - acorn: 8.14.1 - browserslist: 4.24.4 - chrome-trace-event: 1.0.4 - enhanced-resolve: 5.18.1 - es-module-lexer: 1.6.0 - eslint-scope: 5.1.1 - events: 3.3.0 - glob-to-regexp: 0.4.1 - graceful-fs: 4.2.11 - json-parse-even-better-errors: 2.3.1 - loader-runner: 4.3.0 - mime-types: 2.1.35 - neo-async: 2.6.2 - schema-utils: 3.3.0 - tapable: 2.2.1 - terser-webpack-plugin: 5.3.11(esbuild@0.27.4)(webpack@5.97.1) - watchpack: 2.4.2 - webpack-sources: 3.2.3 - optionalDependencies: - webpack-cli: 5.1.4(webpack-dev-server@5.2.0)(webpack@5.97.1) - transitivePeerDependencies: - - '@swc/core' - - esbuild - - uglify-js - websocket-driver@0.7.4: dependencies: http-parser-js: 0.5.9 diff --git a/scripts/nx/playwright-plugin.md b/scripts/nx/playwright-plugin.md new file mode 100644 index 0000000000..8fdf391141 --- /dev/null +++ b/scripts/nx/playwright-plugin.md @@ -0,0 +1,151 @@ +# Playwright E2E Sharding + +Use `scripts/nx/playwright-plugin.ts` to turn a Playwright e2e project into Nx shard targets. + +The plugin looks for `nx.metadata.playwrightShards` in a project's `package.json`. When present, it generates: + +- `test:e2e--shard-1-of-N` through `test:e2e--shard-N-of-N` +- a parent `test:e2e` target that depends on all shard targets + +Each shard target runs Playwright with: + +- `--shard=/` +- a shard-specific `E2E_PORT_KEY` +- a dependency on `build` and `^build` + +## 1. Enable sharding in `package.json` + +```json +{ + "name": "tanstack-react-start-e2e-rsc", + "nx": { + "metadata": { + "playwrightShards": 6 + } + } +} +``` + +The package name is used to build the shard port key: + +```txt +-shard--of- +``` + +## 2. Do not build inside `playwright.config.ts` + +The plugin already makes each shard depend on `build`, so the Playwright `webServer` command should only start the built app. + +Good: + +```ts +webServer: { + command: `PORT=${PORT} pnpm start`, + url: baseURL, +} +``` + +Avoid: + +```ts +webServer: { + command: `PORT=${PORT} pnpm build && PORT=${PORT} pnpm start`, + url: baseURL, +} +``` + +Running the build inside every shard causes unnecessary work and can create races when multiple shards share the same project directory. + +## 3. Use `E2E_PORT_KEY` for every derived port + +If the project uses `getTestServerPort`, `getDummyServerPort`, `e2eStartDummyServer`, or `e2eStopDummyServer`, key them off `process.env.E2E_PORT_KEY` first. + +Example: + +```ts +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } + +const e2ePortKey = process.env.E2E_PORT_KEY ?? packageJson.name +const PORT = await getTestServerPort(e2ePortKey) +``` + +Dummy server setup/teardown should use the same key: + +```ts +await e2eStartDummyServer(process.env.E2E_PORT_KEY ?? packageJson.name) +await e2eStopDummyServer(process.env.E2E_PORT_KEY ?? packageJson.name) +``` + +Without this, multiple shards on the same runner will reuse the same `port-*.txt` files and tear each other down. + +## 4. Clean stale port files once per Playwright run + +If the project allocates ports through `@tanstack/router-e2e-utils`, clean stale `port-*.txt` files before resolving the port. + +Important: do this only in the main Playwright config load. Playwright loads the config more than once, and unconditional cleanup can remap the port after the web server has already started. + +Example: + +```ts +import fs from 'node:fs' +import packageJson from './package.json' with { type: 'json' } + +const e2ePortKey = process.env.E2E_PORT_KEY ?? packageJson.name + +if (process.env.TEST_WORKER_INDEX === undefined) { + for (const portFile of [ + `port-${e2ePortKey}.txt`, + `port-${e2ePortKey}-external.txt`, + ]) { + fs.rmSync(portFile, { force: true }) + } +} +``` + +Avoid broad cleanup such as `rm -rf port*.txt` in shared shard runs. + +## 5. Keep the base URL derived from the shard key + +```ts +const PORT = await getTestServerPort(e2ePortKey) +const baseURL = `http://localhost:${PORT}` + +export default defineConfig({ + use: { + baseURL, + }, + webServer: { + command: `PORT=${PORT} pnpm start`, + url: baseURL, + }, +}) +``` + +## 6. Run the generated targets + +Examples: + +```sh +pnpm nx run tanstack-react-start-e2e-rsc:test:e2e--shard-1-of-6 +pnpm nx run tanstack-react-start-e2e-rsc:test:e2e +``` + +## Checklist + +- add `nx.metadata.playwrightShards` to `package.json` +- make sure the project has a working `build` target +- remove `build` from `webServer.command` +- read ports from `process.env.E2E_PORT_KEY ?? packageJson.name` +- use the same key for helper servers in setup and teardown +- clean shard-specific `port-*.txt` files once, guarded by `TEST_WORKER_INDEX === undefined` +- avoid wildcard port cleanup in shared shard runs + +## Reference + +Working example: + +- `e2e/react-start/rsc/package.json` +- `e2e/react-start/rsc/playwright.config.ts` +- `e2e/react-start/rsc/tests/setup/global.setup.ts` +- `e2e/react-start/rsc/tests/setup/global.teardown.ts` diff --git a/scripts/nx/playwright-plugin.ts b/scripts/nx/playwright-plugin.ts new file mode 100644 index 0000000000..9e8c9618ad --- /dev/null +++ b/scripts/nx/playwright-plugin.ts @@ -0,0 +1,130 @@ +import { dirname } from 'node:path' +import { createNodesFromFiles, readJsonFile } from '@nx/devkit' +import type { + CreateNodesContextV2, + CreateNodesV2, + TargetConfiguration, +} from '@nx/devkit' + +export const createNodesV2: CreateNodesV2 = [ + '**/package.json', + async (configFiles, options, context) => { + return await createNodesFromFiles( + (configFile, options, context) => + createNodesInternal(configFile, context), + configFiles, + options, + context, + ) + }, +] + +async function createNodesInternal( + configFilePath: string, + context: CreateNodesContextV2, +) { + const projectConfiguration = readJsonFile<{ + name?: string + nx?: { metadata?: { playwrightShards?: number } } + }>(configFilePath) + const root = dirname(configFilePath) + + if (!projectConfiguration.nx?.metadata?.playwrightShards) { + return { + projects: { + [root]: {}, + }, + } + } + + const { targets, targetGroupEntries } = buildShardedTargets( + root, + projectConfiguration.name ?? root, + projectConfiguration.nx.metadata.playwrightShards, + ['default', '^production'], + ) + // Project configuration to be merged into the rest of the Nx configuration + return { + projects: { + [root]: { + targets, + metadata: { + targetGroups: { + playwright: targetGroupEntries, + }, + }, + tags: ['playwright:shareded'], + }, + }, + } +} + +const CI_TARGET_NAME = 'test:e2e' + +function buildShardedTargets( + projectRoot: string, + packageName: string, + shardCount: number, + testInputs: TargetConfiguration['inputs'], +): { + targets: Record + targetGroupEntries: Array +} { + const targets: Record = {} + const targetGroup: Array = [] + + // Create individual shard targets + for (let shardIndex = 1; shardIndex <= shardCount; shardIndex++) { + const shardTargetName = `${CI_TARGET_NAME}--shard-${shardIndex}-of-${shardCount}` + const e2ePortKey = `${packageName}-shard-${shardIndex}-of-${shardCount}` + + targets[shardTargetName] = { + executor: 'nx:run-commands', + options: { + command: `playwright test --project=chromium --shard=${shardIndex}/${shardCount}`, + cwd: projectRoot, + env: { + E2E_PORT_KEY: e2ePortKey, + }, + }, + cache: true, + inputs: testInputs, + dependsOn: [`^build`, 'build'], + metadata: { + technologies: ['playwright'], + description: `Run Playwright shard ${shardIndex} of ${shardCount}`, + help: { + command: `npx playwright run --help`, + example: { + options: { + shard: `${shardIndex}/${shardCount}`, + }, + }, + }, + }, + } + + targetGroup.push(shardTargetName) + } + + // Create the parent CI target that depends on merge (which itself depends on all shards) + targets[CI_TARGET_NAME] = { + executor: 'nx:noop', + cache: true, + inputs: testInputs, + dependsOn: targetGroup.map((shardTargetName) => ({ + target: shardTargetName, + projects: 'self' as const, + params: 'forward' as const, + })), + metadata: { + technologies: ['playwright'], + description: `Run all Playwright shards (${shardCount} shards)`, + }, + } + + return { + targets, + targetGroupEntries: [...targetGroup, CI_TARGET_NAME], + } +} From e30814d949110ff25829de44d729ead47555940a Mon Sep 17 00:00:00 2001 From: Manuel Schiller Date: Wed, 15 Apr 2026 02:19:51 +0200 Subject: [PATCH 009/604] fix react-router shared route css persistence on nav (#7186) Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> --- .changeset/tough-bears-tease.md | 5 + .../css-modules/src/routeTree.gen.ts | 61 +-- .../css-modules/src/routes/__root.tsx | 14 - .../src/styles/shared-widget.module.css | 19 - .../css-modules/tests/css.prod.spec.ts | 140 ------ .../rsc/tests/rsc-css-modules.spec.ts | 29 ++ .../src/components/AppShell.tsx | 4 + .../src/components/SharedCard.tsx | 9 + .../src/components/SharedWidget.tsx} | 3 +- .../src/components/SharedWidgetLazy.tsx} | 2 +- .../start-manifest/src/routeTree.gen.ts | 84 ++++ .../start-manifest/src/routes/a.tsx | 17 + .../start-manifest/src/routes/b.tsx | 17 + .../src/routes/lazy-css-lazy.tsx | 6 +- .../src/routes/lazy-css-static.tsx | 6 +- .../src/styles/page-a.module.css | 10 + .../src/styles/page-b.module.css | 10 + .../src/styles/shared-card.module.css | 8 + .../src/styles/shared-widget.module.css | 17 + .../tests/start-manifest.spec.ts | 142 +++++- e2e/solid-start/start-manifest/package.json | 33 ++ .../start-manifest/playwright.config.ts | 30 ++ .../src/components/AppShell.tsx | 38 ++ .../src/components/SharedCard.tsx | 10 + .../src/components/SharedNestedLayout.tsx | 31 ++ .../src/components/SharedWidget.tsx | 15 + .../src/components/SharedWidgetLazy.tsx | 5 + .../start-manifest/src/routeTree.gen.ts | 345 +++++++++++++ e2e/solid-start/start-manifest/src/router.tsx | 18 + .../start-manifest/src/routes/__root.tsx | 29 ++ .../start-manifest/src/routes/a.tsx | 18 + .../start-manifest/src/routes/b.tsx | 18 + .../start-manifest/src/routes/index.tsx | 16 + .../src/routes/lazy-css-lazy.tsx | 26 + .../src/routes/lazy-css-static.tsx | 24 + .../start-manifest/src/routes/r1.tsx | 18 + .../start-manifest/src/routes/r2.tsx | 18 + .../start-manifest/src/routes/r3.tsx | 5 + .../start-manifest/src/routes/r4.tsx | 5 + .../start-manifest/src/routes/r5.tsx | 5 + .../start-manifest/src/routes/r6.tsx | 5 + .../start-manifest/src/routes/shared-a.tsx | 14 + .../start-manifest/src/routes/shared-b.tsx | 14 + .../start-manifest/src/routes/shared-c.tsx | 14 + .../src/styles/page-a.module.css | 10 + .../src/styles/page-b.module.css | 10 + .../src/styles/root-shell.module.css | 37 ++ .../src/styles/route-one.module.css | 7 + .../src/styles/route-two.module.css | 7 + .../src/styles/shared-card.module.css | 8 + .../src/styles/shared-layout.module.css | 16 + .../src/styles/shared-widget.module.css | 17 + .../tests/start-manifest.spec.ts | 453 +++++++++++++++++ e2e/solid-start/start-manifest/tsconfig.json | 23 + e2e/solid-start/start-manifest/vite.config.ts | 13 + e2e/vue-start/start-manifest/package.json | 33 ++ .../start-manifest/playwright.config.ts | 30 ++ .../src/components/AppShell.tsx | 38 ++ .../src/components/SharedCard.tsx | 10 + .../src/components/SharedNestedLayout.tsx | 34 ++ .../src/components/SharedWidget.tsx | 15 + .../src/components/SharedWidgetLazy.tsx | 5 + .../start-manifest/src/routeTree.gen.ts | 345 +++++++++++++ e2e/vue-start/start-manifest/src/router.tsx | 18 + .../start-manifest/src/routes/__root.tsx | 35 ++ e2e/vue-start/start-manifest/src/routes/a.tsx | 18 + e2e/vue-start/start-manifest/src/routes/b.tsx | 18 + .../start-manifest/src/routes/index.tsx | 16 + .../src/routes/lazy-css-lazy.tsx | 31 ++ .../src/routes/lazy-css-static.tsx | 24 + .../start-manifest/src/routes/r1.tsx | 18 + .../start-manifest/src/routes/r2.tsx | 18 + .../start-manifest/src/routes/r3.tsx | 5 + .../start-manifest/src/routes/r4.tsx | 5 + .../start-manifest/src/routes/r5.tsx | 5 + .../start-manifest/src/routes/r6.tsx | 5 + .../start-manifest/src/routes/shared-a.tsx | 14 + .../start-manifest/src/routes/shared-b.tsx | 14 + .../start-manifest/src/routes/shared-c.tsx | 14 + .../src/styles/page-a.module.css | 10 + .../src/styles/page-b.module.css | 10 + .../src/styles/root-shell.module.css | 37 ++ .../src/styles/route-one.module.css | 7 + .../src/styles/route-two.module.css | 7 + .../src/styles/shared-card.module.css | 8 + .../src/styles/shared-layout.module.css | 16 + .../src/styles/shared-widget.module.css | 17 + .../tests/start-manifest.spec.ts | 457 ++++++++++++++++++ e2e/vue-start/start-manifest/tsconfig.json | 23 + e2e/vue-start/start-manifest/vite.config.ts | 13 + packages/react-router/src/Asset.tsx | 12 +- packages/react-router/tests/Scripts.test.tsx | 74 ++- .../start-manifest-plugin/manifestBuilder.ts | 143 ++---- .../manifestBuilder.test.ts | 312 ++---------- pnpm-lock.yaml | 80 ++- 95 files changed, 3305 insertions(+), 647 deletions(-) create mode 100644 .changeset/tough-bears-tease.md delete mode 100644 e2e/react-start/css-modules/src/styles/shared-widget.module.css delete mode 100644 e2e/react-start/css-modules/tests/css.prod.spec.ts create mode 100644 e2e/react-start/start-manifest/src/components/SharedCard.tsx rename e2e/react-start/{css-modules/src/components/shared-widget.tsx => start-manifest/src/components/SharedWidget.tsx} (76%) rename e2e/react-start/{css-modules/src/components/shared-widget-lazy.tsx => start-manifest/src/components/SharedWidgetLazy.tsx} (61%) create mode 100644 e2e/react-start/start-manifest/src/routes/a.tsx create mode 100644 e2e/react-start/start-manifest/src/routes/b.tsx rename e2e/react-start/{css-modules => start-manifest}/src/routes/lazy-css-lazy.tsx (89%) rename e2e/react-start/{css-modules => start-manifest}/src/routes/lazy-css-static.tsx (85%) create mode 100644 e2e/react-start/start-manifest/src/styles/page-a.module.css create mode 100644 e2e/react-start/start-manifest/src/styles/page-b.module.css create mode 100644 e2e/react-start/start-manifest/src/styles/shared-card.module.css create mode 100644 e2e/react-start/start-manifest/src/styles/shared-widget.module.css create mode 100644 e2e/solid-start/start-manifest/package.json create mode 100644 e2e/solid-start/start-manifest/playwright.config.ts create mode 100644 e2e/solid-start/start-manifest/src/components/AppShell.tsx create mode 100644 e2e/solid-start/start-manifest/src/components/SharedCard.tsx create mode 100644 e2e/solid-start/start-manifest/src/components/SharedNestedLayout.tsx create mode 100644 e2e/solid-start/start-manifest/src/components/SharedWidget.tsx create mode 100644 e2e/solid-start/start-manifest/src/components/SharedWidgetLazy.tsx create mode 100644 e2e/solid-start/start-manifest/src/routeTree.gen.ts create mode 100644 e2e/solid-start/start-manifest/src/router.tsx create mode 100644 e2e/solid-start/start-manifest/src/routes/__root.tsx create mode 100644 e2e/solid-start/start-manifest/src/routes/a.tsx create mode 100644 e2e/solid-start/start-manifest/src/routes/b.tsx create mode 100644 e2e/solid-start/start-manifest/src/routes/index.tsx create mode 100644 e2e/solid-start/start-manifest/src/routes/lazy-css-lazy.tsx create mode 100644 e2e/solid-start/start-manifest/src/routes/lazy-css-static.tsx create mode 100644 e2e/solid-start/start-manifest/src/routes/r1.tsx create mode 100644 e2e/solid-start/start-manifest/src/routes/r2.tsx create mode 100644 e2e/solid-start/start-manifest/src/routes/r3.tsx create mode 100644 e2e/solid-start/start-manifest/src/routes/r4.tsx create mode 100644 e2e/solid-start/start-manifest/src/routes/r5.tsx create mode 100644 e2e/solid-start/start-manifest/src/routes/r6.tsx create mode 100644 e2e/solid-start/start-manifest/src/routes/shared-a.tsx create mode 100644 e2e/solid-start/start-manifest/src/routes/shared-b.tsx create mode 100644 e2e/solid-start/start-manifest/src/routes/shared-c.tsx create mode 100644 e2e/solid-start/start-manifest/src/styles/page-a.module.css create mode 100644 e2e/solid-start/start-manifest/src/styles/page-b.module.css create mode 100644 e2e/solid-start/start-manifest/src/styles/root-shell.module.css create mode 100644 e2e/solid-start/start-manifest/src/styles/route-one.module.css create mode 100644 e2e/solid-start/start-manifest/src/styles/route-two.module.css create mode 100644 e2e/solid-start/start-manifest/src/styles/shared-card.module.css create mode 100644 e2e/solid-start/start-manifest/src/styles/shared-layout.module.css create mode 100644 e2e/solid-start/start-manifest/src/styles/shared-widget.module.css create mode 100644 e2e/solid-start/start-manifest/tests/start-manifest.spec.ts create mode 100644 e2e/solid-start/start-manifest/tsconfig.json create mode 100644 e2e/solid-start/start-manifest/vite.config.ts create mode 100644 e2e/vue-start/start-manifest/package.json create mode 100644 e2e/vue-start/start-manifest/playwright.config.ts create mode 100644 e2e/vue-start/start-manifest/src/components/AppShell.tsx create mode 100644 e2e/vue-start/start-manifest/src/components/SharedCard.tsx create mode 100644 e2e/vue-start/start-manifest/src/components/SharedNestedLayout.tsx create mode 100644 e2e/vue-start/start-manifest/src/components/SharedWidget.tsx create mode 100644 e2e/vue-start/start-manifest/src/components/SharedWidgetLazy.tsx create mode 100644 e2e/vue-start/start-manifest/src/routeTree.gen.ts create mode 100644 e2e/vue-start/start-manifest/src/router.tsx create mode 100644 e2e/vue-start/start-manifest/src/routes/__root.tsx create mode 100644 e2e/vue-start/start-manifest/src/routes/a.tsx create mode 100644 e2e/vue-start/start-manifest/src/routes/b.tsx create mode 100644 e2e/vue-start/start-manifest/src/routes/index.tsx create mode 100644 e2e/vue-start/start-manifest/src/routes/lazy-css-lazy.tsx create mode 100644 e2e/vue-start/start-manifest/src/routes/lazy-css-static.tsx create mode 100644 e2e/vue-start/start-manifest/src/routes/r1.tsx create mode 100644 e2e/vue-start/start-manifest/src/routes/r2.tsx create mode 100644 e2e/vue-start/start-manifest/src/routes/r3.tsx create mode 100644 e2e/vue-start/start-manifest/src/routes/r4.tsx create mode 100644 e2e/vue-start/start-manifest/src/routes/r5.tsx create mode 100644 e2e/vue-start/start-manifest/src/routes/r6.tsx create mode 100644 e2e/vue-start/start-manifest/src/routes/shared-a.tsx create mode 100644 e2e/vue-start/start-manifest/src/routes/shared-b.tsx create mode 100644 e2e/vue-start/start-manifest/src/routes/shared-c.tsx create mode 100644 e2e/vue-start/start-manifest/src/styles/page-a.module.css create mode 100644 e2e/vue-start/start-manifest/src/styles/page-b.module.css create mode 100644 e2e/vue-start/start-manifest/src/styles/root-shell.module.css create mode 100644 e2e/vue-start/start-manifest/src/styles/route-one.module.css create mode 100644 e2e/vue-start/start-manifest/src/styles/route-two.module.css create mode 100644 e2e/vue-start/start-manifest/src/styles/shared-card.module.css create mode 100644 e2e/vue-start/start-manifest/src/styles/shared-layout.module.css create mode 100644 e2e/vue-start/start-manifest/src/styles/shared-widget.module.css create mode 100644 e2e/vue-start/start-manifest/tests/start-manifest.spec.ts create mode 100644 e2e/vue-start/start-manifest/tsconfig.json create mode 100644 e2e/vue-start/start-manifest/vite.config.ts diff --git a/.changeset/tough-bears-tease.md b/.changeset/tough-bears-tease.md new file mode 100644 index 0000000000..67fd6a3be8 --- /dev/null +++ b/.changeset/tough-bears-tease.md @@ -0,0 +1,5 @@ +--- +'@tanstack/react-router': patch +--- + +Preserve shared route stylesheet links across client navigation by rendering route CSS assets with React stylesheet precedence. diff --git a/e2e/react-start/css-modules/src/routeTree.gen.ts b/e2e/react-start/css-modules/src/routeTree.gen.ts index ab5f0b6554..d19ae80e5a 100644 --- a/e2e/react-start/css-modules/src/routeTree.gen.ts +++ b/e2e/react-start/css-modules/src/routeTree.gen.ts @@ -12,8 +12,6 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as SassMixinRouteImport } from './routes/sass-mixin' import { Route as QuotesRouteImport } from './routes/quotes' import { Route as ModulesRouteImport } from './routes/modules' -import { Route as LazyCssStaticRouteImport } from './routes/lazy-css-static' -import { Route as LazyCssLazyRouteImport } from './routes/lazy-css-lazy' import { Route as IndexRouteImport } from './routes/index' const SassMixinRoute = SassMixinRouteImport.update({ @@ -31,16 +29,6 @@ const ModulesRoute = ModulesRouteImport.update({ path: '/modules', getParentRoute: () => rootRouteImport, } as any) -const LazyCssStaticRoute = LazyCssStaticRouteImport.update({ - id: '/lazy-css-static', - path: '/lazy-css-static', - getParentRoute: () => rootRouteImport, -} as any) -const LazyCssLazyRoute = LazyCssLazyRouteImport.update({ - id: '/lazy-css-lazy', - path: '/lazy-css-lazy', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', @@ -49,16 +37,12 @@ const IndexRoute = IndexRouteImport.update({ export interface FileRoutesByFullPath { '/': typeof IndexRoute - '/lazy-css-lazy': typeof LazyCssLazyRoute - '/lazy-css-static': typeof LazyCssStaticRoute '/modules': typeof ModulesRoute '/quotes': typeof QuotesRoute '/sass-mixin': typeof SassMixinRoute } export interface FileRoutesByTo { '/': typeof IndexRoute - '/lazy-css-lazy': typeof LazyCssLazyRoute - '/lazy-css-static': typeof LazyCssStaticRoute '/modules': typeof ModulesRoute '/quotes': typeof QuotesRoute '/sass-mixin': typeof SassMixinRoute @@ -66,43 +50,20 @@ export interface FileRoutesByTo { export interface FileRoutesById { __root__: typeof rootRouteImport '/': typeof IndexRoute - '/lazy-css-lazy': typeof LazyCssLazyRoute - '/lazy-css-static': typeof LazyCssStaticRoute '/modules': typeof ModulesRoute '/quotes': typeof QuotesRoute '/sass-mixin': typeof SassMixinRoute } export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/' - | '/lazy-css-lazy' - | '/lazy-css-static' - | '/modules' - | '/quotes' - | '/sass-mixin' + fullPaths: '/' | '/modules' | '/quotes' | '/sass-mixin' fileRoutesByTo: FileRoutesByTo - to: - | '/' - | '/lazy-css-lazy' - | '/lazy-css-static' - | '/modules' - | '/quotes' - | '/sass-mixin' - id: - | '__root__' - | '/' - | '/lazy-css-lazy' - | '/lazy-css-static' - | '/modules' - | '/quotes' - | '/sass-mixin' + to: '/' | '/modules' | '/quotes' | '/sass-mixin' + id: '__root__' | '/' | '/modules' | '/quotes' | '/sass-mixin' fileRoutesById: FileRoutesById } export interface RootRouteChildren { IndexRoute: typeof IndexRoute - LazyCssLazyRoute: typeof LazyCssLazyRoute - LazyCssStaticRoute: typeof LazyCssStaticRoute ModulesRoute: typeof ModulesRoute QuotesRoute: typeof QuotesRoute SassMixinRoute: typeof SassMixinRoute @@ -131,20 +92,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ModulesRouteImport parentRoute: typeof rootRouteImport } - '/lazy-css-static': { - id: '/lazy-css-static' - path: '/lazy-css-static' - fullPath: '/lazy-css-static' - preLoaderRoute: typeof LazyCssStaticRouteImport - parentRoute: typeof rootRouteImport - } - '/lazy-css-lazy': { - id: '/lazy-css-lazy' - path: '/lazy-css-lazy' - fullPath: '/lazy-css-lazy' - preLoaderRoute: typeof LazyCssLazyRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -157,8 +104,6 @@ declare module '@tanstack/react-router' { const rootRouteChildren: RootRouteChildren = { IndexRoute: IndexRoute, - LazyCssLazyRoute: LazyCssLazyRoute, - LazyCssStaticRoute: LazyCssStaticRoute, ModulesRoute: ModulesRoute, QuotesRoute: QuotesRoute, SassMixinRoute: SassMixinRoute, diff --git a/e2e/react-start/css-modules/src/routes/__root.tsx b/e2e/react-start/css-modules/src/routes/__root.tsx index a383beacec..d7840bc0c1 100644 --- a/e2e/react-start/css-modules/src/routes/__root.tsx +++ b/e2e/react-start/css-modules/src/routes/__root.tsx @@ -62,20 +62,6 @@ function RootComponent() { > Quoted CSS - - Lazy CSS Static - - - Lazy CSS Lazy -
diff --git a/e2e/react-start/css-modules/src/styles/shared-widget.module.css b/e2e/react-start/css-modules/src/styles/shared-widget.module.css deleted file mode 100644 index 66f3d679d8..0000000000 --- a/e2e/react-start/css-modules/src/styles/shared-widget.module.css +++ /dev/null @@ -1,19 +0,0 @@ -.widget { - background: rgb(255, 247, 237); - border: 2px solid rgb(249, 115, 22); - border-radius: 14px; - padding: 20px; -} - -.title { - color: rgb(154, 52, 18); - font-size: 20px; - font-weight: 700; - margin-bottom: 8px; -} - -.content { - color: rgb(194, 65, 12); - font-size: 14px; - line-height: 1.5; -} diff --git a/e2e/react-start/css-modules/tests/css.prod.spec.ts b/e2e/react-start/css-modules/tests/css.prod.spec.ts deleted file mode 100644 index 66aeff5700..0000000000 --- a/e2e/react-start/css-modules/tests/css.prod.spec.ts +++ /dev/null @@ -1,140 +0,0 @@ -import { expect } from '@playwright/test' -import { test } from '@tanstack/router-e2e-utils' - -test.skip(process.env.MODE === 'dev', 'Prod-only repro') - -test.describe('CSS styles in SSR (prod only)', () => { - const buildUrl = (baseURL: string, path: string) => { - return baseURL.replace(/\/$/, '') + path - } - - test('CSS modules stay applied when navigating from static to lazy route', async ({ - page, - baseURL, - }) => { - await page.goto(buildUrl(baseURL!, '/lazy-css-static')) - - const widget = page.getByTestId('shared-widget') - await expect(widget).toBeVisible() - - const backgroundColor = await widget.evaluate( - (el) => getComputedStyle(el).backgroundColor, - ) - expect(backgroundColor).toBe('rgb(255, 247, 237)') - - const borderTopColor = await widget.evaluate( - (el) => getComputedStyle(el).borderTopColor, - ) - expect(borderTopColor).toBe('rgb(249, 115, 22)') - - await expect(page.getByTestId('lazy-css-static-hydrated')).toBeVisible() - - await page.getByTestId('nav-lazy-css-lazy').click() - await page.waitForURL('**/lazy-css-lazy') - await expect(page.getByTestId('lazy-css-lazy-heading')).toBeVisible() - - const lazyWidget = page.getByTestId('shared-widget') - await expect(lazyWidget).toBeVisible() - - await expect - .poll( - () => lazyWidget.evaluate((el) => getComputedStyle(el).backgroundColor), - { timeout: 5_000 }, - ) - .toBe('rgb(255, 247, 237)') - }) - - test('CSS modules stay applied when navigating from lazy to static route', async ({ - page, - baseURL, - }) => { - await page.goto(buildUrl(baseURL!, '/lazy-css-lazy')) - await expect(page.getByTestId('lazy-css-lazy-heading')).toBeVisible() - - // Wait for lazy widget to load - const lazyWidget = page.getByTestId('shared-widget') - await expect(lazyWidget).toBeVisible() - - await expect - .poll( - () => lazyWidget.evaluate((el) => getComputedStyle(el).backgroundColor), - { timeout: 5_000 }, - ) - .toBe('rgb(255, 247, 237)') - - // Navigate to static route - await page.getByTestId('nav-lazy-css-static').click() - await page.waitForURL('**/lazy-css-static') - - const staticWidget = page.getByTestId('shared-widget') - await expect(staticWidget).toBeVisible() - - await expect - .poll( - () => - staticWidget.evaluate((el) => getComputedStyle(el).backgroundColor), - { timeout: 5_000 }, - ) - .toBe('rgb(255, 247, 237)') - - const borderTopColor = await staticWidget.evaluate( - (el) => getComputedStyle(el).borderTopColor, - ) - expect(borderTopColor).toBe('rgb(249, 115, 22)') - }) - - test('CSS modules applied on direct navigation to lazy route', async ({ - page, - baseURL, - }) => { - // Navigate directly to the lazy route (cold start, no prior static route) - await page.goto(buildUrl(baseURL!, '/lazy-css-lazy')) - await expect(page.getByTestId('lazy-css-lazy-heading')).toBeVisible() - - const widget = page.getByTestId('shared-widget') - await expect(widget).toBeVisible() - - await expect - .poll( - () => widget.evaluate((el) => getComputedStyle(el).backgroundColor), - { timeout: 5_000 }, - ) - .toBe('rgb(255, 247, 237)') - - const borderTopColor = await widget.evaluate( - (el) => getComputedStyle(el).borderTopColor, - ) - expect(borderTopColor).toBe('rgb(249, 115, 22)') - }) - - test('CSS persists after navigating away from lazy and back', async ({ - page, - baseURL, - }) => { - await page.goto(buildUrl(baseURL!, '/lazy-css-static')) - await expect(page.getByTestId('lazy-css-static-hydrated')).toBeVisible() - - // Navigate to lazy - await page.getByTestId('nav-lazy-css-lazy').click() - await page.waitForURL('**/lazy-css-lazy') - await expect(page.getByTestId('shared-widget')).toBeVisible() - - // Navigate away to home - await page.getByTestId('nav-home').click() - await page.waitForURL(/\/([^/]*)(\/)?($|\?)/) - - // Navigate back to lazy - await page.getByTestId('nav-lazy-css-lazy').click() - await page.waitForURL('**/lazy-css-lazy') - - const widget = page.getByTestId('shared-widget') - await expect(widget).toBeVisible() - - await expect - .poll( - () => widget.evaluate((el) => getComputedStyle(el).backgroundColor), - { timeout: 5_000 }, - ) - .toBe('rgb(255, 247, 237)') - }) -}) diff --git a/e2e/react-start/rsc/tests/rsc-css-modules.spec.ts b/e2e/react-start/rsc/tests/rsc-css-modules.spec.ts index 50d461803b..01a499a70f 100644 --- a/e2e/react-start/rsc/tests/rsc-css-modules.spec.ts +++ b/e2e/react-start/rsc/tests/rsc-css-modules.spec.ts @@ -122,4 +122,33 @@ test.describe('RSC CSS Modules Tests', () => { ) expect(backgroundColor).toBe('rgb(224, 242, 254)') }) + + test('RSC CSS module styles persist across sibling client-side navigation', async ({ + page, + }) => { + await page.goto('/rsc-css-modules') + await page.waitForURL('/rsc-css-modules') + + const cssModulesContent = page.getByTestId('rsc-css-modules-content') + await expect(cssModulesContent).toBeVisible() + + const initialBackgroundColor = await cssModulesContent.evaluate( + (el) => getComputedStyle(el).backgroundColor, + ) + expect(initialBackgroundColor).toBe('rgb(224, 242, 254)') + + await page.getByTestId('nav-global-css').click() + await page.waitForURL('/rsc-global-css') + await expect(page.getByTestId('rsc-global-css-content')).toBeVisible() + + await page.getByTestId('nav-css-modules').click() + await page.waitForURL('/rsc-css-modules') + + await expect(cssModulesContent).toBeVisible() + + const finalBackgroundColor = await cssModulesContent.evaluate( + (el) => getComputedStyle(el).backgroundColor, + ) + expect(finalBackgroundColor).toBe('rgb(224, 242, 254)') + }) }) diff --git a/e2e/react-start/start-manifest/src/components/AppShell.tsx b/e2e/react-start/start-manifest/src/components/AppShell.tsx index 99df40387b..f504a4fd66 100644 --- a/e2e/react-start/start-manifest/src/components/AppShell.tsx +++ b/e2e/react-start/start-manifest/src/components/AppShell.tsx @@ -3,6 +3,10 @@ import styles from '~/styles/root-shell.module.css' const ROUTES = linkOptions([ { to: '/', label: 'home' }, + { to: '/a', label: '/a' }, + { to: '/b', label: '/b' }, + { to: '/lazy-css-static', label: '/lazy-css-static' }, + { to: '/lazy-css-lazy', label: '/lazy-css-lazy' }, { to: '/r1', label: '/r1' }, { to: '/r2', label: '/r2' }, { to: '/shared-a', label: '/shared-a' }, diff --git a/e2e/react-start/start-manifest/src/components/SharedCard.tsx b/e2e/react-start/start-manifest/src/components/SharedCard.tsx new file mode 100644 index 0000000000..812e02da3d --- /dev/null +++ b/e2e/react-start/start-manifest/src/components/SharedCard.tsx @@ -0,0 +1,9 @@ +import styles from '~/styles/shared-card.module.css' + +export function SharedCard({ label }: { label: string }) { + return ( +
+ Shared card {label} +
+ ) +} diff --git a/e2e/react-start/css-modules/src/components/shared-widget.tsx b/e2e/react-start/start-manifest/src/components/SharedWidget.tsx similarity index 76% rename from e2e/react-start/css-modules/src/components/shared-widget.tsx rename to e2e/react-start/start-manifest/src/components/SharedWidget.tsx index 51a3be072c..0937bd1c7b 100644 --- a/e2e/react-start/css-modules/src/components/shared-widget.tsx +++ b/e2e/react-start/start-manifest/src/components/SharedWidget.tsx @@ -1,4 +1,3 @@ -/// import styles from '~/styles/shared-widget.module.css' export function SharedWidget() { @@ -8,7 +7,7 @@ export function SharedWidget() { Shared widget styles
- This widget uses a CSS module shared by a static route and a lazy route. + This widget uses CSS shared by a static route and a lazy route.
) diff --git a/e2e/react-start/css-modules/src/components/shared-widget-lazy.tsx b/e2e/react-start/start-manifest/src/components/SharedWidgetLazy.tsx similarity index 61% rename from e2e/react-start/css-modules/src/components/shared-widget-lazy.tsx rename to e2e/react-start/start-manifest/src/components/SharedWidgetLazy.tsx index 6d9ddce6f5..5f1f6410a5 100644 --- a/e2e/react-start/css-modules/src/components/shared-widget-lazy.tsx +++ b/e2e/react-start/start-manifest/src/components/SharedWidgetLazy.tsx @@ -1,4 +1,4 @@ -import { SharedWidget } from './shared-widget' +import { SharedWidget } from './SharedWidget' export default function SharedWidgetLazy() { return diff --git a/e2e/react-start/start-manifest/src/routeTree.gen.ts b/e2e/react-start/start-manifest/src/routeTree.gen.ts index 0571da3592..b7ee033842 100644 --- a/e2e/react-start/start-manifest/src/routeTree.gen.ts +++ b/e2e/react-start/start-manifest/src/routeTree.gen.ts @@ -18,6 +18,10 @@ import { Route as R4RouteImport } from './routes/r4' import { Route as R3RouteImport } from './routes/r3' import { Route as R2RouteImport } from './routes/r2' import { Route as R1RouteImport } from './routes/r1' +import { Route as LazyCssStaticRouteImport } from './routes/lazy-css-static' +import { Route as LazyCssLazyRouteImport } from './routes/lazy-css-lazy' +import { Route as BRouteImport } from './routes/b' +import { Route as ARouteImport } from './routes/a' import { Route as IndexRouteImport } from './routes/index' const SharedCRoute = SharedCRouteImport.update({ @@ -65,6 +69,26 @@ const R1Route = R1RouteImport.update({ path: '/r1', getParentRoute: () => rootRouteImport, } as any) +const LazyCssStaticRoute = LazyCssStaticRouteImport.update({ + id: '/lazy-css-static', + path: '/lazy-css-static', + getParentRoute: () => rootRouteImport, +} as any) +const LazyCssLazyRoute = LazyCssLazyRouteImport.update({ + id: '/lazy-css-lazy', + path: '/lazy-css-lazy', + getParentRoute: () => rootRouteImport, +} as any) +const BRoute = BRouteImport.update({ + id: '/b', + path: '/b', + getParentRoute: () => rootRouteImport, +} as any) +const ARoute = ARouteImport.update({ + id: '/a', + path: '/a', + getParentRoute: () => rootRouteImport, +} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', @@ -73,6 +97,10 @@ const IndexRoute = IndexRouteImport.update({ export interface FileRoutesByFullPath { '/': typeof IndexRoute + '/a': typeof ARoute + '/b': typeof BRoute + '/lazy-css-lazy': typeof LazyCssLazyRoute + '/lazy-css-static': typeof LazyCssStaticRoute '/r1': typeof R1Route '/r2': typeof R2Route '/r3': typeof R3Route @@ -85,6 +113,10 @@ export interface FileRoutesByFullPath { } export interface FileRoutesByTo { '/': typeof IndexRoute + '/a': typeof ARoute + '/b': typeof BRoute + '/lazy-css-lazy': typeof LazyCssLazyRoute + '/lazy-css-static': typeof LazyCssStaticRoute '/r1': typeof R1Route '/r2': typeof R2Route '/r3': typeof R3Route @@ -98,6 +130,10 @@ export interface FileRoutesByTo { export interface FileRoutesById { __root__: typeof rootRouteImport '/': typeof IndexRoute + '/a': typeof ARoute + '/b': typeof BRoute + '/lazy-css-lazy': typeof LazyCssLazyRoute + '/lazy-css-static': typeof LazyCssStaticRoute '/r1': typeof R1Route '/r2': typeof R2Route '/r3': typeof R3Route @@ -112,6 +148,10 @@ export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath fullPaths: | '/' + | '/a' + | '/b' + | '/lazy-css-lazy' + | '/lazy-css-static' | '/r1' | '/r2' | '/r3' @@ -124,6 +164,10 @@ export interface FileRouteTypes { fileRoutesByTo: FileRoutesByTo to: | '/' + | '/a' + | '/b' + | '/lazy-css-lazy' + | '/lazy-css-static' | '/r1' | '/r2' | '/r3' @@ -136,6 +180,10 @@ export interface FileRouteTypes { id: | '__root__' | '/' + | '/a' + | '/b' + | '/lazy-css-lazy' + | '/lazy-css-static' | '/r1' | '/r2' | '/r3' @@ -149,6 +197,10 @@ export interface FileRouteTypes { } export interface RootRouteChildren { IndexRoute: typeof IndexRoute + ARoute: typeof ARoute + BRoute: typeof BRoute + LazyCssLazyRoute: typeof LazyCssLazyRoute + LazyCssStaticRoute: typeof LazyCssStaticRoute R1Route: typeof R1Route R2Route: typeof R2Route R3Route: typeof R3Route @@ -225,6 +277,34 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof R1RouteImport parentRoute: typeof rootRouteImport } + '/lazy-css-static': { + id: '/lazy-css-static' + path: '/lazy-css-static' + fullPath: '/lazy-css-static' + preLoaderRoute: typeof LazyCssStaticRouteImport + parentRoute: typeof rootRouteImport + } + '/lazy-css-lazy': { + id: '/lazy-css-lazy' + path: '/lazy-css-lazy' + fullPath: '/lazy-css-lazy' + preLoaderRoute: typeof LazyCssLazyRouteImport + parentRoute: typeof rootRouteImport + } + '/b': { + id: '/b' + path: '/b' + fullPath: '/b' + preLoaderRoute: typeof BRouteImport + parentRoute: typeof rootRouteImport + } + '/a': { + id: '/a' + path: '/a' + fullPath: '/a' + preLoaderRoute: typeof ARouteImport + parentRoute: typeof rootRouteImport + } '/': { id: '/' path: '/' @@ -237,6 +317,10 @@ declare module '@tanstack/react-router' { const rootRouteChildren: RootRouteChildren = { IndexRoute: IndexRoute, + ARoute: ARoute, + BRoute: BRoute, + LazyCssLazyRoute: LazyCssLazyRoute, + LazyCssStaticRoute: LazyCssStaticRoute, R1Route: R1Route, R2Route: R2Route, R3Route: R3Route, diff --git a/e2e/react-start/start-manifest/src/routes/a.tsx b/e2e/react-start/start-manifest/src/routes/a.tsx new file mode 100644 index 0000000000..434803920d --- /dev/null +++ b/e2e/react-start/start-manifest/src/routes/a.tsx @@ -0,0 +1,17 @@ +import { createFileRoute } from '@tanstack/react-router' +import { SharedCard } from '~/components/SharedCard' +import styles from '~/styles/page-a.module.css' + +export const Route = createFileRoute('/a')({ + component: RouteComponent, +}) + +function RouteComponent() { + return ( +
+

Route /a

+

Route /a keeps the shared card styled.

+ +
+ ) +} diff --git a/e2e/react-start/start-manifest/src/routes/b.tsx b/e2e/react-start/start-manifest/src/routes/b.tsx new file mode 100644 index 0000000000..a418aeabeb --- /dev/null +++ b/e2e/react-start/start-manifest/src/routes/b.tsx @@ -0,0 +1,17 @@ +import { createFileRoute } from '@tanstack/react-router' +import { SharedCard } from '~/components/SharedCard' +import styles from '~/styles/page-b.module.css' + +export const Route = createFileRoute('/b')({ + component: RouteComponent, +}) + +function RouteComponent() { + return ( +
+

Route /b

+

Route /b should keep the shared card stylesheet after nav.

+ +
+ ) +} diff --git a/e2e/react-start/css-modules/src/routes/lazy-css-lazy.tsx b/e2e/react-start/start-manifest/src/routes/lazy-css-lazy.tsx similarity index 89% rename from e2e/react-start/css-modules/src/routes/lazy-css-lazy.tsx rename to e2e/react-start/start-manifest/src/routes/lazy-css-lazy.tsx index 4d147a9651..28cec3aff3 100644 --- a/e2e/react-start/css-modules/src/routes/lazy-css-lazy.tsx +++ b/e2e/react-start/start-manifest/src/routes/lazy-css-lazy.tsx @@ -2,7 +2,7 @@ import * as React from 'react' import { createFileRoute } from '@tanstack/react-router' const LazySharedWidget = React.lazy( - () => import('~/components/shared-widget-lazy'), + () => import('~/components/SharedWidgetLazy'), ) export const Route = createFileRoute('/lazy-css-lazy')({ @@ -11,7 +11,7 @@ export const Route = createFileRoute('/lazy-css-lazy')({ function LazyCssLazyRoute() { return ( -
+

Lazy CSS Repro - Lazy Route

This route renders the same widget through React.lazy so the CSS only @@ -23,6 +23,6 @@ function LazyCssLazyRoute() { > -

+ ) } diff --git a/e2e/react-start/css-modules/src/routes/lazy-css-static.tsx b/e2e/react-start/start-manifest/src/routes/lazy-css-static.tsx similarity index 85% rename from e2e/react-start/css-modules/src/routes/lazy-css-static.tsx rename to e2e/react-start/start-manifest/src/routes/lazy-css-static.tsx index c9e3f33a0e..349e90f33e 100644 --- a/e2e/react-start/css-modules/src/routes/lazy-css-static.tsx +++ b/e2e/react-start/start-manifest/src/routes/lazy-css-static.tsx @@ -1,5 +1,5 @@ import { ClientOnly, createFileRoute } from '@tanstack/react-router' -import { SharedWidget } from '~/components/shared-widget' +import { SharedWidget } from '~/components/SharedWidget' export const Route = createFileRoute('/lazy-css-static')({ component: LazyCssStaticRoute, @@ -7,7 +7,7 @@ export const Route = createFileRoute('/lazy-css-static')({ function LazyCssStaticRoute() { return ( -
+

Lazy CSS Repro - Static Route

This route statically imports the shared widget so its CSS is present in @@ -19,6 +19,6 @@ function LazyCssStaticRoute() { -

+ ) } diff --git a/e2e/react-start/start-manifest/src/styles/page-a.module.css b/e2e/react-start/start-manifest/src/styles/page-a.module.css new file mode 100644 index 0000000000..7ed4301097 --- /dev/null +++ b/e2e/react-start/start-manifest/src/styles/page-a.module.css @@ -0,0 +1,10 @@ +.page { + padding: 1rem; + min-height: 12rem; + background: rgb(240, 253, 244); + border: 4px solid rgb(22, 163, 74); +} + +.title { + color: rgb(21, 128, 61); +} diff --git a/e2e/react-start/start-manifest/src/styles/page-b.module.css b/e2e/react-start/start-manifest/src/styles/page-b.module.css new file mode 100644 index 0000000000..93d1d39a01 --- /dev/null +++ b/e2e/react-start/start-manifest/src/styles/page-b.module.css @@ -0,0 +1,10 @@ +.page { + padding: 1rem; + min-height: 12rem; + background: rgb(239, 246, 255); + border: 4px solid rgb(37, 99, 235); +} + +.title { + color: rgb(29, 78, 216); +} diff --git a/e2e/react-start/start-manifest/src/styles/shared-card.module.css b/e2e/react-start/start-manifest/src/styles/shared-card.module.css new file mode 100644 index 0000000000..2aa5a6ac17 --- /dev/null +++ b/e2e/react-start/start-manifest/src/styles/shared-card.module.css @@ -0,0 +1,8 @@ +.card { + margin-top: 1rem; + padding: 1.5rem; + border-radius: 0.75rem; + background: rgb(252, 231, 243); + border: 2px solid rgb(190, 24, 93); + color: rgb(157, 23, 77); +} diff --git a/e2e/react-start/start-manifest/src/styles/shared-widget.module.css b/e2e/react-start/start-manifest/src/styles/shared-widget.module.css new file mode 100644 index 0000000000..ed197cddb0 --- /dev/null +++ b/e2e/react-start/start-manifest/src/styles/shared-widget.module.css @@ -0,0 +1,17 @@ +.widget { + margin-top: 1rem; + padding: 1rem; + border-top: 4px solid rgb(249, 115, 22); + border-radius: 0.75rem; + background: rgb(255, 247, 237); +} + +.title { + font-weight: 700; + color: rgb(154, 52, 18); +} + +.content { + margin-top: 0.5rem; + color: rgb(124, 45, 18); +} diff --git a/e2e/react-start/start-manifest/tests/start-manifest.spec.ts b/e2e/react-start/start-manifest/tests/start-manifest.spec.ts index d04d42b2db..1767728ac3 100644 --- a/e2e/react-start/start-manifest/tests/start-manifest.spec.ts +++ b/e2e/react-start/start-manifest/tests/start-manifest.spec.ts @@ -5,11 +5,12 @@ import { readdir } from 'node:fs/promises' import path from 'node:path' import { pathToFileURL } from 'node:url' -test.skip(process.env.MODE === 'dev', 'Prod-only manifest dehydration coverage') - const ROOT_SHELL_COLOR = 'rgb(22, 101, 52)' const ROUTE_ONE_COLOR = 'rgb(30, 64, 175)' const ROUTE_TWO_COLOR = 'rgb(126, 34, 206)' +const SHARED_CARD_BG = 'rgb(252, 231, 243)' +const SHARED_WIDGET_BG = 'rgb(255, 247, 237)' +const SHARED_WIDGET_BORDER = 'rgb(249, 115, 22)' const buildUrl = (baseURL: string, pathname: string) => baseURL.replace(/\/$/, '') + pathname @@ -20,6 +21,12 @@ async function getColor(testId: string, page: Page) { .evaluate((element) => getComputedStyle(element).color) } +async function getBackgroundColor(testId: string, page: Page) { + return page + .getByTestId(testId) + .evaluate((element) => getComputedStyle(element).backgroundColor) +} + function getStylesheetHrefsFromHtml(html: string) { return Array.from( html.matchAll(/]+rel="stylesheet"[^>]+href="([^"]+)"/g), @@ -313,3 +320,134 @@ test('built start manifest preserves shared layout asset identity across sibling expect(sharedAAsset).toBe(sharedBAsset) expect(sharedBAsset).toBe(sharedCAsset) }) + +test('shared CSS chunk persists across client-side nav', async ({ + page, + baseURL, +}) => { + await page.goto(buildUrl(baseURL!, '/a')) + + await expect(page.getByTestId('page-a')).toBeVisible() + await expect(page.getByTestId('shared-card')).toBeVisible() + await expect + .poll(() => getBackgroundColor('shared-card', page)) + .toBe(SHARED_CARD_BG) + await expect( + page.locator('head link[rel="stylesheet"][href*="SharedCard"]'), + ).toHaveCount(1) + + await page.getByTestId('nav-/b').click() + await page.waitForURL('**/b') + await expect(page.getByTestId('page-b')).toBeVisible() + + await expect( + page.locator('head link[rel="stylesheet"][href*="SharedCard"]'), + ).toHaveCount(1) + await expect + .poll(() => getBackgroundColor('shared-card', page)) + .toBe(SHARED_CARD_BG) +}) + +test('shared widget CSS stays applied when navigating from static to lazy route', async ({ + page, + baseURL, +}) => { + await page.goto(buildUrl(baseURL!, '/lazy-css-static')) + + const widget = page.getByTestId('shared-widget') + await expect(widget).toBeVisible() + expect(await getBackgroundColor('shared-widget', page)).toBe(SHARED_WIDGET_BG) + expect( + await widget.evaluate( + (element) => getComputedStyle(element).borderTopColor, + ), + ).toBe(SHARED_WIDGET_BORDER) + + await expect(page.getByTestId('lazy-css-static-hydrated')).toBeVisible() + + await page.getByTestId('nav-/lazy-css-lazy').click() + await page.waitForURL('**/lazy-css-lazy') + await expect(page.getByTestId('lazy-css-lazy-heading')).toBeVisible() + + await expect + .poll(() => getBackgroundColor('shared-widget', page), { + timeout: 5_000, + }) + .toBe(SHARED_WIDGET_BG) +}) + +test('shared widget CSS stays applied when navigating from lazy to static route', async ({ + page, + baseURL, +}) => { + await page.goto(buildUrl(baseURL!, '/lazy-css-lazy')) + await expect(page.getByTestId('lazy-css-lazy-heading')).toBeVisible() + + await expect + .poll(() => getBackgroundColor('shared-widget', page), { + timeout: 5_000, + }) + .toBe(SHARED_WIDGET_BG) + + await page.getByTestId('nav-/lazy-css-static').click() + await page.waitForURL('**/lazy-css-static') + + const widget = page.getByTestId('shared-widget') + await expect(widget).toBeVisible() + await expect + .poll(() => getBackgroundColor('shared-widget', page), { + timeout: 5_000, + }) + .toBe(SHARED_WIDGET_BG) + expect( + await widget.evaluate( + (element) => getComputedStyle(element).borderTopColor, + ), + ).toBe(SHARED_WIDGET_BORDER) +}) + +test('shared widget CSS is applied on direct navigation to lazy route', async ({ + page, + baseURL, +}) => { + await page.goto(buildUrl(baseURL!, '/lazy-css-lazy')) + await expect(page.getByTestId('lazy-css-lazy-heading')).toBeVisible() + + const widget = page.getByTestId('shared-widget') + await expect(widget).toBeVisible() + + await expect + .poll(() => getBackgroundColor('shared-widget', page), { + timeout: 5_000, + }) + .toBe(SHARED_WIDGET_BG) + expect( + await widget.evaluate( + (element) => getComputedStyle(element).borderTopColor, + ), + ).toBe(SHARED_WIDGET_BORDER) +}) + +test('shared widget CSS persists after navigating away from lazy and back', async ({ + page, + baseURL, +}) => { + await page.goto(buildUrl(baseURL!, '/lazy-css-static')) + await expect(page.getByTestId('lazy-css-static-hydrated')).toBeVisible() + + await page.getByTestId('nav-/lazy-css-lazy').click() + await page.waitForURL('**/lazy-css-lazy') + await expect(page.getByTestId('shared-widget')).toBeVisible() + + await page.getByTestId('nav-home').click() + await page.waitForURL((url) => url.pathname === '/') + + await page.getByTestId('nav-/lazy-css-lazy').click() + await page.waitForURL('**/lazy-css-lazy') + + await expect + .poll(() => getBackgroundColor('shared-widget', page), { + timeout: 5_000, + }) + .toBe(SHARED_WIDGET_BG) +}) diff --git a/e2e/solid-start/start-manifest/package.json b/e2e/solid-start/start-manifest/package.json new file mode 100644 index 0000000000..1fe9c87c94 --- /dev/null +++ b/e2e/solid-start/start-manifest/package.json @@ -0,0 +1,33 @@ +{ + "name": "tanstack-solid-start-e2e-start-manifest", + "private": true, + "sideEffects": false, + "type": "module", + "scripts": { + "build": "vite build && tsc --noEmit", + "preview": "vite preview", + "start": "pnpx srvx --prod -s ../client dist/server/server.js", + "test:e2e": "playwright test --project=chromium" + }, + "dependencies": { + "@tanstack/solid-router": "workspace:^", + "@tanstack/solid-start": "workspace:^", + "solid-js": "^1.9.10" + }, + "devDependencies": { + "@playwright/test": "^1.50.1", + "@tanstack/router-e2e-utils": "workspace:^", + "@types/node": "^22.10.2", + "srvx": "^0.11.9", + "typescript": "^6.0.2", + "vite": "^8.0.0", + "vite-plugin-solid": "^2.11.11" + }, + "nx": { + "targets": { + "test:e2e": { + "parallelism": false + } + } + } +} diff --git a/e2e/solid-start/start-manifest/playwright.config.ts b/e2e/solid-start/start-manifest/playwright.config.ts new file mode 100644 index 0000000000..b9f835c16a --- /dev/null +++ b/e2e/solid-start/start-manifest/playwright.config.ts @@ -0,0 +1,30 @@ +import { defineConfig, devices } from '@playwright/test' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } + +const PORT = await getTestServerPort(packageJson.name) +const baseURL = `http://localhost:${PORT}` + +export default defineConfig({ + testDir: './tests', + workers: 1, + reporter: [['line']], + + use: { + baseURL, + }, + + webServer: { + command: `pnpm build && PORT=${PORT} pnpm start`, + url: baseURL, + reuseExistingServer: !process.env.CI, + stdout: 'pipe', + }, + + projects: [ + { + name: 'chromium', + use: { ...devices['Desktop Chrome'] }, + }, + ], +}) diff --git a/e2e/solid-start/start-manifest/src/components/AppShell.tsx b/e2e/solid-start/start-manifest/src/components/AppShell.tsx new file mode 100644 index 0000000000..cb1101c0c4 --- /dev/null +++ b/e2e/solid-start/start-manifest/src/components/AppShell.tsx @@ -0,0 +1,38 @@ +/// +import { ClientOnly, Link, Outlet, linkOptions } from '@tanstack/solid-router' +import styles from '~/styles/root-shell.module.css' + +const ROUTES = linkOptions([ + { to: '/', label: 'home' }, + { to: '/a', label: '/a' }, + { to: '/b', label: '/b' }, + { to: '/lazy-css-static', label: '/lazy-css-static' }, + { to: '/lazy-css-lazy', label: '/lazy-css-lazy' }, + { to: '/r1', label: '/r1' }, + { to: '/r2', label: '/r2' }, + { to: '/shared-a', label: '/shared-a' }, +]) + +export function AppShell() { + return ( +
+ + +
+
+ Start manifest CSS root shell +
+ +
hydrated
+
+ +
+
+ ) +} diff --git a/e2e/solid-start/start-manifest/src/components/SharedCard.tsx b/e2e/solid-start/start-manifest/src/components/SharedCard.tsx new file mode 100644 index 0000000000..c82b2b0ea5 --- /dev/null +++ b/e2e/solid-start/start-manifest/src/components/SharedCard.tsx @@ -0,0 +1,10 @@ +/// +import styles from '~/styles/shared-card.module.css' + +export function SharedCard({ label }: { label: string }) { + return ( +
+ Shared card {label} +
+ ) +} diff --git a/e2e/solid-start/start-manifest/src/components/SharedNestedLayout.tsx b/e2e/solid-start/start-manifest/src/components/SharedNestedLayout.tsx new file mode 100644 index 0000000000..5e86c0e8ad --- /dev/null +++ b/e2e/solid-start/start-manifest/src/components/SharedNestedLayout.tsx @@ -0,0 +1,31 @@ +/// +import { Link, linkOptions } from '@tanstack/solid-router' +import styles from '~/styles/shared-layout.module.css' + +const ROUTES = linkOptions([ + { to: '/shared-a', label: '/shared-a' }, + { to: '/shared-b', label: '/shared-b' }, + { to: '/shared-c', label: '/shared-c' }, +]) + +export function SharedNestedLayout(props: { children?: any }) { + return ( +
+
+ Shared nested layout CSS +
+ + + +
+ {props.children} +
+
+ ) +} diff --git a/e2e/solid-start/start-manifest/src/components/SharedWidget.tsx b/e2e/solid-start/start-manifest/src/components/SharedWidget.tsx new file mode 100644 index 0000000000..9074d5b2b0 --- /dev/null +++ b/e2e/solid-start/start-manifest/src/components/SharedWidget.tsx @@ -0,0 +1,15 @@ +/// +import styles from '~/styles/shared-widget.module.css' + +export function SharedWidget() { + return ( +
+
+ Shared widget styles +
+
+ This widget uses CSS shared by a static route and a lazy route. +
+
+ ) +} diff --git a/e2e/solid-start/start-manifest/src/components/SharedWidgetLazy.tsx b/e2e/solid-start/start-manifest/src/components/SharedWidgetLazy.tsx new file mode 100644 index 0000000000..5f1f6410a5 --- /dev/null +++ b/e2e/solid-start/start-manifest/src/components/SharedWidgetLazy.tsx @@ -0,0 +1,5 @@ +import { SharedWidget } from './SharedWidget' + +export default function SharedWidgetLazy() { + return +} diff --git a/e2e/solid-start/start-manifest/src/routeTree.gen.ts b/e2e/solid-start/start-manifest/src/routeTree.gen.ts new file mode 100644 index 0000000000..982f80b150 --- /dev/null +++ b/e2e/solid-start/start-manifest/src/routeTree.gen.ts @@ -0,0 +1,345 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as SharedCRouteImport } from './routes/shared-c' +import { Route as SharedBRouteImport } from './routes/shared-b' +import { Route as SharedARouteImport } from './routes/shared-a' +import { Route as R6RouteImport } from './routes/r6' +import { Route as R5RouteImport } from './routes/r5' +import { Route as R4RouteImport } from './routes/r4' +import { Route as R3RouteImport } from './routes/r3' +import { Route as R2RouteImport } from './routes/r2' +import { Route as R1RouteImport } from './routes/r1' +import { Route as LazyCssStaticRouteImport } from './routes/lazy-css-static' +import { Route as LazyCssLazyRouteImport } from './routes/lazy-css-lazy' +import { Route as BRouteImport } from './routes/b' +import { Route as ARouteImport } from './routes/a' +import { Route as IndexRouteImport } from './routes/index' + +const SharedCRoute = SharedCRouteImport.update({ + id: '/shared-c', + path: '/shared-c', + getParentRoute: () => rootRouteImport, +} as any) +const SharedBRoute = SharedBRouteImport.update({ + id: '/shared-b', + path: '/shared-b', + getParentRoute: () => rootRouteImport, +} as any) +const SharedARoute = SharedARouteImport.update({ + id: '/shared-a', + path: '/shared-a', + getParentRoute: () => rootRouteImport, +} as any) +const R6Route = R6RouteImport.update({ + id: '/r6', + path: '/r6', + getParentRoute: () => rootRouteImport, +} as any) +const R5Route = R5RouteImport.update({ + id: '/r5', + path: '/r5', + getParentRoute: () => rootRouteImport, +} as any) +const R4Route = R4RouteImport.update({ + id: '/r4', + path: '/r4', + getParentRoute: () => rootRouteImport, +} as any) +const R3Route = R3RouteImport.update({ + id: '/r3', + path: '/r3', + getParentRoute: () => rootRouteImport, +} as any) +const R2Route = R2RouteImport.update({ + id: '/r2', + path: '/r2', + getParentRoute: () => rootRouteImport, +} as any) +const R1Route = R1RouteImport.update({ + id: '/r1', + path: '/r1', + getParentRoute: () => rootRouteImport, +} as any) +const LazyCssStaticRoute = LazyCssStaticRouteImport.update({ + id: '/lazy-css-static', + path: '/lazy-css-static', + getParentRoute: () => rootRouteImport, +} as any) +const LazyCssLazyRoute = LazyCssLazyRouteImport.update({ + id: '/lazy-css-lazy', + path: '/lazy-css-lazy', + getParentRoute: () => rootRouteImport, +} as any) +const BRoute = BRouteImport.update({ + id: '/b', + path: '/b', + getParentRoute: () => rootRouteImport, +} as any) +const ARoute = ARouteImport.update({ + id: '/a', + path: '/a', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/a': typeof ARoute + '/b': typeof BRoute + '/lazy-css-lazy': typeof LazyCssLazyRoute + '/lazy-css-static': typeof LazyCssStaticRoute + '/r1': typeof R1Route + '/r2': typeof R2Route + '/r3': typeof R3Route + '/r4': typeof R4Route + '/r5': typeof R5Route + '/r6': typeof R6Route + '/shared-a': typeof SharedARoute + '/shared-b': typeof SharedBRoute + '/shared-c': typeof SharedCRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/a': typeof ARoute + '/b': typeof BRoute + '/lazy-css-lazy': typeof LazyCssLazyRoute + '/lazy-css-static': typeof LazyCssStaticRoute + '/r1': typeof R1Route + '/r2': typeof R2Route + '/r3': typeof R3Route + '/r4': typeof R4Route + '/r5': typeof R5Route + '/r6': typeof R6Route + '/shared-a': typeof SharedARoute + '/shared-b': typeof SharedBRoute + '/shared-c': typeof SharedCRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/a': typeof ARoute + '/b': typeof BRoute + '/lazy-css-lazy': typeof LazyCssLazyRoute + '/lazy-css-static': typeof LazyCssStaticRoute + '/r1': typeof R1Route + '/r2': typeof R2Route + '/r3': typeof R3Route + '/r4': typeof R4Route + '/r5': typeof R5Route + '/r6': typeof R6Route + '/shared-a': typeof SharedARoute + '/shared-b': typeof SharedBRoute + '/shared-c': typeof SharedCRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: + | '/' + | '/a' + | '/b' + | '/lazy-css-lazy' + | '/lazy-css-static' + | '/r1' + | '/r2' + | '/r3' + | '/r4' + | '/r5' + | '/r6' + | '/shared-a' + | '/shared-b' + | '/shared-c' + fileRoutesByTo: FileRoutesByTo + to: + | '/' + | '/a' + | '/b' + | '/lazy-css-lazy' + | '/lazy-css-static' + | '/r1' + | '/r2' + | '/r3' + | '/r4' + | '/r5' + | '/r6' + | '/shared-a' + | '/shared-b' + | '/shared-c' + id: + | '__root__' + | '/' + | '/a' + | '/b' + | '/lazy-css-lazy' + | '/lazy-css-static' + | '/r1' + | '/r2' + | '/r3' + | '/r4' + | '/r5' + | '/r6' + | '/shared-a' + | '/shared-b' + | '/shared-c' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + ARoute: typeof ARoute + BRoute: typeof BRoute + LazyCssLazyRoute: typeof LazyCssLazyRoute + LazyCssStaticRoute: typeof LazyCssStaticRoute + R1Route: typeof R1Route + R2Route: typeof R2Route + R3Route: typeof R3Route + R4Route: typeof R4Route + R5Route: typeof R5Route + R6Route: typeof R6Route + SharedARoute: typeof SharedARoute + SharedBRoute: typeof SharedBRoute + SharedCRoute: typeof SharedCRoute +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/shared-c': { + id: '/shared-c' + path: '/shared-c' + fullPath: '/shared-c' + preLoaderRoute: typeof SharedCRouteImport + parentRoute: typeof rootRouteImport + } + '/shared-b': { + id: '/shared-b' + path: '/shared-b' + fullPath: '/shared-b' + preLoaderRoute: typeof SharedBRouteImport + parentRoute: typeof rootRouteImport + } + '/shared-a': { + id: '/shared-a' + path: '/shared-a' + fullPath: '/shared-a' + preLoaderRoute: typeof SharedARouteImport + parentRoute: typeof rootRouteImport + } + '/r6': { + id: '/r6' + path: '/r6' + fullPath: '/r6' + preLoaderRoute: typeof R6RouteImport + parentRoute: typeof rootRouteImport + } + '/r5': { + id: '/r5' + path: '/r5' + fullPath: '/r5' + preLoaderRoute: typeof R5RouteImport + parentRoute: typeof rootRouteImport + } + '/r4': { + id: '/r4' + path: '/r4' + fullPath: '/r4' + preLoaderRoute: typeof R4RouteImport + parentRoute: typeof rootRouteImport + } + '/r3': { + id: '/r3' + path: '/r3' + fullPath: '/r3' + preLoaderRoute: typeof R3RouteImport + parentRoute: typeof rootRouteImport + } + '/r2': { + id: '/r2' + path: '/r2' + fullPath: '/r2' + preLoaderRoute: typeof R2RouteImport + parentRoute: typeof rootRouteImport + } + '/r1': { + id: '/r1' + path: '/r1' + fullPath: '/r1' + preLoaderRoute: typeof R1RouteImport + parentRoute: typeof rootRouteImport + } + '/lazy-css-static': { + id: '/lazy-css-static' + path: '/lazy-css-static' + fullPath: '/lazy-css-static' + preLoaderRoute: typeof LazyCssStaticRouteImport + parentRoute: typeof rootRouteImport + } + '/lazy-css-lazy': { + id: '/lazy-css-lazy' + path: '/lazy-css-lazy' + fullPath: '/lazy-css-lazy' + preLoaderRoute: typeof LazyCssLazyRouteImport + parentRoute: typeof rootRouteImport + } + '/b': { + id: '/b' + path: '/b' + fullPath: '/b' + preLoaderRoute: typeof BRouteImport + parentRoute: typeof rootRouteImport + } + '/a': { + id: '/a' + path: '/a' + fullPath: '/a' + preLoaderRoute: typeof ARouteImport + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + ARoute: ARoute, + BRoute: BRoute, + LazyCssLazyRoute: LazyCssLazyRoute, + LazyCssStaticRoute: LazyCssStaticRoute, + R1Route: R1Route, + R2Route: R2Route, + R3Route: R3Route, + R4Route: R4Route, + R5Route: R5Route, + R6Route: R6Route, + SharedARoute: SharedARoute, + SharedBRoute: SharedBRoute, + SharedCRoute: SharedCRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() + +import type { getRouter } from './router.tsx' +import type { createStart } from '@tanstack/solid-start' +declare module '@tanstack/solid-start' { + interface Register { + ssr: true + router: Awaited> + } +} diff --git a/e2e/solid-start/start-manifest/src/router.tsx b/e2e/solid-start/start-manifest/src/router.tsx new file mode 100644 index 0000000000..801095c695 --- /dev/null +++ b/e2e/solid-start/start-manifest/src/router.tsx @@ -0,0 +1,18 @@ +import { createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' + +export const getRouter = () => { + const router = createRouter({ + routeTree, + scrollRestoration: true, + defaultPreload: 'intent', + }) + + return router +} + +declare module '@tanstack/solid-router' { + interface Register { + router: ReturnType + } +} diff --git a/e2e/solid-start/start-manifest/src/routes/__root.tsx b/e2e/solid-start/start-manifest/src/routes/__root.tsx new file mode 100644 index 0000000000..90935e1236 --- /dev/null +++ b/e2e/solid-start/start-manifest/src/routes/__root.tsx @@ -0,0 +1,29 @@ +import { HeadContent, Scripts, createRootRoute } from '@tanstack/solid-router' +import { HydrationScript } from 'solid-js/web' +import { AppShell } from '~/components/AppShell' + +export const Route = createRootRoute({ + head: () => ({ + meta: [ + { charSet: 'utf-8' }, + { name: 'viewport', content: 'width=device-width, initial-scale=1' }, + { title: 'TanStack Start Manifest Bloat E2E' }, + ], + }), + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + + ) +} diff --git a/e2e/solid-start/start-manifest/src/routes/a.tsx b/e2e/solid-start/start-manifest/src/routes/a.tsx new file mode 100644 index 0000000000..d9cda03adc --- /dev/null +++ b/e2e/solid-start/start-manifest/src/routes/a.tsx @@ -0,0 +1,18 @@ +/// +import { createFileRoute } from '@tanstack/solid-router' +import { SharedCard } from '~/components/SharedCard' +import styles from '~/styles/page-a.module.css' + +export const Route = createFileRoute('/a')({ + component: RouteComponent, +}) + +function RouteComponent() { + return ( +
+

Route /a

+

Route /a keeps the shared card styled.

+ +
+ ) +} diff --git a/e2e/solid-start/start-manifest/src/routes/b.tsx b/e2e/solid-start/start-manifest/src/routes/b.tsx new file mode 100644 index 0000000000..fd17811d56 --- /dev/null +++ b/e2e/solid-start/start-manifest/src/routes/b.tsx @@ -0,0 +1,18 @@ +/// +import { createFileRoute } from '@tanstack/solid-router' +import { SharedCard } from '~/components/SharedCard' +import styles from '~/styles/page-b.module.css' + +export const Route = createFileRoute('/b')({ + component: RouteComponent, +}) + +function RouteComponent() { + return ( +
+

Route /b

+

Route /b should keep the shared card stylesheet after nav.

+ +
+ ) +} diff --git a/e2e/solid-start/start-manifest/src/routes/index.tsx b/e2e/solid-start/start-manifest/src/routes/index.tsx new file mode 100644 index 0000000000..e61358aa7b --- /dev/null +++ b/e2e/solid-start/start-manifest/src/routes/index.tsx @@ -0,0 +1,16 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/')({ + component: HomeRoute, +}) + +function HomeRoute() { + return ( +
+

Start manifest fixture

+

+ Use this page to navigate between CSS module routes. +

+
+ ) +} diff --git a/e2e/solid-start/start-manifest/src/routes/lazy-css-lazy.tsx b/e2e/solid-start/start-manifest/src/routes/lazy-css-lazy.tsx new file mode 100644 index 0000000000..dc2bb845bf --- /dev/null +++ b/e2e/solid-start/start-manifest/src/routes/lazy-css-lazy.tsx @@ -0,0 +1,26 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { Suspense, lazy } from 'solid-js' + +const LazySharedWidget = lazy(() => import('~/components/SharedWidgetLazy')) + +export const Route = createFileRoute('/lazy-css-lazy')({ + component: LazyCssLazyRoute, +}) + +function LazyCssLazyRoute() { + return ( +
+

Lazy CSS Repro - Lazy Route

+

+ This route renders the same widget through a lazy component so the CSS + only exists behind a dynamic import boundary. +

+ + Loading...} + > + + +
+ ) +} diff --git a/e2e/solid-start/start-manifest/src/routes/lazy-css-static.tsx b/e2e/solid-start/start-manifest/src/routes/lazy-css-static.tsx new file mode 100644 index 0000000000..1112c8ae90 --- /dev/null +++ b/e2e/solid-start/start-manifest/src/routes/lazy-css-static.tsx @@ -0,0 +1,24 @@ +import { ClientOnly, createFileRoute } from '@tanstack/solid-router' +import { SharedWidget } from '~/components/SharedWidget' + +export const Route = createFileRoute('/lazy-css-static')({ + component: LazyCssStaticRoute, +}) + +function LazyCssStaticRoute() { + return ( +
+

Lazy CSS Repro - Static Route

+

+ This route statically imports the shared widget so its CSS is present in + the SSR head. +

+ + +
hydrated
+
+ + +
+ ) +} diff --git a/e2e/solid-start/start-manifest/src/routes/r1.tsx b/e2e/solid-start/start-manifest/src/routes/r1.tsx new file mode 100644 index 0000000000..d3979ecaf1 --- /dev/null +++ b/e2e/solid-start/start-manifest/src/routes/r1.tsx @@ -0,0 +1,18 @@ +/// +import { createFileRoute } from '@tanstack/solid-router' +import styles from '~/styles/route-one.module.css' + +export const Route = createFileRoute('/r1')({ + component: RouteComponent, +}) + +function RouteComponent() { + return ( +
+

Route /r1

+
+ Route /r1 CSS module styling +
+
+ ) +} diff --git a/e2e/solid-start/start-manifest/src/routes/r2.tsx b/e2e/solid-start/start-manifest/src/routes/r2.tsx new file mode 100644 index 0000000000..836257cd2e --- /dev/null +++ b/e2e/solid-start/start-manifest/src/routes/r2.tsx @@ -0,0 +1,18 @@ +/// +import { createFileRoute } from '@tanstack/solid-router' +import styles from '~/styles/route-two.module.css' + +export const Route = createFileRoute('/r2')({ + component: RouteComponent, +}) + +function RouteComponent() { + return ( +
+

Route /r2

+
+ Route /r2 CSS module styling +
+
+ ) +} diff --git a/e2e/solid-start/start-manifest/src/routes/r3.tsx b/e2e/solid-start/start-manifest/src/routes/r3.tsx new file mode 100644 index 0000000000..178a4b2a41 --- /dev/null +++ b/e2e/solid-start/start-manifest/src/routes/r3.tsx @@ -0,0 +1,5 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/r3')({ + component: () =>
Route /r3
, +}) diff --git a/e2e/solid-start/start-manifest/src/routes/r4.tsx b/e2e/solid-start/start-manifest/src/routes/r4.tsx new file mode 100644 index 0000000000..c625e4961e --- /dev/null +++ b/e2e/solid-start/start-manifest/src/routes/r4.tsx @@ -0,0 +1,5 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/r4')({ + component: () =>
Route /r4
, +}) diff --git a/e2e/solid-start/start-manifest/src/routes/r5.tsx b/e2e/solid-start/start-manifest/src/routes/r5.tsx new file mode 100644 index 0000000000..d4f5dcb95f --- /dev/null +++ b/e2e/solid-start/start-manifest/src/routes/r5.tsx @@ -0,0 +1,5 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/r5')({ + component: () =>
Route /r5
, +}) diff --git a/e2e/solid-start/start-manifest/src/routes/r6.tsx b/e2e/solid-start/start-manifest/src/routes/r6.tsx new file mode 100644 index 0000000000..235ff13538 --- /dev/null +++ b/e2e/solid-start/start-manifest/src/routes/r6.tsx @@ -0,0 +1,5 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/r6')({ + component: () =>
Route /r6
, +}) diff --git a/e2e/solid-start/start-manifest/src/routes/shared-a.tsx b/e2e/solid-start/start-manifest/src/routes/shared-a.tsx new file mode 100644 index 0000000000..ccb94d1e46 --- /dev/null +++ b/e2e/solid-start/start-manifest/src/routes/shared-a.tsx @@ -0,0 +1,14 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { SharedNestedLayout } from '~/components/SharedNestedLayout' + +export const Route = createFileRoute('/shared-a')({ + component: RouteComponent, +}) + +function RouteComponent() { + return ( + +
Shared route A
+
+ ) +} diff --git a/e2e/solid-start/start-manifest/src/routes/shared-b.tsx b/e2e/solid-start/start-manifest/src/routes/shared-b.tsx new file mode 100644 index 0000000000..ced02fcf12 --- /dev/null +++ b/e2e/solid-start/start-manifest/src/routes/shared-b.tsx @@ -0,0 +1,14 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { SharedNestedLayout } from '~/components/SharedNestedLayout' + +export const Route = createFileRoute('/shared-b')({ + component: RouteComponent, +}) + +function RouteComponent() { + return ( + +
Shared route B
+
+ ) +} diff --git a/e2e/solid-start/start-manifest/src/routes/shared-c.tsx b/e2e/solid-start/start-manifest/src/routes/shared-c.tsx new file mode 100644 index 0000000000..9b8ea62f3f --- /dev/null +++ b/e2e/solid-start/start-manifest/src/routes/shared-c.tsx @@ -0,0 +1,14 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { SharedNestedLayout } from '~/components/SharedNestedLayout' + +export const Route = createFileRoute('/shared-c')({ + component: RouteComponent, +}) + +function RouteComponent() { + return ( + +
Shared route C
+
+ ) +} diff --git a/e2e/solid-start/start-manifest/src/styles/page-a.module.css b/e2e/solid-start/start-manifest/src/styles/page-a.module.css new file mode 100644 index 0000000000..7ed4301097 --- /dev/null +++ b/e2e/solid-start/start-manifest/src/styles/page-a.module.css @@ -0,0 +1,10 @@ +.page { + padding: 1rem; + min-height: 12rem; + background: rgb(240, 253, 244); + border: 4px solid rgb(22, 163, 74); +} + +.title { + color: rgb(21, 128, 61); +} diff --git a/e2e/solid-start/start-manifest/src/styles/page-b.module.css b/e2e/solid-start/start-manifest/src/styles/page-b.module.css new file mode 100644 index 0000000000..93d1d39a01 --- /dev/null +++ b/e2e/solid-start/start-manifest/src/styles/page-b.module.css @@ -0,0 +1,10 @@ +.page { + padding: 1rem; + min-height: 12rem; + background: rgb(239, 246, 255); + border: 4px solid rgb(37, 99, 235); +} + +.title { + color: rgb(29, 78, 216); +} diff --git a/e2e/solid-start/start-manifest/src/styles/root-shell.module.css b/e2e/solid-start/start-manifest/src/styles/root-shell.module.css new file mode 100644 index 0000000000..e7bece8664 --- /dev/null +++ b/e2e/solid-start/start-manifest/src/styles/root-shell.module.css @@ -0,0 +1,37 @@ +.shell { + font-family: + -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; + min-height: 100vh; + background: rgb(248, 250, 252); + color: rgb(15, 23, 42); +} + +.nav { + display: flex; + flex-wrap: wrap; + gap: 0.75rem; + padding: 1rem; + border-bottom: 1px solid rgb(226, 232, 240); + background: white; +} + +.nav a { + color: rgb(37, 99, 235); + text-decoration: none; +} + +.content { + max-width: 760px; + margin: 0 auto; + padding: 1.5rem 1rem 3rem; +} + +.rootBadge { + display: inline-block; + margin-bottom: 1rem; + padding: 0.375rem 0.75rem; + border-radius: 9999px; + background: rgb(220, 252, 231); + color: rgb(22, 101, 52); + font-weight: 700; +} diff --git a/e2e/solid-start/start-manifest/src/styles/route-one.module.css b/e2e/solid-start/start-manifest/src/styles/route-one.module.css new file mode 100644 index 0000000000..623d03e6a3 --- /dev/null +++ b/e2e/solid-start/start-manifest/src/styles/route-one.module.css @@ -0,0 +1,7 @@ +.card { + padding: 1rem; + border-radius: 0.75rem; + background: rgb(239, 246, 255); + color: rgb(30, 64, 175); + border: 2px solid rgb(96, 165, 250); +} diff --git a/e2e/solid-start/start-manifest/src/styles/route-two.module.css b/e2e/solid-start/start-manifest/src/styles/route-two.module.css new file mode 100644 index 0000000000..66ed355711 --- /dev/null +++ b/e2e/solid-start/start-manifest/src/styles/route-two.module.css @@ -0,0 +1,7 @@ +.card { + padding: 1rem; + border-radius: 0.75rem; + background: rgb(250, 245, 255); + color: rgb(126, 34, 206); + border: 2px solid rgb(192, 132, 252); +} diff --git a/e2e/solid-start/start-manifest/src/styles/shared-card.module.css b/e2e/solid-start/start-manifest/src/styles/shared-card.module.css new file mode 100644 index 0000000000..2aa5a6ac17 --- /dev/null +++ b/e2e/solid-start/start-manifest/src/styles/shared-card.module.css @@ -0,0 +1,8 @@ +.card { + margin-top: 1rem; + padding: 1.5rem; + border-radius: 0.75rem; + background: rgb(252, 231, 243); + border: 2px solid rgb(190, 24, 93); + color: rgb(157, 23, 77); +} diff --git a/e2e/solid-start/start-manifest/src/styles/shared-layout.module.css b/e2e/solid-start/start-manifest/src/styles/shared-layout.module.css new file mode 100644 index 0000000000..6025a1da06 --- /dev/null +++ b/e2e/solid-start/start-manifest/src/styles/shared-layout.module.css @@ -0,0 +1,16 @@ +.layout { + padding: 1rem; + border-radius: 0.75rem; + background: rgb(255, 251, 235); + border: 2px solid rgb(245, 158, 11); +} + +.heading { + color: rgb(180, 83, 9); + font-weight: 700; + margin-bottom: 0.5rem; +} + +.body { + color: rgb(146, 64, 14); +} diff --git a/e2e/solid-start/start-manifest/src/styles/shared-widget.module.css b/e2e/solid-start/start-manifest/src/styles/shared-widget.module.css new file mode 100644 index 0000000000..ed197cddb0 --- /dev/null +++ b/e2e/solid-start/start-manifest/src/styles/shared-widget.module.css @@ -0,0 +1,17 @@ +.widget { + margin-top: 1rem; + padding: 1rem; + border-top: 4px solid rgb(249, 115, 22); + border-radius: 0.75rem; + background: rgb(255, 247, 237); +} + +.title { + font-weight: 700; + color: rgb(154, 52, 18); +} + +.content { + margin-top: 0.5rem; + color: rgb(124, 45, 18); +} diff --git a/e2e/solid-start/start-manifest/tests/start-manifest.spec.ts b/e2e/solid-start/start-manifest/tests/start-manifest.spec.ts new file mode 100644 index 0000000000..23244db828 --- /dev/null +++ b/e2e/solid-start/start-manifest/tests/start-manifest.spec.ts @@ -0,0 +1,453 @@ +import { expect } from '@playwright/test' +import { test } from '@tanstack/router-e2e-utils' +import type { Page } from '@playwright/test' +import { readdir } from 'node:fs/promises' +import path from 'node:path' +import { pathToFileURL } from 'node:url' + +const ROOT_SHELL_COLOR = 'rgb(22, 101, 52)' +const ROUTE_ONE_COLOR = 'rgb(30, 64, 175)' +const ROUTE_TWO_COLOR = 'rgb(126, 34, 206)' +const SHARED_CARD_BG = 'rgb(252, 231, 243)' +const SHARED_WIDGET_BG = 'rgb(255, 247, 237)' +const SHARED_WIDGET_BORDER = 'rgb(249, 115, 22)' + +const buildUrl = (baseURL: string, pathname: string) => + baseURL.replace(/\/$/, '') + pathname + +async function getColor(testId: string, page: Page) { + return page + .getByTestId(testId) + .evaluate((element) => getComputedStyle(element).color) +} + +async function getBackgroundColor(testId: string, page: Page) { + return page + .getByTestId(testId) + .evaluate((element) => getComputedStyle(element).backgroundColor) +} + +function getStylesheetHrefsFromHtml(html: string) { + return Array.from( + html.matchAll(/]+rel="stylesheet"[^>]+href="([^"]+)"/g), + (match) => match[1]!, + ) +} + +async function getHeadStylesheetHrefs(page: Page) { + return page.locator('head link[rel="stylesheet"]').evaluateAll((links) => { + return links.map( + (link) => (link as HTMLLinkElement).getAttribute('href') || '', + ) + }) +} + +function countMatchingStylesheetHrefs(hrefs: Array, pattern: string) { + return hrefs.filter((href) => href.includes(pattern)).length +} + +async function loadBuiltStartManifest() { + const serverDir = path.resolve(import.meta.dirname, '../dist/server/assets') + const entries = await readdir(serverDir) + const manifestFile = entries.find( + (entry) => + entry.startsWith('_tanstack-start-manifest_v-') && entry.endsWith('.js'), + ) + + expect(manifestFile).toBeTruthy() + + const moduleUrl = `${pathToFileURL(path.join(serverDir, manifestFile!)).href}?t=${Date.now()}` + const manifestModule = await import(moduleUrl) + + return manifestModule.tsrStartManifest() as { + routes: Record }> + } +} + +async function expectDirectEntry({ + page, + request, + baseURL, + pathname, + expectedVisibleTestId, + expectedAbsentTestId, + expectedStylesheetPattern, + unexpectedStylesheetPattern, + expectedColorTestId, + expectedColor, +}: { + page: Page + request: { + get: (url: string) => Promise<{ ok(): boolean; text(): Promise }> + } + baseURL: string + pathname: string + expectedVisibleTestId: string + expectedAbsentTestId: string + expectedStylesheetPattern: string + unexpectedStylesheetPattern: string + expectedColorTestId: string + expectedColor: string +}) { + const url = buildUrl(baseURL, pathname) + const response = await request.get(url) + const ssrHtml = await response.text() + + expect(response.ok()).toBe(true) + expect(ssrHtml).toContain('root-shell-marker') + expect(ssrHtml).toContain(expectedVisibleTestId) + expect(ssrHtml).not.toContain(expectedAbsentTestId) + + const stylesheetLinks = getStylesheetHrefsFromHtml(ssrHtml) + + expect( + countMatchingStylesheetHrefs(stylesheetLinks, expectedStylesheetPattern), + ).toBe(1) + expect( + countMatchingStylesheetHrefs(stylesheetLinks, unexpectedStylesheetPattern), + ).toBe(0) + expect(stylesheetLinks).toHaveLength(2) + + await page.goto(url) + await expect(page.getByTestId(expectedVisibleTestId)).toBeVisible() + await expect(page.getByTestId('hydration-marker')).toBeVisible() + + await expect + .poll(async () => { + const hrefs = await getHeadStylesheetHrefs(page) + return countMatchingStylesheetHrefs(hrefs, expectedStylesheetPattern) + }) + .toBe(1) + await expect + .poll(async () => { + const hrefs = await getHeadStylesheetHrefs(page) + return countMatchingStylesheetHrefs(hrefs, unexpectedStylesheetPattern) + }) + .toBe(0) + + await expect + .poll(() => getColor('root-shell-marker', page)) + .toBe(ROOT_SHELL_COLOR) + await expect + .poll(() => getColor(expectedColorTestId, page)) + .toBe(expectedColor) +} + +test('SSR and client navigation keep CSS module styles correct without hydration errors', async ({ + page, + baseURL, + request, +}) => { + const routeOneUrl = buildUrl(baseURL!, '/r1') + const response = await request.get(routeOneUrl) + const ssrHtml = await response.text() + + expect(response.ok()).toBe(true) + expect(ssrHtml).toContain('root-shell-marker') + expect(ssrHtml).toContain('route-r1-card') + expect(ssrHtml).not.toContain('route-r2-card') + + const stylesheetLinks = getStylesheetHrefsFromHtml(ssrHtml) + + expect(countMatchingStylesheetHrefs(stylesheetLinks, 'r1-')).toBe(1) + expect(countMatchingStylesheetHrefs(stylesheetLinks, 'r2-')).toBe(0) + expect(stylesheetLinks).toHaveLength(2) + + await page.goto(routeOneUrl) + + await expect(page.getByTestId('route-r1-card')).toBeVisible() + await expect(page.getByTestId('hydration-marker')).toBeVisible() + + await expect + .poll(async () => { + const hrefs = await getHeadStylesheetHrefs(page) + return countMatchingStylesheetHrefs(hrefs, 'r1-') + }) + .toBe(1) + await expect + .poll(async () => { + const hrefs = await getHeadStylesheetHrefs(page) + return countMatchingStylesheetHrefs(hrefs, 'r2-') + }) + .toBe(0) + + await expect + .poll(() => getColor('root-shell-marker', page)) + .toBe(ROOT_SHELL_COLOR) + await expect.poll(() => getColor('route-r1-card', page)).toBe(ROUTE_ONE_COLOR) + + await page.getByTestId('nav-/r2').click() + await page.waitForURL('**/r2') + await expect(page.getByTestId('route-r2-card')).toBeVisible() + + await expect + .poll(async () => { + const hrefs = await getHeadStylesheetHrefs(page) + return countMatchingStylesheetHrefs(hrefs, 'r2-') + }) + .toBe(1) + + await expect + .poll(() => getColor('root-shell-marker', page)) + .toBe(ROOT_SHELL_COLOR) + await expect.poll(() => getColor('route-r2-card', page)).toBe(ROUTE_TWO_COLOR) + + await page.getByTestId('nav-/r1').click() + await page.waitForURL('**/r1') + await expect(page.getByTestId('route-r1-card')).toBeVisible() + + await expect + .poll(async () => { + const hrefs = await getHeadStylesheetHrefs(page) + return countMatchingStylesheetHrefs(hrefs, 'r1-') + }) + .toBe(1) + + await expect + .poll(() => getColor('root-shell-marker', page)) + .toBe(ROOT_SHELL_COLOR) + await expect.poll(() => getColor('route-r1-card', page)).toBe(ROUTE_ONE_COLOR) +}) + +test('direct SSR entry on /r2 only includes its stylesheet and hydrates cleanly', async ({ + page, + baseURL, + request, +}) => { + await expectDirectEntry({ + page, + request, + baseURL: baseURL!, + pathname: '/r2', + expectedVisibleTestId: 'route-r2-card', + expectedAbsentTestId: 'route-r1-card', + expectedStylesheetPattern: 'r2-', + unexpectedStylesheetPattern: 'r1-', + expectedColorTestId: 'route-r2-card', + expectedColor: ROUTE_TWO_COLOR, + }) +}) + +test('direct SSR entries on different route-css pages stay isolated', async ({ + page, + baseURL, + request, +}) => { + await expectDirectEntry({ + page, + request, + baseURL: baseURL!, + pathname: '/r2', + expectedVisibleTestId: 'route-r2-card', + expectedAbsentTestId: 'route-r1-card', + expectedStylesheetPattern: 'r2-', + unexpectedStylesheetPattern: 'r1-', + expectedColorTestId: 'route-r2-card', + expectedColor: ROUTE_TWO_COLOR, + }) + + await expectDirectEntry({ + page, + request, + baseURL: baseURL!, + pathname: '/r1', + expectedVisibleTestId: 'route-r1-card', + expectedAbsentTestId: 'route-r2-card', + expectedStylesheetPattern: 'r1-', + unexpectedStylesheetPattern: 'r2-', + expectedColorTestId: 'route-r1-card', + expectedColor: ROUTE_ONE_COLOR, + }) +}) + +test('home route only renders the root stylesheet and no route-specific CSS', async ({ + page, + baseURL, + request, +}) => { + const homeUrl = buildUrl(baseURL!, '/') + const response = await request.get(homeUrl) + const ssrHtml = await response.text() + + expect(response.ok()).toBe(true) + expect(ssrHtml).toContain('root-shell-marker') + expect(ssrHtml).toContain('home-copy') + expect(ssrHtml).not.toContain('route-r1-card') + expect(ssrHtml).not.toContain('route-r2-card') + + const stylesheetLinks = getStylesheetHrefsFromHtml(ssrHtml) + + expect(countMatchingStylesheetHrefs(stylesheetLinks, 'r1-')).toBe(0) + expect(countMatchingStylesheetHrefs(stylesheetLinks, 'r2-')).toBe(0) + expect(stylesheetLinks).toHaveLength(1) + + await page.goto(homeUrl) + await expect(page.getByTestId('home-copy')).toBeVisible() + await expect(page.getByTestId('hydration-marker')).toBeVisible() + + await expect + .poll(async () => { + const hrefs = await getHeadStylesheetHrefs(page) + return countMatchingStylesheetHrefs(hrefs, 'r1-') + }) + .toBe(0) + await expect + .poll(async () => { + const hrefs = await getHeadStylesheetHrefs(page) + return countMatchingStylesheetHrefs(hrefs, 'r2-') + }) + .toBe(0) + + await expect + .poll(() => getColor('root-shell-marker', page)) + .toBe(ROOT_SHELL_COLOR) +}) + +test('built start manifest preserves shared layout asset identity across sibling routes', async ({ + page, + baseURL, +}) => { + await page.goto(buildUrl(baseURL!, '/shared-a')) + await expect(page.getByTestId('shared-a-card')).toBeVisible() + + const manifest = await loadBuiltStartManifest() + + const sharedAAsset = manifest.routes['/shared-a']?.assets?.[0] + const sharedBAsset = manifest.routes['/shared-b']?.assets?.[0] + const sharedCAsset = manifest.routes['/shared-c']?.assets?.[0] + + expect(sharedAAsset).toBeTruthy() + expect(sharedAAsset).toBe(sharedBAsset) + expect(sharedBAsset).toBe(sharedCAsset) +}) + +test('shared CSS chunk persists across client-side nav', async ({ + page, + baseURL, +}) => { + await page.goto(buildUrl(baseURL!, '/a')) + + await expect(page.getByTestId('page-a')).toBeVisible() + await expect(page.getByTestId('shared-card')).toBeVisible() + await expect + .poll(() => getBackgroundColor('shared-card', page)) + .toBe(SHARED_CARD_BG) + await expect( + page.locator('head link[rel="stylesheet"][href*="SharedCard"]'), + ).toHaveCount(1) + + await page.getByTestId('nav-/b').click() + await page.waitForURL('**/b') + await expect(page.getByTestId('page-b')).toBeVisible() + + await expect( + page.locator('head link[rel="stylesheet"][href*="SharedCard"]'), + ).toHaveCount(1) + await expect + .poll(() => getBackgroundColor('shared-card', page)) + .toBe(SHARED_CARD_BG) +}) + +test('shared widget CSS stays applied when navigating from static to lazy route', async ({ + page, + baseURL, +}) => { + await page.goto(buildUrl(baseURL!, '/lazy-css-static')) + + const widget = page.getByTestId('shared-widget') + await expect(widget).toBeVisible() + expect(await getBackgroundColor('shared-widget', page)).toBe(SHARED_WIDGET_BG) + expect( + await widget.evaluate( + (element) => getComputedStyle(element).borderTopColor, + ), + ).toBe(SHARED_WIDGET_BORDER) + + await expect(page.getByTestId('lazy-css-static-hydrated')).toBeVisible() + + await page.getByTestId('nav-/lazy-css-lazy').click() + await page.waitForURL('**/lazy-css-lazy') + await expect(page.getByTestId('lazy-css-lazy-heading')).toBeVisible() + + await expect + .poll(() => getBackgroundColor('shared-widget', page), { + timeout: 5_000, + }) + .toBe(SHARED_WIDGET_BG) +}) + +test('shared widget CSS stays applied when navigating from lazy to static route', async ({ + page, + baseURL, +}) => { + await page.goto(buildUrl(baseURL!, '/lazy-css-lazy')) + await expect(page.getByTestId('lazy-css-lazy-heading')).toBeVisible() + + await expect + .poll(() => getBackgroundColor('shared-widget', page), { + timeout: 5_000, + }) + .toBe(SHARED_WIDGET_BG) + + await page.getByTestId('nav-/lazy-css-static').click() + await page.waitForURL('**/lazy-css-static') + + const widget = page.getByTestId('shared-widget') + await expect(widget).toBeVisible() + await expect + .poll(() => getBackgroundColor('shared-widget', page), { + timeout: 5_000, + }) + .toBe(SHARED_WIDGET_BG) + expect( + await widget.evaluate( + (element) => getComputedStyle(element).borderTopColor, + ), + ).toBe(SHARED_WIDGET_BORDER) +}) + +test('shared widget CSS is applied on direct navigation to lazy route', async ({ + page, + baseURL, +}) => { + await page.goto(buildUrl(baseURL!, '/lazy-css-lazy')) + await expect(page.getByTestId('lazy-css-lazy-heading')).toBeVisible() + + const widget = page.getByTestId('shared-widget') + await expect(widget).toBeVisible() + + await expect + .poll(() => getBackgroundColor('shared-widget', page), { + timeout: 5_000, + }) + .toBe(SHARED_WIDGET_BG) + expect( + await widget.evaluate( + (element) => getComputedStyle(element).borderTopColor, + ), + ).toBe(SHARED_WIDGET_BORDER) +}) + +test('shared widget CSS persists after navigating away from lazy and back', async ({ + page, + baseURL, +}) => { + await page.goto(buildUrl(baseURL!, '/lazy-css-static')) + await expect(page.getByTestId('lazy-css-static-hydrated')).toBeVisible() + + await page.getByTestId('nav-/lazy-css-lazy').click() + await page.waitForURL('**/lazy-css-lazy') + await expect(page.getByTestId('shared-widget')).toBeVisible() + + await page.getByTestId('nav-home').click() + await page.waitForURL(/\/([^/]*)(\/)?($|\?)/) + + await page.getByTestId('nav-/lazy-css-lazy').click() + await page.waitForURL('**/lazy-css-lazy') + + await expect + .poll(() => getBackgroundColor('shared-widget', page), { + timeout: 5_000, + }) + .toBe(SHARED_WIDGET_BG) +}) diff --git a/e2e/solid-start/start-manifest/tsconfig.json b/e2e/solid-start/start-manifest/tsconfig.json new file mode 100644 index 0000000000..76cf3401fa --- /dev/null +++ b/e2e/solid-start/start-manifest/tsconfig.json @@ -0,0 +1,23 @@ +{ + "include": ["**/*.ts", "**/*.tsx"], + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "jsx": "preserve", + "jsxImportSource": "solid-js", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["DOM", "DOM.Iterable", "ES2022"], + "isolatedModules": true, + "resolveJsonModule": true, + "skipLibCheck": true, + "target": "ES2024", + "allowJs": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "~/*": ["./src/*"] + }, + "noEmit": true, + "types": ["vite/client"] + } +} diff --git a/e2e/solid-start/start-manifest/vite.config.ts b/e2e/solid-start/start-manifest/vite.config.ts new file mode 100644 index 0000000000..896fa284f1 --- /dev/null +++ b/e2e/solid-start/start-manifest/vite.config.ts @@ -0,0 +1,13 @@ +import { tanstackStart } from '@tanstack/solid-start/plugin/vite' +import { defineConfig } from 'vite' +import viteSolid from 'vite-plugin-solid' + +export default defineConfig({ + server: { + port: 3000, + }, + resolve: { + tsconfigPaths: true, + }, + plugins: [tanstackStart({ srcDirectory: 'src' }), viteSolid({ ssr: true })], +}) diff --git a/e2e/vue-start/start-manifest/package.json b/e2e/vue-start/start-manifest/package.json new file mode 100644 index 0000000000..ffe9b414c9 --- /dev/null +++ b/e2e/vue-start/start-manifest/package.json @@ -0,0 +1,33 @@ +{ + "name": "tanstack-vue-start-e2e-start-manifest", + "private": true, + "sideEffects": false, + "type": "module", + "scripts": { + "build": "vite build && tsc --noEmit", + "preview": "vite preview", + "start": "pnpx srvx --prod -s ../client dist/server/server.js", + "test:e2e": "playwright test --project=chromium" + }, + "dependencies": { + "@tanstack/vue-router": "workspace:^", + "@tanstack/vue-start": "workspace:^", + "vue": "^3.5.16" + }, + "devDependencies": { + "@playwright/test": "^1.50.1", + "@tanstack/router-e2e-utils": "workspace:^", + "@types/node": "^22.10.2", + "@vitejs/plugin-vue-jsx": "^5.1.5", + "srvx": "^0.11.9", + "typescript": "^6.0.2", + "vite": "^8.0.0" + }, + "nx": { + "targets": { + "test:e2e": { + "parallelism": false + } + } + } +} diff --git a/e2e/vue-start/start-manifest/playwright.config.ts b/e2e/vue-start/start-manifest/playwright.config.ts new file mode 100644 index 0000000000..b9f835c16a --- /dev/null +++ b/e2e/vue-start/start-manifest/playwright.config.ts @@ -0,0 +1,30 @@ +import { defineConfig, devices } from '@playwright/test' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } + +const PORT = await getTestServerPort(packageJson.name) +const baseURL = `http://localhost:${PORT}` + +export default defineConfig({ + testDir: './tests', + workers: 1, + reporter: [['line']], + + use: { + baseURL, + }, + + webServer: { + command: `pnpm build && PORT=${PORT} pnpm start`, + url: baseURL, + reuseExistingServer: !process.env.CI, + stdout: 'pipe', + }, + + projects: [ + { + name: 'chromium', + use: { ...devices['Desktop Chrome'] }, + }, + ], +}) diff --git a/e2e/vue-start/start-manifest/src/components/AppShell.tsx b/e2e/vue-start/start-manifest/src/components/AppShell.tsx new file mode 100644 index 0000000000..0d57b2d0e3 --- /dev/null +++ b/e2e/vue-start/start-manifest/src/components/AppShell.tsx @@ -0,0 +1,38 @@ +/// +import { ClientOnly, Link, Outlet, linkOptions } from '@tanstack/vue-router' +import styles from '~/styles/root-shell.module.css' + +const ROUTES = linkOptions([ + { to: '/', label: 'home' }, + { to: '/a', label: '/a' }, + { to: '/b', label: '/b' }, + { to: '/lazy-css-static', label: '/lazy-css-static' }, + { to: '/lazy-css-lazy', label: '/lazy-css-lazy' }, + { to: '/r1', label: '/r1' }, + { to: '/r2', label: '/r2' }, + { to: '/shared-a', label: '/shared-a' }, +]) + +export function AppShell() { + return ( +
+ + +
+
+ Start manifest CSS root shell +
+ +
hydrated
+
+ +
+
+ ) +} diff --git a/e2e/vue-start/start-manifest/src/components/SharedCard.tsx b/e2e/vue-start/start-manifest/src/components/SharedCard.tsx new file mode 100644 index 0000000000..c82b2b0ea5 --- /dev/null +++ b/e2e/vue-start/start-manifest/src/components/SharedCard.tsx @@ -0,0 +1,10 @@ +/// +import styles from '~/styles/shared-card.module.css' + +export function SharedCard({ label }: { label: string }) { + return ( +
+ Shared card {label} +
+ ) +} diff --git a/e2e/vue-start/start-manifest/src/components/SharedNestedLayout.tsx b/e2e/vue-start/start-manifest/src/components/SharedNestedLayout.tsx new file mode 100644 index 0000000000..9c1f63f2f9 --- /dev/null +++ b/e2e/vue-start/start-manifest/src/components/SharedNestedLayout.tsx @@ -0,0 +1,34 @@ +/// +import { Link, linkOptions } from '@tanstack/vue-router' +import { defineComponent } from 'vue' +import styles from '~/styles/shared-layout.module.css' + +const ROUTES = linkOptions([ + { to: '/shared-a', label: '/shared-a' }, + { to: '/shared-b', label: '/shared-b' }, + { to: '/shared-c', label: '/shared-c' }, +]) + +export const SharedNestedLayout = defineComponent({ + setup(_, { slots }) { + return () => ( +
+
+ Shared nested layout CSS +
+ + + +
+ {slots.default?.()} +
+
+ ) + }, +}) diff --git a/e2e/vue-start/start-manifest/src/components/SharedWidget.tsx b/e2e/vue-start/start-manifest/src/components/SharedWidget.tsx new file mode 100644 index 0000000000..9074d5b2b0 --- /dev/null +++ b/e2e/vue-start/start-manifest/src/components/SharedWidget.tsx @@ -0,0 +1,15 @@ +/// +import styles from '~/styles/shared-widget.module.css' + +export function SharedWidget() { + return ( +
+
+ Shared widget styles +
+
+ This widget uses CSS shared by a static route and a lazy route. +
+
+ ) +} diff --git a/e2e/vue-start/start-manifest/src/components/SharedWidgetLazy.tsx b/e2e/vue-start/start-manifest/src/components/SharedWidgetLazy.tsx new file mode 100644 index 0000000000..5f1f6410a5 --- /dev/null +++ b/e2e/vue-start/start-manifest/src/components/SharedWidgetLazy.tsx @@ -0,0 +1,5 @@ +import { SharedWidget } from './SharedWidget' + +export default function SharedWidgetLazy() { + return +} diff --git a/e2e/vue-start/start-manifest/src/routeTree.gen.ts b/e2e/vue-start/start-manifest/src/routeTree.gen.ts new file mode 100644 index 0000000000..357d3be62b --- /dev/null +++ b/e2e/vue-start/start-manifest/src/routeTree.gen.ts @@ -0,0 +1,345 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as SharedCRouteImport } from './routes/shared-c' +import { Route as SharedBRouteImport } from './routes/shared-b' +import { Route as SharedARouteImport } from './routes/shared-a' +import { Route as R6RouteImport } from './routes/r6' +import { Route as R5RouteImport } from './routes/r5' +import { Route as R4RouteImport } from './routes/r4' +import { Route as R3RouteImport } from './routes/r3' +import { Route as R2RouteImport } from './routes/r2' +import { Route as R1RouteImport } from './routes/r1' +import { Route as LazyCssStaticRouteImport } from './routes/lazy-css-static' +import { Route as LazyCssLazyRouteImport } from './routes/lazy-css-lazy' +import { Route as BRouteImport } from './routes/b' +import { Route as ARouteImport } from './routes/a' +import { Route as IndexRouteImport } from './routes/index' + +const SharedCRoute = SharedCRouteImport.update({ + id: '/shared-c', + path: '/shared-c', + getParentRoute: () => rootRouteImport, +} as any) +const SharedBRoute = SharedBRouteImport.update({ + id: '/shared-b', + path: '/shared-b', + getParentRoute: () => rootRouteImport, +} as any) +const SharedARoute = SharedARouteImport.update({ + id: '/shared-a', + path: '/shared-a', + getParentRoute: () => rootRouteImport, +} as any) +const R6Route = R6RouteImport.update({ + id: '/r6', + path: '/r6', + getParentRoute: () => rootRouteImport, +} as any) +const R5Route = R5RouteImport.update({ + id: '/r5', + path: '/r5', + getParentRoute: () => rootRouteImport, +} as any) +const R4Route = R4RouteImport.update({ + id: '/r4', + path: '/r4', + getParentRoute: () => rootRouteImport, +} as any) +const R3Route = R3RouteImport.update({ + id: '/r3', + path: '/r3', + getParentRoute: () => rootRouteImport, +} as any) +const R2Route = R2RouteImport.update({ + id: '/r2', + path: '/r2', + getParentRoute: () => rootRouteImport, +} as any) +const R1Route = R1RouteImport.update({ + id: '/r1', + path: '/r1', + getParentRoute: () => rootRouteImport, +} as any) +const LazyCssStaticRoute = LazyCssStaticRouteImport.update({ + id: '/lazy-css-static', + path: '/lazy-css-static', + getParentRoute: () => rootRouteImport, +} as any) +const LazyCssLazyRoute = LazyCssLazyRouteImport.update({ + id: '/lazy-css-lazy', + path: '/lazy-css-lazy', + getParentRoute: () => rootRouteImport, +} as any) +const BRoute = BRouteImport.update({ + id: '/b', + path: '/b', + getParentRoute: () => rootRouteImport, +} as any) +const ARoute = ARouteImport.update({ + id: '/a', + path: '/a', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/a': typeof ARoute + '/b': typeof BRoute + '/lazy-css-lazy': typeof LazyCssLazyRoute + '/lazy-css-static': typeof LazyCssStaticRoute + '/r1': typeof R1Route + '/r2': typeof R2Route + '/r3': typeof R3Route + '/r4': typeof R4Route + '/r5': typeof R5Route + '/r6': typeof R6Route + '/shared-a': typeof SharedARoute + '/shared-b': typeof SharedBRoute + '/shared-c': typeof SharedCRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/a': typeof ARoute + '/b': typeof BRoute + '/lazy-css-lazy': typeof LazyCssLazyRoute + '/lazy-css-static': typeof LazyCssStaticRoute + '/r1': typeof R1Route + '/r2': typeof R2Route + '/r3': typeof R3Route + '/r4': typeof R4Route + '/r5': typeof R5Route + '/r6': typeof R6Route + '/shared-a': typeof SharedARoute + '/shared-b': typeof SharedBRoute + '/shared-c': typeof SharedCRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/a': typeof ARoute + '/b': typeof BRoute + '/lazy-css-lazy': typeof LazyCssLazyRoute + '/lazy-css-static': typeof LazyCssStaticRoute + '/r1': typeof R1Route + '/r2': typeof R2Route + '/r3': typeof R3Route + '/r4': typeof R4Route + '/r5': typeof R5Route + '/r6': typeof R6Route + '/shared-a': typeof SharedARoute + '/shared-b': typeof SharedBRoute + '/shared-c': typeof SharedCRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: + | '/' + | '/a' + | '/b' + | '/lazy-css-lazy' + | '/lazy-css-static' + | '/r1' + | '/r2' + | '/r3' + | '/r4' + | '/r5' + | '/r6' + | '/shared-a' + | '/shared-b' + | '/shared-c' + fileRoutesByTo: FileRoutesByTo + to: + | '/' + | '/a' + | '/b' + | '/lazy-css-lazy' + | '/lazy-css-static' + | '/r1' + | '/r2' + | '/r3' + | '/r4' + | '/r5' + | '/r6' + | '/shared-a' + | '/shared-b' + | '/shared-c' + id: + | '__root__' + | '/' + | '/a' + | '/b' + | '/lazy-css-lazy' + | '/lazy-css-static' + | '/r1' + | '/r2' + | '/r3' + | '/r4' + | '/r5' + | '/r6' + | '/shared-a' + | '/shared-b' + | '/shared-c' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + ARoute: typeof ARoute + BRoute: typeof BRoute + LazyCssLazyRoute: typeof LazyCssLazyRoute + LazyCssStaticRoute: typeof LazyCssStaticRoute + R1Route: typeof R1Route + R2Route: typeof R2Route + R3Route: typeof R3Route + R4Route: typeof R4Route + R5Route: typeof R5Route + R6Route: typeof R6Route + SharedARoute: typeof SharedARoute + SharedBRoute: typeof SharedBRoute + SharedCRoute: typeof SharedCRoute +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/shared-c': { + id: '/shared-c' + path: '/shared-c' + fullPath: '/shared-c' + preLoaderRoute: typeof SharedCRouteImport + parentRoute: typeof rootRouteImport + } + '/shared-b': { + id: '/shared-b' + path: '/shared-b' + fullPath: '/shared-b' + preLoaderRoute: typeof SharedBRouteImport + parentRoute: typeof rootRouteImport + } + '/shared-a': { + id: '/shared-a' + path: '/shared-a' + fullPath: '/shared-a' + preLoaderRoute: typeof SharedARouteImport + parentRoute: typeof rootRouteImport + } + '/r6': { + id: '/r6' + path: '/r6' + fullPath: '/r6' + preLoaderRoute: typeof R6RouteImport + parentRoute: typeof rootRouteImport + } + '/r5': { + id: '/r5' + path: '/r5' + fullPath: '/r5' + preLoaderRoute: typeof R5RouteImport + parentRoute: typeof rootRouteImport + } + '/r4': { + id: '/r4' + path: '/r4' + fullPath: '/r4' + preLoaderRoute: typeof R4RouteImport + parentRoute: typeof rootRouteImport + } + '/r3': { + id: '/r3' + path: '/r3' + fullPath: '/r3' + preLoaderRoute: typeof R3RouteImport + parentRoute: typeof rootRouteImport + } + '/r2': { + id: '/r2' + path: '/r2' + fullPath: '/r2' + preLoaderRoute: typeof R2RouteImport + parentRoute: typeof rootRouteImport + } + '/r1': { + id: '/r1' + path: '/r1' + fullPath: '/r1' + preLoaderRoute: typeof R1RouteImport + parentRoute: typeof rootRouteImport + } + '/lazy-css-static': { + id: '/lazy-css-static' + path: '/lazy-css-static' + fullPath: '/lazy-css-static' + preLoaderRoute: typeof LazyCssStaticRouteImport + parentRoute: typeof rootRouteImport + } + '/lazy-css-lazy': { + id: '/lazy-css-lazy' + path: '/lazy-css-lazy' + fullPath: '/lazy-css-lazy' + preLoaderRoute: typeof LazyCssLazyRouteImport + parentRoute: typeof rootRouteImport + } + '/b': { + id: '/b' + path: '/b' + fullPath: '/b' + preLoaderRoute: typeof BRouteImport + parentRoute: typeof rootRouteImport + } + '/a': { + id: '/a' + path: '/a' + fullPath: '/a' + preLoaderRoute: typeof ARouteImport + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + ARoute: ARoute, + BRoute: BRoute, + LazyCssLazyRoute: LazyCssLazyRoute, + LazyCssStaticRoute: LazyCssStaticRoute, + R1Route: R1Route, + R2Route: R2Route, + R3Route: R3Route, + R4Route: R4Route, + R5Route: R5Route, + R6Route: R6Route, + SharedARoute: SharedARoute, + SharedBRoute: SharedBRoute, + SharedCRoute: SharedCRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() + +import type { getRouter } from './router.tsx' +import type { createStart } from '@tanstack/vue-start' +declare module '@tanstack/vue-start' { + interface Register { + ssr: true + router: Awaited> + } +} diff --git a/e2e/vue-start/start-manifest/src/router.tsx b/e2e/vue-start/start-manifest/src/router.tsx new file mode 100644 index 0000000000..d7cd8e8284 --- /dev/null +++ b/e2e/vue-start/start-manifest/src/router.tsx @@ -0,0 +1,18 @@ +import { createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +export const getRouter = () => { + const router = createRouter({ + routeTree, + scrollRestoration: true, + defaultPreload: 'intent', + }) + + return router +} + +declare module '@tanstack/vue-router' { + interface Register { + router: ReturnType + } +} diff --git a/e2e/vue-start/start-manifest/src/routes/__root.tsx b/e2e/vue-start/start-manifest/src/routes/__root.tsx new file mode 100644 index 0000000000..b62d37c0f0 --- /dev/null +++ b/e2e/vue-start/start-manifest/src/routes/__root.tsx @@ -0,0 +1,35 @@ +/// +import { + Body, + HeadContent, + Html, + Scripts, + createRootRoute, +} from '@tanstack/vue-router' +import { AppShell } from '~/components/AppShell' + +export const Route = createRootRoute({ + head: () => ({ + meta: [ + { charSet: 'utf-8' }, + { name: 'viewport', content: 'width=device-width, initial-scale=1' }, + { title: 'TanStack Start Manifest Bloat E2E' }, + ], + }), + component: AppShell, + shellComponent: RootDocument, +}) + +function RootDocument(_: unknown, { slots }: { slots: any }) { + return ( + + + + + + {slots.default?.()} + + + + ) +} diff --git a/e2e/vue-start/start-manifest/src/routes/a.tsx b/e2e/vue-start/start-manifest/src/routes/a.tsx new file mode 100644 index 0000000000..e53399273d --- /dev/null +++ b/e2e/vue-start/start-manifest/src/routes/a.tsx @@ -0,0 +1,18 @@ +/// +import { createFileRoute } from '@tanstack/vue-router' +import { SharedCard } from '~/components/SharedCard' +import styles from '~/styles/page-a.module.css' + +export const Route = createFileRoute('/a')({ + component: RouteComponent, +}) + +function RouteComponent() { + return ( +
+

Route /a

+

Route /a keeps the shared card styled.

+ +
+ ) +} diff --git a/e2e/vue-start/start-manifest/src/routes/b.tsx b/e2e/vue-start/start-manifest/src/routes/b.tsx new file mode 100644 index 0000000000..cb989a257f --- /dev/null +++ b/e2e/vue-start/start-manifest/src/routes/b.tsx @@ -0,0 +1,18 @@ +/// +import { createFileRoute } from '@tanstack/vue-router' +import { SharedCard } from '~/components/SharedCard' +import styles from '~/styles/page-b.module.css' + +export const Route = createFileRoute('/b')({ + component: RouteComponent, +}) + +function RouteComponent() { + return ( +
+

Route /b

+

Route /b should keep the shared card stylesheet after nav.

+ +
+ ) +} diff --git a/e2e/vue-start/start-manifest/src/routes/index.tsx b/e2e/vue-start/start-manifest/src/routes/index.tsx new file mode 100644 index 0000000000..728cc55e88 --- /dev/null +++ b/e2e/vue-start/start-manifest/src/routes/index.tsx @@ -0,0 +1,16 @@ +import { createFileRoute } from '@tanstack/vue-router' + +export const Route = createFileRoute('/')({ + component: HomeRoute, +}) + +function HomeRoute() { + return ( +
+

Start manifest fixture

+

+ Use this page to navigate between CSS module routes. +

+
+ ) +} diff --git a/e2e/vue-start/start-manifest/src/routes/lazy-css-lazy.tsx b/e2e/vue-start/start-manifest/src/routes/lazy-css-lazy.tsx new file mode 100644 index 0000000000..0db0845425 --- /dev/null +++ b/e2e/vue-start/start-manifest/src/routes/lazy-css-lazy.tsx @@ -0,0 +1,31 @@ +import { createFileRoute } from '@tanstack/vue-router' +import { Suspense, defineAsyncComponent } from 'vue' + +const LazySharedWidget = defineAsyncComponent( + () => import('~/components/SharedWidgetLazy'), +) + +export const Route = createFileRoute('/lazy-css-lazy')({ + component: LazyCssLazyRoute, +}) + +function LazyCssLazyRoute() { + return ( +
+

Lazy CSS Repro - Lazy Route

+

+ This route renders the same widget through a lazy component so the CSS + only exists behind a dynamic import boundary. +

+ + + {{ + default: () => , + fallback: () => ( +
Loading...
+ ), + }} +
+
+ ) +} diff --git a/e2e/vue-start/start-manifest/src/routes/lazy-css-static.tsx b/e2e/vue-start/start-manifest/src/routes/lazy-css-static.tsx new file mode 100644 index 0000000000..2a8352e67e --- /dev/null +++ b/e2e/vue-start/start-manifest/src/routes/lazy-css-static.tsx @@ -0,0 +1,24 @@ +import { ClientOnly, createFileRoute } from '@tanstack/vue-router' +import { SharedWidget } from '~/components/SharedWidget' + +export const Route = createFileRoute('/lazy-css-static')({ + component: LazyCssStaticRoute, +}) + +function LazyCssStaticRoute() { + return ( +
+

Lazy CSS Repro - Static Route

+

+ This route statically imports the shared widget so its CSS is present in + the SSR head. +

+ + +
hydrated
+
+ + +
+ ) +} diff --git a/e2e/vue-start/start-manifest/src/routes/r1.tsx b/e2e/vue-start/start-manifest/src/routes/r1.tsx new file mode 100644 index 0000000000..b35bec54e3 --- /dev/null +++ b/e2e/vue-start/start-manifest/src/routes/r1.tsx @@ -0,0 +1,18 @@ +/// +import { createFileRoute } from '@tanstack/vue-router' +import styles from '~/styles/route-one.module.css' + +export const Route = createFileRoute('/r1')({ + component: RouteComponent, +}) + +function RouteComponent() { + return ( +
+

Route /r1

+
+ Route /r1 CSS module styling +
+
+ ) +} diff --git a/e2e/vue-start/start-manifest/src/routes/r2.tsx b/e2e/vue-start/start-manifest/src/routes/r2.tsx new file mode 100644 index 0000000000..eadd952f98 --- /dev/null +++ b/e2e/vue-start/start-manifest/src/routes/r2.tsx @@ -0,0 +1,18 @@ +/// +import { createFileRoute } from '@tanstack/vue-router' +import styles from '~/styles/route-two.module.css' + +export const Route = createFileRoute('/r2')({ + component: RouteComponent, +}) + +function RouteComponent() { + return ( +
+

Route /r2

+
+ Route /r2 CSS module styling +
+
+ ) +} diff --git a/e2e/vue-start/start-manifest/src/routes/r3.tsx b/e2e/vue-start/start-manifest/src/routes/r3.tsx new file mode 100644 index 0000000000..a5a486cfaa --- /dev/null +++ b/e2e/vue-start/start-manifest/src/routes/r3.tsx @@ -0,0 +1,5 @@ +import { createFileRoute } from '@tanstack/vue-router' + +export const Route = createFileRoute('/r3')({ + component: () =>
Route /r3
, +}) diff --git a/e2e/vue-start/start-manifest/src/routes/r4.tsx b/e2e/vue-start/start-manifest/src/routes/r4.tsx new file mode 100644 index 0000000000..9739966d02 --- /dev/null +++ b/e2e/vue-start/start-manifest/src/routes/r4.tsx @@ -0,0 +1,5 @@ +import { createFileRoute } from '@tanstack/vue-router' + +export const Route = createFileRoute('/r4')({ + component: () =>
Route /r4
, +}) diff --git a/e2e/vue-start/start-manifest/src/routes/r5.tsx b/e2e/vue-start/start-manifest/src/routes/r5.tsx new file mode 100644 index 0000000000..7c081e29a6 --- /dev/null +++ b/e2e/vue-start/start-manifest/src/routes/r5.tsx @@ -0,0 +1,5 @@ +import { createFileRoute } from '@tanstack/vue-router' + +export const Route = createFileRoute('/r5')({ + component: () =>
Route /r5
, +}) diff --git a/e2e/vue-start/start-manifest/src/routes/r6.tsx b/e2e/vue-start/start-manifest/src/routes/r6.tsx new file mode 100644 index 0000000000..c56c2afda3 --- /dev/null +++ b/e2e/vue-start/start-manifest/src/routes/r6.tsx @@ -0,0 +1,5 @@ +import { createFileRoute } from '@tanstack/vue-router' + +export const Route = createFileRoute('/r6')({ + component: () =>
Route /r6
, +}) diff --git a/e2e/vue-start/start-manifest/src/routes/shared-a.tsx b/e2e/vue-start/start-manifest/src/routes/shared-a.tsx new file mode 100644 index 0000000000..e7253a94ac --- /dev/null +++ b/e2e/vue-start/start-manifest/src/routes/shared-a.tsx @@ -0,0 +1,14 @@ +import { createFileRoute } from '@tanstack/vue-router' +import { SharedNestedLayout } from '~/components/SharedNestedLayout' + +export const Route = createFileRoute('/shared-a')({ + component: RouteComponent, +}) + +function RouteComponent() { + return ( + +
Shared route A
+
+ ) +} diff --git a/e2e/vue-start/start-manifest/src/routes/shared-b.tsx b/e2e/vue-start/start-manifest/src/routes/shared-b.tsx new file mode 100644 index 0000000000..ed02b3429b --- /dev/null +++ b/e2e/vue-start/start-manifest/src/routes/shared-b.tsx @@ -0,0 +1,14 @@ +import { createFileRoute } from '@tanstack/vue-router' +import { SharedNestedLayout } from '~/components/SharedNestedLayout' + +export const Route = createFileRoute('/shared-b')({ + component: RouteComponent, +}) + +function RouteComponent() { + return ( + +
Shared route B
+
+ ) +} diff --git a/e2e/vue-start/start-manifest/src/routes/shared-c.tsx b/e2e/vue-start/start-manifest/src/routes/shared-c.tsx new file mode 100644 index 0000000000..e395b33ed5 --- /dev/null +++ b/e2e/vue-start/start-manifest/src/routes/shared-c.tsx @@ -0,0 +1,14 @@ +import { createFileRoute } from '@tanstack/vue-router' +import { SharedNestedLayout } from '~/components/SharedNestedLayout' + +export const Route = createFileRoute('/shared-c')({ + component: RouteComponent, +}) + +function RouteComponent() { + return ( + +
Shared route C
+
+ ) +} diff --git a/e2e/vue-start/start-manifest/src/styles/page-a.module.css b/e2e/vue-start/start-manifest/src/styles/page-a.module.css new file mode 100644 index 0000000000..7ed4301097 --- /dev/null +++ b/e2e/vue-start/start-manifest/src/styles/page-a.module.css @@ -0,0 +1,10 @@ +.page { + padding: 1rem; + min-height: 12rem; + background: rgb(240, 253, 244); + border: 4px solid rgb(22, 163, 74); +} + +.title { + color: rgb(21, 128, 61); +} diff --git a/e2e/vue-start/start-manifest/src/styles/page-b.module.css b/e2e/vue-start/start-manifest/src/styles/page-b.module.css new file mode 100644 index 0000000000..93d1d39a01 --- /dev/null +++ b/e2e/vue-start/start-manifest/src/styles/page-b.module.css @@ -0,0 +1,10 @@ +.page { + padding: 1rem; + min-height: 12rem; + background: rgb(239, 246, 255); + border: 4px solid rgb(37, 99, 235); +} + +.title { + color: rgb(29, 78, 216); +} diff --git a/e2e/vue-start/start-manifest/src/styles/root-shell.module.css b/e2e/vue-start/start-manifest/src/styles/root-shell.module.css new file mode 100644 index 0000000000..e7bece8664 --- /dev/null +++ b/e2e/vue-start/start-manifest/src/styles/root-shell.module.css @@ -0,0 +1,37 @@ +.shell { + font-family: + -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; + min-height: 100vh; + background: rgb(248, 250, 252); + color: rgb(15, 23, 42); +} + +.nav { + display: flex; + flex-wrap: wrap; + gap: 0.75rem; + padding: 1rem; + border-bottom: 1px solid rgb(226, 232, 240); + background: white; +} + +.nav a { + color: rgb(37, 99, 235); + text-decoration: none; +} + +.content { + max-width: 760px; + margin: 0 auto; + padding: 1.5rem 1rem 3rem; +} + +.rootBadge { + display: inline-block; + margin-bottom: 1rem; + padding: 0.375rem 0.75rem; + border-radius: 9999px; + background: rgb(220, 252, 231); + color: rgb(22, 101, 52); + font-weight: 700; +} diff --git a/e2e/vue-start/start-manifest/src/styles/route-one.module.css b/e2e/vue-start/start-manifest/src/styles/route-one.module.css new file mode 100644 index 0000000000..623d03e6a3 --- /dev/null +++ b/e2e/vue-start/start-manifest/src/styles/route-one.module.css @@ -0,0 +1,7 @@ +.card { + padding: 1rem; + border-radius: 0.75rem; + background: rgb(239, 246, 255); + color: rgb(30, 64, 175); + border: 2px solid rgb(96, 165, 250); +} diff --git a/e2e/vue-start/start-manifest/src/styles/route-two.module.css b/e2e/vue-start/start-manifest/src/styles/route-two.module.css new file mode 100644 index 0000000000..66ed355711 --- /dev/null +++ b/e2e/vue-start/start-manifest/src/styles/route-two.module.css @@ -0,0 +1,7 @@ +.card { + padding: 1rem; + border-radius: 0.75rem; + background: rgb(250, 245, 255); + color: rgb(126, 34, 206); + border: 2px solid rgb(192, 132, 252); +} diff --git a/e2e/vue-start/start-manifest/src/styles/shared-card.module.css b/e2e/vue-start/start-manifest/src/styles/shared-card.module.css new file mode 100644 index 0000000000..2aa5a6ac17 --- /dev/null +++ b/e2e/vue-start/start-manifest/src/styles/shared-card.module.css @@ -0,0 +1,8 @@ +.card { + margin-top: 1rem; + padding: 1.5rem; + border-radius: 0.75rem; + background: rgb(252, 231, 243); + border: 2px solid rgb(190, 24, 93); + color: rgb(157, 23, 77); +} diff --git a/e2e/vue-start/start-manifest/src/styles/shared-layout.module.css b/e2e/vue-start/start-manifest/src/styles/shared-layout.module.css new file mode 100644 index 0000000000..6025a1da06 --- /dev/null +++ b/e2e/vue-start/start-manifest/src/styles/shared-layout.module.css @@ -0,0 +1,16 @@ +.layout { + padding: 1rem; + border-radius: 0.75rem; + background: rgb(255, 251, 235); + border: 2px solid rgb(245, 158, 11); +} + +.heading { + color: rgb(180, 83, 9); + font-weight: 700; + margin-bottom: 0.5rem; +} + +.body { + color: rgb(146, 64, 14); +} diff --git a/e2e/vue-start/start-manifest/src/styles/shared-widget.module.css b/e2e/vue-start/start-manifest/src/styles/shared-widget.module.css new file mode 100644 index 0000000000..ed197cddb0 --- /dev/null +++ b/e2e/vue-start/start-manifest/src/styles/shared-widget.module.css @@ -0,0 +1,17 @@ +.widget { + margin-top: 1rem; + padding: 1rem; + border-top: 4px solid rgb(249, 115, 22); + border-radius: 0.75rem; + background: rgb(255, 247, 237); +} + +.title { + font-weight: 700; + color: rgb(154, 52, 18); +} + +.content { + margin-top: 0.5rem; + color: rgb(124, 45, 18); +} diff --git a/e2e/vue-start/start-manifest/tests/start-manifest.spec.ts b/e2e/vue-start/start-manifest/tests/start-manifest.spec.ts new file mode 100644 index 0000000000..6d13e25764 --- /dev/null +++ b/e2e/vue-start/start-manifest/tests/start-manifest.spec.ts @@ -0,0 +1,457 @@ +import { expect } from '@playwright/test' +import { test } from '@tanstack/router-e2e-utils' +import type { Page } from '@playwright/test' +import { readdir } from 'node:fs/promises' +import path from 'node:path' +import { pathToFileURL } from 'node:url' + +const ROOT_SHELL_COLOR = 'rgb(22, 101, 52)' +const ROUTE_ONE_COLOR = 'rgb(30, 64, 175)' +const ROUTE_TWO_COLOR = 'rgb(126, 34, 206)' +const SHARED_CARD_BG = 'rgb(252, 231, 243)' +const SHARED_WIDGET_BG = 'rgb(255, 247, 237)' +const SHARED_WIDGET_BORDER = 'rgb(249, 115, 22)' + +const buildUrl = (baseURL: string, pathname: string) => + baseURL.replace(/\/$/, '') + pathname + +async function getColor(testId: string, page: Page) { + return page + .getByTestId(testId) + .evaluate((element) => getComputedStyle(element).color) +} + +async function getBackgroundColor(testId: string, page: Page) { + return page + .getByTestId(testId) + .evaluate((element) => getComputedStyle(element).backgroundColor) +} + +function getStylesheetHrefsFromHtml(html: string) { + return Array.from( + html.matchAll(/]+rel="stylesheet"[^>]+href="([^"]+)"/g), + (match) => match[1]!, + ) +} + +async function getHeadStylesheetHrefs(page: Page) { + return page.locator('head link[rel="stylesheet"]').evaluateAll((links) => { + return links.map( + (link) => (link as HTMLLinkElement).getAttribute('href') || '', + ) + }) +} + +function hasMatchingStylesheetHref(hrefs: Array, pattern: string) { + return hrefs.some((href) => href.includes(pattern)) +} + +function countMatchingStylesheetHrefs(hrefs: Array, pattern: string) { + return hrefs.filter((href) => href.includes(pattern)).length +} + +async function loadBuiltStartManifest() { + const serverDir = path.resolve(import.meta.dirname, '../dist/server/assets') + const entries = await readdir(serverDir) + const manifestFile = entries.find( + (entry) => + entry.startsWith('_tanstack-start-manifest_v-') && entry.endsWith('.js'), + ) + + expect(manifestFile).toBeTruthy() + + const moduleUrl = `${pathToFileURL(path.join(serverDir, manifestFile!)).href}?t=${Date.now()}` + const manifestModule = await import(moduleUrl) + + return manifestModule.tsrStartManifest() as { + routes: Record }> + } +} + +async function expectDirectEntry({ + page, + request, + baseURL, + pathname, + expectedVisibleTestId, + expectedAbsentTestId, + expectedStylesheetPattern, + unexpectedStylesheetPattern, + expectedColorTestId, + expectedColor, +}: { + page: Page + request: { + get: (url: string) => Promise<{ ok(): boolean; text(): Promise }> + } + baseURL: string + pathname: string + expectedVisibleTestId: string + expectedAbsentTestId: string + expectedStylesheetPattern: string + unexpectedStylesheetPattern: string + expectedColorTestId: string + expectedColor: string +}) { + const url = buildUrl(baseURL, pathname) + const response = await request.get(url) + const ssrHtml = await response.text() + + expect(response.ok()).toBe(true) + expect(ssrHtml).toContain('root-shell-marker') + expect(ssrHtml).toContain(expectedVisibleTestId) + expect(ssrHtml).not.toContain(expectedAbsentTestId) + + const stylesheetLinks = getStylesheetHrefsFromHtml(ssrHtml) + + expect( + countMatchingStylesheetHrefs(stylesheetLinks, expectedStylesheetPattern), + ).toBe(1) + expect( + countMatchingStylesheetHrefs(stylesheetLinks, unexpectedStylesheetPattern), + ).toBe(0) + expect(stylesheetLinks).toHaveLength(2) + + await page.goto(url) + await expect(page.getByTestId(expectedVisibleTestId)).toBeVisible() + await expect(page.getByTestId('hydration-marker')).toBeVisible() + + await expect + .poll(async () => { + const hrefs = await getHeadStylesheetHrefs(page) + return hasMatchingStylesheetHref(hrefs, expectedStylesheetPattern) + }) + .toBe(true) + await expect + .poll(async () => { + const hrefs = await getHeadStylesheetHrefs(page) + return countMatchingStylesheetHrefs(hrefs, unexpectedStylesheetPattern) + }) + .toBe(0) + + await expect + .poll(() => getColor('root-shell-marker', page)) + .toBe(ROOT_SHELL_COLOR) + await expect + .poll(() => getColor(expectedColorTestId, page)) + .toBe(expectedColor) +} + +test('SSR and client navigation keep CSS module styles correct without hydration errors', async ({ + page, + baseURL, + request, +}) => { + const routeOneUrl = buildUrl(baseURL!, '/r1') + const response = await request.get(routeOneUrl) + const ssrHtml = await response.text() + + expect(response.ok()).toBe(true) + expect(ssrHtml).toContain('root-shell-marker') + expect(ssrHtml).toContain('route-r1-card') + expect(ssrHtml).not.toContain('route-r2-card') + + const stylesheetLinks = getStylesheetHrefsFromHtml(ssrHtml) + + expect(countMatchingStylesheetHrefs(stylesheetLinks, 'r1-')).toBe(1) + expect(countMatchingStylesheetHrefs(stylesheetLinks, 'r2-')).toBe(0) + expect(stylesheetLinks).toHaveLength(2) + + await page.goto(routeOneUrl) + + await expect(page.getByTestId('route-r1-card')).toBeVisible() + await expect(page.getByTestId('hydration-marker')).toBeVisible() + + await expect + .poll(async () => { + const hrefs = await getHeadStylesheetHrefs(page) + return hasMatchingStylesheetHref(hrefs, 'r1-') + }) + .toBe(true) + await expect + .poll(async () => { + const hrefs = await getHeadStylesheetHrefs(page) + return countMatchingStylesheetHrefs(hrefs, 'r2-') + }) + .toBe(0) + + await expect + .poll(() => getColor('root-shell-marker', page)) + .toBe(ROOT_SHELL_COLOR) + await expect.poll(() => getColor('route-r1-card', page)).toBe(ROUTE_ONE_COLOR) + + await page.getByTestId('nav-/r2').click() + await page.waitForURL('**/r2') + await expect(page.getByTestId('route-r2-card')).toBeVisible() + + await expect + .poll(async () => { + const hrefs = await getHeadStylesheetHrefs(page) + return hasMatchingStylesheetHref(hrefs, 'r2-') + }) + .toBe(true) + + await expect + .poll(() => getColor('root-shell-marker', page)) + .toBe(ROOT_SHELL_COLOR) + await expect.poll(() => getColor('route-r2-card', page)).toBe(ROUTE_TWO_COLOR) + + await page.getByTestId('nav-/r1').click() + await page.waitForURL('**/r1') + await expect(page.getByTestId('route-r1-card')).toBeVisible() + + await expect + .poll(async () => { + const hrefs = await getHeadStylesheetHrefs(page) + return hasMatchingStylesheetHref(hrefs, 'r1-') + }) + .toBe(true) + + await expect + .poll(() => getColor('root-shell-marker', page)) + .toBe(ROOT_SHELL_COLOR) + await expect.poll(() => getColor('route-r1-card', page)).toBe(ROUTE_ONE_COLOR) +}) + +test('direct SSR entry on /r2 only includes its stylesheet and hydrates cleanly', async ({ + page, + baseURL, + request, +}) => { + await expectDirectEntry({ + page, + request, + baseURL: baseURL!, + pathname: '/r2', + expectedVisibleTestId: 'route-r2-card', + expectedAbsentTestId: 'route-r1-card', + expectedStylesheetPattern: 'r2-', + unexpectedStylesheetPattern: 'r1-', + expectedColorTestId: 'route-r2-card', + expectedColor: ROUTE_TWO_COLOR, + }) +}) + +test('direct SSR entries on different route-css pages stay isolated', async ({ + page, + baseURL, + request, +}) => { + await expectDirectEntry({ + page, + request, + baseURL: baseURL!, + pathname: '/r2', + expectedVisibleTestId: 'route-r2-card', + expectedAbsentTestId: 'route-r1-card', + expectedStylesheetPattern: 'r2-', + unexpectedStylesheetPattern: 'r1-', + expectedColorTestId: 'route-r2-card', + expectedColor: ROUTE_TWO_COLOR, + }) + + await expectDirectEntry({ + page, + request, + baseURL: baseURL!, + pathname: '/r1', + expectedVisibleTestId: 'route-r1-card', + expectedAbsentTestId: 'route-r2-card', + expectedStylesheetPattern: 'r1-', + unexpectedStylesheetPattern: 'r2-', + expectedColorTestId: 'route-r1-card', + expectedColor: ROUTE_ONE_COLOR, + }) +}) + +test('home route only renders the root stylesheet and no route-specific CSS', async ({ + page, + baseURL, + request, +}) => { + const homeUrl = buildUrl(baseURL!, '/') + const response = await request.get(homeUrl) + const ssrHtml = await response.text() + + expect(response.ok()).toBe(true) + expect(ssrHtml).toContain('root-shell-marker') + expect(ssrHtml).toContain('home-copy') + expect(ssrHtml).not.toContain('route-r1-card') + expect(ssrHtml).not.toContain('route-r2-card') + + const stylesheetLinks = getStylesheetHrefsFromHtml(ssrHtml) + + expect(countMatchingStylesheetHrefs(stylesheetLinks, 'r1-')).toBe(0) + expect(countMatchingStylesheetHrefs(stylesheetLinks, 'r2-')).toBe(0) + expect(stylesheetLinks).toHaveLength(1) + + await page.goto(homeUrl) + await expect(page.getByTestId('home-copy')).toBeVisible() + await expect(page.getByTestId('hydration-marker')).toBeVisible() + + await expect + .poll(async () => { + const hrefs = await getHeadStylesheetHrefs(page) + return countMatchingStylesheetHrefs(hrefs, 'r1-') + }) + .toBe(0) + await expect + .poll(async () => { + const hrefs = await getHeadStylesheetHrefs(page) + return countMatchingStylesheetHrefs(hrefs, 'r2-') + }) + .toBe(0) + + await expect + .poll(() => getColor('root-shell-marker', page)) + .toBe(ROOT_SHELL_COLOR) +}) + +test('built start manifest preserves shared layout asset identity across sibling routes', async ({ + page, + baseURL, +}) => { + await page.goto(buildUrl(baseURL!, '/shared-a')) + await expect(page.getByTestId('shared-a-card')).toBeVisible() + + const manifest = await loadBuiltStartManifest() + + const sharedAAsset = manifest.routes['/shared-a']?.assets?.[0] + const sharedBAsset = manifest.routes['/shared-b']?.assets?.[0] + const sharedCAsset = manifest.routes['/shared-c']?.assets?.[0] + + expect(sharedAAsset).toBeTruthy() + expect(sharedAAsset).toBe(sharedBAsset) + expect(sharedBAsset).toBe(sharedCAsset) +}) + +test('shared CSS chunk persists across client-side nav', async ({ + page, + baseURL, +}) => { + await page.goto(buildUrl(baseURL!, '/a')) + + await expect(page.getByTestId('page-a')).toBeVisible() + await expect(page.getByTestId('shared-card')).toBeVisible() + await expect + .poll(() => getBackgroundColor('shared-card', page)) + .toBe(SHARED_CARD_BG) + await expect( + page.locator('head link[rel="stylesheet"][href*="SharedCard"]'), + ).toHaveCount(1) + + await page.getByTestId('nav-/b').click() + await page.waitForURL('**/b') + await expect(page.getByTestId('page-b')).toBeVisible() + + await expect( + page.locator('head link[rel="stylesheet"][href*="SharedCard"]'), + ).toHaveCount(1) + await expect + .poll(() => getBackgroundColor('shared-card', page)) + .toBe(SHARED_CARD_BG) +}) + +test('shared widget CSS stays applied when navigating from static to lazy route', async ({ + page, + baseURL, +}) => { + await page.goto(buildUrl(baseURL!, '/lazy-css-static')) + + const widget = page.getByTestId('shared-widget') + await expect(widget).toBeVisible() + expect(await getBackgroundColor('shared-widget', page)).toBe(SHARED_WIDGET_BG) + expect( + await widget.evaluate( + (element) => getComputedStyle(element).borderTopColor, + ), + ).toBe(SHARED_WIDGET_BORDER) + + await expect(page.getByTestId('lazy-css-static-hydrated')).toBeVisible() + + await page.getByTestId('nav-/lazy-css-lazy').click() + await page.waitForURL('**/lazy-css-lazy') + await expect(page.getByTestId('lazy-css-lazy-heading')).toBeVisible() + + await expect + .poll(() => getBackgroundColor('shared-widget', page), { + timeout: 5_000, + }) + .toBe(SHARED_WIDGET_BG) +}) + +test('shared widget CSS stays applied when navigating from lazy to static route', async ({ + page, + baseURL, +}) => { + await page.goto(buildUrl(baseURL!, '/lazy-css-lazy')) + await expect(page.getByTestId('lazy-css-lazy-heading')).toBeVisible() + + await expect + .poll(() => getBackgroundColor('shared-widget', page), { + timeout: 5_000, + }) + .toBe(SHARED_WIDGET_BG) + + await page.getByTestId('nav-/lazy-css-static').click() + await page.waitForURL('**/lazy-css-static') + + const widget = page.getByTestId('shared-widget') + await expect(widget).toBeVisible() + await expect + .poll(() => getBackgroundColor('shared-widget', page), { + timeout: 5_000, + }) + .toBe(SHARED_WIDGET_BG) + expect( + await widget.evaluate( + (element) => getComputedStyle(element).borderTopColor, + ), + ).toBe(SHARED_WIDGET_BORDER) +}) + +test('shared widget CSS is applied on direct navigation to lazy route', async ({ + page, + baseURL, +}) => { + await page.goto(buildUrl(baseURL!, '/lazy-css-lazy')) + await expect(page.getByTestId('lazy-css-lazy-heading')).toBeVisible() + + const widget = page.getByTestId('shared-widget') + await expect(widget).toBeVisible() + + await expect + .poll(() => getBackgroundColor('shared-widget', page), { + timeout: 5_000, + }) + .toBe(SHARED_WIDGET_BG) + expect( + await widget.evaluate( + (element) => getComputedStyle(element).borderTopColor, + ), + ).toBe(SHARED_WIDGET_BORDER) +}) + +test('shared widget CSS persists after navigating away from lazy and back', async ({ + page, + baseURL, +}) => { + await page.goto(buildUrl(baseURL!, '/lazy-css-static')) + await expect(page.getByTestId('lazy-css-static-hydrated')).toBeVisible() + + await page.getByTestId('nav-/lazy-css-lazy').click() + await page.waitForURL('**/lazy-css-lazy') + await expect(page.getByTestId('shared-widget')).toBeVisible() + + await page.getByTestId('nav-home').click() + await page.waitForURL(/\/([^/]*)(\/)?($|\?)/) + + await page.getByTestId('nav-/lazy-css-lazy').click() + await page.waitForURL('**/lazy-css-lazy') + + await expect + .poll(() => getBackgroundColor('shared-widget', page), { + timeout: 5_000, + }) + .toBe(SHARED_WIDGET_BG) +}) diff --git a/e2e/vue-start/start-manifest/tsconfig.json b/e2e/vue-start/start-manifest/tsconfig.json new file mode 100644 index 0000000000..44a68ebf56 --- /dev/null +++ b/e2e/vue-start/start-manifest/tsconfig.json @@ -0,0 +1,23 @@ +{ + "include": ["**/*.ts", "**/*.tsx"], + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "jsx": "preserve", + "jsxImportSource": "vue", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["DOM", "DOM.Iterable", "ES2022"], + "isolatedModules": true, + "resolveJsonModule": true, + "skipLibCheck": true, + "target": "ES2024", + "allowJs": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "~/*": ["./src/*"] + }, + "noEmit": true, + "types": ["vite/client"] + } +} diff --git a/e2e/vue-start/start-manifest/vite.config.ts b/e2e/vue-start/start-manifest/vite.config.ts new file mode 100644 index 0000000000..f1102cffab --- /dev/null +++ b/e2e/vue-start/start-manifest/vite.config.ts @@ -0,0 +1,13 @@ +import { defineConfig } from 'vite' +import { tanstackStart } from '@tanstack/vue-start/plugin/vite' +import vueJsx from '@vitejs/plugin-vue-jsx' + +export default defineConfig({ + server: { + port: 3000, + }, + resolve: { + tsconfigPaths: true, + }, + plugins: [tanstackStart({ srcDirectory: 'src' }), vueJsx()], +}) diff --git a/packages/react-router/src/Asset.tsx b/packages/react-router/src/Asset.tsx index a1018ac93b..5ad2e01516 100644 --- a/packages/react-router/src/Asset.tsx +++ b/packages/react-router/src/Asset.tsx @@ -28,7 +28,17 @@ export function Asset({ case 'meta': return case 'link': - return + return ( + + ) case 'style': return ( case 'script': return @@ -26,6 +34,29 @@ export function Asset({ } } +function InlineCssStyle({ + attrs, + children, +}: { + attrs?: Record + children?: RouterManagedTag['children'] +}) { + const isInlineCssPlaceholder = children === undefined + const html = isInlineCssPlaceholder + ? typeof document === 'undefined' + ? '' + : (document.querySelector( + `style[${INLINE_CSS_HYDRATION_ATTR}]`, + )?.textContent ?? '') + : (children ?? '') + + return ( + + ) +} + interface ScriptAttrs { [key: string]: string | boolean | undefined src?: string diff --git a/packages/solid-router/src/headContentUtils.tsx b/packages/solid-router/src/headContentUtils.tsx index 853daa5c3b..7886ba4696 100644 --- a/packages/solid-router/src/headContentUtils.tsx +++ b/packages/solid-router/src/headContentUtils.tsx @@ -2,6 +2,7 @@ import * as Solid from 'solid-js' import { escapeHtml, getAssetCrossOrigin, + isInlinableStylesheet, replaceEqualDeep, resolveManifestAssetLink, } from '@tanstack/router-core' @@ -117,20 +118,42 @@ export const useTags = (assetCrossOrigin?: AssetCrossOriginConfig) => { .map((match) => manifest?.routes[match.routeId]?.assets ?? []) .filter(Boolean) .flat(1) - .filter((asset) => asset.tag === 'link') - .map( - (asset) => - ({ - tag: 'link', - attrs: { - ...asset.attrs, - crossOrigin: - getAssetCrossOrigin(assetCrossOrigin, 'stylesheet') ?? - asset.attrs?.crossOrigin, - nonce, + .flatMap((asset): Array => { + if (asset.tag === 'link') { + if (isInlinableStylesheet(manifest, asset)) { + return [] + } + + return [ + { + tag: 'link', + attrs: { + ...asset.attrs, + crossOrigin: + getAssetCrossOrigin(assetCrossOrigin, 'stylesheet') ?? + asset.attrs?.crossOrigin, + nonce, + }, }, - }) satisfies RouterManagedTag, - ) + ] + } + + if (asset.tag === 'style') { + return [ + { + tag: 'style', + attrs: { + ...asset.attrs, + nonce, + }, + children: asset.children, + ...(asset.inlineCss ? { inlineCss: true as const } : {}), + }, + ] + } + + return [] + }) return [...constructed, ...assets] }) diff --git a/packages/start-plugin-core/package.json b/packages/start-plugin-core/package.json index ed9335ec4b..8e70f34986 100644 --- a/packages/start-plugin-core/package.json +++ b/packages/start-plugin-core/package.json @@ -98,6 +98,7 @@ "seroval": "^1.5.0", "cheerio": "^1.0.0", "exsolve": "^1.0.7", + "lightningcss": "^1.32.0", "pathe": "^2.0.3", "picomatch": "^4.0.3", "srvx": "^0.11.9", diff --git a/packages/start-plugin-core/src/rsbuild/normalized-client-build.ts b/packages/start-plugin-core/src/rsbuild/normalized-client-build.ts index bc0234095d..b349b68040 100644 --- a/packages/start-plugin-core/src/rsbuild/normalized-client-build.ts +++ b/packages/start-plugin-core/src/rsbuild/normalized-client-build.ts @@ -1,4 +1,5 @@ import { tsrSplit } from '@tanstack/router-plugin' +import { getCssAssetSource } from '../start-manifest-plugin/inlineCss' import { RSBUILD_ENVIRONMENT_NAMES } from './planning' import type { RsbuildPluginAPI, Rspack } from '@rsbuild/core' import type { NormalizedClientBuild, NormalizedClientChunk } from '../types' @@ -162,6 +163,7 @@ export function normalizeRspackClientBuild( const chunksByFileName = new Map() const chunkFileNamesByRouteFilePath = new Map>() const cssFilesBySourcePath = new Map>() + const cssContentByFileName = new Map() let entryChunkFileName: string | undefined // Collect all initial JS file names from the main entry for computing @@ -272,6 +274,17 @@ export function normalizeRspackClientBuild( throw new Error('No entry file found in rspack client build') } + for (const asset of compilation.getAssets()) { + if (!asset.name.endsWith('.css')) { + continue + } + + const css = getCssAssetSource(asset.source.source()) + if (css !== undefined) { + cssContentByFileName.set(asset.name, css) + } + } + // In RSC mode, CSS from server components is associated with the 'rsc' // client entry chunk (not the main 'index' entry). The manifest builder // merges the entry chunk's CSS into __root__, so by appending RSC CSS @@ -299,6 +312,7 @@ export function normalizeRspackClientBuild( chunksByFileName, chunkFileNamesByRouteFilePath, cssFilesBySourcePath, + cssContentByFileName, } } diff --git a/packages/start-plugin-core/src/rsbuild/plugin.ts b/packages/start-plugin-core/src/rsbuild/plugin.ts index 6ac23451ab..81d526dd1e 100644 --- a/packages/start-plugin-core/src/rsbuild/plugin.ts +++ b/packages/start-plugin-core/src/rsbuild/plugin.ts @@ -161,6 +161,7 @@ export function tanStackStartRsbuild( routerBasepath, serverFnBase: startConfig.serverFns.base, }) + const inlineCssEnabled = !isDev && startConfig.server.build.inlineCss return mergeRsbuildConfig(rsbuildConfig, { source: { @@ -188,6 +189,12 @@ export function tanStackStartRsbuild( 'import.meta.env.TSS_DEV_SSR_STYLES_BASEPATH': JSON.stringify( resolvedStartConfig.basePaths.publicBase, ), + 'process.env.TSS_INLINE_CSS_ENABLED': JSON.stringify( + inlineCssEnabled ? 'true' : 'false', + ), + 'import.meta.env.TSS_INLINE_CSS_ENABLED': JSON.stringify( + inlineCssEnabled ? 'true' : 'false', + ), }, }, server: { diff --git a/packages/start-plugin-core/src/rsbuild/virtual-modules.ts b/packages/start-plugin-core/src/rsbuild/virtual-modules.ts index a084164aa3..2f7d92a4d4 100644 --- a/packages/start-plugin-core/src/rsbuild/virtual-modules.ts +++ b/packages/start-plugin-core/src/rsbuild/virtual-modules.ts @@ -76,33 +76,39 @@ export const tsrStartManifest = () => globalThis[${JSON.stringify(DEV_START_MANI function buildStartManifestData( clientBuild: NormalizedClientBuild, publicBase: string, + inlineCss: boolean, ) { const routeTreeRoutes = globalThis.TSS_ROUTES_MANIFEST return buildStartManifest({ clientBuild, routeTreeRoutes, basePath: publicBase, + inlineCss, }) } function serializeStartManifestData( clientBuild: NormalizedClientBuild, publicBase: string, + inlineCss: boolean, ): string { - return JSON.stringify(buildStartManifestData(clientBuild, publicBase)) + return JSON.stringify( + buildStartManifestData(clientBuild, publicBase, inlineCss), + ) } function generateManifestModuleBuild( clientBuild: NormalizedClientBuild | undefined, publicBase: string, _devClientEntryUrl: string, + inlineCss: boolean, ): string { if (!clientBuild) { return `const tsrStartManifestData = ${JSON.stringify(START_MANIFEST_PLACEHOLDER)} export const tsrStartManifest = () => tsrStartManifestData` } - return `export const tsrStartManifest = () => (${serializeStartManifestData(clientBuild, publicBase)})` + return `export const tsrStartManifest = () => (${serializeStartManifestData(clientBuild, publicBase, inlineCss)})` } // --------------------------------------------------------------------------- @@ -345,7 +351,7 @@ export function registerVirtualModules( // Generate initial content for each virtual module per environment function getInitialContent(environmentName: string): Record { // Safe to call getConfig() here — this runs inside modifyRspackConfig - const { resolvedStartConfig } = opts.getConfig() + const { resolvedStartConfig, startConfig } = opts.getConfig() const isServerEnv = environmentName === RSBUILD_ENVIRONMENT_NAMES.server const isClientEnv = environmentName === RSBUILD_ENVIRONMENT_NAMES.client const content: Record = {} @@ -361,6 +367,7 @@ export function registerVirtualModules( clientBuild, resolvedStartConfig.basePaths.publicBase, devClientEntryUrl, + startConfig.server.build.inlineCss, ) } else { content[paths.manifest] = 'export default {}' @@ -495,7 +502,7 @@ export function createFromReadableStream() { throw new Error('RSC SSR decode is }, generateManifestContent(newClientBuild: NormalizedClientBuild): string { - const { resolvedStartConfig } = opts.getConfig() + const { resolvedStartConfig, startConfig } = opts.getConfig() const devClientEntryUrl = opts.getDevClientEntryUrl( resolvedStartConfig.basePaths.publicBase, ) @@ -503,16 +510,18 @@ export function createFromReadableStream() { throw new Error('RSC SSR decode is newClientBuild, resolvedStartConfig.basePaths.publicBase, devClientEntryUrl, + !isDev && startConfig.server.build.inlineCss, ) }, generateManifestValueLiteral( newClientBuild: NormalizedClientBuild, ): string { - const { resolvedStartConfig } = opts.getConfig() + const { resolvedStartConfig, startConfig } = opts.getConfig() return serializeStartManifestData( newClientBuild, resolvedStartConfig.basePaths.publicBase, + !isDev && startConfig.server.build.inlineCss, ) }, @@ -528,6 +537,7 @@ export function createFromReadableStream() { throw new Error('RSC SSR decode is )[DEV_START_MANIFEST_GLOBAL] = buildStartManifestData( clientBuild, resolvedStartConfig.basePaths.publicBase, + false, ) } }, diff --git a/packages/start-plugin-core/src/schema.ts b/packages/start-plugin-core/src/schema.ts index 58a2b77470..e0287858e6 100644 --- a/packages/start-plugin-core/src/schema.ts +++ b/packages/start-plugin-core/src/schema.ts @@ -209,6 +209,12 @@ export const tanstackStartOptionsObjectSchema = z.object({ build: z .object({ staticNodeEnv: z.boolean().optional().default(true), + /** + * Inline route CSS into the server-rendered HTML response. + * + * @experimental This option is experimental! + */ + inlineCss: z.boolean().optional().default(false), }) .optional() .default({}), diff --git a/packages/start-plugin-core/src/start-manifest-plugin/inlineCss.ts b/packages/start-plugin-core/src/start-manifest-plugin/inlineCss.ts new file mode 100644 index 0000000000..432f0738ba --- /dev/null +++ b/packages/start-plugin-core/src/start-manifest-plugin/inlineCss.ts @@ -0,0 +1,93 @@ +import { transform } from 'lightningcss' + +const cssUrlPattern = + /url\(\s*(?:"([^"]*)"|'([^']*)'|([^)"']*?))\s*\)|@import\s+(?:url\(\s*(?:"([^"]*)"|'([^']*)'|([^)"']*?))\s*\)|"([^"]*)"|'([^']*)')/gi + +function isRelativeCssUrl(url: string) { + if (!url) return false + if (url.startsWith('#')) return false + if (url.startsWith('/')) return false + if (/^[a-z][a-z\d+.-]*:/i.test(url)) return false + return true +} + +export function shouldRebaseInlineCssUrls(css: string) { + cssUrlPattern.lastIndex = 0 + + for (const match of css.matchAll(cssUrlPattern)) { + const url = ( + match[1] ?? + match[2] ?? + match[3] ?? + match[4] ?? + match[5] ?? + match[6] ?? + match[7] ?? + match[8] ?? + '' + ).trim() + + if (isRelativeCssUrl(url)) { + return true + } + } + + return false +} + +function rebaseCssUrl(url: string, cssHref: string) { + if (!isRelativeCssUrl(url)) { + return url + } + + const fakeOrigin = 'http://tanstack.local' + const resolved = new URL(url, new URL(cssHref, fakeOrigin)) + + if (resolved.origin === fakeOrigin) { + return `${resolved.pathname}${resolved.search}${resolved.hash}` + } + + return resolved.href +} + +export function rebaseInlineCssUrls(options: { css: string; cssHref: string }) { + const css = options.css.trim() + + if (!shouldRebaseInlineCssUrls(css)) { + return css + } + + const result = transform({ + filename: options.cssHref, + code: Buffer.from(css), + minify: true, + visitor: { + Url(url) { + return { + ...url, + url: rebaseCssUrl(url.url, options.cssHref), + } + }, + Rule: { + import(rule: any) { + return { + ...rule, + value: { + ...rule.value, + url: rebaseCssUrl(rule.value.url, options.cssHref), + }, + } + }, + }, + }, + }) + + return Buffer.from(result.code).toString('utf8') +} + +export function getCssAssetSource(source: unknown) { + if (typeof source === 'string') return source + if (source instanceof Uint8Array) return Buffer.from(source).toString('utf8') + if (source == null) return undefined + return String(source) +} diff --git a/packages/start-plugin-core/src/start-manifest-plugin/manifestBuilder.ts b/packages/start-plugin-core/src/start-manifest-plugin/manifestBuilder.ts index 83285a60e8..1c52d124eb 100644 --- a/packages/start-plugin-core/src/start-manifest-plugin/manifestBuilder.ts +++ b/packages/start-plugin-core/src/start-manifest-plugin/manifestBuilder.ts @@ -1,12 +1,17 @@ /* eslint-disable @typescript-eslint/prefer-for-of */ import { serialize } from 'seroval' import { joinURL } from 'ufo' -import { resolveManifestAssetLink, rootRouteId } from '@tanstack/router-core' +import { + getStylesheetHref, + resolveManifestAssetLink, + rootRouteId, +} from '@tanstack/router-core' import { getRouteFilePathsFromModuleIds, normalizeViteClientBuild, normalizeViteClientChunk, } from '../vite/start-manifest-plugin/normalized-client-build' +import { rebaseInlineCssUrls } from './inlineCss' import type { ManifestAssetLink, RouterManagedTag } from '@tanstack/router-core' import type { NormalizedClientBuild, NormalizedClientChunk } from '../types' @@ -42,6 +47,9 @@ type DedupeRoute = { export interface StartManifest { routes: Record clientEntry: string + inlineCss?: { + styles: Record + } } export function appendUniqueStrings( @@ -152,6 +160,7 @@ export function buildStartManifest(options: { clientBuild: NormalizedClientBuild routeTreeRoutes: RouteTreeRoutes basePath: string + inlineCss?: boolean additionalRouteAssets?: Partial< Record> > @@ -180,10 +189,20 @@ export function buildStartManifest(options: { } } - return { + const result: StartManifest = { routes, clientEntry: assetResolvers.getAssetPath(scannedChunks.entryChunk.fileName), } + + if (options.inlineCss) { + result.inlineCss = buildInlineCssManifestData({ + routes, + basePath: options.basePath, + cssContentByFileName: options.clientBuild.cssContentByFileName, + }) + } + + return result } export function serializeStartManifest(startManifest: StartManifest) { @@ -347,6 +366,57 @@ export function createChunkCssAssetCollector(options: { return { getChunkCssAssets } } +function buildInlineCssManifestData(options: { + routes: Record + basePath: string + cssContentByFileName: ReadonlyMap | undefined +}): StartManifest['inlineCss'] { + const stylesheetHrefs = new Set() + + for (const route of Object.values(options.routes)) { + for (const asset of route.assets ?? []) { + const href = getStylesheetHref(asset) + if (href) { + stylesheetHrefs.add(href) + } + } + } + + if (stylesheetHrefs.size === 0) { + return { styles: {} } + } + + if (!options.cssContentByFileName) { + throw new Error( + 'TanStack Start inlineCss is enabled, but the client build did not provide CSS content', + ) + } + + const { getAssetPath } = createManifestAssetResolvers(options.basePath) + const styles: Record = {} + const missingHrefs = new Set(stylesheetHrefs) + + for (const [cssFile, css] of options.cssContentByFileName) { + const cssHref = getAssetPath(cssFile) + if (!stylesheetHrefs.has(cssHref)) { + continue + } + + styles[cssHref] = rebaseInlineCssUrls({ css, cssHref }) + missingHrefs.delete(cssHref) + } + + if (missingHrefs.size > 0) { + throw new Error( + `TanStack Start inlineCss could not find CSS content for: ${Array.from( + missingHrefs, + ).join(', ')}`, + ) + } + + return { styles } +} + export function buildRouteManifestRoutes(options: { routeTreeRoutes: RouteTreeRoutes routeChunksByFilePath: ReadonlyMap< diff --git a/packages/start-plugin-core/src/types.ts b/packages/start-plugin-core/src/types.ts index 0c83d32583..a5f4324315 100644 --- a/packages/start-plugin-core/src/types.ts +++ b/packages/start-plugin-core/src/types.ts @@ -47,6 +47,7 @@ export interface NormalizedClientBuild { chunksByFileName: ReadonlyMap chunkFileNamesByRouteFilePath: ReadonlyMap> cssFilesBySourcePath: ReadonlyMap> + cssContentByFileName?: ReadonlyMap } export interface TanStackStartCoreOptions { diff --git a/packages/start-plugin-core/src/vite/planning.ts b/packages/start-plugin-core/src/vite/planning.ts index 56766a58af..5db724ba8d 100644 --- a/packages/start-plugin-core/src/vite/planning.ts +++ b/packages/start-plugin-core/src/vite/planning.ts @@ -136,6 +136,7 @@ export function createViteDefineConfig(opts: { spaEnabled: boolean | undefined devSsrStylesEnabled: boolean devSsrStylesBasepath: string + inlineCssEnabled: boolean staticNodeEnv: boolean }) { return { @@ -156,6 +157,10 @@ export function createViteDefineConfig(opts: { 'TSS_DEV_SSR_STYLES_BASEPATH', opts.devSsrStylesBasepath, ), + ...defineReplaceEnv( + 'TSS_INLINE_CSS_ENABLED', + opts.inlineCssEnabled ? 'true' : 'false', + ), ...(opts.command === 'build' && opts.staticNodeEnv ? { 'process.env.NODE_ENV': JSON.stringify( diff --git a/packages/start-plugin-core/src/vite/plugin.ts b/packages/start-plugin-core/src/vite/plugin.ts index 084565ecc6..e6cee02e48 100644 --- a/packages/start-plugin-core/src/vite/plugin.ts +++ b/packages/start-plugin-core/src/vite/plugin.ts @@ -185,6 +185,8 @@ export function tanStackStartVite( devSsrStylesBasepath: startConfig.dev.ssrStyles.basepath ?? resolvedStartConfig.basePaths.publicBase, + inlineCssEnabled: + command === 'build' && startConfig.server.build.inlineCss, staticNodeEnv: startConfig.server.build.staticNodeEnv, }), builder: { diff --git a/packages/start-plugin-core/src/vite/start-manifest-plugin/normalized-client-build.ts b/packages/start-plugin-core/src/vite/start-manifest-plugin/normalized-client-build.ts index 39c55b5484..8ac7915ff0 100644 --- a/packages/start-plugin-core/src/vite/start-manifest-plugin/normalized-client-build.ts +++ b/packages/start-plugin-core/src/vite/start-manifest-plugin/normalized-client-build.ts @@ -1,4 +1,5 @@ import { tsrSplit } from '@tanstack/router-plugin' +import { getCssAssetSource } from '../../start-manifest-plugin/inlineCss' import type { Rollup } from 'vite' import type { NormalizedClientBuild, NormalizedClientChunk } from '../../types' @@ -40,6 +41,7 @@ export function normalizeViteClientBuild( const chunksByFileName = normalizeViteClientChunks(clientBundle) const chunkFileNamesByRouteFilePath = new Map>() const cssFilesBySourcePath = new Map>() + const cssContentByFileName = new Map() for (const chunk of chunksByFileName.values()) { const bundleEntry = clientBundle[chunk.fileName] as Rollup.OutputChunk @@ -78,6 +80,22 @@ export function normalizeViteClientBuild( } } + for (const fileName in clientBundle) { + if (!fileName.endsWith('.css')) { + continue + } + + const bundleEntry = clientBundle[fileName]! + if (bundleEntry.type !== 'asset') { + continue + } + + const css = getCssAssetSource(bundleEntry.source) + if (css !== undefined) { + cssContentByFileName.set(fileName, css) + } + } + if (!entryChunkFileName) { throw new Error('No entry file found') } @@ -87,6 +105,7 @@ export function normalizeViteClientBuild( chunksByFileName, chunkFileNamesByRouteFilePath, cssFilesBySourcePath, + cssContentByFileName, } } diff --git a/packages/start-plugin-core/src/vite/start-manifest-plugin/plugin.ts b/packages/start-plugin-core/src/vite/start-manifest-plugin/plugin.ts index 22a290f08b..dc027cf32f 100644 --- a/packages/start-plugin-core/src/vite/start-manifest-plugin/plugin.ts +++ b/packages/start-plugin-core/src/vite/start-manifest-plugin/plugin.ts @@ -44,7 +44,7 @@ export function startManifestPlugin(opts: { moduleId: VIRTUAL_MODULES.startManifest, enforce: 'pre', load() { - const { resolvedStartConfig } = opts.getConfig() + const { resolvedStartConfig, startConfig } = opts.getConfig() const clientEntry = joinURL( resolvedStartConfig.basePaths.publicBase, '@id', @@ -70,6 +70,7 @@ export function startManifestPlugin(opts: { clientBuild, routeTreeRoutes, basePath: resolvedStartConfig.basePaths.publicBase, + inlineCss: startConfig.server.build.inlineCss, additionalRouteAssets: getViteAdditionalRouteAssets({ cssCodeSplitDisabledFileName, basePath: resolvedStartConfig.basePaths.publicBase, diff --git a/packages/start-plugin-core/tests/start-manifest-plugin/manifestBuilder.test.ts b/packages/start-plugin-core/tests/start-manifest-plugin/manifestBuilder.test.ts index 8d673e07ae..de1d67c3e0 100644 --- a/packages/start-plugin-core/tests/start-manifest-plugin/manifestBuilder.test.ts +++ b/packages/start-plugin-core/tests/start-manifest-plugin/manifestBuilder.test.ts @@ -1,5 +1,6 @@ import { describe, expect, test } from 'vitest' import { deserialize } from 'seroval' +import { shouldRebaseInlineCssUrls } from '../../src/start-manifest-plugin/inlineCss' import { appendUniqueAssets, appendUniqueStrings, @@ -60,6 +61,18 @@ function makeChunk(options: { } as unknown as Rollup.OutputChunk } +function makeCssAsset(fileName: string, source: string): Rollup.OutputAsset { + return { + type: 'asset', + fileName, + name: fileName, + names: [fileName], + source, + needsCodeReference: false, + originalFileNames: [], + } as unknown as Rollup.OutputAsset +} + describe('getRouteFilePathsFromModuleIds', () => { test('returns unique route file paths only for tsr split modules', () => { expect( @@ -389,6 +402,81 @@ describe('createChunkCssAssetCollector', () => { }) describe('buildStartManifest', () => { + test('skips inline CSS transforms when no relative URLs need rebasing', () => { + expect(shouldRebaseInlineCssUrls('.root {\n color: red;\n}')).toBe(false) + expect(shouldRebaseInlineCssUrls('.root{background:url(/dot.svg)}')).toBe( + false, + ) + expect( + shouldRebaseInlineCssUrls( + '.root{background:url(data:image/svg+xml,foo)}', + ), + ).toBe(false) + expect(shouldRebaseInlineCssUrls('.card{background:url(./dot.svg)}')).toBe( + true, + ) + expect(shouldRebaseInlineCssUrls('@import "../theme.css";')).toBe(true) + }) + + test('embeds rebased inline CSS content when enabled', () => { + const entryChunk = makeChunk({ + fileName: 'entry.js', + isEntry: true, + importedCss: ['root.css'], + }) + const routeChunk = makeChunk({ + fileName: 'dashboard.js', + importedCss: ['dashboard.css'], + moduleIds: ['/routes/dashboard.tsx?tsr-split=component'], + }) + + const manifest = buildStartManifest({ + clientBuild: normalizeTestBuild({ + 'entry.js': entryChunk, + 'dashboard.js': routeChunk, + 'root.css': makeCssAsset('root.css', '.root{color:red}'), + 'dashboard.css': makeCssAsset( + 'dashboard.css', + '.card{background:url("./dot.svg")}', + ), + }), + routeTreeRoutes: { + __root__: {}, + '/dashboard': { filePath: '/routes/dashboard.tsx' }, + }, + basePath: '/assets', + inlineCss: true, + }) + + expect(manifest.inlineCss?.styles['/assets/root.css']).toBe( + '.root{color:red}', + ) + expect(manifest.inlineCss?.styles['/assets/dashboard.css']).toBe( + '.card{background:url(/assets/dot.svg)}', + ) + }) + + test('throws when inline CSS content is missing for a stylesheet asset', () => { + const entryChunk = makeChunk({ + fileName: 'entry.js', + isEntry: true, + importedCss: ['root.css'], + }) + + expect(() => + buildStartManifest({ + clientBuild: normalizeTestBuild({ + 'entry.js': entryChunk, + }), + routeTreeRoutes: { + __root__: {}, + }, + basePath: '/assets', + inlineCss: true, + }), + ).toThrow('could not find CSS content') + }) + test('allows callers to attach additional route assets', () => { const entryChunk = makeChunk({ fileName: 'entry.js', diff --git a/packages/start-server-core/src/router-manifest.ts b/packages/start-server-core/src/router-manifest.ts index d20be26942..f15b689c7d 100644 --- a/packages/start-server-core/src/router-manifest.ts +++ b/packages/start-server-core/src/router-manifest.ts @@ -62,6 +62,7 @@ export async function getStartManifest( } const manifest = { + inlineCss: startManifest.inlineCss, routes: Object.fromEntries( Object.entries(startManifest.routes).flatMap(([k, v]) => { const result = {} as { diff --git a/packages/start-server-core/src/transformAssetUrls.ts b/packages/start-server-core/src/transformAssetUrls.ts index 6c347e2343..e34cafedec 100644 --- a/packages/start-server-core/src/transformAssetUrls.ts +++ b/packages/start-server-core/src/transformAssetUrls.ts @@ -410,7 +410,7 @@ export async function transformManifestAssets( ) } - if (route.assets) { + if (route.assets && !source.manifest.inlineCss) { for (const asset of route.assets) { if (asset.tag === 'link' && asset.attrs?.href) { const rel = asset.attrs.rel @@ -481,5 +481,5 @@ export function buildManifestWithClientEntry( }, } - return { routes } + return { inlineCss: source.manifest.inlineCss, routes } } diff --git a/packages/vue-router/src/Asset.tsx b/packages/vue-router/src/Asset.tsx index 128ffa8ad3..fdbf140c79 100644 --- a/packages/vue-router/src/Asset.tsx +++ b/packages/vue-router/src/Asset.tsx @@ -3,6 +3,8 @@ import { isServer } from '@tanstack/router-core/isServer' import { useRouter } from './useRouter' import type { RouterManagedTag } from '@tanstack/router-core' +const INLINE_CSS_HYDRATION_ATTR = 'data-tsr-inline-css' + interface ScriptAttrs { [key: string]: string | boolean | undefined src?: string @@ -171,7 +173,42 @@ const Script = Vue.defineComponent({ }, }) -export function Asset({ tag, attrs, children }: RouterManagedTag): any { +const InlineCssStyle = Vue.defineComponent({ + name: 'InlineCssStyle', + props: { + attrs: { + type: Object as Vue.PropType>, + default: () => ({}), + }, + children: { + type: String, + default: undefined, + }, + }, + setup(props) { + const isInlineCssPlaceholder = props.children === undefined + const hydratedInlineCss = + isInlineCssPlaceholder && typeof document !== 'undefined' + ? (document.querySelector( + `style[${INLINE_CSS_HYDRATION_ATTR}]`, + )?.textContent ?? '') + : undefined + + return () => + Vue.h('style', { + ...props.attrs, + [INLINE_CSS_HYDRATION_ATTR]: '', + 'data-allow-mismatch': true, + innerHTML: isInlineCssPlaceholder + ? (hydratedInlineCss ?? '') + : (props.children ?? ''), + }) + }, +}) + +export function Asset(asset: RouterManagedTag): any { + const { tag, attrs, children } = asset + switch (tag) { case 'title': return Vue.h(Title, { children: children }) @@ -180,7 +217,21 @@ export function Asset({ tag, attrs, children }: RouterManagedTag): any { case 'link': return case 'style': - return + + + + {children} + + + + ) +} diff --git a/e2e/react-start/deferred-hydration/src/routes/components.tsx b/e2e/react-start/deferred-hydration/src/routes/components.tsx new file mode 100644 index 0000000000..95fa7531a4 --- /dev/null +++ b/e2e/react-start/deferred-hydration/src/routes/components.tsx @@ -0,0 +1,179 @@ +import { createFileRoute } from '@tanstack/react-router' +import * as React from 'react' +import { Hydrate } from '@tanstack/react-start' +import { + condition, + idle, + interaction, + load, + media, + never, + visible, +} from '@tanstack/react-start/hydration' + +export const Route = createFileRoute('/components')({ + component: ComponentHydrationPage, +}) + +function InteractiveBox(props: { id: string; label: string }) { + const [count, setCount] = React.useState(0) + const [hydrated, setHydrated] = React.useState(false) + + React.useEffect(() => { + setHydrated(true) + }, []) + + return ( + + ) +} + +type HydrationFallbackWindow = Window & { + __componentFallbackReady?: boolean + __componentFallbackPromise?: Promise +} + +function DelayedFallbackBox() { + if (typeof window !== 'undefined') { + const win = window as HydrationFallbackWindow + + if (!win.__componentFallbackReady) { + win.__componentFallbackPromise ??= new Promise((resolve) => { + win.setTimeout(() => { + win.__componentFallbackReady = true + resolve() + }, 1000) + }) + + throw win.__componentFallbackPromise + } + } + + return
fallback child
+} + +function ComponentHydrationPage() { + const [hydratedCallbacks, setHydratedCallbacks] = React.useState(0) + const [conditionReady, setConditionReady] = React.useState(false) + const [showClientFallbackBoundary, setShowClientFallbackBoundary] = + React.useState(false) + + return ( +
+

Component Deferred Hydration

+
+ Manual test guide + + Pink buttons are server HTML that has not hydrated yet. Green buttons + have hydrated and should increment when clicked. Follow the notes + below to trigger each strategy intentionally. + +
+

{hydratedCallbacks}

+

+ load and idle should become green + without interaction shortly after the page loads. +

+ + + + + + +
+ Scroll down to reveal the visible boundary +
+

+ visible hydrates only after this button enters the + viewport. +

+ + + +

+ media hydrates when (min-width: 1px) + matches. interaction hydrates on hover, focus, pointer + down, or click intent. +

+ + + + + + +

+ Custom interaction boundaries below hydrate only for their configured + events: double-click for the single-event example, and right-click or + double-click for the multi-event example. The prefetch example should + download code on hover but hydrate on click. +

+ setHydratedCallbacks((count) => count + 1)} + > + + + + + + + + + + + + + + + + + + + + + + + +

+ never stays as server HTML forever on the initial page, + so clicking should not increment it. +

+ + {showClientFallbackBoundary ? ( + client fallback + } + > + + + ) : null} +
+ ) +} diff --git a/e2e/react-start/deferred-hydration/src/routes/css.tsx b/e2e/react-start/deferred-hydration/src/routes/css.tsx new file mode 100644 index 0000000000..2c01aa9e57 --- /dev/null +++ b/e2e/react-start/deferred-hydration/src/routes/css.tsx @@ -0,0 +1,57 @@ +import { createFileRoute } from '@tanstack/react-router' +import { Hydrate } from '@tanstack/react-start' +import { media, never, visible } from '@tanstack/react-start/hydration' +import outerStyles from './css/outer.module.css' +import deferredStyles from './css/deferred-only.module.css' +import sharedStyles from './css/shared.module.css' + +export const Route = createFileRoute('/css')({ + component: CssHydrationPage, +}) + +function CssHydrationPage() { + return ( +
+
+

+ CSS Deferred Hydration +

+

+ CSS from deferred, never, shared, and nested Hydrate boundaries should + be available even before the client JavaScript hydrates those islands. +

+
+
+
+ Outer CSS +
+
+ Shared outer CSS +
+
+ +
+ Deferred CSS +
+
+ +
+ Never CSS +
+
+ + +
+ Nested CSS +
+
+
+
+ ) +} diff --git a/e2e/react-start/deferred-hydration/src/routes/css/deferred-only.module.css b/e2e/react-start/deferred-hydration/src/routes/css/deferred-only.module.css new file mode 100644 index 0000000000..05eafda03c --- /dev/null +++ b/e2e/react-start/deferred-hydration/src/routes/css/deferred-only.module.css @@ -0,0 +1,15 @@ +.deferredBox { + background-color: rgb(23, 45, 67); + color: rgb(255, 255, 255); + padding: 12px; +} + +.neverBox { + color: rgb(45, 67, 89); + padding: 12px; +} + +.nestedBox { + border-left: 5px solid rgb(67, 89, 123); + padding-left: 12px; +} diff --git a/e2e/react-start/deferred-hydration/src/routes/css/outer.module.css b/e2e/react-start/deferred-hydration/src/routes/css/outer.module.css new file mode 100644 index 0000000000..98ca5e0934 --- /dev/null +++ b/e2e/react-start/deferred-hydration/src/routes/css/outer.module.css @@ -0,0 +1,9 @@ +.heading { + color: rgb(11, 31, 53); +} + +.outerBox { + background-color: rgb(242, 250, 255); + color: rgb(12, 34, 56); + padding: 12px; +} diff --git a/e2e/react-start/deferred-hydration/src/routes/css/shared.module.css b/e2e/react-start/deferred-hydration/src/routes/css/shared.module.css new file mode 100644 index 0000000000..020da5d7ad --- /dev/null +++ b/e2e/react-start/deferred-hydration/src/routes/css/shared.module.css @@ -0,0 +1,4 @@ +.sharedBox { + border-top: 4px solid rgb(98, 76, 54); + margin-top: 8px; +} diff --git a/e2e/react-start/deferred-hydration/src/routes/enhanced.tsx b/e2e/react-start/deferred-hydration/src/routes/enhanced.tsx new file mode 100644 index 0000000000..628a5c4ae3 --- /dev/null +++ b/e2e/react-start/deferred-hydration/src/routes/enhanced.tsx @@ -0,0 +1,339 @@ +import { createFileRoute } from '@tanstack/react-router' +import * as React from 'react' +import { Hydrate } from '@tanstack/react-start' +import { interaction, media } from '@tanstack/react-start/hydration' +import { EnhancedNestedWidget } from '../shared/EnhancedNestedWidget' + +type EnhancedSearch = { + dynamic?: 'interaction' +} + +export const Route = createFileRoute('/enhanced')({ + validateSearch: (search: Record): EnhancedSearch => ({ + dynamic: search.dynamic === 'interaction' ? 'interaction' : undefined, + }), + component: EnhancedHydrationPage, +}) + +type DeferredGate = { + promise: Promise + resolve: () => void +} + +const clickIntent = interaction({ events: 'click' }) +const pointerOverIntent = interaction({ events: 'pointerover' }) +const doubleClickIntent = interaction({ events: 'dblclick' }) + +function createDeferredGate(): DeferredGate { + let resolve!: () => void + const promise = new Promise((next) => { + resolve = next + }) + return { promise, resolve } +} + +function useDeferredGate() { + const ref = React.useRef(undefined) + ref.current ??= createDeferredGate() + return ref.current +} + +function mergeStatus>( + setStatus: React.Dispatch>, + patch: Partial, +) { + setStatus((current) => ({ ...current, ...patch })) +} + +function InteractiveBox(props: { id: string; label: string }) { + const [count, setCount] = React.useState(0) + const [hydrated, setHydrated] = React.useState(false) + + React.useEffect(() => { + setHydrated(true) + }, []) + + return ( + + ) +} + +function DynamicWhenExamples() { + const search = Route.useSearch() + const searchDrivenHydration = React.useCallback( + () => (search.dynamic === 'interaction' ? clickIntent : doubleClickIntent), + [search.dynamic], + ) + + return ( + <> +

+ Dynamic callbacks are client-only. The first boundary always hydrates on + click; the second reads typed router search state before choosing its + interaction event. +

+ clickIntent}> + + + + + + + ) +} + +function SplitPrefetchExample() { + const gate = useDeferredGate() + const [status, setStatus] = React.useState({ + wait: 'idle', + preload: 'idle', + query: 'idle', + }) + + return ( + <> +

{status.wait}

+

{status.preload}

+

{status.query}

+ + { + mergeStatus(setStatus, { + query: element ? 'element' : 'missing-element', + wait: 'waiting', + }) + + const reason = await waitFor(pointerOverIntent) + mergeStatus(setStatus, { wait: reason }) + if (reason === 'abort' || signal.aborted) return + + await preload() + mergeStatus(setStatus, { preload: 'done' }) + await gate.promise + mergeStatus(setStatus, { query: 'done' }) + }} + > + + + + ) +} + +function FireAndForgetPrefetchExample() { + const gate = useDeferredGate() + const [status, setStatus] = React.useState({ + wait: 'idle', + work: 'idle', + query: 'idle', + }) + + return ( + <> +

{status.work}

+

{status.wait}

+

{status.query}

+ + { + mergeStatus(setStatus, { wait: 'waiting' }) + void waitFor(pointerOverIntent).then((reason) => { + mergeStatus(setStatus, { wait: reason }) + if (reason === 'abort') return + + mergeStatus(setStatus, { work: 'started' }) + void gate.promise.then(() => { + mergeStatus(setStatus, { query: 'done' }) + }) + }) + }} + > + + + + ) +} + +function HydrateFirstPrefetchExample() { + const [reason, setReason] = React.useState('idle') + + return ( + <> +

{reason}

+ { + setReason(await waitFor(doubleClickIntent)) + }} + > + + + + ) +} + +function RuntimeOnlyPrefetchExample() { + const gate = useDeferredGate() + const [status, setStatus] = React.useState({ + wait: 'idle', + ready: 'idle', + }) + + return ( + <> +

{status.wait}

+

{status.ready}

+ + { + mergeStatus(setStatus, { wait: 'waiting' }) + const reason = await waitFor(pointerOverIntent) + mergeStatus(setStatus, { wait: reason }) + if (reason === 'abort') return + + await gate.promise + await preload() + mergeStatus(setStatus, { ready: 'ready' }) + }} + > + + + + ) +} + +function WaitForAbortExample() { + const [showBoundary, setShowBoundary] = React.useState(true) + const [reason, setReason] = React.useState('idle') + + return ( + <> +

{reason}

+ + {showBoundary ? ( + { + setReason('waiting') + setReason(await waitFor(pointerOverIntent)) + }} + > + + + ) : null} + + ) +} + +function SignalAbortExample() { + const [showBoundary, setShowBoundary] = React.useState(true) + const [status, setStatus] = React.useState('idle') + + return ( + <> +

{status}

+ + {showBoundary ? ( + { + setStatus('listening') + await new Promise((resolve) => { + const onAbort = () => { + setStatus('aborted') + resolve() + } + + if (signal.aborted) { + onAbort() + return + } + + signal.addEventListener('abort', onAbort, { once: true }) + }) + }} + > + + + ) : null} + + ) +} + +function NestedDynamicExamples() { + return ( + <> + + clickIntent}> + + + + + + ) +} + +function EnhancedHydrationPage() { + return ( +
+

Enhanced Hydrate APIs

+ + + + + + + + +
+ ) +} diff --git a/e2e/react-start/deferred-hydration/src/routes/imported.tsx b/e2e/react-start/deferred-hydration/src/routes/imported.tsx new file mode 100644 index 0000000000..bf0f8b74bd --- /dev/null +++ b/e2e/react-start/deferred-hydration/src/routes/imported.tsx @@ -0,0 +1,15 @@ +import { createFileRoute } from '@tanstack/react-router' +import { ImportedHydrateWidget } from '../shared/ImportedHydrateWidget' + +export const Route = createFileRoute('/imported')({ + component: ImportedHydrationPage, +}) + +function ImportedHydrationPage() { + return ( +
+

Imported Hydrate

+ +
+ ) +} diff --git a/e2e/react-start/deferred-hydration/src/routes/index.tsx b/e2e/react-start/deferred-hydration/src/routes/index.tsx new file mode 100644 index 0000000000..0585f4bc87 --- /dev/null +++ b/e2e/react-start/deferred-hydration/src/routes/index.tsx @@ -0,0 +1,23 @@ +import { Link, createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + component: Home, +}) + +function Home() { + return ( +
+

Deferred Hydration

+

Component strategies

+ component strategies +

CSS

+ CSS deferred hydration +

Imported component

+ + imported Hydrate + +

Enhanced APIs

+ enhanced Hydrate APIs +
+ ) +} diff --git a/e2e/react-start/deferred-hydration/src/routes/scroll-restoration.tsx b/e2e/react-start/deferred-hydration/src/routes/scroll-restoration.tsx new file mode 100644 index 0000000000..7b52cf25fe --- /dev/null +++ b/e2e/react-start/deferred-hydration/src/routes/scroll-restoration.tsx @@ -0,0 +1,93 @@ +import { ClientOnly, createFileRoute } from '@tanstack/react-router' +import { Hydrate } from '@tanstack/react-start' +import { visible } from '@tanstack/react-start/hydration' +import * as React from 'react' + +export const Route = createFileRoute('/scroll-restoration')({ + component: ScrollRestorationRoute, +}) + +function BottomWidget() { + const [hydrated, setHydrated] = React.useState(false) + + React.useEffect(() => { + setHydrated(true) + }, []) + + return ( +
+

Bottom widget

+

+ This visible deferred boundary is intentionally near the bottom of the + document. +

+

+ The hydrated widget is taller than the server skeleton so the test can + catch scroll restoration that happens before late hydration settles. +

+
+ ) +} + +function BottomWidgetSkeleton() { + return ( +
+

Bottom widget skeleton

+

+ The server-rendered placeholder reserves the same vertical space as the + hydrated widget. +

+
+ ) +} + +function ScrollRestorationRoute() { + return ( +
+

+ Scroll restoration deferred hydration +

+

+ This route keeps the reproduction small: a tall page, a visible Hydrate + boundary near the bottom, and normal router scroll restoration. +

+
+ Scroll to the bottom widget +
+ + }> + + + +
+ ) +} diff --git a/e2e/react-start/deferred-hydration/src/shared/EnhancedNestedWidget.tsx b/e2e/react-start/deferred-hydration/src/shared/EnhancedNestedWidget.tsx new file mode 100644 index 0000000000..fb2f094e51 --- /dev/null +++ b/e2e/react-start/deferred-hydration/src/shared/EnhancedNestedWidget.tsx @@ -0,0 +1,33 @@ +import * as React from 'react' +import { Hydrate } from '@tanstack/react-start' +import { interaction, media } from '@tanstack/react-start/hydration' + +function CrossFileNestedButton() { + const [count, setCount] = React.useState(0) + const [hydrated, setHydrated] = React.useState(false) + + React.useEffect(() => { + setHydrated(true) + }, []) + + return ( + + ) +} + +export function EnhancedNestedWidget() { + return ( + + + + + + ) +} diff --git a/e2e/react-start/deferred-hydration/src/shared/ImportedHydrateWidget.tsx b/e2e/react-start/deferred-hydration/src/shared/ImportedHydrateWidget.tsx new file mode 100644 index 0000000000..f2be89ec1c --- /dev/null +++ b/e2e/react-start/deferred-hydration/src/shared/ImportedHydrateWidget.tsx @@ -0,0 +1,39 @@ +import * as React from 'react' +import { Hydrate } from '@tanstack/react-start' +import { interaction } from '@tanstack/react-start/hydration' + +function ImportedHydrateChild() { + const [count, setCount] = React.useState(0) + const [hydrated, setHydrated] = React.useState(false) + + React.useEffect(() => { + setHydrated(true) + }, []) + + return ( + + ) +} + +export function ImportedHydrateWidget() { + return ( + + imported hydrate fallback + + } + > + + + ) +} diff --git a/e2e/react-start/deferred-hydration/tests/hydration.spec.ts b/e2e/react-start/deferred-hydration/tests/hydration.spec.ts new file mode 100644 index 0000000000..0a2c332271 --- /dev/null +++ b/e2e/react-start/deferred-hydration/tests/hydration.spec.ts @@ -0,0 +1,1028 @@ +import { expect } from '@playwright/test' +import { createHmrFileEditor, test } from '@tanstack/router-e2e-utils' +import crypto from 'node:crypto' +import path from 'node:path' +import type { APIRequestContext, Page } from '@playwright/test' + +const isDev = process.env.MODE === 'dev' +const toolchain = process.env.E2E_TOOLCHAIN ?? 'vite' +const isVite = toolchain === 'vite' +const hmrExpect = expect.configure({ timeout: 20_000 }) +const componentsRouteFile = path.join( + process.cwd(), + 'src/routes/components.tsx', +) +const interactiveBoxLabelSource = + ' {props.label}: {count}' +const interactiveBoxHmrLabelSource = + ' hmr {props.label}: {count}' + +function normalizeComponentsRouteSource(source: string) { + return source + .split(interactiveBoxHmrLabelSource) + .join(interactiveBoxLabelSource) +} + +const componentsRouteEditor = createHmrFileEditor({ + files: { + componentsRoute: componentsRouteFile, + }, + normalizeSource: (_fileKey, source) => normalizeComponentsRouteSource(source), +}) + +function getVisibleHydrateVirtualPath() { + const normalizedSourcePath = path + .relative(process.cwd(), componentsRouteFile) + .replaceAll('\\', '/') + const sourceHash = crypto + .createHash('sha1') + .update(normalizedSourcePath) + .digest('hex') + .slice(0, 10) + const params = new URLSearchParams() + params.set('tss-hydrate', `0_${sourceHash}`) + + return `${componentsRouteFile}?${params.toString()}` +} + +async function waitForVisibleHydrateVirtualModule(page: Page, marker: string) { + const virtualPath = getVisibleHydrateVirtualPath() + + await expect + .poll( + async () => { + try { + const response = await page.request.get(virtualPath) + const text = await response.text() + + if (response.ok() && text.includes(marker)) { + return 'ready' + } + + return `${response.status()} ${text.slice(0, 240)}` + } catch (error) { + return String(error) + } + }, + { timeout: 20_000 }, + ) + .toBe('ready') +} + +async function clickAndExpectCount( + page: Page, + buttonTestId: string, + countTestId: string, + count: string, +) { + await expect(page.getByTestId(buttonTestId)).toHaveAttribute( + 'data-hydrated', + 'true', + ) + await page.getByTestId(buttonTestId).click() + await expect(page.getByTestId(countTestId)).toHaveText(count) +} + +async function clickIntentAndExpectReplayedCount( + page: Page, + buttonTestId: string, + countTestId: string, + count: string, +) { + await expectRouteToStayUnhydrated(page, buttonTestId) + await page.getByTestId(buttonTestId).click() + await expect(page.getByTestId(buttonTestId)).toHaveAttribute( + 'data-hydrated', + 'true', + ) + await expect(page.getByTestId(countTestId)).toHaveText(count) +} + +async function clickToHydrateThenClickAndExpectIncrement( + page: Page, + buttonTestId: string, + countTestId: string, +) { + await expectRouteToStayUnhydrated(page, buttonTestId) + await page.getByTestId(buttonTestId).click() + await expect(page.getByTestId(buttonTestId)).toHaveAttribute( + 'data-hydrated', + 'true', + ) + const previousCount = Number( + await page.getByTestId(countTestId).textContent(), + ) + await page.getByTestId(buttonTestId).click() + await expect + .poll(async () => Number(await page.getByTestId(countTestId).textContent())) + .toBe(previousCount + 1) +} + +async function hoverIntentAndExpectCount( + page: Page, + buttonTestId: string, + countTestId: string, + count: string, +) { + await expectRouteToStayUnhydrated(page, buttonTestId) + await page.mouse.move(0, 0) + await page.getByTestId(buttonTestId).hover() + await clickAndExpectCount(page, buttonTestId, countTestId, count) +} + +async function dispatchHydrationIntent( + page: Page, + buttonTestId: string, + eventName: string, +) { + await page.getByTestId(buttonTestId).evaluate((element, eventName) => { + const marker = element.closest('[data-ts-hydrate-id]') + + if (!marker) { + throw new Error('Expected Hydrate marker to exist') + } + + marker.dispatchEvent( + new Event(eventName, { bubbles: true, cancelable: true }), + ) + }, eventName) +} + +async function expectRouteToStayUnhydrated( + page: Page, + buttonTestId: string, + duration = 250, +) { + await expect(page.getByTestId(buttonTestId)).toHaveAttribute( + 'data-hydrated', + 'false', + ) + await page.waitForTimeout(duration) + await expect(page.getByTestId(buttonTestId)).toHaveAttribute( + 'data-hydrated', + 'false', + ) +} + +async function scrollToBoundary(page: Page, buttonTestId: string) { + const button = page.getByTestId(buttonTestId) + for (let attempt = 0; attempt < 3; attempt++) { + await button.evaluate((element) => { + element.scrollIntoView({ block: 'center', inline: 'nearest' }) + }) + + await page.waitForTimeout(100) + const isVisible = await button.evaluate((element) => { + const rect = element.getBoundingClientRect() + return rect.bottom > 0 && rect.top < window.innerHeight + }) + + if (isVisible) return + } + + await expect(button).toBeInViewport() +} + +async function expectCssProperty( + page: Page, + testId: string, + property: string, + value: string, +) { + await expect + .poll(() => + page.getByTestId(testId).evaluate((element, propertyName) => { + return getComputedStyle(element).getPropertyValue(propertyName) + }, property), + ) + .toBe(value) +} + +function htmlContainsText(html: string, text: string) { + const pattern = text.split(' ').join('(?:\\s|)+') + expect(html).toMatch(new RegExp(pattern)) +} + +async function waitForComponentsServerHtmlText(page: Page, text: string) { + await expect + .poll( + async () => { + const response = await page.request.get('/components') + const html = await response.text() + + if (!response.ok()) { + return `${response.status()} ${html.slice(0, 240)}` + } + + try { + htmlContainsText(html, text) + return 'ready' + } catch { + return html.slice(0, 240) + } + }, + { timeout: 20_000 }, + ) + .toBe('ready') +} + +function getModulePreloadHrefs(html: string) { + return Array.from(html.matchAll(/]*>/g), (match) => match[0]) + .filter((tag) => /\brel="modulepreload"/.test(tag)) + .map((tag) => tag.match(/\bhref="([^"]+)"/)?.[1]) + .filter((href): href is string => !!href) +} + +async function modulePreloadContentsContain( + request: APIRequestContext, + hrefs: Array, + marker: string, +) { + for (const href of hrefs) { + const response = await request.get(href) + if (!response.ok()) continue + + const text = await response.text() + if (text.includes(marker)) return true + } + + return false +} + +async function resourceContentsContain( + page: Page, + request: APIRequestContext, + marker: string, + filter: (url: string) => boolean, +) { + const resourceUrls = await page.evaluate(() => + performance.getEntriesByType('resource').map((entry) => entry.name), + ) + + return modulePreloadContentsContain( + request, + resourceUrls.filter(filter), + marker, + ) +} + +async function documentModulePreloadHrefs(page: Page) { + return page.evaluate(() => + Array.from( + document.querySelectorAll('link[rel~="modulepreload"]'), + (link) => link.href, + ), + ) +} + +function isHydrateBoundaryResource(url: string) { + return ( + url.includes('/assets/components-') || url.includes('/static/js/async/') + ) +} + +function isClientJavaScriptResource(url: string) { + return ( + url.includes('/assets/') || + url.includes('/static/js/') || + url.includes('/static/js/async/') + ) +} + +async function expectClientRouterReady(page: Page) { + await expect + .poll(() => + page.evaluate(() => + Boolean( + ( + globalThis as typeof globalThis & { + __TSR_ROUTER__?: unknown + } + ).__TSR_ROUTER__, + ), + ), + ) + .toBe(true) +} + +async function gotoEnhanced(page: Page, search = '') { + await page.goto(`/enhanced${search}`) + await expectClientRouterReady(page) +} + +test.describe('Hydrate HMR', () => { + test.skip(!isDev, 'HMR regression coverage runs against the dev server only') + + test.beforeAll(async () => { + await componentsRouteEditor.capturePromise + }) + + test.afterEach(async () => { + await componentsRouteEditor.capturePromise + await componentsRouteEditor.restoreFiles() + }) + + test.afterAll(async () => { + await componentsRouteEditor.capturePromise + await componentsRouteEditor.restoreFiles() + }) + + test('updates deferred child chunks after the parent route is edited', async ({ + page, + }) => { + const pageErrors: Array = [] + page.on('pageerror', (error) => { + pageErrors.push(error.message) + }) + + await page.goto('/components') + await expectClientRouterReady(page) + await expectRouteToStayUnhydrated(page, 'component-visible-button') + + await componentsRouteEditor.replaceText( + 'componentsRoute', + interactiveBoxLabelSource, + interactiveBoxHmrLabelSource, + ) + + await waitForComponentsServerHtmlText(page, 'hmr visible') + if (isVite) { + await waitForVisibleHydrateVirtualModule(page, 'hmr ') + } + + await page.goto('/components') + await expectClientRouterReady(page) + await expectRouteToStayUnhydrated(page, 'component-visible-button') + await scrollToBoundary(page, 'component-visible-button') + await hmrExpect(page.getByTestId('component-visible-button')).toContainText( + 'hmr visible', + ) + await clickAndExpectCount( + page, + 'component-visible-button', + 'component-visible-count', + '1', + ) + expect(pageErrors).toEqual([]) + }) +}) + +test.describe('component-level Hydrate runtime strategies', () => { + test.skip( + isDev, + 'production hydration coverage runs against the preview server', + ) + + test('renders SSR HTML and hydrates each runtime when appropriately', async ({ + page, + request, + }) => { + await page.goto('/components') + + await expect(page.getByTestId('component-heading')).toHaveText( + 'Component Deferred Hydration', + ) + + await clickAndExpectCount( + page, + 'component-load-button', + 'component-load-count', + '1', + ) + await clickAndExpectCount( + page, + 'component-idle-button', + 'component-idle-count', + '1', + ) + await expect( + resourceContentsContain(page, request, 'component-visible', (url) => + isHydrateBoundaryResource(url), + ), + ).resolves.toBe(false) + await expectRouteToStayUnhydrated(page, 'component-visible-button') + await scrollToBoundary(page, 'component-visible-button') + await clickAndExpectCount( + page, + 'component-visible-button', + 'component-visible-count', + '1', + ) + await expect + .poll(() => + resourceContentsContain(page, request, 'component-visible', (url) => + isHydrateBoundaryResource(url), + ), + ) + .toBe(true) + await clickAndExpectCount( + page, + 'component-media-button', + 'component-media-count', + '1', + ) + await hoverIntentAndExpectCount( + page, + 'component-interaction-button', + 'component-interaction-count', + '1', + ) + await expect(page.getByTestId('component-on-hydrated-count')).toHaveText( + '0', + ) + await expectRouteToStayUnhydrated(page, 'component-custom-single-button') + await page.getByTestId('component-custom-single-button').hover() + await expectRouteToStayUnhydrated(page, 'component-custom-single-button') + await page.getByTestId('component-custom-single-button').click() + await expectRouteToStayUnhydrated(page, 'component-custom-single-button') + await dispatchHydrationIntent( + page, + 'component-custom-single-button', + 'dblclick', + ) + await expect( + page.getByTestId('component-custom-single-button'), + ).toHaveAttribute('data-hydrated', 'true') + await expect(page.getByTestId('component-on-hydrated-count')).toHaveText( + '1', + ) + await clickAndExpectCount( + page, + 'component-custom-single-button', + 'component-custom-single-count', + '1', + ) + await expect(page.getByTestId('component-on-hydrated-count')).toHaveText( + '1', + ) + await expectRouteToStayUnhydrated(page, 'component-custom-multi-button') + await dispatchHydrationIntent( + page, + 'component-custom-multi-button', + 'contextmenu', + ) + await clickAndExpectCount( + page, + 'component-custom-multi-button', + 'component-custom-multi-count', + '1', + ) + await expectRouteToStayUnhydrated(page, 'component-condition-button') + await page.getByTestId('component-enable-condition').click() + await clickAndExpectCount( + page, + 'component-condition-button', + 'component-condition-count', + '1', + ) + await expectRouteToStayUnhydrated(page, 'component-click-replay-button') + await page.getByTestId('component-click-replay-button').click() + await expect( + page.getByTestId('component-click-replay-button'), + ).toHaveAttribute('data-hydrated', 'true') + await expect(page.getByTestId('component-click-replay-count')).toHaveText( + '1', + ) + await expectRouteToStayUnhydrated(page, 'component-prefetch-button') + await expect( + resourceContentsContain(page, request, 'component-prefetch', (url) => + isHydrateBoundaryResource(url), + ), + ).resolves.toBe(false) + await page.mouse.move(0, 0) + await page.getByTestId('component-prefetch-button').hover() + await expect(page.getByTestId('component-prefetch-button')).toHaveAttribute( + 'data-hydrated', + 'false', + ) + await expect + .poll(() => + resourceContentsContain(page, request, 'component-prefetch', (url) => + isHydrateBoundaryResource(url), + ), + ) + .toBe(true) + await expect(page.getByTestId('component-prefetch-button')).toHaveAttribute( + 'data-hydrated', + 'false', + ) + await page.getByTestId('component-prefetch-button').click() + await expect(page.getByTestId('component-prefetch-button')).toHaveAttribute( + 'data-hydrated', + 'true', + ) + await expect(page.getByTestId('component-prefetch-count')).toHaveText('1') + await hoverIntentAndExpectCount( + page, + 'component-nested-child-button', + 'component-nested-child-count', + '1', + ) + + await page.getByTestId('component-never-button').click() + await expect(page.getByTestId('component-never-count')).toHaveText('0') + }) + + test('replays click after another interaction boundary hydrates first', async ({ + page, + }) => { + await page.goto('/components') + await expectClientRouterReady(page) + + await scrollToBoundary(page, 'component-custom-multi-button') + await expectRouteToStayUnhydrated(page, 'component-custom-multi-button') + await page.getByTestId('component-custom-multi-button').click({ + button: 'right', + }) + await expect( + page.getByTestId('component-custom-multi-button'), + ).toHaveAttribute('data-hydrated', 'true') + + await scrollToBoundary(page, 'component-click-replay-button') + await expectRouteToStayUnhydrated(page, 'component-click-replay-button') + await page.getByTestId('component-click-replay-button').click() + await expect( + page.getByTestId('component-click-replay-button'), + ).toHaveAttribute('data-hydrated', 'true') + await expect(page.getByTestId('component-click-replay-count')).toHaveText( + '1', + ) + }) + + test('shows fallback during a client-only mount while the child suspends', async ({ + page, + }) => { + await page.goto('/components') + await expect(page.getByTestId('component-load-button')).toHaveAttribute( + 'data-hydrated', + 'true', + ) + await page.getByTestId('component-show-client-fallback').click() + + await expect(page.getByTestId('component-client-fallback')).toHaveText( + 'client fallback', + ) + await expect(page.getByTestId('component-fallback-child')).toHaveText( + 'fallback child', + ) + await expect(page.getByTestId('component-client-fallback')).toHaveCount(0) + }) + + test('preserves scroll position after a force reload on a visible boundary', async ({ + page, + }) => { + await page.goto('/scroll-restoration') + await expectClientRouterReady(page) + await page + .getByTestId('scroll-restoration-skeleton') + .scrollIntoViewIfNeeded() + await expect(page.getByTestId('scroll-restoration-widget')).toHaveAttribute( + 'data-hydrated', + 'true', + ) + await page.evaluate(() => { + window.scrollTo(0, document.documentElement.scrollHeight) + }) + + const beforeReloadDistanceFromBottom = await page.evaluate( + () => + document.documentElement.scrollHeight - + window.innerHeight - + window.scrollY, + ) + expect(beforeReloadDistanceFromBottom).toBeLessThan(5) + + const client = await page.context().newCDPSession(page) + const reloaded = page.waitForEvent('load') + await client.send('Page.reload', { ignoreCache: true }) + await reloaded + + await expectClientRouterReady(page) + await expect(page.getByTestId('scroll-restoration-widget')).toHaveAttribute( + 'data-hydrated', + 'true', + ) + + await expect + .poll(() => + page.evaluate( + () => + document.documentElement.scrollHeight - + window.innerHeight - + window.scrollY, + ), + ) + .toBeLessThan(20) + }) +}) + +test.describe('enhanced Hydrate API combinations', () => { + test.skip( + isDev, + 'production hydration coverage runs against the preview server', + ) + + test('server renders dynamic markers without evaluating client-only callbacks or prefetch functions', async ({ + request, + }) => { + const response = await request.get('/enhanced?dynamic=interaction') + const html = await response.text() + + expect(response.ok()).toBe(true) + htmlContainsText(html, 'Enhanced Hydrate APIs') + htmlContainsText(html, 'conditional dynamic') + expect(html).toContain('data-ts-hydrate-when="dynamic"') + expect(html).not.toContain('missing-element') + }) + + test('dynamic when functions hydrate and replay interaction events', async ({ + page, + }) => { + await gotoEnhanced(page, '?dynamic=interaction') + await expect(page.getByTestId('enhanced-heading')).toHaveText( + 'Enhanced Hydrate APIs', + ) + await clickIntentAndExpectReplayedCount( + page, + 'enhanced-dynamic-interaction-button', + 'enhanced-dynamic-interaction-count', + '1', + ) + + await expectRouteToStayUnhydrated( + page, + 'enhanced-dynamic-conditional-button', + ) + await page.getByTestId('enhanced-dynamic-conditional-button').hover() + await expectRouteToStayUnhydrated( + page, + 'enhanced-dynamic-conditional-button', + ) + await clickIntentAndExpectReplayedCount( + page, + 'enhanced-dynamic-conditional-button', + 'enhanced-dynamic-conditional-count', + '1', + ) + }) + + test('procedural prefetch can block hydration, preload the split chunk, and prepare query-like work', async ({ + page, + request, + }) => { + await gotoEnhanced(page) + await expect( + resourceContentsContain( + page, + request, + 'enhanced-procedural-split-child', + isClientJavaScriptResource, + ), + ).resolves.toBe(false) + + await expectRouteToStayUnhydrated(page, 'enhanced-procedural-split-button') + await expect(page.getByTestId('enhanced-split-wait-reason')).toHaveText( + 'waiting', + ) + await dispatchHydrationIntent( + page, + 'enhanced-procedural-split-button', + 'pointerover', + ) + await expect(page.getByTestId('enhanced-split-query')).toHaveText('element') + await expect(page.getByTestId('enhanced-split-wait-reason')).toHaveText( + 'prefetch', + ) + await expect(page.getByTestId('enhanced-split-preload')).toHaveText('done') + await expect + .poll(() => + resourceContentsContain( + page, + request, + 'enhanced-procedural-split-child', + isClientJavaScriptResource, + ), + ) + .toBe(true) + + await page.getByTestId('enhanced-procedural-split-button').click() + await expect( + page.getByTestId('enhanced-procedural-split-button'), + ).toHaveAttribute('data-hydrated', 'false') + await expect( + page.getByTestId('enhanced-procedural-split-count'), + ).toHaveText('0') + await page.getByTestId('enhanced-release-split-prefetch').click() + await expect( + page.getByTestId('enhanced-procedural-split-button'), + ).toHaveAttribute('data-hydrated', 'true') + await expect( + page.getByTestId('enhanced-procedural-split-count'), + ).toHaveText('1') + await expect(page.getByTestId('enhanced-split-query')).toHaveText('done') + }) + + test('function prefetch supports fire-and-forget work and waitFor hydrate-first resolution', async ({ + page, + }) => { + await gotoEnhanced(page) + + await expect(page.getByTestId('enhanced-fire-wait-reason')).toHaveText( + 'waiting', + ) + await dispatchHydrationIntent( + page, + 'enhanced-fire-and-forget-button', + 'pointerover', + ) + await expect(page.getByTestId('enhanced-fire-wait-reason')).toHaveText( + 'prefetch', + ) + await expect(page.getByTestId('enhanced-fire-status')).toHaveText('started') + await clickIntentAndExpectReplayedCount( + page, + 'enhanced-fire-and-forget-button', + 'enhanced-fire-and-forget-count', + '1', + ) + await expect(page.getByTestId('enhanced-fire-query')).toHaveText('idle') + await page.getByTestId('enhanced-release-fire-prefetch').click() + await expect(page.getByTestId('enhanced-fire-query')).toHaveText('done') + + await clickIntentAndExpectReplayedCount( + page, + 'enhanced-hydrate-first-button', + 'enhanced-hydrate-first-count', + '1', + ) + await expect(page.getByTestId('enhanced-hydrate-first-reason')).toHaveText( + 'hydrate', + ) + }) + + test('split=false procedural prefetch blocks hydration without requiring a child preload chunk', async ({ + page, + }) => { + await gotoEnhanced(page) + + await expectRouteToStayUnhydrated(page, 'enhanced-runtime-only-button') + await expect(page.getByTestId('enhanced-runtime-wait-reason')).toHaveText( + 'waiting', + ) + await dispatchHydrationIntent( + page, + 'enhanced-runtime-only-button', + 'pointerover', + ) + await expect(page.getByTestId('enhanced-runtime-wait-reason')).toHaveText( + 'prefetch', + ) + await page.getByTestId('enhanced-runtime-only-button').click() + await expect( + page.getByTestId('enhanced-runtime-only-button'), + ).toHaveAttribute('data-hydrated', 'false') + await expect(page.getByTestId('enhanced-runtime-only-count')).toHaveText( + '0', + ) + await page.getByTestId('enhanced-release-runtime-prefetch').click() + await expect(page.getByTestId('enhanced-runtime-status')).toHaveText( + 'ready', + ) + await expect( + page.getByTestId('enhanced-runtime-only-button'), + ).toHaveAttribute('data-hydrated', 'true') + await expect(page.getByTestId('enhanced-runtime-only-count')).toHaveText( + '1', + ) + }) + + test('procedural prefetch aborts waiters and signals when boundaries unmount', async ({ + page, + }) => { + await gotoEnhanced(page) + + await expectRouteToStayUnhydrated(page, 'enhanced-wait-abort-button') + await expect(page.getByTestId('enhanced-wait-abort-reason')).toHaveText( + 'waiting', + ) + await page.getByTestId('enhanced-hide-wait-abort').click() + await expect(page.getByTestId('enhanced-wait-abort-reason')).toHaveText( + 'abort', + ) + + await expect(page.getByTestId('enhanced-abort-status')).toHaveText( + 'listening', + ) + await page.getByTestId('enhanced-hide-abort').click() + await expect(page.getByTestId('enhanced-abort-status')).toHaveText( + 'aborted', + ) + }) + + test('nested dynamic interaction boundaries delegate through outer boundaries', async ({ + page, + }) => { + await gotoEnhanced(page) + + await clickToHydrateThenClickAndExpectIncrement( + page, + 'enhanced-dynamic-nested-button', + 'enhanced-dynamic-nested-count', + ) + await clickToHydrateThenClickAndExpectIncrement( + page, + 'enhanced-cross-file-nested-button', + 'enhanced-cross-file-nested-count', + ) + }) +}) + +test.describe('Hydrate CSS delivery', () => { + test.skip( + isDev, + 'production hydration coverage runs against the preview server', + ) + + test('ships CSS for deferred, never, shared, and nested boundaries without JavaScript', async ({ + browser, + request, + }) => { + const response = await request.get('/css') + const html = await response.text() + + htmlContainsText(html, 'CSS Deferred Hydration') + htmlContainsText(html, 'Outer CSS') + htmlContainsText(html, 'Deferred CSS') + htmlContainsText(html, 'Never CSS') + htmlContainsText(html, 'Nested CSS') + + const context = await browser.newContext({ javaScriptEnabled: false }) + const page = await context.newPage() + + try { + await page.goto('/css') + + await expect(page.getByTestId('css-heading')).toHaveText( + 'CSS Deferred Hydration', + ) + await expect(page.getByTestId('css-deferred')).toHaveText('Deferred CSS') + await expect(page.getByTestId('css-never')).toHaveText('Never CSS') + await expect(page.getByTestId('css-nested')).toHaveText('Nested CSS') + + await expectCssProperty(page, 'css-outer', 'color', 'rgb(12, 34, 56)') + await expectCssProperty( + page, + 'css-deferred', + 'background-color', + 'rgb(23, 45, 67)', + ) + await expectCssProperty(page, 'css-never', 'color', 'rgb(45, 67, 89)') + await expectCssProperty( + page, + 'css-shared-outer', + 'border-top-color', + 'rgb(98, 76, 54)', + ) + await expectCssProperty( + page, + 'css-deferred', + 'border-top-color', + 'rgb(98, 76, 54)', + ) + await expectCssProperty( + page, + 'css-nested', + 'border-left-color', + 'rgb(67, 89, 123)', + ) + await expectCssProperty(page, 'css-nested', 'border-left-width', '5px') + } finally { + await context.close() + } + }) + + test('renders deferred content and omits never content after client-side navigation', async ({ + page, + }) => { + await page.goto('/') + await expectClientRouterReady(page) + await page.getByRole('link', { name: 'CSS', exact: true }).click() + await expect(page).toHaveURL(/\/css$/) + + await expect(page.getByTestId('css-heading')).toHaveText( + 'CSS Deferred Hydration', + ) + await expect(page.getByTestId('css-deferred')).toHaveText('Deferred CSS') + await expect(page.getByTestId('css-never')).toHaveCount(0) + await expect(page.getByTestId('css-nested')).toHaveCount(0) + + await expectCssProperty( + page, + 'css-deferred', + 'background-color', + 'rgb(23, 45, 67)', + ) + }) +}) + +test.describe('imported Hydrate boundaries', () => { + test.skip( + isDev, + 'production hydration coverage runs against the preview server', + ) + + test('does not emit filtered shared Hydrate child JS on the initial document', async ({ + request, + }) => { + const response = await request.get('/imported') + const html = await response.text() + + htmlContainsText(html, 'Imported Hydrate') + htmlContainsText(html, 'Imported Hydrate Child') + + await expect( + modulePreloadContentsContain( + request, + getModulePreloadHrefs(html), + 'imported-hydrate-child', + ), + ).resolves.toBe(false) + }) + + test('does not preload Hydrate child chunks before client navigation', async ({ + page, + request, + }) => { + await page.goto('/') + await expect(page.getByTestId('home-heading')).toHaveText( + 'Deferred Hydration', + ) + await expectClientRouterReady(page) + + const link = page.getByRole('link', { name: 'imported Hydrate' }) + await page.mouse.move(0, 0) + await link.hover() + await link.focus() + + await expect( + modulePreloadContentsContain( + request, + await documentModulePreloadHrefs(page), + 'imported-hydrate-child', + ), + ).resolves.toBe(false) + await expect( + resourceContentsContain(page, request, 'imported-hydrate-child', (url) => + isClientJavaScriptResource(url), + ), + ).resolves.toBe(false) + + await page.getByRole('link', { name: 'imported Hydrate' }).click() + await expect(page).toHaveURL(/\/imported$/) + await expect(page.getByTestId('imported-hydrate-fallback')).toHaveCount(0) + await expect(page.getByTestId('imported-hydrate-child')).toContainText( + 'Imported Hydrate Child', + ) + await clickAndExpectCount( + page, + 'imported-hydrate-child', + 'imported-hydrate-count', + '1', + ) + }) + + test('hydrates imported child boundaries from the initial document on interaction', async ({ + page, + request, + }) => { + await page.goto('/imported') + await expect(page.getByTestId('imported-heading')).toHaveText( + 'Imported Hydrate', + ) + await expectClientRouterReady(page) + await expect(page.getByTestId('imported-hydrate-fallback')).toHaveCount(0) + await expectRouteToStayUnhydrated(page, 'imported-hydrate-child') + await expect( + resourceContentsContain(page, request, 'imported-hydrate-child', (url) => + isClientJavaScriptResource(url), + ), + ).resolves.toBe(false) + + await page.getByTestId('imported-hydrate-child').click() + await expect(page.getByTestId('imported-hydrate-child')).toHaveAttribute( + 'data-hydrated', + 'true', + ) + await expect(page.getByTestId('imported-hydrate-count')).toHaveText('1') + await expect + .poll(() => + resourceContentsContain( + page, + request, + 'imported-hydrate-child', + isClientJavaScriptResource, + ), + ) + .toBe(true) + }) +}) diff --git a/e2e/react-start/deferred-hydration/tests/setup/global.setup.ts b/e2e/react-start/deferred-hydration/tests/setup/global.setup.ts new file mode 100644 index 0000000000..1117664a14 --- /dev/null +++ b/e2e/react-start/deferred-hydration/tests/setup/global.setup.ts @@ -0,0 +1,38 @@ +import { + e2eStartDummyServer, + getTestServerPort, + preOptimizeDevServer, + waitForServer, +} from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +function getE2EPortKey() { + const toolchain = process.env.E2E_TOOLCHAIN ?? 'vite' + return process.env.E2E_PORT_KEY ?? `${packageJson.name}-${toolchain}` +} + +export default async function setup() { + if (process.env.MODE !== 'dev') return + + const e2ePortKey = getE2EPortKey() + + await e2eStartDummyServer(e2ePortKey) + + const port = await getTestServerPort(e2ePortKey) + const baseURL = `http://localhost:${port}` + + await waitForServer(baseURL) + await preOptimizeDevServer({ + baseURL, + readyTestId: 'home-heading', + warmup: async (page) => { + await page.goto(`${baseURL}/components`, { + waitUntil: 'domcontentloaded', + }) + await page.getByTestId('component-heading').waitFor({ + state: 'visible', + }) + await page.waitForLoadState('networkidle') + }, + }) +} diff --git a/e2e/react-start/deferred-hydration/tests/setup/global.teardown.ts b/e2e/react-start/deferred-hydration/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..df79f50e82 --- /dev/null +++ b/e2e/react-start/deferred-hydration/tests/setup/global.teardown.ts @@ -0,0 +1,13 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +function getE2EPortKey() { + const toolchain = process.env.E2E_TOOLCHAIN ?? 'vite' + return process.env.E2E_PORT_KEY ?? `${packageJson.name}-${toolchain}` +} + +export default async function teardown() { + if (process.env.MODE !== 'dev') return + + await e2eStopDummyServer(getE2EPortKey()) +} diff --git a/e2e/react-start/deferred-hydration/tsconfig.json b/e2e/react-start/deferred-hydration/tsconfig.json new file mode 100644 index 0000000000..cef9369516 --- /dev/null +++ b/e2e/react-start/deferred-hydration/tsconfig.json @@ -0,0 +1,21 @@ +{ + "include": ["**/*.ts", "**/*.tsx"], + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "jsx": "react-jsx", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["DOM", "DOM.Iterable", "ES2022"], + "isolatedModules": true, + "resolveJsonModule": true, + "skipLibCheck": true, + "target": "ES2022", + "allowJs": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "~/*": ["./src/*"] + }, + "noEmit": true + } +} diff --git a/e2e/react-start/deferred-hydration/vite.config.ts b/e2e/react-start/deferred-hydration/vite.config.ts new file mode 100644 index 0000000000..1289bc0be7 --- /dev/null +++ b/e2e/react-start/deferred-hydration/vite.config.ts @@ -0,0 +1,14 @@ +import { defineConfig } from 'vite' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import viteReact from '@vitejs/plugin-react' + +const outDir = process.env.E2E_DIST_DIR ?? 'dist-vite-ssr' + +export default defineConfig({ + resolve: { tsconfigPaths: true }, + build: { + outDir, + }, + server: { port: 3000 }, + plugins: [tanstackStart(), viteReact()], +}) diff --git a/e2e/react-start/hmr/tests/app.spec.ts b/e2e/react-start/hmr/tests/app.spec.ts index b3ac8b6a1a..95914f6270 100644 --- a/e2e/react-start/hmr/tests/app.spec.ts +++ b/e2e/react-start/hmr/tests/app.spec.ts @@ -1,7 +1,10 @@ -import { readFile, writeFile } from 'node:fs/promises' -import path from 'node:path' import { expect } from '@playwright/test' -import { test } from '@tanstack/router-e2e-utils' +import { + createHmrFileEditor, + replaceAll, + test, +} from '@tanstack/router-e2e-utils' +import path from 'node:path' import type { Page } from '@playwright/test' @@ -115,14 +118,6 @@ const routeFileRestoreChecks: Partial< }, } -// Capture original file contents once so beforeEach can restore them -const originalContents: Partial> = {} -const routeKeysPendingRestoreCheck = new Set() - -function replaceAll(source: string, from: string, to: string) { - return source.split(from).join(to) -} - function normalizeRouteSource(routeFileKey: RouteFileKey, source: string) { let next = source @@ -254,59 +249,14 @@ function normalizeRouteSource(routeFileKey: RouteFileKey, source: string) { return next } -async function captureOriginals() { - for (const [key, filePath] of Object.entries(routeFiles) as Array< - [RouteFileKey, string] - >) { - const current = await readFile(filePath, 'utf8') - const normalized = normalizeRouteSource(key, current) - if (normalized !== current) { - await writeFile(filePath, normalized) - routeKeysPendingRestoreCheck.add(key) - } - originalContents[key] = normalized - } -} - -const capturePromise = captureOriginals() - -async function restoreRouteFiles( - forceRouteFileKeys: Iterable = [], -) { - const forceRestoreKeys = new Set(forceRouteFileKeys) - const restoredRouteKeys: Array = [] - - for (const [key, filePath] of Object.entries(routeFiles) as Array< - [RouteFileKey, string] - >) { - const content = originalContents[key] - if (content === undefined) continue - const current = await readFile(filePath, 'utf8') - // Re-emit pending restores in case the watcher coalesced the previous - // restore write and the dev server is still serving stale route options. - if (current !== content || forceRestoreKeys.has(key)) { - await writeFile(filePath, content) - restoredRouteKeys.push(key) - } - } - - return restoredRouteKeys -} - -async function replaceRouteText( - routeFileKey: RouteFileKey, - from: string, - to: string, -) { - const filePath = routeFiles[routeFileKey] - const source = await readFile(filePath, 'utf8') - - if (!source.includes(from)) { - throw new Error(`Expected route file to include ${JSON.stringify(from)}`) - } - - await writeFile(filePath, source.replace(from, to)) -} +const routeFileEditor = createHmrFileEditor({ + files: routeFiles, + normalizeSource: normalizeRouteSource, +}) +const capturePromise = routeFileEditor.capturePromise +const routeKeysPendingRestoreCheck = routeFileEditor.pendingRestoreKeys +const restoreRouteFiles = routeFileEditor.restoreFiles +const replaceRouteText = routeFileEditor.replaceText async function replaceRouteTextAndWait( page: Page, @@ -315,7 +265,7 @@ async function replaceRouteTextAndWait( to: string, assertion: () => Promise, ) { - await replaceRouteText(routeFileKey, from, to) + await routeFileEditor.replaceText(routeFileKey, from, to) await assertion() } @@ -326,17 +276,7 @@ async function rewriteRouteFile( assertion: () => Promise, options: { allowNoop?: boolean } = {}, ) { - const filePath = routeFiles[routeFileKey] - const source = await readFile(filePath, 'utf8') - const updated = updater(source) - - if (updated === source && !options.allowNoop) { - throw new Error(`Expected ${filePath} to change during rewrite`) - } - - // Even a no-op write is useful for tests that need to force the dev server - // to reconcile a stale in-memory module with the current file contents. - await writeFile(filePath, updated) + await routeFileEditor.rewriteFile(routeFileKey, updater, options) await assertion() } diff --git a/e2e/react-start/rsc-deferred-hydration/.gitignore b/e2e/react-start/rsc-deferred-hydration/.gitignore new file mode 100644 index 0000000000..cc99170fbb --- /dev/null +++ b/e2e/react-start/rsc-deferred-hydration/.gitignore @@ -0,0 +1,5 @@ +dist +node_modules +port*.txt +test-results +playwright-report diff --git a/e2e/react-start/rsc-deferred-hydration/package.json b/e2e/react-start/rsc-deferred-hydration/package.json new file mode 100644 index 0000000000..7944b81552 --- /dev/null +++ b/e2e/react-start/rsc-deferred-hydration/package.json @@ -0,0 +1,45 @@ +{ + "name": "tanstack-react-start-e2e-rsc-deferred-hydration", + "private": true, + "sideEffects": false, + "type": "module", + "scripts": { + "dev": "vite dev --port 3000", + "dev:e2e": "vite dev", + "build": "vite build && tsc --noEmit", + "preview": "vite preview", + "start": "node server.js", + "test:e2e": "pnpm test:e2e:dev && pnpm test:e2e:prod", + "test:e2e:dev": "MODE=dev playwright test --project=chromium", + "test:e2e:prod": "MODE=prod playwright test --project=chromium" + }, + "nx": { + "metadata": { + "playwrightModes": [ + { + "toolchain": "vite", + "mode": "ssr", + "shards": 1 + } + ] + } + }, + "dependencies": { + "@tanstack/react-router": "workspace:^", + "@tanstack/react-start": "workspace:^", + "react": "^19.0.0", + "react-dom": "^19.0.0", + "vite": "^8.0.0" + }, + "devDependencies": { + "@playwright/test": "^1.50.1", + "@tanstack/router-e2e-utils": "workspace:^", + "@types/node": "^22.10.2", + "@types/react": "^19.0.8", + "@types/react-dom": "^19.0.3", + "@vitejs/plugin-react": "^6.0.1", + "@vitejs/plugin-rsc": "^0.5.20", + "srvx": "^0.11.9", + "typescript": "^6.0.2" + } +} diff --git a/e2e/react-start/rsc-deferred-hydration/playwright.config.ts b/e2e/react-start/rsc-deferred-hydration/playwright.config.ts new file mode 100644 index 0000000000..10f41cd911 --- /dev/null +++ b/e2e/react-start/rsc-deferred-hydration/playwright.config.ts @@ -0,0 +1,35 @@ +import { defineConfig, devices } from '@playwright/test' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } + +const PORT = await getTestServerPort(packageJson.name) +const baseURL = `http://localhost:${PORT}` +const mode = process.env.MODE ?? 'prod' +const isDev = mode === 'dev' + +export default defineConfig({ + testDir: './tests', + workers: 1, + reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { baseURL }, + webServer: { + command: isDev ? 'pnpm dev:e2e' : 'pnpm build && pnpm start', + url: baseURL, + reuseExistingServer: !process.env.CI, + stdout: 'pipe', + env: { + VITE_NODE_ENV: 'test', + NODE_ENV: isDev ? 'development' : 'production', + PORT: String(PORT), + VITE_SERVER_PORT: String(PORT), + }, + }, + projects: [ + { + name: 'chromium', + use: { ...devices['Desktop Chrome'] }, + }, + ], +}) diff --git a/e2e/react-start/rsc-deferred-hydration/server.js b/e2e/react-start/rsc-deferred-hydration/server.js new file mode 100644 index 0000000000..6365c568d4 --- /dev/null +++ b/e2e/react-start/rsc-deferred-hydration/server.js @@ -0,0 +1,47 @@ +import fs from 'node:fs' +import path from 'node:path' +import { spawn } from 'node:child_process' +import { pathToFileURL } from 'node:url' + +const distDir = process.env.E2E_DIST_DIR || 'dist' + +function resolveDistClientDir() { + return path.resolve(distDir, 'client') +} + +function resolveDistServerEntryPath() { + const serverJsPath = path.resolve(distDir, 'server', 'server.js') + if (fs.existsSync(serverJsPath)) return serverJsPath + + const indexJsPath = path.resolve(distDir, 'server', 'index.js') + if (fs.existsSync(indexJsPath)) return indexJsPath + + return serverJsPath +} + +export function start() { + const child = spawn( + 'srvx', + ['--prod', '-s', resolveDistClientDir(), resolveDistServerEntryPath()], + { + stdio: 'inherit', + shell: process.platform === 'win32', + }, + ) + + child.on('exit', (code, signal) => { + if (signal) { + process.kill(process.pid, signal) + return + } + + process.exit(code ?? 0) + }) +} + +if ( + process.argv[1] && + import.meta.url === pathToFileURL(process.argv[1]).href +) { + start() +} diff --git a/e2e/react-start/rsc-deferred-hydration/src/components/CssHydrateIsland.module.css b/e2e/react-start/rsc-deferred-hydration/src/components/CssHydrateIsland.module.css new file mode 100644 index 0000000000..d80e17aebe --- /dev/null +++ b/e2e/react-start/rsc-deferred-hydration/src/components/CssHydrateIsland.module.css @@ -0,0 +1,42 @@ +.cssIsland { + border-color: rgba(16, 185, 129, 0.38); + background: + linear-gradient( + 135deg, + rgba(236, 253, 245, 0.96), + rgba(255, 255, 255, 0.9) + ), + repeating-linear-gradient( + 45deg, + rgba(16, 185, 129, 0.12) 0 8px, + transparent 8px 16px + ); + color: rgb(6, 78, 59); +} + +.cssIsland h2 { + color: rgb(6, 95, 70); +} + +.cssMarker { + width: fit-content; + padding: 0.45rem 0.7rem; + border-radius: 999px; + font-weight: 900; + transition: + background 180ms ease, + color 180ms ease, + box-shadow 180ms ease; +} + +.cssMarkerPending { + background: rgb(252, 231, 243); + color: rgb(157, 23, 77); + box-shadow: 0 8px 26px rgba(219, 39, 119, 0.18); +} + +.cssMarkerHydrated { + background: rgb(209, 250, 229); + color: rgb(6, 95, 70); + box-shadow: 0 8px 26px rgba(5, 150, 105, 0.18); +} diff --git a/e2e/react-start/rsc-deferred-hydration/src/components/CssHydrateIsland.tsx b/e2e/react-start/rsc-deferred-hydration/src/components/CssHydrateIsland.tsx new file mode 100644 index 0000000000..7f023bd10c --- /dev/null +++ b/e2e/react-start/rsc-deferred-hydration/src/components/CssHydrateIsland.tsx @@ -0,0 +1,45 @@ +'use client' + +import * as React from 'react' +import { Hydrate } from '@tanstack/react-start' +import { media } from '@tanstack/react-start/hydration' +import { DeferredHydrateIsland } from './DeferredHydrateIsland' +import styles from './CssHydrateIsland.module.css' + +function CssHydratePanel() { + const [hydrated, setHydrated] = React.useState(false) + + React.useEffect(() => { + setHydrated(true) + }, []) + + return ( +
+ CSS module Hydrate island +

CSS modules survive the RSC to client boundary

+

+ {hydrated + ? 'Hydrated module-styled client content' + : 'Pending module-styled client content'} +

+ +
+ ) +} + +export function CssHydrateIsland() { + return ( +
+ + + +
+ ) +} diff --git a/e2e/react-start/rsc-deferred-hydration/src/components/DeferredHydrateIsland.tsx b/e2e/react-start/rsc-deferred-hydration/src/components/DeferredHydrateIsland.tsx new file mode 100644 index 0000000000..0a716fe39c --- /dev/null +++ b/e2e/react-start/rsc-deferred-hydration/src/components/DeferredHydrateIsland.tsx @@ -0,0 +1,67 @@ +'use client' + +import * as React from 'react' +import { Hydrate } from '@tanstack/react-start' +import { interaction, media, visible } from '@tanstack/react-start/hydration' + +type Strategy = 'interaction' | 'visible' | 'media' + +const strategyCopy: Record = { + interaction: 'Hydrates after pointer or focus intent reaches this island.', + visible: 'Hydrates only after the island scrolls into the viewport.', + media: 'Hydrates immediately when the matching media query is true.', +} + +function getStrategy(strategy: Strategy) { + if (strategy === 'interaction') return interaction() + if (strategy === 'visible') return visible({ rootMargin: '0px' }) + return media('(min-width: 1px)') +} + +export function CounterButton(props: { id: string; label: string }) { + const [count, setCount] = React.useState(0) + const [hydrated, setHydrated] = React.useState(false) + + React.useEffect(() => { + setHydrated(true) + }, []) + + return ( + + ) +} + +export function DeferredHydrateIsland(props: { + id: string + title: string + strategy: Strategy + className?: string +}) { + return ( +
+ Client Hydrate island +

{props.title}

+

{strategyCopy[props.strategy]}

+ + + +
+ ) +} diff --git a/e2e/react-start/rsc-deferred-hydration/src/routeTree.gen.ts b/e2e/react-start/rsc-deferred-hydration/src/routeTree.gen.ts new file mode 100644 index 0000000000..246737b515 --- /dev/null +++ b/e2e/react-start/rsc-deferred-hydration/src/routeTree.gen.ts @@ -0,0 +1,122 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as ServerClientRouteImport } from './routes/server-client' +import { Route as CssRouteImport } from './routes/css' +import { Route as CompositeRouteImport } from './routes/composite' +import { Route as IndexRouteImport } from './routes/index' + +const ServerClientRoute = ServerClientRouteImport.update({ + id: '/server-client', + path: '/server-client', + getParentRoute: () => rootRouteImport, +} as any) +const CssRoute = CssRouteImport.update({ + id: '/css', + path: '/css', + getParentRoute: () => rootRouteImport, +} as any) +const CompositeRoute = CompositeRouteImport.update({ + id: '/composite', + path: '/composite', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/composite': typeof CompositeRoute + '/css': typeof CssRoute + '/server-client': typeof ServerClientRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/composite': typeof CompositeRoute + '/css': typeof CssRoute + '/server-client': typeof ServerClientRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/composite': typeof CompositeRoute + '/css': typeof CssRoute + '/server-client': typeof ServerClientRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/composite' | '/css' | '/server-client' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/composite' | '/css' | '/server-client' + id: '__root__' | '/' | '/composite' | '/css' | '/server-client' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + CompositeRoute: typeof CompositeRoute + CssRoute: typeof CssRoute + ServerClientRoute: typeof ServerClientRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/server-client': { + id: '/server-client' + path: '/server-client' + fullPath: '/server-client' + preLoaderRoute: typeof ServerClientRouteImport + parentRoute: typeof rootRouteImport + } + '/css': { + id: '/css' + path: '/css' + fullPath: '/css' + preLoaderRoute: typeof CssRouteImport + parentRoute: typeof rootRouteImport + } + '/composite': { + id: '/composite' + path: '/composite' + fullPath: '/composite' + preLoaderRoute: typeof CompositeRouteImport + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + CompositeRoute: CompositeRoute, + CssRoute: CssRoute, + ServerClientRoute: ServerClientRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() + +import type { getRouter } from './router.tsx' +import type { createStart } from '@tanstack/react-start' +declare module '@tanstack/react-start' { + interface Register { + ssr: true + router: Awaited> + } +} diff --git a/e2e/react-start/rsc-deferred-hydration/src/router.tsx b/e2e/react-start/rsc-deferred-hydration/src/router.tsx new file mode 100644 index 0000000000..9d87d8748b --- /dev/null +++ b/e2e/react-start/rsc-deferred-hydration/src/router.tsx @@ -0,0 +1,9 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + scrollRestoration: true, + }) +} diff --git a/e2e/react-start/rsc-deferred-hydration/src/routes/__root.tsx b/e2e/react-start/rsc-deferred-hydration/src/routes/__root.tsx new file mode 100644 index 0000000000..7ce2e7bdb1 --- /dev/null +++ b/e2e/react-start/rsc-deferred-hydration/src/routes/__root.tsx @@ -0,0 +1,122 @@ +/// +import * as React from 'react' +import { + HeadContent, + Link, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/react-router' + +export const Route = createRootRoute({ + head: () => ({ + meta: [ + { charSet: 'utf-8' }, + { name: 'viewport', content: 'width=device-width, initial-scale=1' }, + { title: 'RSC Deferred Hydration E2E' }, + ], + }), + shellComponent: RootDocument, + component: () => ( +
+ +
+ ), +}) + +function RootDocument({ children }: { children: React.ReactNode }) { + return ( + + + + + + + + {children} + + + + ) +} diff --git a/e2e/react-start/rsc-deferred-hydration/src/routes/composite.tsx b/e2e/react-start/rsc-deferred-hydration/src/routes/composite.tsx new file mode 100644 index 0000000000..3241ee487d --- /dev/null +++ b/e2e/react-start/rsc-deferred-hydration/src/routes/composite.tsx @@ -0,0 +1,24 @@ +import { createFileRoute } from '@tanstack/react-router' +import { CompositeComponent } from '@tanstack/react-start/rsc' +import { getCompositeHydrate } from '~/server/serverHydrateComponents' +import { DeferredHydrateIsland } from '~/components/DeferredHydrateIsland' + +export const Route = createFileRoute('/composite')({ + loader: async () => ({ + Composite: await getCompositeHydrate(), + }), + component: CompositeRoute, +}) + +function CompositeRoute() { + const { Composite } = Route.useLoaderData() + return ( + + + + ) +} diff --git a/e2e/react-start/rsc-deferred-hydration/src/routes/css.tsx b/e2e/react-start/rsc-deferred-hydration/src/routes/css.tsx new file mode 100644 index 0000000000..ddb22f318a --- /dev/null +++ b/e2e/react-start/rsc-deferred-hydration/src/routes/css.tsx @@ -0,0 +1,14 @@ +import { createFileRoute } from '@tanstack/react-router' +import { getCssModuleHydrate } from '~/server/serverHydrateComponents' + +export const Route = createFileRoute('/css')({ + loader: async () => ({ + Server: await getCssModuleHydrate(), + }), + component: CssRoute, +}) + +function CssRoute() { + const { Server } = Route.useLoaderData() + return Server +} diff --git a/e2e/react-start/rsc-deferred-hydration/src/routes/index.tsx b/e2e/react-start/rsc-deferred-hydration/src/routes/index.tsx new file mode 100644 index 0000000000..ebe57e7028 --- /dev/null +++ b/e2e/react-start/rsc-deferred-hydration/src/routes/index.tsx @@ -0,0 +1,35 @@ +import { createFileRoute, Link } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + component: Home, +}) + +function Home() { + return ( +
+

RSC meets Deferred Hydration

+

+ These routes render React Server Components that cross into client + components using Hydrate. Each card explains when its + client island should hydrate and keeps server-rendered HTML visible + first. +

+
+ + Server component to client Hydrate + The RSC renders a separate "use client" component that + defers hydration until interaction. + + + Composite server shellA server component owns the + visual frame while a client child hydrates only after it becomes + visible. + + + CSS module client islandA server component renders a + client Hydrate boundary whose child uses CSS modules. + +
+
+ ) +} diff --git a/e2e/react-start/rsc-deferred-hydration/src/routes/server-client.tsx b/e2e/react-start/rsc-deferred-hydration/src/routes/server-client.tsx new file mode 100644 index 0000000000..f39b635241 --- /dev/null +++ b/e2e/react-start/rsc-deferred-hydration/src/routes/server-client.tsx @@ -0,0 +1,14 @@ +import { createFileRoute } from '@tanstack/react-router' +import { getServerClientHydrate } from '~/server/serverHydrateComponents' + +export const Route = createFileRoute('/server-client')({ + loader: async () => ({ + Server: await getServerClientHydrate(), + }), + component: ServerClientRoute, +}) + +function ServerClientRoute() { + const { Server } = Route.useLoaderData() + return Server +} diff --git a/e2e/react-start/rsc-deferred-hydration/src/server/serverHydrateComponents.tsx b/e2e/react-start/rsc-deferred-hydration/src/server/serverHydrateComponents.tsx new file mode 100644 index 0000000000..d4e431061a --- /dev/null +++ b/e2e/react-start/rsc-deferred-hydration/src/server/serverHydrateComponents.tsx @@ -0,0 +1,35 @@ +import * as React from 'react' +import { createServerFn } from '@tanstack/react-start' +import { + createCompositeComponent, + renderServerComponent, +} from '@tanstack/react-start/rsc' +import { + CompositeHydrateContent, + CssModuleHydrateContent, + ServerClientHydrateContent, +} from './serverHydrateContent' + +export const getServerClientHydrate = createServerFn({ method: 'GET' }).handler( + async () => { + const renderedAt = new Date().toISOString() + + return renderServerComponent( + , + ) + }, +) + +export const getCompositeHydrate = createServerFn({ method: 'GET' }).handler( + async () => { + return createCompositeComponent((props: { children?: React.ReactNode }) => ( + {props.children} + )) + }, +) + +export const getCssModuleHydrate = createServerFn({ method: 'GET' }).handler( + async () => { + return renderServerComponent() + }, +) diff --git a/e2e/react-start/rsc-deferred-hydration/src/server/serverHydrateContent.tsx b/e2e/react-start/rsc-deferred-hydration/src/server/serverHydrateContent.tsx new file mode 100644 index 0000000000..dc785a16ce --- /dev/null +++ b/e2e/react-start/rsc-deferred-hydration/src/server/serverHydrateContent.tsx @@ -0,0 +1,63 @@ +import * as React from 'react' +import { DeferredHydrateIsland } from '../components/DeferredHydrateIsland' +import { CssHydrateIsland } from '../components/CssHydrateIsland' + +export function ServerClientHydrateContent({ + renderedAt, +}: { + renderedAt: string +}) { + return ( +
+ React Server Component +

Server component renders a deferred client island

+

+ Server rendered at . The button below is + present in HTML but stays unhydrated until interaction. +

+ +
+ ) +} + +export function CompositeHydrateContent({ + children, +}: { + children?: React.ReactNode +}) { + return ( +
+ Composite Server Component +

Server shell, client Hydrate slot

+

+ The server owns this descriptive shell. The client slot below remains + server HTML until an interaction reaches it. +

+
+ {children} +
+ ) +} + +export function CssModuleHydrateContent() { + return ( +
+ + Server Component plus CSS module client island + +

CSS module Hydrate boundary

+

+ This server component renders a separate client component that uses + Hydrate and CSS modules. +

+ +
+ ) +} diff --git a/e2e/react-start/rsc-deferred-hydration/tests/hydration.spec.ts b/e2e/react-start/rsc-deferred-hydration/tests/hydration.spec.ts new file mode 100644 index 0000000000..2d543c5406 --- /dev/null +++ b/e2e/react-start/rsc-deferred-hydration/tests/hydration.spec.ts @@ -0,0 +1,82 @@ +import { expect } from '@playwright/test' +import { test } from '@tanstack/router-e2e-utils' +import type { Page } from '@playwright/test' + +async function expectUnhydrated(page: Page, id: string) { + await expect(page.getByTestId(`${id}-button`)).toHaveAttribute( + 'data-hydrated', + 'false', + ) +} + +async function clickAndExpectCount(page: Page, id: string, count: string) { + await expect(page.getByTestId(`${id}-button`)).toHaveAttribute( + 'data-hydrated', + 'true', + ) + await page.getByTestId(`${id}-button`).click() + await expect(page.getByTestId(`${id}-count`)).toHaveText(count) +} + +async function waitForHydrateMarkerToMount(page: Page, id: string) { + await page.waitForFunction((testId) => { + const button = document.querySelector(`[data-testid="${testId}-button"]`) + const marker = button?.closest('[data-ts-hydrate-id]') + return Object.keys(marker ?? {}).some((key) => key.startsWith('__react')) + }, id) +} + +test.describe('RSC deferred hydration', () => { + test('server component renders a client Hydrate island that hydrates on interaction', async ({ + page, + }) => { + await page.goto('/server-client') + + await expect(page.getByTestId('server-client-rsc')).toContainText( + 'Server component renders a deferred client island', + ) + await expect(page.getByTestId('server-client-island')).toContainText( + 'Interaction strategy inside RSC output', + ) + await expectUnhydrated(page, 'server-client') + + await page.getByTestId('server-client-button').hover() + await clickAndExpectCount(page, 'server-client', '1') + }) + + test('composite server component can wrap an interaction Hydrate client island', async ({ + page, + }) => { + await page.goto('/composite') + + await expect(page.getByTestId('composite-rsc')).toContainText( + 'Server shell, client Hydrate slot', + ) + await expect( + page.getByTestId('composite-interaction-island'), + ).toContainText('Interaction strategy inside a composite server component') + await expectUnhydrated(page, 'composite-interaction') + + await waitForHydrateMarkerToMount(page, 'composite-interaction') + await page.getByTestId('composite-interaction-button').hover() + await clickAndExpectCount(page, 'composite-interaction', '1') + }) + + test('server component can render a CSS module Hydrate client island', async ({ + page, + }) => { + await page.goto('/css') + + await expect(page.getByTestId('css-rsc')).toContainText( + 'CSS module Hydrate boundary', + ) + await expect(page.getByTestId('css-module-marker')).toHaveCSS( + 'font-weight', + '900', + ) + await expectUnhydrated(page, 'css-nested') + await waitForHydrateMarkerToMount(page, 'css-nested') + await page.getByTestId('css-nested-button').hover() + await clickAndExpectCount(page, 'css-nested', '1') + }) +}) diff --git a/e2e/react-start/rsc-deferred-hydration/tests/setup/global.setup.ts b/e2e/react-start/rsc-deferred-hydration/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3d1579ee87 --- /dev/null +++ b/e2e/react-start/rsc-deferred-hydration/tests/setup/global.setup.ts @@ -0,0 +1,28 @@ +import { + e2eStartDummyServer, + getTestServerPort, + preOptimizeDevServer, + waitForServer, +} from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) + + if (process.env.MODE !== 'dev') return + + const port = await getTestServerPort(packageJson.name) + const baseURL = `http://localhost:${port}` + + await waitForServer(baseURL) + await preOptimizeDevServer({ + baseURL, + readyTestId: 'home-heading', + warmup: async (page) => { + for (const route of ['/server-client', '/composite', '/css']) { + await page.goto(`${baseURL}${route}`, { waitUntil: 'domcontentloaded' }) + await page.waitForLoadState('networkidle') + } + }, + }) +} diff --git a/e2e/react-start/rsc-deferred-hydration/tests/setup/global.teardown.ts b/e2e/react-start/rsc-deferred-hydration/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-start/rsc-deferred-hydration/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/react-start/rsc-deferred-hydration/tsconfig.json b/e2e/react-start/rsc-deferred-hydration/tsconfig.json new file mode 100644 index 0000000000..cef9369516 --- /dev/null +++ b/e2e/react-start/rsc-deferred-hydration/tsconfig.json @@ -0,0 +1,21 @@ +{ + "include": ["**/*.ts", "**/*.tsx"], + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "jsx": "react-jsx", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["DOM", "DOM.Iterable", "ES2022"], + "isolatedModules": true, + "resolveJsonModule": true, + "skipLibCheck": true, + "target": "ES2022", + "allowJs": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "~/*": ["./src/*"] + }, + "noEmit": true + } +} diff --git a/e2e/react-start/rsc-deferred-hydration/vite.config.ts b/e2e/react-start/rsc-deferred-hydration/vite.config.ts new file mode 100644 index 0000000000..1919761bc3 --- /dev/null +++ b/e2e/react-start/rsc-deferred-hydration/vite.config.ts @@ -0,0 +1,25 @@ +import { defineConfig } from 'vite' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import viteReact from '@vitejs/plugin-react' +import rsc from '@vitejs/plugin-rsc' + +const outDir = process.env.E2E_DIST_DIR ?? 'dist' + +export default defineConfig({ + resolve: { tsconfigPaths: true }, + build: { + outDir, + }, + server: { + port: Number(process.env.VITE_SERVER_PORT ?? 3000), + }, + plugins: [ + tanstackStart({ + rsc: { + enabled: true, + }, + }), + rsc(), + viteReact(), + ], +}) diff --git a/e2e/solid-start/deferred-hydration/.gitignore b/e2e/solid-start/deferred-hydration/.gitignore new file mode 100644 index 0000000000..1b3a07ede1 --- /dev/null +++ b/e2e/solid-start/deferred-hydration/.gitignore @@ -0,0 +1,15 @@ +node_modules +package-lock.json +yarn.lock +.DS_Store +.cache +.env +.vercel +.output +/build/ +/api/ +/server/build +/test-results/ +/playwright-report/ +/blob-report/ +/playwright/.cache/ diff --git a/e2e/solid-start/deferred-hydration/package.json b/e2e/solid-start/deferred-hydration/package.json new file mode 100644 index 0000000000..77f55458fe --- /dev/null +++ b/e2e/solid-start/deferred-hydration/package.json @@ -0,0 +1,56 @@ +{ + "name": "tanstack-solid-start-e2e-deferred-hydration", + "private": true, + "sideEffects": false, + "type": "module", + "scripts": { + "dev": "pnpm dev:vite --port 3000", + "dev:e2e": "pnpm dev:vite", + "dev:vite": "vite dev", + "dev:rsbuild": "rsbuild dev", + "build": "pnpm build:vite", + "build:vite": "vite build && tsc --noEmit", + "build:rsbuild": "rsbuild build && tsc --noEmit", + "preview": "vite preview", + "start": "pnpm start:vite", + "start:vite": "srvx --prod --dir=. -s dist-vite-ssr/client --entry dist-vite-ssr/server/server.js", + "start:rsbuild": "srvx --prod --dir=. -s dist-rsbuild-ssr/client --entry dist-rsbuild-ssr/server/index.js", + "test:e2e": "playwright test --project=chromium" + }, + "dependencies": { + "@tanstack/solid-router": "workspace:^", + "@tanstack/solid-start": "workspace:^", + "solid-js": "^1.9.10", + "vite": "^8.0.0" + }, + "devDependencies": { + "@rsbuild/core": "^2.0.1", + "@rsbuild/plugin-babel": "^1.1.2", + "@rsbuild/plugin-solid": "^1.1.1", + "@tanstack/router-e2e-utils": "workspace:^", + "@types/node": "^22.10.2", + "rolldown": "1.0.0-rc.18", + "srvx": "^0.11.9", + "typescript": "^6.0.2", + "vite-plugin-solid": "^2.11.11" + }, + "nx": { + "targets": { + "test:e2e": { + "parallelism": false + } + }, + "metadata": { + "playwrightModes": [ + { + "toolchain": "vite", + "mode": "ssr" + }, + { + "toolchain": "rsbuild", + "mode": "ssr" + } + ] + } + } +} diff --git a/e2e/solid-start/deferred-hydration/playwright.config.ts b/e2e/solid-start/deferred-hydration/playwright.config.ts new file mode 100644 index 0000000000..ea9e73a856 --- /dev/null +++ b/e2e/solid-start/deferred-hydration/playwright.config.ts @@ -0,0 +1,43 @@ +import fs from 'node:fs' +import { defineConfig, devices } from '@playwright/test' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } + +const toolchain = process.env.E2E_TOOLCHAIN ?? 'vite' +const distDir = process.env.E2E_DIST_DIR ?? `dist-${toolchain}-ssr` +const e2ePortKey = + process.env.E2E_PORT_KEY ?? `${packageJson.name}-${toolchain}` +const serverEntryFile = toolchain === 'rsbuild' ? 'index.js' : 'server.js' +const startCommand = `pnpm exec srvx --prod --dir=. -s ${distDir}/client --entry ${distDir}/server/${serverEntryFile}` + +if (process.env.TEST_WORKER_INDEX === undefined) { + fs.rmSync(`port-${e2ePortKey}.txt`, { force: true }) +} + +const PORT = await getTestServerPort(e2ePortKey) +const baseURL = `http://localhost:${PORT}` + +export default defineConfig({ + testDir: './tests', + workers: 1, + reporter: [['line']], + use: { baseURL }, + webServer: { + command: startCommand, + url: baseURL, + reuseExistingServer: !process.env.CI, + stdout: 'pipe', + env: { + E2E_DIST_DIR: distDir, + NODE_ENV: 'production', + PORT: String(PORT), + VITE_SERVER_PORT: String(PORT), + }, + }, + projects: [ + { + name: 'chromium', + use: { ...devices['Desktop Chrome'] }, + }, + ], +}) diff --git a/e2e/solid-start/deferred-hydration/rsbuild.config.ts b/e2e/solid-start/deferred-hydration/rsbuild.config.ts new file mode 100644 index 0000000000..7ab152bb58 --- /dev/null +++ b/e2e/solid-start/deferred-hydration/rsbuild.config.ts @@ -0,0 +1,21 @@ +import { defineConfig } from '@rsbuild/core' +import { pluginBabel } from '@rsbuild/plugin-babel' +import { pluginSolid } from '@rsbuild/plugin-solid' +import { tanstackStart } from '@tanstack/solid-start/plugin/rsbuild' + +const outDir = process.env.E2E_DIST_DIR ?? 'dist-rsbuild-ssr' + +export default defineConfig({ + plugins: [ + pluginBabel({ + include: /\.(?:jsx|tsx)$/, + }), + pluginSolid(), + tanstackStart(), + ], + output: { + distPath: { + root: outDir, + }, + }, +}) diff --git a/e2e/solid-start/deferred-hydration/src/routeTree.gen.ts b/e2e/solid-start/deferred-hydration/src/routeTree.gen.ts new file mode 100644 index 0000000000..e75225b500 --- /dev/null +++ b/e2e/solid-start/deferred-hydration/src/routeTree.gen.ts @@ -0,0 +1,140 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as ImportedRouteImport } from './routes/imported' +import { Route as EnhancedRouteImport } from './routes/enhanced' +import { Route as CssRouteImport } from './routes/css' +import { Route as ComponentsRouteImport } from './routes/components' +import { Route as IndexRouteImport } from './routes/index' + +const ImportedRoute = ImportedRouteImport.update({ + id: '/imported', + path: '/imported', + getParentRoute: () => rootRouteImport, +} as any) +const EnhancedRoute = EnhancedRouteImport.update({ + id: '/enhanced', + path: '/enhanced', + getParentRoute: () => rootRouteImport, +} as any) +const CssRoute = CssRouteImport.update({ + id: '/css', + path: '/css', + getParentRoute: () => rootRouteImport, +} as any) +const ComponentsRoute = ComponentsRouteImport.update({ + id: '/components', + path: '/components', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/components': typeof ComponentsRoute + '/css': typeof CssRoute + '/enhanced': typeof EnhancedRoute + '/imported': typeof ImportedRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/components': typeof ComponentsRoute + '/css': typeof CssRoute + '/enhanced': typeof EnhancedRoute + '/imported': typeof ImportedRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/components': typeof ComponentsRoute + '/css': typeof CssRoute + '/enhanced': typeof EnhancedRoute + '/imported': typeof ImportedRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/components' | '/css' | '/enhanced' | '/imported' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/components' | '/css' | '/enhanced' | '/imported' + id: '__root__' | '/' | '/components' | '/css' | '/enhanced' | '/imported' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + ComponentsRoute: typeof ComponentsRoute + CssRoute: typeof CssRoute + EnhancedRoute: typeof EnhancedRoute + ImportedRoute: typeof ImportedRoute +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/imported': { + id: '/imported' + path: '/imported' + fullPath: '/imported' + preLoaderRoute: typeof ImportedRouteImport + parentRoute: typeof rootRouteImport + } + '/enhanced': { + id: '/enhanced' + path: '/enhanced' + fullPath: '/enhanced' + preLoaderRoute: typeof EnhancedRouteImport + parentRoute: typeof rootRouteImport + } + '/css': { + id: '/css' + path: '/css' + fullPath: '/css' + preLoaderRoute: typeof CssRouteImport + parentRoute: typeof rootRouteImport + } + '/components': { + id: '/components' + path: '/components' + fullPath: '/components' + preLoaderRoute: typeof ComponentsRouteImport + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + ComponentsRoute: ComponentsRoute, + CssRoute: CssRoute, + EnhancedRoute: EnhancedRoute, + ImportedRoute: ImportedRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() + +import type { getRouter } from './router.tsx' +import type { createStart } from '@tanstack/solid-start' +declare module '@tanstack/solid-start' { + interface Register { + ssr: true + router: Awaited> + } +} diff --git a/e2e/solid-start/deferred-hydration/src/router.tsx b/e2e/solid-start/deferred-hydration/src/router.tsx new file mode 100644 index 0000000000..aa7ead6752 --- /dev/null +++ b/e2e/solid-start/deferred-hydration/src/router.tsx @@ -0,0 +1,9 @@ +import { createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + scrollRestoration: true, + }) +} diff --git a/e2e/solid-start/deferred-hydration/src/routes/__root.tsx b/e2e/solid-start/deferred-hydration/src/routes/__root.tsx new file mode 100644 index 0000000000..b8c8189c6b --- /dev/null +++ b/e2e/solid-start/deferred-hydration/src/routes/__root.tsx @@ -0,0 +1,98 @@ +/// +import { + HeadContent, + Link, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/solid-router' +import { HydrationScript } from 'solid-js/web' + +export const Route = createRootRoute({ + head: () => ({ + meta: [ + { charSet: 'utf-8' }, + { name: 'viewport', content: 'width=device-width, initial-scale=1' }, + { title: 'Deferred Hydration E2E' }, + ], + }), + component: RootDocument, +}) + +function RootDocument() { + return ( + + + + + + + + +
+ +
+ + + + ) +} diff --git a/e2e/solid-start/deferred-hydration/src/routes/components.tsx b/e2e/solid-start/deferred-hydration/src/routes/components.tsx new file mode 100644 index 0000000000..9dd6387f09 --- /dev/null +++ b/e2e/solid-start/deferred-hydration/src/routes/components.tsx @@ -0,0 +1,171 @@ +import * as Solid from 'solid-js' + +import { createFileRoute } from '@tanstack/solid-router' +import { Hydrate } from '@tanstack/solid-start' +import { + condition, + idle, + interaction, + load, + media, + never, + visible, +} from '@tanstack/solid-start/hydration' + +export const Route = createFileRoute('/components')({ + component: ComponentHydrationPage, +}) + +function InteractiveBox(props: { id: string; label: string }) { + const [count, setCount] = Solid.createSignal(0) + const [hydrated, setHydrated] = Solid.createSignal(false) + + Solid.onMount(() => { + setHydrated(true) + }) + + return ( + + ) +} + +function DelayedFallbackBox() { + if (typeof window !== 'undefined') { + const [ready] = Solid.createResource(async () => { + await new Promise((resolve) => window.setTimeout(resolve, 1000)) + return true + }) + + return ( + +
fallback child
+
+ ) + } + + return
fallback child
+} + +function ComponentHydrationPage() { + const [hydratedCallbacks, setHydratedCallbacks] = Solid.createSignal(0) + const [conditionReady, setConditionReady] = Solid.createSignal(false) + const [showClientFallbackBoundary, setShowClientFallbackBoundary] = + Solid.createSignal(false) + + return ( +
+

Component Deferred Hydration

+
+ Manual test guide + + Pink buttons are server HTML that has not hydrated yet. Green buttons + have hydrated and should increment when clicked. Follow the notes + below to trigger each strategy intentionally. + +
+

{hydratedCallbacks()}

+

+ load and idle should become green + without interaction shortly after the page loads. +

+ + + + + + +
Scroll down to reveal the visible boundary
+

+ visible hydrates only after this button enters the + viewport. +

+ + + +

+ media hydrates when (min-width: 1px) + matches. interaction hydrates on hover, focus, pointer + down, or click intent. +

+ + + + + + +

+ Custom interaction boundaries below hydrate only for their configured + events: double-click for the single-event example, and right-click or + double-click for the multi-event example. The prefetch example should + download code on hover but hydrate on click. +

+ setHydratedCallbacks((count) => count + 1)} + > + + + + + + + + + + + + + + + + + + + + + + + +

+ never stays as server HTML forever on the initial page, + so clicking should not increment it. +

+ + + client fallback + } + > + + + +
+ ) +} diff --git a/e2e/solid-start/deferred-hydration/src/routes/css.tsx b/e2e/solid-start/deferred-hydration/src/routes/css.tsx new file mode 100644 index 0000000000..c1a80d492b --- /dev/null +++ b/e2e/solid-start/deferred-hydration/src/routes/css.tsx @@ -0,0 +1,57 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { Hydrate } from '@tanstack/solid-start' +import { media, never, visible } from '@tanstack/solid-start/hydration' +import outerStyles from './css/outer.module.css' +import deferredStyles from './css/deferred-only.module.css' +import sharedStyles from './css/shared.module.css' + +export const Route = createFileRoute('/css')({ + component: CssHydrationPage, +}) + +function CssHydrationPage() { + return ( +
+
+

+ CSS Deferred Hydration +

+

+ CSS from deferred, never, shared, and nested Hydrate boundaries should + be available even before the client JavaScript hydrates those islands. +

+
+
+
+ Outer CSS +
+
+ Shared outer CSS +
+
+ +
+ Deferred CSS +
+
+ +
+ Never CSS +
+
+ + +
+ Nested CSS +
+
+
+
+ ) +} diff --git a/e2e/solid-start/deferred-hydration/src/routes/css/deferred-only.module.css b/e2e/solid-start/deferred-hydration/src/routes/css/deferred-only.module.css new file mode 100644 index 0000000000..05eafda03c --- /dev/null +++ b/e2e/solid-start/deferred-hydration/src/routes/css/deferred-only.module.css @@ -0,0 +1,15 @@ +.deferredBox { + background-color: rgb(23, 45, 67); + color: rgb(255, 255, 255); + padding: 12px; +} + +.neverBox { + color: rgb(45, 67, 89); + padding: 12px; +} + +.nestedBox { + border-left: 5px solid rgb(67, 89, 123); + padding-left: 12px; +} diff --git a/e2e/solid-start/deferred-hydration/src/routes/css/outer.module.css b/e2e/solid-start/deferred-hydration/src/routes/css/outer.module.css new file mode 100644 index 0000000000..98ca5e0934 --- /dev/null +++ b/e2e/solid-start/deferred-hydration/src/routes/css/outer.module.css @@ -0,0 +1,9 @@ +.heading { + color: rgb(11, 31, 53); +} + +.outerBox { + background-color: rgb(242, 250, 255); + color: rgb(12, 34, 56); + padding: 12px; +} diff --git a/e2e/solid-start/deferred-hydration/src/routes/css/shared.module.css b/e2e/solid-start/deferred-hydration/src/routes/css/shared.module.css new file mode 100644 index 0000000000..020da5d7ad --- /dev/null +++ b/e2e/solid-start/deferred-hydration/src/routes/css/shared.module.css @@ -0,0 +1,4 @@ +.sharedBox { + border-top: 4px solid rgb(98, 76, 54); + margin-top: 8px; +} diff --git a/e2e/solid-start/deferred-hydration/src/routes/enhanced.tsx b/e2e/solid-start/deferred-hydration/src/routes/enhanced.tsx new file mode 100644 index 0000000000..d699a644f1 --- /dev/null +++ b/e2e/solid-start/deferred-hydration/src/routes/enhanced.tsx @@ -0,0 +1,316 @@ +import { Show, createSignal, onMount, type JSX } from 'solid-js' +import { createFileRoute } from '@tanstack/solid-router' +import { Hydrate } from '@tanstack/solid-start' +import { interaction, media } from '@tanstack/solid-start/hydration' +import { EnhancedNestedWidget } from '../shared/EnhancedNestedWidget' + +type EnhancedSearch = { + dynamic?: 'interaction' +} + +export const Route = createFileRoute('/enhanced')({ + validateSearch: (search: Record): EnhancedSearch => ({ + dynamic: search.dynamic === 'interaction' ? 'interaction' : undefined, + }), + component: EnhancedHydrationPage, +}) + +type DeferredGate = { + promise: Promise + resolve: () => void +} + +const clickIntent = interaction({ events: 'click' }) +const pointerOverIntent = interaction({ events: 'pointerover' }) +const doubleClickIntent = interaction({ events: 'dblclick' }) + +function createDeferredGate(): DeferredGate { + let resolve!: () => void + const promise = new Promise((next) => { + resolve = next + }) + return { promise, resolve } +} + +function InteractiveBox(props: { id: string; label: string }): JSX.Element { + const [count, setCount] = createSignal(0) + const [hydrated, setHydrated] = createSignal(false) + + onMount(() => { + setHydrated(true) + }) + + return ( + + ) +} + +function DynamicWhenExamples(): JSX.Element { + const search = Route.useSearch() + const searchDrivenHydration = () => + search().dynamic === 'interaction' ? clickIntent : doubleClickIntent + + return ( + <> +

+ Dynamic callbacks are client-only. The first boundary always hydrates on + click; the second reads typed router search state before choosing its + interaction event. +

+ clickIntent}> + + + + + + + ) +} + +function SplitPrefetchExample(): JSX.Element { + const gate = createDeferredGate() + const [waitReason, setWaitReason] = createSignal('idle') + const [preloadStatus, setPreloadStatus] = createSignal('idle') + const [queryStatus, setQueryStatus] = createSignal('idle') + + return ( + <> +

{waitReason()}

+

{preloadStatus()}

+

{queryStatus()}

+ + { + setQueryStatus(element ? 'element' : 'missing-element') + setWaitReason('waiting') + + const reason = await waitFor(pointerOverIntent) + setWaitReason(reason) + if (reason === 'abort' || signal.aborted) return + + await preload() + setPreloadStatus('done') + await gate.promise + setQueryStatus('done') + }} + > + + + + ) +} + +function FireAndForgetPrefetchExample(): JSX.Element { + const gate = createDeferredGate() + const [waitReason, setWaitReason] = createSignal('idle') + const [workStatus, setWorkStatus] = createSignal('idle') + const [queryStatus, setQueryStatus] = createSignal('idle') + + return ( + <> +

{workStatus()}

+

{waitReason()}

+

{queryStatus()}

+ + { + setWaitReason('waiting') + void waitFor(pointerOverIntent).then((reason) => { + setWaitReason(reason) + if (reason === 'abort') return + + setWorkStatus('started') + void gate.promise.then(() => { + setQueryStatus('done') + }) + }) + }} + > + + + + ) +} + +function HydrateFirstPrefetchExample(): JSX.Element { + const [reason, setReason] = createSignal('idle') + + return ( + <> +

{reason()}

+ { + setReason(await waitFor(doubleClickIntent)) + }} + > + + + + ) +} + +function RuntimeOnlyPrefetchExample(): JSX.Element { + const gate = createDeferredGate() + const [waitReason, setWaitReason] = createSignal('idle') + const [runtimeStatus, setRuntimeStatus] = createSignal('idle') + + return ( + <> +

{waitReason()}

+

{runtimeStatus()}

+ + { + setWaitReason('waiting') + const reason = await waitFor(pointerOverIntent) + setWaitReason(reason) + if (reason === 'abort') return + + await gate.promise + await preload() + setRuntimeStatus('ready') + }} + > + + + + ) +} + +function WaitForAbortExample(): JSX.Element { + const [showBoundary, setShowBoundary] = createSignal(true) + const [reason, setReason] = createSignal('idle') + + return ( + <> +

{reason()}

+ + + { + setReason('waiting') + setReason(await waitFor(pointerOverIntent)) + }} + > + + + + + ) +} + +function SignalAbortExample(): JSX.Element { + const [showBoundary, setShowBoundary] = createSignal(true) + const [status, setStatus] = createSignal('idle') + + return ( + <> +

{status()}

+ + + { + setStatus('listening') + await new Promise((resolve) => { + const onAbort = () => { + setStatus('aborted') + resolve() + } + + if (signal.aborted) { + onAbort() + return + } + + signal.addEventListener('abort', onAbort, { once: true }) + }) + }} + > + + + + + ) +} + +function NestedDynamicExamples(): JSX.Element { + return ( + <> + + clickIntent}> + + + + + + ) +} + +function EnhancedHydrationPage(): JSX.Element { + return ( +
+

Enhanced Hydrate APIs

+ + + + + + + + +
+ ) +} diff --git a/e2e/solid-start/deferred-hydration/src/routes/imported.tsx b/e2e/solid-start/deferred-hydration/src/routes/imported.tsx new file mode 100644 index 0000000000..abfb827c91 --- /dev/null +++ b/e2e/solid-start/deferred-hydration/src/routes/imported.tsx @@ -0,0 +1,15 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { ImportedHydrateWidget } from '../shared/ImportedHydrateWidget' + +export const Route = createFileRoute('/imported')({ + component: ImportedHydrationPage, +}) + +function ImportedHydrationPage() { + return ( +
+

Imported Hydrate

+ +
+ ) +} diff --git a/e2e/solid-start/deferred-hydration/src/routes/index.tsx b/e2e/solid-start/deferred-hydration/src/routes/index.tsx new file mode 100644 index 0000000000..61fbf7f6dc --- /dev/null +++ b/e2e/solid-start/deferred-hydration/src/routes/index.tsx @@ -0,0 +1,23 @@ +import { Link, createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/')({ + component: Home, +}) + +function Home() { + return ( +
+

Deferred Hydration

+

Component strategies

+ component strategies +

CSS

+ CSS deferred hydration +

Imported component

+ + imported Hydrate + +

Enhanced APIs

+ enhanced Hydrate APIs +
+ ) +} diff --git a/e2e/solid-start/deferred-hydration/src/shared/EnhancedNestedWidget.tsx b/e2e/solid-start/deferred-hydration/src/shared/EnhancedNestedWidget.tsx new file mode 100644 index 0000000000..e595e38da8 --- /dev/null +++ b/e2e/solid-start/deferred-hydration/src/shared/EnhancedNestedWidget.tsx @@ -0,0 +1,33 @@ +import { createSignal, onMount } from 'solid-js' +import { Hydrate } from '@tanstack/solid-start' +import { interaction, media } from '@tanstack/solid-start/hydration' + +function CrossFileNestedButton() { + const [count, setCount] = createSignal(0) + const [hydrated, setHydrated] = createSignal(false) + + onMount(() => { + setHydrated(true) + }) + + return ( + + ) +} + +export function EnhancedNestedWidget() { + return ( + + + + + + ) +} diff --git a/e2e/solid-start/deferred-hydration/src/shared/ImportedHydrateWidget.tsx b/e2e/solid-start/deferred-hydration/src/shared/ImportedHydrateWidget.tsx new file mode 100644 index 0000000000..859b741755 --- /dev/null +++ b/e2e/solid-start/deferred-hydration/src/shared/ImportedHydrateWidget.tsx @@ -0,0 +1,34 @@ +import { createSignal } from 'solid-js' + +import { Hydrate } from '@tanstack/solid-start' +import { media } from '@tanstack/solid-start/hydration' + +function ImportedHydrateChild() { + const [count, setCount] = createSignal(0) + + return ( + + ) +} + +export function ImportedHydrateWidget() { + return ( + + imported hydrate fallback + + } + > + + + ) +} diff --git a/e2e/solid-start/deferred-hydration/tests/hydration.spec.ts b/e2e/solid-start/deferred-hydration/tests/hydration.spec.ts new file mode 100644 index 0000000000..dff2357837 --- /dev/null +++ b/e2e/solid-start/deferred-hydration/tests/hydration.spec.ts @@ -0,0 +1,909 @@ +import { expect } from '@playwright/test' +import { test } from '@tanstack/router-e2e-utils' +import type { APIRequestContext, Page } from '@playwright/test' + +async function clickAndExpectCount( + page: Page, + buttonTestId: string, + countTestId: string, + count: string, +) { + await expect(page.getByTestId(buttonTestId)).toHaveAttribute( + 'data-hydrated', + 'true', + ) + await page.getByTestId(buttonTestId).click() + await expect(page.getByTestId(countTestId)).toHaveText(count) +} + +async function clickIntentAndExpectReplayedCount( + page: Page, + buttonTestId: string, + countTestId: string, + count: string, +) { + await expectRouteToStayUnhydrated(page, buttonTestId) + await page.getByTestId(buttonTestId).click() + await expect(page.getByTestId(buttonTestId)).toHaveAttribute( + 'data-hydrated', + 'true', + ) + await expect(page.getByTestId(countTestId)).toHaveText(count) +} + +async function clickToHydrateThenClickAndExpectIncrement( + page: Page, + buttonTestId: string, + countTestId: string, +) { + await expectRouteToStayUnhydrated(page, buttonTestId) + await page.getByTestId(buttonTestId).click() + await expect(page.getByTestId(buttonTestId)).toHaveAttribute( + 'data-hydrated', + 'true', + ) + const previousCount = Number( + await page.getByTestId(countTestId).textContent(), + ) + await page.getByTestId(buttonTestId).click() + await expect + .poll(async () => Number(await page.getByTestId(countTestId).textContent())) + .toBe(previousCount + 1) +} + +async function hoverIntentAndExpectCount( + page: Page, + buttonTestId: string, + countTestId: string, + count: string, +) { + await expectRouteToStayUnhydrated(page, buttonTestId) + await page.mouse.move(0, 0) + await page.getByTestId(buttonTestId).hover() + await clickAndExpectCount(page, buttonTestId, countTestId, count) +} + +async function dispatchHydrationIntent( + page: Page, + buttonTestId: string, + eventName: string, +) { + await page.getByTestId(buttonTestId).evaluate((element, eventName) => { + const marker = element.closest('[data-ts-hydrate-id]') + + if (!marker) { + throw new Error('Expected Hydrate marker to exist') + } + + marker.dispatchEvent( + new Event(eventName, { bubbles: true, cancelable: true }), + ) + }, eventName) +} + +async function trackBoundaryStability(page: Page, buttonTestId: string) { + await page.getByTestId(buttonTestId).evaluate((element, testId) => { + const marker = element.closest('[data-ts-hydrate-id]') + + if (!(marker instanceof HTMLElement)) { + throw new Error('Expected Hydrate marker to exist') + } + + const win = window as typeof window & { + __hydrateBoundaryVisualGapCount?: number + __hydrateBoundaryMaxScrollDelta?: number + __hydrateBoundaryStabilityDone?: boolean + } + const hasBoundaryButton = () => + Array.from(marker.querySelectorAll('[data-testid]')).some( + (child) => child.getAttribute('data-testid') === testId, + ) + const hasHydratedBoundaryButton = () => + Array.from(marker.querySelectorAll('[data-testid]')).some( + (child) => + child.getAttribute('data-testid') === testId && + child.getAttribute('data-hydrated') === 'true', + ) + const initialScrollY = window.scrollY + + win.__hydrateBoundaryVisualGapCount = 0 + win.__hydrateBoundaryMaxScrollDelta = 0 + win.__hydrateBoundaryStabilityDone = false + + let frameCount = 0 + let hydratedFrameCount = 0 + let observer: MutationObserver | undefined + const recordScroll = () => { + win.__hydrateBoundaryMaxScrollDelta = Math.max( + win.__hydrateBoundaryMaxScrollDelta ?? 0, + Math.abs(window.scrollY - initialScrollY), + ) + + if (hasHydratedBoundaryButton()) hydratedFrameCount++ + + frameCount++ + if (hydratedFrameCount >= 10 || frameCount >= 300) { + observer?.disconnect() + win.__hydrateBoundaryStabilityDone = true + return + } + + requestAnimationFrame(recordScroll) + } + + observer = new MutationObserver(() => { + if (!hasBoundaryButton()) { + win.__hydrateBoundaryVisualGapCount!++ + } + }) + observer.observe(marker, { childList: true }) + + requestAnimationFrame(recordScroll) + }, buttonTestId) +} + +async function expectBoundaryStable(page: Page) { + await expect + .poll(() => + page.evaluate( + () => + ( + window as typeof window & { + __hydrateBoundaryStabilityDone?: boolean + } + ).__hydrateBoundaryStabilityDone ?? false, + ), + ) + .toBe(true) + await expect + .poll(() => + page.evaluate( + () => + ( + window as typeof window & { + __hydrateBoundaryVisualGapCount?: number + } + ).__hydrateBoundaryVisualGapCount ?? 0, + ), + ) + .toBe(0) + await expect + .poll(() => + page.evaluate( + () => + ( + window as typeof window & { + __hydrateBoundaryMaxScrollDelta?: number + } + ).__hydrateBoundaryMaxScrollDelta ?? 0, + ), + ) + .toBeLessThanOrEqual(1) +} + +async function expectRouteToStayUnhydrated( + page: Page, + buttonTestId: string, + duration = 250, +) { + await expect(page.getByTestId(buttonTestId)).toHaveAttribute( + 'data-hydrated', + 'false', + ) + await page.waitForTimeout(duration) + await expect(page.getByTestId(buttonTestId)).toHaveAttribute( + 'data-hydrated', + 'false', + ) +} + +async function scrollToBoundary(page: Page, buttonTestId: string) { + const button = page.getByTestId(buttonTestId) + for (let attempt = 0; attempt < 3; attempt++) { + await button.evaluate((element) => { + element.scrollIntoView({ block: 'center', inline: 'nearest' }) + }) + + await page.waitForTimeout(100) + const isVisible = await button.evaluate((element) => { + const rect = element.getBoundingClientRect() + return rect.bottom > 0 && rect.top < window.innerHeight + }) + + if (isVisible) return + } + + await expect(button).toBeInViewport() +} + +async function expectCssProperty( + page: Page, + testId: string, + property: string, + value: string, +) { + await expect + .poll(() => + page.getByTestId(testId).evaluate((element, propertyName) => { + return getComputedStyle(element).getPropertyValue(propertyName) + }, property), + ) + .toBe(value) +} + +function htmlContainsText(html: string, text: string) { + const pattern = text.split(' ').join('(?:\\s|)+') + expect(html).toMatch(new RegExp(pattern)) +} + +function getModulePreloadHrefs(html: string) { + return Array.from(html.matchAll(/]*>/g), (match) => match[0]) + .filter((tag) => /\brel="modulepreload"/.test(tag)) + .map((tag) => tag.match(/\bhref="([^"]+)"/)?.[1]) + .filter((href): href is string => !!href) +} + +async function modulePreloadContentsContain( + request: APIRequestContext, + hrefs: Array, + marker: string, +) { + for (const href of hrefs) { + const response = await request.get(href) + if (!response.ok()) continue + + const text = await response.text() + if (text.includes(marker)) return true + } + + return false +} + +async function resourceContentsContain( + page: Page, + request: APIRequestContext, + marker: string, + filter: (url: string) => boolean, +) { + const resourceUrls = await page.evaluate(() => + performance.getEntriesByType('resource').map((entry) => entry.name), + ) + + return modulePreloadContentsContain( + request, + resourceUrls.filter(filter), + marker, + ) +} + +async function documentModulePreloadHrefs(page: Page) { + return page.evaluate(() => + Array.from( + document.querySelectorAll('link[rel~="modulepreload"]'), + (link) => link.href, + ), + ) +} + +function isHydrateBoundaryResource(url: string) { + return ( + url.includes('/assets/components-') || url.includes('/static/js/async/') + ) +} + +function isClientJavaScriptResource(url: string) { + return ( + url.includes('/assets/') || + url.includes('/static/js/') || + url.includes('/static/js/async/') + ) +} + +async function expectClientRouterReady(page: Page) { + await expect + .poll(() => + page.evaluate(() => + Boolean( + ( + globalThis as typeof globalThis & { + __TSR_ROUTER__?: unknown + } + ).__TSR_ROUTER__, + ), + ), + ) + .toBe(true) +} + +async function gotoEnhanced(page: Page, search = '') { + await page.goto(`/enhanced${search}`) + await expectClientRouterReady(page) +} + +test.describe('component-level Hydrate runtime strategies', () => { + test('renders SSR HTML and hydrates each runtime when appropriately', async ({ + page, + request, + }) => { + await page.goto('/components') + + await expect(page.getByTestId('component-heading')).toHaveText( + 'Component Deferred Hydration', + ) + + await clickAndExpectCount( + page, + 'component-load-button', + 'component-load-count', + '1', + ) + await clickAndExpectCount( + page, + 'component-idle-button', + 'component-idle-count', + '1', + ) + await expect( + resourceContentsContain(page, request, 'component-visible', (url) => + isHydrateBoundaryResource(url), + ), + ).resolves.toBe(false) + await expectRouteToStayUnhydrated(page, 'component-visible-button') + await scrollToBoundary(page, 'component-visible-button') + await clickAndExpectCount( + page, + 'component-visible-button', + 'component-visible-count', + '1', + ) + await expect + .poll(() => + resourceContentsContain(page, request, 'component-visible', (url) => + isHydrateBoundaryResource(url), + ), + ) + .toBe(true) + await clickAndExpectCount( + page, + 'component-media-button', + 'component-media-count', + '1', + ) + await hoverIntentAndExpectCount( + page, + 'component-interaction-button', + 'component-interaction-count', + '1', + ) + await expect(page.getByTestId('component-on-hydrated-count')).toHaveText( + '0', + ) + await expectRouteToStayUnhydrated(page, 'component-custom-single-button') + await page.getByTestId('component-custom-single-button').hover() + await expectRouteToStayUnhydrated(page, 'component-custom-single-button') + await page.getByTestId('component-custom-single-button').click() + await expectRouteToStayUnhydrated(page, 'component-custom-single-button') + await dispatchHydrationIntent( + page, + 'component-custom-single-button', + 'dblclick', + ) + await expect( + page.getByTestId('component-custom-single-button'), + ).toHaveAttribute('data-hydrated', 'true') + await expect(page.getByTestId('component-on-hydrated-count')).toHaveText( + '1', + ) + await clickAndExpectCount( + page, + 'component-custom-single-button', + 'component-custom-single-count', + '1', + ) + await expect(page.getByTestId('component-on-hydrated-count')).toHaveText( + '1', + ) + await expectRouteToStayUnhydrated(page, 'component-custom-multi-button') + await dispatchHydrationIntent( + page, + 'component-custom-multi-button', + 'contextmenu', + ) + await clickAndExpectCount( + page, + 'component-custom-multi-button', + 'component-custom-multi-count', + '1', + ) + await expectRouteToStayUnhydrated(page, 'component-condition-button') + await page.getByTestId('component-enable-condition').click() + await clickAndExpectCount( + page, + 'component-condition-button', + 'component-condition-count', + '1', + ) + await scrollToBoundary(page, 'component-click-replay-button') + await expectRouteToStayUnhydrated(page, 'component-click-replay-button') + await trackBoundaryStability(page, 'component-click-replay-button') + await page.getByTestId('component-click-replay-button').click() + await expect( + page.getByTestId('component-click-replay-button'), + ).toHaveAttribute('data-hydrated', 'true') + await expectBoundaryStable(page) + await expect(page.getByTestId('component-click-replay-count')).toHaveText( + '1', + ) + await expectRouteToStayUnhydrated(page, 'component-prefetch-button') + await expect( + resourceContentsContain(page, request, 'component-prefetch', (url) => + isHydrateBoundaryResource(url), + ), + ).resolves.toBe(false) + await page.mouse.move(0, 0) + await page.getByTestId('component-prefetch-button').hover() + await expect(page.getByTestId('component-prefetch-button')).toHaveAttribute( + 'data-hydrated', + 'false', + ) + await expect + .poll(() => + resourceContentsContain(page, request, 'component-prefetch', (url) => + isHydrateBoundaryResource(url), + ), + ) + .toBe(true) + await expect(page.getByTestId('component-prefetch-button')).toHaveAttribute( + 'data-hydrated', + 'false', + ) + await page.getByTestId('component-prefetch-button').click() + await expect(page.getByTestId('component-prefetch-button')).toHaveAttribute( + 'data-hydrated', + 'true', + ) + await expect(page.getByTestId('component-prefetch-count')).toHaveText('1') + await hoverIntentAndExpectCount( + page, + 'component-nested-child-button', + 'component-nested-child-count', + '1', + ) + + await page.getByTestId('component-never-button').click() + await expect(page.getByTestId('component-never-count')).toHaveText('0') + }) + + test('replays click after another interaction boundary hydrates first', async ({ + page, + }) => { + await page.goto('/components') + await expectClientRouterReady(page) + + await scrollToBoundary(page, 'component-custom-multi-button') + await expectRouteToStayUnhydrated(page, 'component-custom-multi-button') + await page.getByTestId('component-custom-multi-button').click({ + button: 'right', + }) + await expect( + page.getByTestId('component-custom-multi-button'), + ).toHaveAttribute('data-hydrated', 'true') + + await scrollToBoundary(page, 'component-click-replay-button') + await expectRouteToStayUnhydrated(page, 'component-click-replay-button') + await trackBoundaryStability(page, 'component-click-replay-button') + await page.getByTestId('component-click-replay-button').click() + await expect( + page.getByTestId('component-click-replay-button'), + ).toHaveAttribute('data-hydrated', 'true') + await expectBoundaryStable(page) + await expect(page.getByTestId('component-click-replay-count')).toHaveText( + '1', + ) + }) + + test('keeps bottom scroll stable when a condition boundary hydrates', async ({ + page, + }) => { + await page.goto('/components') + await expectClientRouterReady(page) + await expectRouteToStayUnhydrated(page, 'component-condition-button') + + await page.evaluate(() => { + window.scrollTo(0, document.documentElement.scrollHeight) + }) + await page.waitForTimeout(100) + await expect( + page.getByTestId('component-enable-condition'), + ).toBeInViewport() + + await trackBoundaryStability(page, 'component-condition-button') + await page.getByTestId('component-enable-condition').click() + await expect( + page.getByTestId('component-condition-button'), + ).toHaveAttribute('data-hydrated', 'true') + await expectBoundaryStable(page) + await clickAndExpectCount( + page, + 'component-condition-button', + 'component-condition-count', + '1', + ) + }) + + test('shows fallback during a client-only mount while the child suspends', async ({ + page, + }) => { + await page.goto('/components') + await expect(page.getByTestId('component-load-button')).toHaveAttribute( + 'data-hydrated', + 'true', + ) + await page.getByTestId('component-show-client-fallback').click() + + await expect(page.getByTestId('component-client-fallback')).toHaveText( + 'client fallback', + ) + await expect(page.getByTestId('component-fallback-child')).toHaveText( + 'fallback child', + ) + await expect(page.getByTestId('component-client-fallback')).toHaveCount(0) + }) +}) + +test.describe('enhanced Hydrate API combinations', () => { + test('server renders dynamic markers without evaluating client-only callbacks or prefetch functions', async ({ + request, + }) => { + const response = await request.get('/enhanced?dynamic=interaction') + const html = await response.text() + + expect(response.ok()).toBe(true) + htmlContainsText(html, 'Enhanced Hydrate APIs') + htmlContainsText(html, 'conditional dynamic') + expect(html).toContain('data-ts-hydrate-when="dynamic"') + expect(html).not.toContain('missing-element') + }) + + test('dynamic when functions hydrate and replay interaction events', async ({ + page, + }) => { + await gotoEnhanced(page, '?dynamic=interaction') + await expect(page.getByTestId('enhanced-heading')).toHaveText( + 'Enhanced Hydrate APIs', + ) + await clickIntentAndExpectReplayedCount( + page, + 'enhanced-dynamic-interaction-button', + 'enhanced-dynamic-interaction-count', + '1', + ) + + await expectRouteToStayUnhydrated( + page, + 'enhanced-dynamic-conditional-button', + ) + await page.getByTestId('enhanced-dynamic-conditional-button').hover() + await expectRouteToStayUnhydrated( + page, + 'enhanced-dynamic-conditional-button', + ) + await clickIntentAndExpectReplayedCount( + page, + 'enhanced-dynamic-conditional-button', + 'enhanced-dynamic-conditional-count', + '1', + ) + }) + + test('procedural prefetch can block hydration, preload the split chunk, and prepare query-like work', async ({ + page, + request, + }) => { + await gotoEnhanced(page) + await expect( + resourceContentsContain( + page, + request, + 'enhanced-procedural-split-child', + isClientJavaScriptResource, + ), + ).resolves.toBe(false) + + await expectRouteToStayUnhydrated(page, 'enhanced-procedural-split-button') + await expect(page.getByTestId('enhanced-split-wait-reason')).toHaveText( + 'waiting', + ) + await dispatchHydrationIntent( + page, + 'enhanced-procedural-split-button', + 'pointerover', + ) + await expect(page.getByTestId('enhanced-split-query')).toHaveText('element') + await expect(page.getByTestId('enhanced-split-wait-reason')).toHaveText( + 'prefetch', + ) + await expect(page.getByTestId('enhanced-split-preload')).toHaveText('done') + await expect + .poll(() => + resourceContentsContain( + page, + request, + 'enhanced-procedural-split-child', + isClientJavaScriptResource, + ), + ) + .toBe(true) + + await page.getByTestId('enhanced-procedural-split-button').click() + await expect( + page.getByTestId('enhanced-procedural-split-button'), + ).toHaveAttribute('data-hydrated', 'false') + await expect( + page.getByTestId('enhanced-procedural-split-count'), + ).toHaveText('0') + await page.getByTestId('enhanced-release-split-prefetch').click() + await expect( + page.getByTestId('enhanced-procedural-split-button'), + ).toHaveAttribute('data-hydrated', 'true') + await expect( + page.getByTestId('enhanced-procedural-split-count'), + ).toHaveText('1') + await expect(page.getByTestId('enhanced-split-query')).toHaveText('done') + }) + + test('function prefetch supports fire-and-forget work and waitFor hydrate-first resolution', async ({ + page, + }) => { + await gotoEnhanced(page) + + await expect(page.getByTestId('enhanced-fire-wait-reason')).toHaveText( + 'waiting', + ) + await dispatchHydrationIntent( + page, + 'enhanced-fire-and-forget-button', + 'pointerover', + ) + await expect(page.getByTestId('enhanced-fire-wait-reason')).toHaveText( + 'prefetch', + ) + await expect(page.getByTestId('enhanced-fire-status')).toHaveText('started') + await clickIntentAndExpectReplayedCount( + page, + 'enhanced-fire-and-forget-button', + 'enhanced-fire-and-forget-count', + '1', + ) + await expect(page.getByTestId('enhanced-fire-query')).toHaveText('idle') + await page.getByTestId('enhanced-release-fire-prefetch').click() + await expect(page.getByTestId('enhanced-fire-query')).toHaveText('done') + + await clickIntentAndExpectReplayedCount( + page, + 'enhanced-hydrate-first-button', + 'enhanced-hydrate-first-count', + '1', + ) + await expect(page.getByTestId('enhanced-hydrate-first-reason')).toHaveText( + 'hydrate', + ) + }) + + test('split=false procedural prefetch blocks hydration without requiring a child preload chunk', async ({ + page, + }) => { + await gotoEnhanced(page) + + await expectRouteToStayUnhydrated(page, 'enhanced-runtime-only-button') + await expect(page.getByTestId('enhanced-runtime-wait-reason')).toHaveText( + 'waiting', + ) + await dispatchHydrationIntent( + page, + 'enhanced-runtime-only-button', + 'pointerover', + ) + await expect(page.getByTestId('enhanced-runtime-wait-reason')).toHaveText( + 'prefetch', + ) + await page.getByTestId('enhanced-runtime-only-button').click() + await expect( + page.getByTestId('enhanced-runtime-only-button'), + ).toHaveAttribute('data-hydrated', 'false') + await expect(page.getByTestId('enhanced-runtime-only-count')).toHaveText( + '0', + ) + await page.getByTestId('enhanced-release-runtime-prefetch').click() + await expect(page.getByTestId('enhanced-runtime-status')).toHaveText( + 'ready', + ) + await expect( + page.getByTestId('enhanced-runtime-only-button'), + ).toHaveAttribute('data-hydrated', 'true') + await expect(page.getByTestId('enhanced-runtime-only-count')).toHaveText( + '1', + ) + }) + + test('procedural prefetch aborts waiters and signals when boundaries unmount', async ({ + page, + }) => { + await gotoEnhanced(page) + + await expectRouteToStayUnhydrated(page, 'enhanced-wait-abort-button') + await expect(page.getByTestId('enhanced-wait-abort-reason')).toHaveText( + 'waiting', + ) + await page.getByTestId('enhanced-hide-wait-abort').click() + await expect(page.getByTestId('enhanced-wait-abort-reason')).toHaveText( + 'abort', + ) + + await expect(page.getByTestId('enhanced-abort-status')).toHaveText( + 'listening', + ) + await page.getByTestId('enhanced-hide-abort').click() + await expect(page.getByTestId('enhanced-abort-status')).toHaveText( + 'aborted', + ) + }) + + test('nested dynamic interaction boundaries delegate through outer boundaries', async ({ + page, + }) => { + await gotoEnhanced(page) + + await clickToHydrateThenClickAndExpectIncrement( + page, + 'enhanced-dynamic-nested-button', + 'enhanced-dynamic-nested-count', + ) + await clickToHydrateThenClickAndExpectIncrement( + page, + 'enhanced-cross-file-nested-button', + 'enhanced-cross-file-nested-count', + ) + }) +}) + +test.describe('Hydrate CSS delivery', () => { + test('ships CSS for deferred, never, shared, and nested boundaries without JavaScript', async ({ + browser, + request, + }) => { + const response = await request.get('/css') + const html = await response.text() + + htmlContainsText(html, 'CSS Deferred Hydration') + htmlContainsText(html, 'Outer CSS') + htmlContainsText(html, 'Deferred CSS') + htmlContainsText(html, 'Never CSS') + htmlContainsText(html, 'Nested CSS') + + const context = await browser.newContext({ javaScriptEnabled: false }) + const page = await context.newPage() + + try { + await page.goto('/css') + + await expect(page.getByTestId('css-heading')).toHaveText( + 'CSS Deferred Hydration', + ) + await expect(page.getByTestId('css-deferred')).toHaveText('Deferred CSS') + await expect(page.getByTestId('css-never')).toHaveText('Never CSS') + await expect(page.getByTestId('css-nested')).toHaveText('Nested CSS') + + await expectCssProperty(page, 'css-outer', 'color', 'rgb(12, 34, 56)') + await expectCssProperty( + page, + 'css-deferred', + 'background-color', + 'rgb(23, 45, 67)', + ) + await expectCssProperty(page, 'css-never', 'color', 'rgb(45, 67, 89)') + await expectCssProperty( + page, + 'css-shared-outer', + 'border-top-color', + 'rgb(98, 76, 54)', + ) + await expectCssProperty( + page, + 'css-deferred', + 'border-top-color', + 'rgb(98, 76, 54)', + ) + await expectCssProperty( + page, + 'css-nested', + 'border-left-color', + 'rgb(67, 89, 123)', + ) + await expectCssProperty(page, 'css-nested', 'border-left-width', '5px') + } finally { + await context.close() + } + }) + + test('renders deferred content and omits never content after client-side navigation', async ({ + page, + }) => { + await page.goto('/') + await expectClientRouterReady(page) + await page.getByRole('link', { name: 'CSS', exact: true }).click() + await expect(page).toHaveURL(/\/css$/) + + await expect(page.getByTestId('css-heading')).toHaveText( + 'CSS Deferred Hydration', + ) + await expect(page.getByTestId('css-deferred')).toHaveText('Deferred CSS') + await expect(page.getByTestId('css-never')).toHaveCount(0) + await expect(page.getByTestId('css-nested')).toHaveCount(0) + + await expectCssProperty( + page, + 'css-deferred', + 'background-color', + 'rgb(23, 45, 67)', + ) + }) +}) + +test.describe('imported Hydrate boundaries', () => { + test('does not emit filtered shared Hydrate child JS on the initial document', async ({ + request, + }) => { + const response = await request.get('/imported') + const html = await response.text() + + htmlContainsText(html, 'Imported Hydrate') + htmlContainsText(html, 'Imported Hydrate Child') + + await expect( + modulePreloadContentsContain( + request, + getModulePreloadHrefs(html), + 'imported-hydrate-child', + ), + ).resolves.toBe(false) + }) + + test('does not preload Hydrate child chunks before client navigation', async ({ + page, + request, + }) => { + await page.goto('/') + await expect(page.getByTestId('home-heading')).toHaveText( + 'Deferred Hydration', + ) + await expectClientRouterReady(page) + + const link = page.getByRole('link', { name: 'imported Hydrate' }) + await page.mouse.move(0, 0) + await link.hover() + await link.focus() + + await expect( + modulePreloadContentsContain( + request, + await documentModulePreloadHrefs(page), + 'imported-hydrate-child', + ), + ).resolves.toBe(false) + await expect( + resourceContentsContain(page, request, 'imported-hydrate-child', (url) => + isClientJavaScriptResource(url), + ), + ).resolves.toBe(false) + + await page.getByRole('link', { name: 'imported Hydrate' }).click() + await expect(page).toHaveURL(/\/imported$/) + await expect(page.getByTestId('imported-hydrate-fallback')).toHaveCount(0) + await expect(page.getByTestId('imported-hydrate-child')).toContainText( + 'Imported Hydrate Child', + ) + await page.getByTestId('imported-hydrate-child').click() + await expect(page.getByTestId('imported-hydrate-count')).toHaveText('1') + }) +}) diff --git a/e2e/solid-start/deferred-hydration/tsconfig.json b/e2e/solid-start/deferred-hydration/tsconfig.json new file mode 100644 index 0000000000..76cf3401fa --- /dev/null +++ b/e2e/solid-start/deferred-hydration/tsconfig.json @@ -0,0 +1,23 @@ +{ + "include": ["**/*.ts", "**/*.tsx"], + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "jsx": "preserve", + "jsxImportSource": "solid-js", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["DOM", "DOM.Iterable", "ES2022"], + "isolatedModules": true, + "resolveJsonModule": true, + "skipLibCheck": true, + "target": "ES2024", + "allowJs": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "~/*": ["./src/*"] + }, + "noEmit": true, + "types": ["vite/client"] + } +} diff --git a/e2e/solid-start/deferred-hydration/vite.config.ts b/e2e/solid-start/deferred-hydration/vite.config.ts new file mode 100644 index 0000000000..70f388638a --- /dev/null +++ b/e2e/solid-start/deferred-hydration/vite.config.ts @@ -0,0 +1,14 @@ +import { defineConfig } from 'vite' +import { tanstackStart } from '@tanstack/solid-start/plugin/vite' +import viteSolid from 'vite-plugin-solid' + +const outDir = process.env.E2E_DIST_DIR ?? 'dist-vite-ssr' + +export default defineConfig({ + resolve: { tsconfigPaths: true }, + build: { + outDir, + }, + server: { port: 3000 }, + plugins: [tanstackStart(), viteSolid({ ssr: true })], +}) diff --git a/packages/react-router/src/index.tsx b/packages/react-router/src/index.tsx index 48de353b2e..6637c7542b 100644 --- a/packages/react-router/src/index.tsx +++ b/packages/react-router/src/index.tsx @@ -129,6 +129,7 @@ export type { AwaitOptions } from './awaited' export { CatchBoundary, ErrorComponent } from './CatchBoundary' export { ClientOnly, useHydrated } from './ClientOnly' +export { reactUse, useLayoutEffect } from './utils' export { FileRoute, diff --git a/packages/react-start-client/package.json b/packages/react-start-client/package.json index 0e2129bb01..83dee85c78 100644 --- a/packages/react-start-client/package.json +++ b/packages/react-start-client/package.json @@ -48,6 +48,12 @@ "default": "./dist/esm/index.js" } }, + "./hydration": { + "import": { + "types": "./dist/esm/hydration.d.ts", + "default": "./dist/esm/hydration.js" + } + }, "./package.json": "./package.json" }, "sideEffects": false, diff --git a/packages/react-start-client/src/GenericHydrate.tsx b/packages/react-start-client/src/GenericHydrate.tsx new file mode 100644 index 0000000000..e92042a0d7 --- /dev/null +++ b/packages/react-start-client/src/GenericHydrate.tsx @@ -0,0 +1,436 @@ +'use client' + +import * as React from 'react' + +import { reactUse, useHydrated, useLayoutEffect } from '@tanstack/react-router' +import { isServer } from '@tanstack/router-core/isServer' +import { + hydrateIdAttribute, + hydrateWhenAttribute, +} from '@tanstack/start-client-core/hydration/constants' +import { + createResolvedGate, + getFallbackHtml, + getOrCreateGate, + onGateResolve, + releaseGate, + runHydrationStrategyCleanup, + saveFallbackHtml, + waitForHydrationPrefetchStrategy, +} from '@tanstack/start-client-core/hydration/runtime' +import { listenForDelegatedHydrationIntent } from '@tanstack/start-client-core/hydration' +import type { + HydrationRuntimeContext, + HydrationStrategy, + HydrationWhen, +} from '@tanstack/start-client-core/hydration' +import type { HydrationGateRecord } from '@tanstack/start-client-core/hydration/runtime' +import type { HydrateProps, InternalHydrateProps } from './Hydrate' + +type Gate = HydrationGateRecord & { promise: Promise } +type PrefetchController = { + abortController: AbortController + hydrationRequested: boolean + hydrationListeners: Set<() => void> + hydrationResolvePending: boolean + started: boolean + promise?: Promise + cleanup?: () => void +} + +const dynamicType = 'dynamic' +const dynamicHydrateStrategy = { + _t: dynamicType, + _d: () => true, +} satisfies HydrationStrategy + +function shouldDeferHydration(strategy: HydrationStrategy) { + return strategy._d ? strategy._d() : strategy._t !== 'load' +} + +function useLatest(value: T) { + const ref = React.useRef(value) + ref.current = value + return ref +} + +function useHydrationGate(props: InternalHydrateProps) { + const hydrated = useHydrated() + const reactId = React.useId() + const id = props.h ? `${props.h}${reactId}` : reactId + const when = props.when + const isDynamicHydrate = typeof when === 'function' + const dynamicHydrateStrategyRef = React.useRef( + undefined, + ) + if (isDynamicHydrate) { + dynamicHydrateStrategyRef.current ??= + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + (isServer ?? typeof window === 'undefined') + ? dynamicHydrateStrategy + : when() + } + const hydrateStrategy = isDynamicHydrate + ? dynamicHydrateStrategyRef.current! + : when + const markerHydrateType: HydrationWhen = isDynamicHydrate + ? dynamicType + : hydrateStrategy._t! + const [prefetchError, setPrefetchError] = React.useState() + const latestRef = useLatest({ + prefetch: props.prefetch, + preload: props.p, + }) + const gateRef = React.useRef(undefined) + const markerElementRef = React.useRef(null) + const shouldPreserveServerHTMLRef = React.useRef( + undefined, + ) + const shouldDeferInitialHydrationRef = React.useRef( + undefined, + ) + const didPrefetchRef = React.useRef(false) + const prefetchControllerRef = React.useRef( + undefined, + ) + + prefetchControllerRef.current ??= { + abortController: new AbortController(), + hydrationRequested: false, + hydrationListeners: new Set<() => void>(), + hydrationResolvePending: false, + started: false, + } + + shouldPreserveServerHTMLRef.current ??= + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + (isServer ?? typeof window === 'undefined') || !hydrated + shouldDeferInitialHydrationRef.current ??= + !hydrated && shouldDeferHydration(hydrateStrategy) + + if (!gateRef.current) { + gateRef.current = + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + (isServer ?? typeof window === 'undefined') + ? createResolvedGate(id, hydrateStrategy._t!) + : getOrCreateGate(id, hydrateStrategy._t!) + } + + gateRef.current.when = hydrateStrategy._t! + + if ( + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + !(isServer ?? typeof window === 'undefined') && + hydrateStrategy._t !== 'never' && + (!shouldDeferInitialHydrationRef.current || + !shouldDeferHydration(hydrateStrategy)) + ) { + gateRef.current.resolve() + } + + const markerRef = React.useCallback( + (element: HTMLDivElement | null) => { + markerElementRef.current = element + if (element) { + if ( + hydrateStrategy._t === 'never' && + !shouldPreserveServerHTMLRef.current + ) { + element.replaceChildren() + } + saveFallbackHtml(id, element) + } + }, + [hydrateStrategy._t, id], + ) + + React.useEffect(() => { + const gate = gateRef.current! + return () => { + const controller = prefetchControllerRef.current + controller?.abortController.abort() + controller?.cleanup?.() + controller?.hydrationListeners.clear() + releaseGate(gate) + } + }, []) + + React.useEffect(() => { + if ( + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + (isServer ?? typeof window === 'undefined') || + !latestRef.current.prefetch + ) { + return + } + + const controller = prefetchControllerRef.current! + if (controller.started) return + controller.started = true + + const onHydrate = (listener: () => void) => { + if (controller.hydrationRequested) { + listener() + return () => {} + } + + controller.hydrationListeners.add(listener) + return () => { + controller.hydrationListeners.delete(listener) + } + } + + const preload = () => latestRef.current.preload?.() ?? Promise.resolve() + const prefetchInput = latestRef.current.prefetch + + if (typeof prefetchInput === 'function') { + const promise = Promise.resolve() + .then(() => + prefetchInput({ + element: markerElementRef.current, + signal: controller.abortController.signal, + preload, + waitFor: (strategy) => + waitForHydrationPrefetchStrategy(strategy, { + element: markerElementRef.current, + signal: controller.abortController.signal, + onHydrate, + }), + }), + ) + .then(() => undefined) + + controller.promise = promise + promise.catch((error) => { + if (!controller.abortController.signal.aborted) { + setPrefetchError(error) + } + }) + return + } + + if (!latestRef.current.preload) return + + const prefetch = () => { + if (didPrefetchRef.current) return + didPrefetchRef.current = true + void preload() + } + + controller.cleanup = runHydrationStrategyCleanup( + prefetchInput._s?.({ + element: markerElementRef.current, + prefetch, + }), + ) + }, [hydrateStrategy, latestRef]) + + useLayoutEffect(() => { + const gate = gateRef.current! + if ( + !shouldDeferInitialHydrationRef.current || + hydrateStrategy._t === 'never' + ) { + return + } + + if (gate.resolved) { + return + } + + const cleanups: Array<() => void> = [] + let removeResolveListener = () => {} + let disposed = false + const resolveGate = gate.resolve + + const cleanup = () => { + if (disposed) return + disposed = true + if (gate.resolve === requestHydration) { + gate.resolve = resolveGate + } + removeResolveListener() + cleanups.forEach((fn) => fn()) + } + + const addCleanup = (fn: void | (() => void)) => { + if (!fn) return + if (disposed || gate.resolved) { + fn() + return + } + cleanups.push(fn) + } + + const requestHydration = () => { + const controller = prefetchControllerRef.current! + if (!controller.hydrationRequested) { + controller.hydrationRequested = true + controller.hydrationListeners.forEach((listener) => listener()) + controller.hydrationListeners.clear() + } + + if (!controller.promise) { + resolveGate() + return + } + if (controller.hydrationResolvePending) return + controller.hydrationResolvePending = true + + controller.promise.then( + () => resolveGate(), + (error) => { + if (!controller.abortController.signal.aborted) { + setPrefetchError(error) + } + }, + ) + } + + gate.resolve = requestHydration + removeResolveListener = onGateResolve(gate, cleanup) + + const context: HydrationRuntimeContext = { + element: markerElementRef.current, + gate, + } + addCleanup(runHydrationStrategyCleanup(hydrateStrategy._s?.(context))) + + if (hydrateStrategy._t !== 'interaction') { + addCleanup( + runHydrationStrategyCleanup( + markerElementRef.current + ? listenForDelegatedHydrationIntent( + markerElementRef.current, + context, + ) + : undefined, + ), + ) + } + + return cleanup + }, [hydrateStrategy, latestRef]) + + return { + gate: gateRef.current, + markerRef, + markerElementRef, + hydrateStrategy, + markerHydrateType, + prefetchError, + shouldPreserveServerHTML: shouldPreserveServerHTMLRef.current, + } +} + +function HydrationGate(props: { gate: Gate; children: React.ReactNode }) { + if ( + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + isServer ?? + typeof window === 'undefined' + ) { + return props.children as React.JSX.Element + } + + if (props.gate.resolved) { + return props.children as React.JSX.Element + } + + if (!reactUse) { + throw props.gate.promise + } + + reactUse(props.gate.promise) + + return props.children as React.JSX.Element +} + +function HydratedBoundary(props: { + id: string + onHydrated?: () => void + onStrategyHydrated?: (id: string) => void + children: React.ReactNode +}) { + const { id, onHydrated, onStrategyHydrated } = props + const didHydrateRef = React.useRef(false) + + React.useEffect(() => { + if (didHydrateRef.current) return + didHydrateRef.current = true + onHydrated?.() + onStrategyHydrated?.(id) + }, [id, onHydrated, onStrategyHydrated]) + + return props.children as React.JSX.Element +} + +export function GenericHydrate(props: HydrateProps): React.JSX.Element { + const internalProps = props as InternalHydrateProps + const { + gate, + hydrateStrategy, + markerHydrateType, + markerElementRef, + markerRef, + prefetchError, + shouldPreserveServerHTML, + } = useHydrationGate(internalProps) + if (prefetchError) throw prefetchError + + const fallback = shouldPreserveServerHTML + ? (() => { + const html = getFallbackHtml(gate.id) + return html ? ( +
+ ) : null + })() + : (props.fallback ?? null) + const markerAttributes = + markerHydrateType === dynamicType ? undefined : hydrateStrategy._a?.() + + const hydrateType = hydrateStrategy._t! + + if (hydrateType === 'never' && !shouldPreserveServerHTML) { + return ( +
+ {props.fallback ?? null} +
+ ) + } + + return ( +
+ + + { + markerElementRef.current?.removeAttribute(hydrateWhenAttribute) + hydrateStrategy._o?.(id) + }} + > + {props.children} + + + +
+ ) +} diff --git a/packages/react-start-client/src/Hydrate.tsx b/packages/react-start-client/src/Hydrate.tsx new file mode 100644 index 0000000000..019730f3be --- /dev/null +++ b/packages/react-start-client/src/Hydrate.tsx @@ -0,0 +1,107 @@ +'use client' + +import * as React from 'react' + +import { isServer } from '@tanstack/router-core/isServer' +import type { + HydrationStrategy as CoreHydrationStrategy, + HydrationPrefetchFunction, + HydrationPrefetchStrategy, + HydrationWhen, +} from '@tanstack/start-client-core/hydration' + +export type { + HydrationInteractionEvent, + HydrationInteractionEvents, + HydrationPrefetchContext, + HydrationPrefetchFunction, + HydrationPrefetchStrategy, + HydrationPrefetchWaitReason, + HydrationWhen, +} from '@tanstack/start-client-core/hydration' + +export type ReactHydrationStrategy< + TWhen extends HydrationWhen = HydrationWhen, + TCanPrefetch extends boolean = boolean, +> = CoreHydrationStrategy & { + _h: (this: ReactHydrationStrategy, props: HydrateProps) => React.JSX.Element +} + +export type HydrationStrategy< + TWhen extends HydrationWhen = HydrationWhen, + TCanPrefetch extends boolean = boolean, +> = ReactHydrationStrategy + +export type HydrateWhen = + | ReactHydrationStrategy + | (() => ReactHydrationStrategy) + +type HydrateCommonOptions = { + when: HydrateWhen + fallback?: React.ReactNode + onHydrated?: () => void +} + +export type HydrateOptions = + | (HydrateCommonOptions & { + prefetch?: never + split?: boolean + }) + | (HydrateCommonOptions & { + prefetch: HydrationPrefetchStrategy + split?: true + }) + | (HydrateCommonOptions & { + prefetch: HydrationPrefetchFunction + split?: boolean + }) + +export type HydrateProps = HydrateOptions & { + children: React.ReactNode +} + +export type InternalHydrateProps = HydrateProps & { + h?: string + p?: () => Promise +} + +const dynamicType = 'dynamic' +const hydrateIdAttribute = 'data-ts-hydrate-id' +const hydrateWhenAttribute = 'data-ts-hydrate-when' + +/* @__NO_SIDE_EFFECTS__ */ +function ServerDynamicHydrate(props: HydrateProps): React.JSX.Element { + const internalProps = props as InternalHydrateProps + const reactId = React.useId() + const id = internalProps.h ? `${internalProps.h}${reactId}` : reactId + + return ( +
+ + {props.children} + +
+ ) +} + +/* @__NO_SIDE_EFFECTS__ */ +export function Hydrate(props: HydrateProps): React.JSX.Element { + if (typeof props.when === 'function') { + if ( + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + isServer ?? + typeof window === 'undefined' + ) { + return + } + + return props.when()._h(props) + } + + return props.when._h(props) +} diff --git a/packages/react-start-client/src/hydration.ts b/packages/react-start-client/src/hydration.ts new file mode 100644 index 0000000000..fad458175c --- /dev/null +++ b/packages/react-start-client/src/hydration.ts @@ -0,0 +1,22 @@ +'use client' + +export { condition, interaction, media } from './hydration/generic' +export { idle } from './hydration/idle' +export { load } from './hydration/load' +export { never } from './hydration/never' +export { visible } from './hydration/visible' +export type { + HydrationCondition, + HydrationInteractionEvent, + HydrationInteractionEvents, + IdleHydrationOptions, + HydrationPrefetchContext, + HydrationPrefetchFunction, + HydrationPrefetchWhen, + HydrationPrefetchStrategy, + HydrationPrefetchWaitReason, + HydrationStrategyTypes, + HydrationWhen, + VisibleHydrationOptions, +} from '@tanstack/start-client-core/hydration' +export type { HydrationStrategy, ReactHydrationStrategy } from './Hydrate' diff --git a/packages/react-start-client/src/hydration/generic.ts b/packages/react-start-client/src/hydration/generic.ts new file mode 100644 index 0000000000..5ee6d3c3d6 --- /dev/null +++ b/packages/react-start-client/src/hydration/generic.ts @@ -0,0 +1,43 @@ +'use client' + +import { + condition as coreCondition, + interaction as coreInteraction, + media as coreMedia, + withHydrationRenderer, +} from '@tanstack/start-client-core/hydration' +import { GenericHydrate } from '../GenericHydrate' +import type { + HydrationCondition, + HydrationInteractionEvents, + HydrationPrefetchStrategy, +} from '@tanstack/start-client-core/hydration' +import type { ReactHydrationStrategy } from '../Hydrate' + +/* @__NO_SIDE_EFFECTS__ */ +export function media( + query: string, +): ReactHydrationStrategy<'media', true> & HydrationPrefetchStrategy<'media'> { + return /* @__PURE__ */ withHydrationRenderer(coreMedia(query), GenericHydrate) +} + +/* @__NO_SIDE_EFFECTS__ */ +export function condition( + condition: HydrationCondition, +): ReactHydrationStrategy<'condition', false> { + return /* @__PURE__ */ withHydrationRenderer( + coreCondition(condition), + GenericHydrate, + ) +} + +/* @__NO_SIDE_EFFECTS__ */ +export function interaction(options?: { + events?: HydrationInteractionEvents +}): ReactHydrationStrategy<'interaction', true> & + HydrationPrefetchStrategy<'interaction'> { + return /* @__PURE__ */ withHydrationRenderer( + coreInteraction(options), + GenericHydrate, + ) +} diff --git a/packages/react-start-client/src/hydration/idle.ts b/packages/react-start-client/src/hydration/idle.ts new file mode 100644 index 0000000000..58c7f265eb --- /dev/null +++ b/packages/react-start-client/src/hydration/idle.ts @@ -0,0 +1,22 @@ +'use client' + +import { + idle as coreIdle, + withHydrationRenderer, +} from '@tanstack/start-client-core/hydration' +import { GenericHydrate } from '../GenericHydrate' +import type { + HydrationPrefetchStrategy, + IdleHydrationOptions, +} from '@tanstack/start-client-core/hydration' +import type { ReactHydrationStrategy } from '../Hydrate' + +/* @__NO_SIDE_EFFECTS__ */ +export function idle( + options: IdleHydrationOptions = {}, +): ReactHydrationStrategy<'idle', true> & HydrationPrefetchStrategy<'idle'> { + return /* @__PURE__ */ withHydrationRenderer( + coreIdle(options), + GenericHydrate, + ) +} diff --git a/packages/react-start-client/src/hydration/load.tsx b/packages/react-start-client/src/hydration/load.tsx new file mode 100644 index 0000000000..006f4e6952 --- /dev/null +++ b/packages/react-start-client/src/hydration/load.tsx @@ -0,0 +1,49 @@ +'use client' + +import * as React from 'react' + +import { + load as coreLoad, + withHydrationRenderer, +} from '@tanstack/start-client-core/hydration' +import type { HydrationPrefetchStrategy } from '@tanstack/start-client-core/hydration' +import type { HydrateProps, ReactHydrationStrategy } from '../Hydrate' + +function HydratedBoundary(props: { + onHydrated?: () => void + children: React.ReactNode +}) { + const { onHydrated, children } = props + const didHydrateRef = React.useRef(false) + + React.useEffect(() => { + if (didHydrateRef.current) return + didHydrateRef.current = true + onHydrated?.() + }, [onHydrated]) + + return children as React.JSX.Element +} + +export function LoadHydrate(props: HydrateProps): React.JSX.Element { + return ( +
+ + + {props.children} + + +
+ ) +} + +const loadStrategy = /* @__PURE__ */ withHydrationRenderer( + coreLoad(), + LoadHydrate, +) as ReactHydrationStrategy<'load', true> & HydrationPrefetchStrategy<'load'> + +/* @__NO_SIDE_EFFECTS__ */ +export function load(): ReactHydrationStrategy<'load', true> & + HydrationPrefetchStrategy<'load'> { + return loadStrategy +} diff --git a/packages/react-start-client/src/hydration/never.tsx b/packages/react-start-client/src/hydration/never.tsx new file mode 100644 index 0000000000..250a8ed1ae --- /dev/null +++ b/packages/react-start-client/src/hydration/never.tsx @@ -0,0 +1,97 @@ +'use client' + +import * as React from 'react' + +import { reactUse, useHydrated } from '@tanstack/react-router' +import { isServer } from '@tanstack/router-core/isServer' +import { + never as coreNever, + withHydrationRenderer, +} from '@tanstack/start-client-core/hydration' +import { + hydrateIdAttribute, + hydrateWhenAttribute, +} from '@tanstack/start-client-core/hydration/constants' +import { + getFallbackHtml, + saveFallbackHtml, +} from '@tanstack/start-client-core/hydration/runtime' +import type { + HydrateProps, + InternalHydrateProps, + ReactHydrationStrategy, +} from '../Hydrate' + +const neverType = 'never' +const neverPromise = new Promise(() => {}) + +function NeverGate(props: { children: React.ReactNode }) { + if ( + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + isServer ?? + typeof window === 'undefined' + ) { + return props.children as React.JSX.Element + } + + if (!reactUse) { + throw neverPromise + } + + reactUse(neverPromise) + + return props.children as React.JSX.Element +} + +export function NeverHydrate(props: HydrateProps): React.JSX.Element { + const internalProps = props as InternalHydrateProps + const hydrated = useHydrated() + const reactId = React.useId() + const id = internalProps.h ? `${internalProps.h}${reactId}` : reactId + const shouldPreserveServerHTMLRef = React.useRef( + undefined, + ) + shouldPreserveServerHTMLRef.current ??= + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + (isServer ?? typeof window === 'undefined') || !hydrated + const markerRef = React.useCallback( + (element: HTMLDivElement | null) => { + if (!element) return + if (!shouldPreserveServerHTMLRef.current) { + element.replaceChildren() + } else { + saveFallbackHtml(id, element) + } + }, + [id], + ) + const markerProps = { + ref: markerRef, + [hydrateIdAttribute]: id, + [hydrateWhenAttribute]: neverType, + } + const fallback = (() => { + const html = getFallbackHtml(id) + return html ? ( +
+ ) : ( + (props.fallback ?? null) + ) + })() + + return ( +
+ + {props.children} + +
+ ) +} + +/* @__NO_SIDE_EFFECTS__ */ +export function never(): ReactHydrationStrategy<'never', false> { + return /* @__PURE__ */ withHydrationRenderer(coreNever(), NeverHydrate) +} diff --git a/packages/react-start-client/src/hydration/visible.tsx b/packages/react-start-client/src/hydration/visible.tsx new file mode 100644 index 0000000000..e274285cb8 --- /dev/null +++ b/packages/react-start-client/src/hydration/visible.tsx @@ -0,0 +1,139 @@ +'use client' + +import * as React from 'react' + +import { reactUse } from '@tanstack/react-router' +import { isServer } from '@tanstack/router-core/isServer' +import type { + HydrationPrefetchStrategy, + VisibleHydrationOptions, +} from '@tanstack/start-client-core/hydration' +import type { + HydrateProps, + InternalHydrateProps, + ReactHydrationStrategy, +} from '../Hydrate' + +type VisibleGate = { + p: Promise + r: boolean + s: () => void +} + +/* @__NO_SIDE_EFFECTS__ */ +function HydrationBoundary(props: { + g: VisibleGate + o?: () => void + children?: React.ReactNode +}) { + const { g, o } = props + + if (!g.r) { + if (!reactUse) { + throw g.p + } + + reactUse(g.p) + } + + React.useEffect(() => { + o?.() + }, [o]) + + return props.children as React.JSX.Element +} + +/* @__NO_SIDE_EFFECTS__ */ +export function VisibleHydrate( + this: ReactHydrationStrategy, + props: HydrateProps, +): React.JSX.Element { + const strategy = this as ReactHydrationStrategy<'visible', true> + const prefetchStrategy = props.prefetch + const preload = (props as InternalHydrateProps).p + const markerRef = React.useRef(null) + const [gate] = React.useState(() => { + let resolvePromise!: () => void + const nextGate: VisibleGate = { + p: new Promise((resolve) => { + resolvePromise = resolve + }), + r: false, + s: () => { + nextGate.r = true + resolvePromise() + }, + } + if ( + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + isServer ?? + typeof window === 'undefined' + ) { + nextGate.s() + } + + return nextGate + }) + + React.useEffect(() => { + if (!preload || typeof prefetchStrategy === 'function') { + return + } + + return prefetchStrategy?._s?.({ + element: markerRef.current, + prefetch: preload, + }) + }, [prefetchStrategy, preload]) + + React.useEffect(() => { + if (gate.r) return + + return strategy._s?.({ + element: markerRef.current, + gate: gate as never, + }) + }, [gate, strategy]) + + return ( +
+ + + {props.children} + + +
+ ) +} + +/* @__NO_SIDE_EFFECTS__ */ +export function visible( + options?: VisibleHydrationOptions, +): ReactHydrationStrategy<'visible', true> & + HydrationPrefetchStrategy<'visible'> { + const rootMargin = options?.rootMargin ?? '600px' + const threshold = options?.threshold ?? 0 + + return { + _s: ({ element, gate, prefetch }) => { + const callback = prefetch || (gate as never as VisibleGate).s + + if (!element) { + callback() + return + } + + const observer = new IntersectionObserver( + (entries) => { + if (!entries[0]!.isIntersecting) return + observer.disconnect() + callback() + }, + { rootMargin, threshold }, + ) + observer.observe(element) + return () => observer.disconnect() + }, + _h: VisibleHydrate, + } +} diff --git a/packages/react-start-client/src/index.tsx b/packages/react-start-client/src/index.tsx index aa73990a57..669b1e0e3f 100644 --- a/packages/react-start-client/src/index.tsx +++ b/packages/react-start-client/src/index.tsx @@ -1,2 +1,18 @@ +'use client' + export { StartClient } from './StartClient' export { hydrateStart } from './hydrateStart' +export { Hydrate } from './Hydrate' +export type { + HydrateOptions, + HydrateProps, + HydrateWhen, + HydrationInteractionEvent, + HydrationInteractionEvents, + HydrationPrefetchContext, + HydrationPrefetchFunction, + HydrationPrefetchStrategy, + HydrationPrefetchWaitReason, + HydrationStrategy, + HydrationWhen, +} from './Hydrate' diff --git a/packages/react-start-client/src/tests/Hydrate.test-d.tsx b/packages/react-start-client/src/tests/Hydrate.test-d.tsx new file mode 100644 index 0000000000..2e3726edfa --- /dev/null +++ b/packages/react-start-client/src/tests/Hydrate.test-d.tsx @@ -0,0 +1,147 @@ +import { expectTypeOf, test } from 'vitest' +import { visible } from '../hydration' +import { Hydrate } from '../Hydrate' +import type { + HydrateOptions, + HydrateProps, + HydrationPrefetchFunction, + HydrationPrefetchStrategy, + HydrationStrategy, +} from '../Hydrate' +import type { HydrationStrategy as CoreHydrationStrategy } from '@tanstack/start-client-core/hydration' +import type { ReactNode } from 'react' + +type CommonHydrateProps = { + fallback?: ReactNode + onHydrated?: () => void + children: ReactNode +} + +type SplitHydrateProps = CommonHydrateProps & { + when: HydrationStrategy | (() => HydrationStrategy) + prefetch?: never + split?: boolean +} + +type PrefetchHydrateProps = CommonHydrateProps & { + when: HydrationStrategy | (() => HydrationStrategy) + prefetch: HydrationPrefetchStrategy + split?: true +} + +type FunctionPrefetchHydrateProps = CommonHydrateProps & { + when: HydrationStrategy | (() => HydrationStrategy) + prefetch: HydrationPrefetchFunction + split?: boolean +} + +test('Hydrate component accepts the public HydrateProps type', () => { + expectTypeOf(Hydrate).toBeFunction() + expectTypeOf(Hydrate).parameter(0).branded.toEqualTypeOf() +}) + +test('HydrateOptions supports reusable spread props', () => { + const belowFoldProps = { + when: () => visible({ rootMargin: '800px' }), + } satisfies HydrateOptions + + expectTypeOf(belowFoldProps).toMatchTypeOf() + + const withFunctionPrefetch = { + when: visible(), + split: false, + prefetch: (ctx) => { + expectTypeOf(ctx.element).toEqualTypeOf() + expectTypeOf(ctx.signal).toEqualTypeOf() + expectTypeOf(ctx.preload).returns.toEqualTypeOf>() + expectTypeOf(ctx.waitFor).returns.toEqualTypeOf< + Promise<'prefetch' | 'hydrate' | 'abort'> + >() + }, + } satisfies HydrateOptions + + expectTypeOf(withFunctionPrefetch).toMatchTypeOf() +}) + +test('Hydrate props are exact for strategy and prefetch forms', () => { + expectTypeOf< + Extract + >().branded.toEqualTypeOf() + expectTypeOf< + Extract + >().branded.toEqualTypeOf() + expectTypeOf< + Extract + >().branded.toEqualTypeOf() +}) + +test('Hydrate requires a strategy', () => { + expectTypeOf<{ + when: HydrationStrategy + children: ReactNode + }>().toMatchTypeOf() + + expectTypeOf<{ + when: () => HydrationStrategy + children: ReactNode + }>().toMatchTypeOf() + + expectTypeOf<{ + children: ReactNode + }>().not.toMatchTypeOf() + + expectTypeOf<{ + when: () => true + children: ReactNode + }>().not.toMatchTypeOf() + + expectTypeOf<{ + when: false + children: ReactNode + }>().not.toMatchTypeOf() +}) + +test('Hydrate requires a framework-renderable strategy', () => { + expectTypeOf().not.toMatchTypeOf() + expectTypeOf>().toMatchTypeOf() + + expectTypeOf<{ + when: CoreHydrationStrategy + children: ReactNode + }>().not.toMatchTypeOf() +}) + +test('Hydrate enforces prefetch only with split boundaries', () => { + expectTypeOf<{ + when: HydrationStrategy + prefetch: HydrationPrefetchStrategy + children: ReactNode + }>().toMatchTypeOf() + + expectTypeOf<{ + when: HydrationStrategy + prefetch: HydrationPrefetchStrategy + split: true + children: ReactNode + }>().toMatchTypeOf() + + expectTypeOf<{ + when: HydrationStrategy + prefetch: HydrationPrefetchStrategy + split: false + children: ReactNode + }>().not.toMatchTypeOf() + + expectTypeOf<{ + when: HydrationStrategy + prefetch: HydrationPrefetchFunction + split: false + children: ReactNode + }>().toMatchTypeOf() + + expectTypeOf<{ + when: HydrationStrategy + prefetch: HydrationPrefetchFunction + children: ReactNode + }>().toMatchTypeOf() +}) diff --git a/packages/react-start-client/src/tests/Hydrate.test.tsx b/packages/react-start-client/src/tests/Hydrate.test.tsx new file mode 100644 index 0000000000..0d0ce1faad --- /dev/null +++ b/packages/react-start-client/src/tests/Hydrate.test.tsx @@ -0,0 +1,676 @@ +import * as React from 'react' +import { renderToString } from 'react-dom/server' +import { hydrateRoot } from 'react-dom/client' +import { + act, + cleanup, + fireEvent, + render, + screen, + waitFor, +} from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { hydrateIdAttribute } from '@tanstack/start-client-core/hydration/constants' +import { Hydrate } from '../Hydrate' +import { condition, idle, interaction, load, never } from '../hydration' +import type { HydrateProps, HydrationPrefetchStrategy } from '../Hydrate' + +const InternalHydrate = Hydrate as React.ComponentType< + HydrateProps & { p?: () => Promise; h?: string } +> + +const hydrateIdSelector = `[${hydrateIdAttribute}]` + +function getMarker() { + const marker = document.querySelector(hydrateIdSelector) + + if (!marker) { + throw new Error('Expected Hydrate marker to exist') + } + + return marker +} + +function InteractiveChild() { + const [count, setCount] = React.useState(0) + const [hydrated, setHydrated] = React.useState(false) + + React.useEffect(() => { + setHydrated(true) + }, []) + + return ( + + ) +} + +function NamedInteractiveChild(props: { id: string }) { + const [hydrated, setHydrated] = React.useState(false) + + React.useEffect(() => { + setHydrated(true) + }, []) + + return ( + + ) +} + +function createSuspendingChild() { + let resolve!: () => void + let resolved = false + const promise = new Promise((resolvePromise) => { + resolve = () => { + resolved = true + resolvePromise() + } + }) + + function SuspendingChild() { + if (!resolved) { + throw promise + } + + return
child
+ } + + return { resolve, SuspendingChild } +} + +async function expectNoHydrationAfterDefaultIntentEvents() { + const marker = getMarker() + + expect(screen.getByTestId('child').getAttribute('data-hydrated')).toBe( + 'false', + ) + + await act(async () => { + fireEvent.pointerEnter(marker) + fireEvent.focusIn(marker) + fireEvent.pointerDown(marker) + fireEvent.click(marker) + await new Promise((resolve) => setTimeout(resolve, 20)) + }) + + expect(screen.getByTestId('child').getAttribute('data-hydrated')).toBe( + 'false', + ) +} + +async function fireIntent(event: () => void) { + await act(async () => { + event() + await Promise.resolve() + }) +} + +async function renderAsync(ui: React.ReactElement) { + await act(async () => { + render(ui) + await Promise.resolve() + }) +} + +async function hydrateFromServer(ui: React.ReactElement) { + vi.stubGlobal('window', undefined) + const html = renderToString(ui) + vi.unstubAllGlobals() + + const container = document.createElement('div') + document.body.append(container) + container.innerHTML = html + + let root!: ReturnType + await act(async () => { + root = hydrateRoot(container, ui) + await Promise.resolve() + }) + + return { container, html, root } +} + +async function unmountHydratedRoot( + root: ReturnType, + container: Element, +) { + await act(async () => { + root.unmount() + }) + container.remove() +} + +afterEach(() => { + cleanup() + vi.unstubAllGlobals() +}) + +describe('Hydrate', () => { + it('uses a single custom interaction event instead of the default intent events', async () => { + const { container, html, root } = await hydrateFromServer( + fallback
} + > + + , + ) + + try { + expect(html).toContain('data-testid="child"') + expect(html).not.toContain('data-testid="fallback"') + expect(screen.queryByTestId('fallback')).toBeNull() + await expectNoHydrationAfterDefaultIntentEvents() + + await fireIntent(() => + getMarker().dispatchEvent( + new MouseEvent('dblclick', { bubbles: true, cancelable: true }), + ), + ) + + await waitFor(() => + expect(screen.getByTestId('child').getAttribute('data-hydrated')).toBe( + 'true', + ), + ) + } finally { + await unmountHydratedRoot(root, container) + } + }) + + it('uses every event in a custom interaction event list', async () => { + const { container, root } = await hydrateFromServer( + fallback
} + > + + , + ) + + try { + expect(screen.queryByTestId('fallback')).toBeNull() + await expectNoHydrationAfterDefaultIntentEvents() + + await fireIntent(() => + getMarker().dispatchEvent( + new MouseEvent('contextmenu', { bubbles: true, cancelable: true }), + ), + ) + + await waitFor(() => + expect(screen.getByTestId('child').getAttribute('data-hydrated')).toBe( + 'true', + ), + ) + } finally { + await unmountHydratedRoot(root, container) + } + }) + + it('omits never content when mounted after the app is already hydrated', async () => { + await renderAsync( + + + , + ) + + expect(screen.queryByTestId('child')).toBeNull() + }) + + it('shows fallback for a client-only mount while children suspend', async () => { + const { resolve, SuspendingChild } = createSuspendingChild() + + await renderAsync( + fallback} + > + + , + ) + + expect(screen.getByTestId('fallback').textContent).toBe('fallback') + expect(screen.queryByTestId('child')).toBeNull() + + await act(async () => { + resolve() + await Promise.resolve() + }) + + await screen.findByTestId('child') + expect(screen.queryByTestId('fallback')).toBeNull() + }) + + it('does not use fallback for an initial never boundary', async () => { + const { container, html, root } = await hydrateFromServer( + fallback} + > + + , + ) + + try { + expect(html).toContain('data-testid="child"') + expect(html).not.toContain('data-testid="fallback"') + expect(screen.queryByTestId('fallback')).toBeNull() + + fireEvent.click(screen.getByTestId('child')) + await new Promise((resolve) => setTimeout(resolve, 20)) + expect(screen.getByTestId('child').getAttribute('data-hydrated')).toBe( + 'false', + ) + expect(screen.getByTestId('child').textContent).toBe('0') + } finally { + await unmountHydratedRoot(root, container) + } + }) + + it('keeps repeated split boundaries independently gated', async () => { + const { container, root } = await hydrateFromServer( + <> + + + + + + + , + ) + + try { + const markers = container.querySelectorAll(hydrateIdSelector) + + expect(markers).toHaveLength(2) + expect(markers[0]!.getAttribute(hydrateIdAttribute)).not.toBe( + markers[1]!.getAttribute(hydrateIdAttribute), + ) + expect( + screen.getByTestId('child-one').getAttribute('data-hydrated'), + ).toBe('false') + expect( + screen.getByTestId('child-two').getAttribute('data-hydrated'), + ).toBe('false') + + await fireIntent(() => + markers[0]!.dispatchEvent( + new MouseEvent('click', { bubbles: true, cancelable: true }), + ), + ) + + await waitFor(() => + expect( + screen.getByTestId('child-one').getAttribute('data-hydrated'), + ).toBe('true'), + ) + expect( + screen.getByTestId('child-two').getAttribute('data-hydrated'), + ).toBe('false') + } finally { + await unmountHydratedRoot(root, container) + } + }) + + it('fires onHydrated once after the client hydration commit', async () => { + const onHydrated = vi.fn() + const app = ( + +
child
+
+ ) + + vi.stubGlobal('window', undefined) + const html = renderToString(app) + expect(html).toContain('child') + expect(onHydrated).not.toHaveBeenCalled() + vi.unstubAllGlobals() + + const container = document.createElement('div') + document.body.append(container) + container.innerHTML = html + + let root!: ReturnType + await act(async () => { + root = hydrateRoot(container, app) + }) + + await waitFor(() => expect(onHydrated).toHaveBeenCalledTimes(1)) + + fireEvent.click(screen.getByTestId('child')) + await new Promise((resolve) => setTimeout(resolve, 20)) + expect(onHydrated).toHaveBeenCalledTimes(1) + + await act(async () => { + root.unmount() + }) + container.remove() + }) + + it('prefetches split children without hydrating the boundary', async () => { + const preload = vi.fn(() => Promise.resolve()) + + const { container, root } = await hydrateFromServer( + + + , + ) + + try { + await waitFor(() => expect(preload).toHaveBeenCalledTimes(1)) + expect(screen.getByTestId('child').getAttribute('data-hydrated')).toBe( + 'false', + ) + + await fireIntent(() => + getMarker().dispatchEvent( + new MouseEvent('click', { bubbles: true, cancelable: true }), + ), + ) + + await waitFor(() => + expect(screen.getByTestId('child').getAttribute('data-hydrated')).toBe( + 'true', + ), + ) + expect(preload).toHaveBeenCalledTimes(1) + } finally { + await unmountHydratedRoot(root, container) + } + }) + + it('does not evaluate dynamic when callbacks on the server', async () => { + const when = vi.fn(() => interaction({ events: 'dblclick' })) + + vi.stubGlobal('window', undefined) + const html = renderToString( + + + , + ) + vi.unstubAllGlobals() + + expect(when).not.toHaveBeenCalled() + expect(html).toContain('data-ts-hydrate-when="dynamic"') + + const container = document.createElement('div') + document.body.append(container) + container.innerHTML = html + + let root!: ReturnType + try { + await act(async () => { + root = hydrateRoot( + container, + + + , + ) + await Promise.resolve() + }) + + expect(when).toHaveBeenCalled() + await expectNoHydrationAfterDefaultIntentEvents() + + await fireIntent(() => + getMarker().dispatchEvent( + new MouseEvent('dblclick', { bubbles: true, cancelable: true }), + ), + ) + + await waitFor(() => + expect(screen.getByTestId('child').getAttribute('data-hydrated')).toBe( + 'true', + ), + ) + } finally { + await unmountHydratedRoot(root, container) + } + }) + + it('replays an interaction captured before the Hydrate component hydrates', async () => { + const when = () => interaction({ events: 'click' }) + + vi.stubGlobal('window', undefined) + const html = renderToString( + + + , + ) + vi.unstubAllGlobals() + + const container = document.createElement('div') + document.body.append(container) + container.innerHTML = html + + const button = container.querySelector('[data-testid="child"]') + if (!button) { + throw new Error('Expected server-rendered child button') + } + + button.dispatchEvent( + new MouseEvent('click', { bubbles: true, cancelable: true }), + ) + + let root!: ReturnType + try { + await act(async () => { + root = hydrateRoot( + container, + + + , + ) + await Promise.resolve() + }) + + await waitFor(() => + expect(screen.getByTestId('child').getAttribute('data-hydrated')).toBe( + 'true', + ), + ) + await waitFor(() => + expect(screen.getByTestId('child').textContent).toBe('1'), + ) + } finally { + await unmountHydratedRoot(root, container) + } + }) + + it('blocks hydration on awaited procedural prefetch work', async () => { + const preload = vi.fn(() => Promise.resolve()) + let resolvePrefetch!: () => void + const prefetchBlocker = new Promise((resolve) => { + resolvePrefetch = resolve + }) + const waitReasons: Array = [] + const neverPrefetches = { + _t: 'idle', + _s: () => () => {}, + } as HydrationPrefetchStrategy<'idle'> + + const { container, root } = await hydrateFromServer( + { + waitReasons.push(await waitFor(neverPrefetches)) + await preload() + await prefetchBlocker + }} + p={preload} + > + + , + ) + + try { + await fireIntent(() => + getMarker().dispatchEvent( + new MouseEvent('click', { bubbles: true, cancelable: true }), + ), + ) + + await waitFor(() => expect(waitReasons).toEqual(['hydrate'])) + expect(preload).toHaveBeenCalledTimes(1) + expect(screen.getByTestId('child').getAttribute('data-hydrated')).toBe( + 'false', + ) + + await act(async () => { + resolvePrefetch() + await prefetchBlocker + await Promise.resolve() + }) + + await waitFor(() => + expect(screen.getByTestId('child').getAttribute('data-hydrated')).toBe( + 'true', + ), + ) + } finally { + await unmountHydratedRoot(root, container) + } + }) + + it('hydrates when a condition strategy changes after the initial render', async () => { + function ConditionHarness() { + const [ready, setReady] = React.useState(false) + + return ( + <> + + + + + + ) + } + + const { container, root } = await hydrateFromServer() + + try { + expect(screen.getByTestId('child').getAttribute('data-hydrated')).toBe( + 'false', + ) + + await act(async () => { + fireEvent.click(screen.getByTestId('ready')) + await Promise.resolve() + }) + + await waitFor(() => + expect(screen.getByTestId('child').getAttribute('data-hydrated')).toBe( + 'true', + ), + ) + } finally { + await unmountHydratedRoot(root, container) + } + }) + + it('does not block hydration on fire-and-forget procedural prefetch work', async () => { + let resolvePrefetch!: () => void + const prefetchBlocker = new Promise((resolve) => { + resolvePrefetch = resolve + }) + + const { container, root } = await hydrateFromServer( + { + void prefetchBlocker + }} + > + + , + ) + + try { + await fireIntent(() => + getMarker().dispatchEvent( + new MouseEvent('click', { bubbles: true, cancelable: true }), + ), + ) + + await waitFor(() => + expect(screen.getByTestId('child').getAttribute('data-hydrated')).toBe( + 'true', + ), + ) + + await act(async () => { + resolvePrefetch() + await prefetchBlocker + }) + } finally { + await unmountHydratedRoot(root, container) + } + }) + + it('aborts procedural prefetch when the boundary unmounts', async () => { + const signals: Array = [] + + const { container, root } = await hydrateFromServer( + { + signals.push(signal) + return new Promise(() => {}) + }} + > + + , + ) + + expect(signals).toHaveLength(1) + expect(signals[0]!.aborted).toBe(false) + + await unmountHydratedRoot(root, container) + expect(signals[0]!.aborted).toBe(true) + }) + + it('delegates nested interaction boundaries at runtime', async () => { + const { container, root } = await hydrateFromServer( + + + + + , + ) + + try { + expect(screen.getByTestId('child').getAttribute('data-hydrated')).toBe( + 'false', + ) + + await fireIntent(() => { + fireEvent.click(screen.getByTestId('child')) + }) + + await waitFor(() => + expect(screen.getByTestId('child').getAttribute('data-hydrated')).toBe( + 'true', + ), + ) + } finally { + await unmountHydratedRoot(root, container) + } + }) +}) diff --git a/packages/react-start-client/vite.config.ts b/packages/react-start-client/vite.config.ts index 32119eee3a..40e07174ac 100644 --- a/packages/react-start-client/vite.config.ts +++ b/packages/react-start-client/vite.config.ts @@ -20,7 +20,7 @@ export default mergeConfig( tanstackViteConfig({ tsconfigPath: './tsconfig.build.json', srcDir: './src', - entry: './src/index.tsx', + entry: ['./src/index.tsx', './src/hydration.ts'], cjs: false, }), ) diff --git a/packages/react-start/package.json b/packages/react-start/package.json index 8f1ca3ba1a..637d9e7546 100644 --- a/packages/react-start/package.json +++ b/packages/react-start/package.json @@ -48,6 +48,12 @@ "default": "./dist/esm/client.js" } }, + "./hydration": { + "import": { + "types": "./dist/esm/hydration.d.ts", + "default": "./dist/esm/hydration.js" + } + }, "./client-rpc": { "import": { "types": "./dist/esm/client-rpc.d.ts", diff --git a/packages/react-start/src/hydration.ts b/packages/react-start/src/hydration.ts new file mode 100644 index 0000000000..e86169e71d --- /dev/null +++ b/packages/react-start/src/hydration.ts @@ -0,0 +1,18 @@ +export { + condition, + idle, + interaction, + load, + media, + never, + visible, +} from '@tanstack/react-start-client/hydration' +export type { + HydrationCondition, + HydrationInteractionEvent, + HydrationInteractionEvents, + HydrationPrefetchStrategy, + HydrationStrategy, + HydrationWhen, + VisibleHydrationOptions, +} from '@tanstack/react-start-client/hydration' diff --git a/packages/react-start/src/index.ts b/packages/react-start/src/index.ts index 8b51b6c783..65b116ec2e 100644 --- a/packages/react-start/src/index.ts +++ b/packages/react-start/src/index.ts @@ -1,2 +1,13 @@ export { useServerFn } from './useServerFn' export * from '@tanstack/start-client-core' +export { createServerFn } from '@tanstack/start-client-core' +export { Hydrate } from '@tanstack/react-start-client' +export type { + HydrateOptions, + HydrateProps, + HydrationInteractionEvent, + HydrationInteractionEvents, + HydrationPrefetchStrategy, + HydrationStrategy, + HydrationWhen, +} from '@tanstack/react-start-client' diff --git a/packages/react-start/vite.config.ts b/packages/react-start/vite.config.ts index 0995b1f9b4..652e4ef842 100644 --- a/packages/react-start/vite.config.ts +++ b/packages/react-start/vite.config.ts @@ -27,6 +27,7 @@ export default mergeConfig( entry: [ './src/index.ts', './src/client.tsx', + './src/hydration.ts', './src/client-rpc.ts', './src/server.tsx', './src/server.rsc.ts', diff --git a/packages/router-core/src/index.ts b/packages/router-core/src/index.ts index ded15fff6d..e737fa50f8 100644 --- a/packages/router-core/src/index.ts +++ b/packages/router-core/src/index.ts @@ -185,6 +185,7 @@ export type { RouteContextFn, ContextOptions, RouteContextOptions, + SsrContextOptions, BeforeLoadContextOptions, RootRouteOptions, RootRouteOptionsExtensions, diff --git a/packages/router-core/src/ssr/ssr-server.ts b/packages/router-core/src/ssr/ssr-server.ts index 2bca7009d9..c1e467f2fb 100644 --- a/packages/router-core/src/ssr/ssr-server.ts +++ b/packages/router-core/src/ssr/ssr-server.ts @@ -292,23 +292,27 @@ export function attachRouterServerSsrUtils({ }) { router.ssr = { get manifest() { + if (!manifest) return manifest + const requestAssets = getRequestAssets?.() - const inlineCssAsset = getInlineCssAssetForMatches( - manifest, - router.stores.matches.get(), - ) - if (!requestAssets?.length && !inlineCssAsset) return manifest + const matches = router.stores.matches.get() + const inlineCssAsset = getInlineCssAssetForMatches(manifest, matches) + + if (!requestAssets?.length && !inlineCssAsset) { + return manifest + } + // Merge request-scoped assets into root route without mutating cached manifest return { ...manifest, routes: { - ...manifest?.routes, + ...manifest.routes, [rootRouteId]: { - ...manifest?.routes?.[rootRouteId], + ...manifest.routes[rootRouteId], assets: [ ...(requestAssets ?? []), ...(inlineCssAsset ? [inlineCssAsset] : []), - ...(manifest?.routes?.[rootRouteId]?.assets ?? []), + ...(manifest.routes[rootRouteId]?.assets ?? []), ], }, }, diff --git a/packages/router-plugin/src/core/code-splitter/compilers.ts b/packages/router-plugin/src/core/code-splitter/compilers.ts index d59b4fa9af..32eade99af 100644 --- a/packages/router-plugin/src/core/code-splitter/compilers.ts +++ b/packages/router-plugin/src/core/code-splitter/compilers.ts @@ -2,15 +2,27 @@ import * as t from '@babel/types' import * as babel from '@babel/core' import * as template from '@babel/template' import { + buildDeclarationMap, + buildDependencyGraph, + collectIdentifiersFromPattern, + collectLocalBindingsFromStatement, + collectModuleLevelRefsFromNode, + createIdentifier, deadCodeElimination, + expandDestructuredDeclarations, + expandSharedDestructuredDeclarators, + expandTransitively, findReferencedIdentifiers, generateFromAst, parseAst, + removeBindingsTransitivelyDependingOn, + retainModuleLevelDeclarations, + stripUnreferencedTopLevelExpressionStatements, + unwrapExportedDeclarations, } from '@tanstack/router-utils' import { tsrShared, tsrSplit } from '../constants' import { createRouteHmrStatement } from '../hmr' import { getObjectPropertyKeyName } from '../utils' -import { createIdentifier } from './path-ids' import { getFrameworkOptions } from './framework-options' import type { CompileCodeSplitReferenceRouteOptions, @@ -20,6 +32,25 @@ import type { GeneratorResult, ParseAstOptions } from '@tanstack/router-utils' import type { CodeSplitGroupings, SplitRouteIdentNodes } from '../constants' import type { SplitNodeMeta } from './types' +export { + buildDeclarationMap, + buildDependencyGraph, + collectIdentifiersFromNode, + collectLocalBindingsFromStatement, + collectModuleLevelRefsFromNode, + expandDestructuredDeclarations, + expandSharedDestructuredDeclarators, + expandTransitively, + removeBindingsTransitivelyDependingOn, +} from '@tanstack/router-utils' + +export function removeBindingsDependingOnRoute( + bindings: Set, + dependencyGraph: Map>, +) { + removeBindingsTransitivelyDependingOn(bindings, dependencyGraph, ['Route']) +} + const SPLIT_NODES_CONFIG = new Map([ [ 'loader', @@ -108,124 +139,6 @@ const allCreateRouteFns = [ ...unsplittableCreateRouteFns, ] -/** - * Recursively walk an AST node and collect referenced identifier-like names. - * Much cheaper than babel.traverse — no path/scope overhead. - * - * Notes: - * - Uses @babel/types `isReferenced` to avoid collecting non-references like - * object keys, member expression properties, or binding identifiers. - * - Also handles JSX identifiers for component references. - */ -export function collectIdentifiersFromNode(node: t.Node): Set { - const ids = new Set() - - ;(function walk( - n: t.Node | null | undefined, - parent?: t.Node, - grandparent?: t.Node, - parentKey?: string, - ) { - if (!n) return - - if (t.isIdentifier(n)) { - // When we don't have parent info (node passed in isolation), treat as referenced. - if (!parent || t.isReferenced(n, parent, grandparent)) { - ids.add(n.name) - } - return - } - - if (t.isJSXIdentifier(n)) { - // Skip attribute names:
- if (parent && t.isJSXAttribute(parent) && parentKey === 'name') { - return - } - - // Skip member properties: should count Foo, not Bar - if ( - parent && - t.isJSXMemberExpression(parent) && - parentKey === 'property' - ) { - return - } - - // Intrinsic elements (lowercase) are not identifiers - const first = n.name[0] - if (first && first === first.toLowerCase()) { - return - } - - ids.add(n.name) - return - } - - for (const key of t.VISITOR_KEYS[n.type] || []) { - const child = (n as any)[key] - if (Array.isArray(child)) { - for (const c of child) { - if (c && typeof c.type === 'string') { - walk(c, n, parent, key) - } - } - } else if (child && typeof child.type === 'string') { - walk(child, n, parent, key) - } - } - })(node) - - return ids -} - -/** - * Build a map from binding name → declaration AST node for all - * locally-declared module-level bindings. Built once, O(1) lookup. - */ -export function buildDeclarationMap(ast: t.File): Map { - const map = new Map() - for (const stmt of ast.program.body) { - const decl = - t.isExportNamedDeclaration(stmt) && stmt.declaration - ? stmt.declaration - : stmt - - if (t.isVariableDeclaration(decl)) { - for (const declarator of decl.declarations) { - for (const name of collectIdentifiersFromPattern(declarator.id)) { - map.set(name, declarator) - } - } - } else if (t.isFunctionDeclaration(decl) && decl.id) { - map.set(decl.id.name, decl) - } else if (t.isClassDeclaration(decl) && decl.id) { - map.set(decl.id.name, decl) - } - } - return map -} - -/** - * Build a dependency graph: for each local binding, the set of other local - * bindings its declaration references. Built once via simple node walking. - */ -export function buildDependencyGraph( - declMap: Map, - localBindings: Set, -): Map> { - const graph = new Map>() - for (const [name, declNode] of declMap) { - if (!localBindings.has(name)) continue - const allIds = collectIdentifiersFromNode(declNode) - const deps = new Set() - for (const id of allIds) { - if (id !== name && localBindings.has(id)) deps.add(id) - } - graph.set(name, deps) - } - return graph -} - /** * Computes module-level bindings that are shared between split and non-split * route properties. These bindings need to be extracted into a shared virtual @@ -381,199 +294,11 @@ export function computeSharedBindings(opts: { // Remove shared bindings that transitively depend on `Route`. // The Route singleton must stay in the reference file; extracting a // binding that references it would duplicate Route in the shared module. - removeBindingsDependingOnRoute(shared, fullDepGraph) + removeBindingsTransitivelyDependingOn(shared, fullDepGraph, ['Route']) return shared } -/** - * If bindings from the same destructured declarator are referenced by - * different groups, mark all bindings from that declarator as shared. - */ -export function expandSharedDestructuredDeclarators( - ast: t.File, - refsByGroup: Map>, - shared: Set, -) { - for (const stmt of ast.program.body) { - const decl = - t.isExportNamedDeclaration(stmt) && stmt.declaration - ? stmt.declaration - : stmt - - if (!t.isVariableDeclaration(decl)) continue - - for (const declarator of decl.declarations) { - if (!t.isObjectPattern(declarator.id) && !t.isArrayPattern(declarator.id)) - continue - - const names = collectIdentifiersFromPattern(declarator.id) - - const usedGroups = new Set() - for (const name of names) { - const groups = refsByGroup.get(name) - if (!groups) continue - for (const g of groups) usedGroups.add(g) - } - - if (usedGroups.size >= 2) { - for (const name of names) { - shared.add(name) - } - } - } - } -} - -/** - * Collect locally-declared module-level binding names from a statement. - * Pure node inspection, no traversal. - */ -export function collectLocalBindingsFromStatement( - node: t.Statement | t.ModuleDeclaration, - bindings: Set, -) { - const decl = - t.isExportNamedDeclaration(node) && node.declaration - ? node.declaration - : node - - if (t.isVariableDeclaration(decl)) { - for (const declarator of decl.declarations) { - for (const name of collectIdentifiersFromPattern(declarator.id)) { - bindings.add(name) - } - } - } else if (t.isFunctionDeclaration(decl) && decl.id) { - bindings.add(decl.id.name) - } else if (t.isClassDeclaration(decl) && decl.id) { - bindings.add(decl.id.name) - } -} - -/** - * Collect direct module-level binding names referenced from a given AST node. - * Uses a simple recursive walk instead of babel.traverse. - */ -export function collectModuleLevelRefsFromNode( - node: t.Node, - localModuleLevelBindings: Set, -): Set { - const allIds = collectIdentifiersFromNode(node) - const refs = new Set() - for (const name of allIds) { - if (localModuleLevelBindings.has(name)) refs.add(name) - } - return refs -} - -/** - * Expand the shared set transitively using a prebuilt dependency graph. - * No AST traversals — pure graph BFS. - */ -export function expandTransitively( - shared: Set, - depGraph: Map>, -) { - const queue = [...shared] - const visited = new Set() - - while (queue.length > 0) { - const name = queue.pop()! - if (visited.has(name)) continue - visited.add(name) - - const deps = depGraph.get(name) - if (!deps) continue - - for (const dep of deps) { - if (!shared.has(dep)) { - shared.add(dep) - queue.push(dep) - } - } - } -} - -/** - * Remove any bindings from `shared` that transitively depend on `Route`. - * The Route singleton must remain in the reference file; if a shared binding - * references it (directly or transitively), extracting that binding would - * duplicate Route in the shared module. - * - * Uses `depGraph` which must include `Route` as a node so the dependency - * chain is visible. - */ -export function removeBindingsDependingOnRoute( - shared: Set, - depGraph: Map>, -) { - const reverseGraph = new Map>() - for (const [name, deps] of depGraph) { - for (const dep of deps) { - let parents = reverseGraph.get(dep) - if (!parents) { - parents = new Set() - reverseGraph.set(dep, parents) - } - parents.add(name) - } - } - - // Walk backwards from Route to find all bindings that can reach it. - const visited = new Set() - const queue = ['Route'] - while (queue.length > 0) { - const cur = queue.pop()! - if (visited.has(cur)) continue - visited.add(cur) - - const parents = reverseGraph.get(cur) - if (!parents) continue - for (const parent of parents) { - if (!visited.has(parent)) queue.push(parent) - } - } - - for (const name of [...shared]) { - if (visited.has(name)) { - shared.delete(name) - } - } -} - -/** - * If any binding from a destructured declaration is shared, - * ensure all bindings from that same declaration are also shared. - * Pure node inspection of program.body, no traversal. - */ -export function expandDestructuredDeclarations( - ast: t.File, - shared: Set, -) { - for (const stmt of ast.program.body) { - const decl = - t.isExportNamedDeclaration(stmt) && stmt.declaration - ? stmt.declaration - : stmt - - if (!t.isVariableDeclaration(decl)) continue - - for (const declarator of decl.declarations) { - if (!t.isObjectPattern(declarator.id) && !t.isArrayPattern(declarator.id)) - continue - - const names = collectIdentifiersFromPattern(declarator.id) - const hasShared = names.some((n) => shared.has(n)) - if (hasShared) { - for (const n of names) { - shared.add(n) - } - } - } - } -} - /** * Find which shared bindings are user-exported in the original source. * These need to be re-exported from the shared module. @@ -740,6 +465,21 @@ export function compileCodeSplitReferenceRoute( if (t.isObjectExpression(routeOptions)) { const insertionPath = path.getStatementParent() ?? path + opts.compilerPlugins?.forEach((plugin) => { + const pluginResult = plugin.onRouteOptions?.({ + programPath, + callExpressionPath: path, + insertionPath, + routeOptions, + createRouteFn, + opts: opts as CompileCodeSplitReferenceRouteOptions, + }) + + if (pluginResult?.modified) { + modified = true + } + }) + if (opts.deleteNodes && opts.deleteNodes.size > 0) { routeOptions.properties = routeOptions.properties.filter( (prop) => { @@ -1525,22 +1265,7 @@ export function compileCodeSplitVirtualRoute( }) deadCodeElimination(ast, refIdents) - - // Strip top-level expression statements that reference no locally-bound names. - // DCE only removes unused declarations; bare side-effect statements like - // `console.log(...)` survive even when the virtual file has no exports. - { - const locallyBound = new Set() - for (const stmt of ast.program.body) { - collectLocalBindingsFromStatement(stmt, locallyBound) - } - ast.program.body = ast.program.body.filter((stmt) => { - if (!t.isExpressionStatement(stmt)) return true - const refs = collectIdentifiersFromNode(stmt) - // Keep if it references at least one locally-bound identifier - return [...refs].some((name) => locallyBound.has(name)) - }) - } + stripUnreferencedTopLevelExpressionStatements(ast) // If the body is empty after DCE, strip directive prologues too. // A file containing only `'use client'` with no real code is useless. @@ -1595,49 +1320,8 @@ export function compileCodeSplitSharedRoute( keepBindings.delete('Route') expandTransitively(keepBindings, depGraph) - // Remove all statements except: - // - Import declarations (needed for deps; DCE will clean unused ones) - // - Declarations of bindings in keepBindings - ast.program.body = ast.program.body.filter((stmt) => { - // Always keep imports — DCE will remove unused ones - if (t.isImportDeclaration(stmt)) return true - - const decl = - t.isExportNamedDeclaration(stmt) && stmt.declaration - ? stmt.declaration - : stmt - - if (t.isVariableDeclaration(decl)) { - // Keep declarators where at least one binding is in keepBindings - decl.declarations = decl.declarations.filter((declarator) => { - const names = collectIdentifiersFromPattern(declarator.id) - return names.some((n) => keepBindings.has(n)) - }) - if (decl.declarations.length === 0) return false - - // Strip the `export` wrapper — shared module controls its own exports - if (t.isExportNamedDeclaration(stmt) && stmt.declaration) { - return true // keep for now, we'll convert below - } - return true - } else if (t.isFunctionDeclaration(decl) && decl.id) { - return keepBindings.has(decl.id.name) - } else if (t.isClassDeclaration(decl) && decl.id) { - return keepBindings.has(decl.id.name) - } - - // Remove everything else (expression statements, other exports, etc.) - return false - }) - - // Convert `export const/function/class` to plain declarations - // (we'll add our own export statement at the end) - ast.program.body = ast.program.body.map((stmt) => { - if (t.isExportNamedDeclaration(stmt) && stmt.declaration) { - return stmt.declaration - } - return stmt - }) + retainModuleLevelDeclarations(ast, keepBindings) + unwrapExportedDeclarations(ast) // Export all shared bindings (sorted for deterministic output) const exportNames = [...opts.sharedBindings].sort((a, b) => @@ -1837,50 +1521,6 @@ function getImportSpecifierAndPathFromLocalName( return { specifier, path } } -/** - * Recursively collects all identifier names from a destructuring pattern - * (ObjectPattern, ArrayPattern, AssignmentPattern, RestElement). - */ -function collectIdentifiersFromPattern( - node: t.LVal | t.Node | null | undefined, -): Array { - if (!node) { - return [] - } - - if (t.isIdentifier(node)) { - return [node.name] - } - - if (t.isAssignmentPattern(node)) { - return collectIdentifiersFromPattern(node.left) - } - - if (t.isRestElement(node)) { - return collectIdentifiersFromPattern(node.argument) - } - - if (t.isObjectPattern(node)) { - return node.properties.flatMap((prop) => { - if (t.isObjectProperty(prop)) { - return collectIdentifiersFromPattern(prop.value as t.LVal) - } - if (t.isRestElement(prop)) { - return collectIdentifiersFromPattern(prop.argument) - } - return [] - }) - } - - if (t.isArrayPattern(node)) { - return node.elements.flatMap((element) => - collectIdentifiersFromPattern(element), - ) - } - - return [] -} - // Reusable function to get literal value or resolve variable to literal function resolveIdentifier(path: any, node: any): t.Node | undefined { if (t.isIdentifier(node)) { diff --git a/packages/router-plugin/src/core/code-splitter/plugins.ts b/packages/router-plugin/src/core/code-splitter/plugins.ts index 4b2363e361..ebf1f4aa30 100644 --- a/packages/router-plugin/src/core/code-splitter/plugins.ts +++ b/packages/router-plugin/src/core/code-splitter/plugins.ts @@ -43,6 +43,9 @@ export type ReferenceRouteCompilerPluginResult = { export type ReferenceRouteCompilerPlugin = { name: string getStableRouteOptionKeys?: () => Array + onRouteOptions?: ( + ctx: ReferenceRouteCompilerPluginContext, + ) => void | ReferenceRouteCompilerPluginResult onAddHmr?: ( ctx: ReferenceRouteCompilerPluginContext, ) => void | ReferenceRouteCompilerPluginResult diff --git a/packages/router-plugin/src/core/config.ts b/packages/router-plugin/src/core/config.ts index f764bfe8bb..d1d36bbe37 100644 --- a/packages/router-plugin/src/core/config.ts +++ b/packages/router-plugin/src/core/config.ts @@ -9,6 +9,7 @@ import type { RouteIds, } from '@tanstack/router-core' import type { CodeSplitGroupings } from './constants' +import type { ReferenceRouteCompilerPlugin } from './code-splitter/plugins' export const splitGroupingsSchema = z .array( @@ -70,6 +71,12 @@ export type CodeSplittingOptions = { * @default true */ addHmr?: boolean + + /** + * Internal compiler plugins used by framework integrations. + * @internal + */ + compilerPlugins?: Array } export type HmrStyle = 'vite' | 'webpack' diff --git a/packages/router-plugin/src/core/router-code-splitter-plugin.ts b/packages/router-plugin/src/core/router-code-splitter-plugin.ts index 8f6324bae1..96d3d1251f 100644 --- a/packages/router-plugin/src/core/router-code-splitter-plugin.ts +++ b/packages/router-plugin/src/core/router-code-splitter-plugin.ts @@ -4,7 +4,7 @@ */ import { fileURLToPath, pathToFileURL } from 'node:url' -import { logDiff } from '@tanstack/router-utils' +import { decodeIdentifier, logDiff } from '@tanstack/router-utils' import { getConfig, splitGroupingsSchema } from './config' import { compileCodeSplitReferenceRoute, @@ -20,7 +20,6 @@ import { tsrShared, tsrSplit, } from './constants' -import { decodeIdentifier } from './code-splitter/path-ids' import { debug, normalizePath, routeFactoryCallCodeFilter } from './utils' import { createRouterPluginContext } from './router-plugin-context' import type { CodeSplitGroupings, SplitRouteIdentNodes } from './constants' @@ -177,11 +176,14 @@ export function createRouterCodeSplitterPlugin( hmrStyle, hmrRouteId: generatorNodeInfo.routeId, sharedBindings: sharedBindings.size > 0 ? sharedBindings : undefined, - compilerPlugins: getReferenceRouteCompilerPlugins({ - targetFramework: userConfig.target, - addHmr, - hmrStyle, - }), + compilerPlugins: [ + ...(getReferenceRouteCompilerPlugins({ + targetFramework: userConfig.target, + addHmr, + hmrStyle, + }) ?? []), + ...(userConfig.codeSplittingOptions?.compilerPlugins ?? []), + ], }) if (compiledReferenceRoute === null) { diff --git a/packages/router-plugin/src/index.ts b/packages/router-plugin/src/index.ts index a56e097d3a..e390c046a2 100644 --- a/packages/router-plugin/src/index.ts +++ b/packages/router-plugin/src/index.ts @@ -11,6 +11,11 @@ export type { HmrOptions, } from './core/config' export type { RouterPluginContext } from './core/router-plugin-context' +export { getObjectPropertyKeyName } from './core/utils' +export type { + ReferenceRouteCompilerPlugin, + ReferenceRouteCompilerPluginContext, +} from './core/code-splitter/plugins' export { tsrSplit, splitRouteIdentNodes, diff --git a/packages/router-plugin/tests/code-splitter.test.ts b/packages/router-plugin/tests/code-splitter.test.ts index 5a68f9453f..ae64e2778b 100644 --- a/packages/router-plugin/tests/code-splitter.test.ts +++ b/packages/router-plugin/tests/code-splitter.test.ts @@ -18,7 +18,7 @@ import { expandTransitively, removeBindingsDependingOnRoute, } from '../src/core/code-splitter/compilers' -import { createIdentifier } from '../src/core/code-splitter/path-ids' +import { createIdentifier } from '@tanstack/router-utils' import { defaultCodeSplitGroupings } from '../src/core/constants' import { frameworks } from './constants' import type { CodeSplitGroupings } from '../src/core/constants' diff --git a/packages/router-utils/src/compiler-helpers.ts b/packages/router-utils/src/compiler-helpers.ts new file mode 100644 index 0000000000..78d6cd9b86 --- /dev/null +++ b/packages/router-utils/src/compiler-helpers.ts @@ -0,0 +1,843 @@ +import * as t from '@babel/types' + +type IdentifierScopeFrame = { + kind: 'program' | 'function' | 'block' + bindings: Set +} +type IdentifierScopeStack = Array + +export type ModuleInfoBinding = + | { + type: 'import' + source: string + importedName: string + } + | { + type: 'var' + init: t.Expression | null + } + +export interface ExtractedModuleInfo { + bindings: Map + exports: Map + reExportAllSources: Array +} + +function getModuleExportName(node: t.Identifier | t.StringLiteral) { + return t.isIdentifier(node) ? node.name : node.value +} + +function addVariableDeclarationModuleInfo( + declaration: t.VariableDeclaration, + bindings: Map, + exportMap?: Map, +) { + for (const declarator of declaration.declarations) { + for (const name of collectIdentifiersFromPattern(declarator.id)) { + bindings.set(name, { + type: 'var', + init: declarator.init ?? null, + }) + exportMap?.set(name, name) + } + } +} + +function addDeclarationModuleInfo( + declaration: t.Declaration, + bindings: Map, + exportMap?: Map, +) { + if (t.isVariableDeclaration(declaration)) { + addVariableDeclarationModuleInfo(declaration, bindings, exportMap) + return + } + + if ( + (t.isFunctionDeclaration(declaration) || + t.isClassDeclaration(declaration)) && + declaration.id + ) { + bindings.set(declaration.id.name, { + type: 'var', + init: null, + }) + exportMap?.set(declaration.id.name, declaration.id.name) + } +} + +function hasIdentifierBinding(scopes: IdentifierScopeStack, name: string) { + for (let i = scopes.length - 1; i >= 0; i--) { + if (scopes[i]!.bindings.has(name)) { + return true + } + } + return false +} + +function currentIdentifierScope(scopes: IdentifierScopeStack) { + return scopes[scopes.length - 1]! +} + +function nearestFunctionIdentifierScope(scopes: IdentifierScopeStack) { + for (let i = scopes.length - 1; i >= 0; i--) { + const scope = scopes[i]! + if (scope.kind === 'function' || scope.kind === 'program') { + return scope + } + } + return currentIdentifierScope(scopes) +} + +function addIdentifierPatternBindings( + pattern: t.LVal | t.Node | null | undefined, + scope: IdentifierScopeFrame, +) { + for (const name of collectIdentifiersFromPattern(pattern)) { + scope.bindings.add(name) + } +} + +function addIdentifierDeclarationBindings( + declaration: t.Node, + scopes: IdentifierScopeStack, +) { + if (t.isVariableDeclaration(declaration)) { + const scope = + declaration.kind === 'var' + ? nearestFunctionIdentifierScope(scopes) + : currentIdentifierScope(scopes) + for (const declarator of declaration.declarations) { + addIdentifierPatternBindings(declarator.id, scope) + } + return + } + + if ( + (t.isFunctionDeclaration(declaration) || + t.isClassDeclaration(declaration) || + t.isTSTypeAliasDeclaration(declaration) || + t.isTSInterfaceDeclaration(declaration) || + t.isTSEnumDeclaration(declaration)) && + declaration.id + ) { + currentIdentifierScope(scopes).bindings.add(declaration.id.name) + } +} + +function addIdentifierImportBindings( + node: t.ImportDeclaration, + scope: IdentifierScopeFrame, +) { + for (const specifier of node.specifiers) { + scope.bindings.add(specifier.local.name) + } +} + +function createNestedIdentifierScope( + kind: IdentifierScopeFrame['kind'], + scopes: IdentifierScopeStack, +): IdentifierScopeStack { + return [...scopes, { kind, bindings: new Set() }] +} + +function addIdentifierBlockBindings( + body: Array, + scopes: IdentifierScopeStack, +) { + for (const statement of body) { + if (t.isImportDeclaration(statement)) { + addIdentifierImportBindings(statement, currentIdentifierScope(scopes)) + } else if (t.isExportNamedDeclaration(statement) && statement.declaration) { + addIdentifierDeclarationBindings(statement.declaration, scopes) + } else { + addIdentifierDeclarationBindings(statement, scopes) + } + } +} + +function walkIdentifierChildren( + current: t.Node, + parent: t.Node | undefined, + scopes: IdentifierScopeStack, + ids: Set, +) { + for (const key of t.VISITOR_KEYS[current.type] ?? []) { + const child = (current as any)[key] + if (Array.isArray(child)) { + for (const item of child) { + if (item && typeof item.type === 'string') { + walkIdentifierNode(item, current, parent, key, scopes, ids) + } + } + } else if (child && typeof child.type === 'string') { + walkIdentifierNode(child, current, parent, key, scopes, ids) + } + } +} + +function walkIdentifierNode( + current: t.Node | null | undefined, + parent: t.Node | undefined, + grandparent: t.Node | undefined, + parentKey: string | undefined, + scopes: IdentifierScopeStack, + ids: Set, +) { + if (!current) return + + if (t.isIdentifier(current)) { + if ( + (!parent || t.isReferenced(current, parent, grandparent)) && + !hasIdentifierBinding(scopes, current.name) + ) { + ids.add(current.name) + } + return + } + + if (t.isJSXIdentifier(current)) { + if (parent && t.isJSXAttribute(parent) && parentKey === 'name') { + return + } + + if (parent && t.isJSXMemberExpression(parent) && parentKey === 'property') { + return + } + + const first = current.name[0] + if (first && first === first.toLowerCase()) { + return + } + + if (!hasIdentifierBinding(scopes, current.name)) { + ids.add(current.name) + } + return + } + + if (t.isProgram(current)) { + const nestedScopes = createNestedIdentifierScope('program', scopes) + addIdentifierBlockBindings(current.body, nestedScopes) + for (const child of current.body) { + walkIdentifierNode(child, current, parent, 'body', nestedScopes, ids) + } + return + } + + if (t.isBlockStatement(current)) { + const nestedScopes = createNestedIdentifierScope('block', scopes) + addIdentifierBlockBindings(current.body, nestedScopes) + for (const child of current.body) { + walkIdentifierNode(child, current, parent, 'body', nestedScopes, ids) + } + return + } + + if ( + t.isFunctionDeclaration(current) || + t.isFunctionExpression(current) || + t.isArrowFunctionExpression(current) || + t.isObjectMethod(current) || + t.isClassMethod(current) || + t.isClassPrivateMethod(current) + ) { + if (t.isFunctionDeclaration(current) && current.id) { + currentIdentifierScope(scopes).bindings.add(current.id.name) + } + + const nestedScopes = createNestedIdentifierScope('function', scopes) + if ( + (t.isFunctionDeclaration(current) || t.isFunctionExpression(current)) && + current.id + ) { + currentIdentifierScope(nestedScopes).bindings.add(current.id.name) + } + for (const param of current.params) { + addIdentifierPatternBindings(param, currentIdentifierScope(nestedScopes)) + } + + walkIdentifierChildren(current, parent, nestedScopes, ids) + return + } + + if (t.isCatchClause(current)) { + const nestedScopes = createNestedIdentifierScope('block', scopes) + addIdentifierPatternBindings( + current.param, + currentIdentifierScope(nestedScopes), + ) + walkIdentifierNode( + current.param, + current, + parent, + 'param', + nestedScopes, + ids, + ) + walkIdentifierNode(current.body, current, parent, 'body', nestedScopes, ids) + return + } + + if (t.isImportDeclaration(current)) { + addIdentifierImportBindings(current, currentIdentifierScope(scopes)) + return + } + + if (t.isClassDeclaration(current) || t.isClassExpression(current)) { + if (t.isClassDeclaration(current) && current.id) { + currentIdentifierScope(scopes).bindings.add(current.id.name) + } + + const nestedScopes = current.id + ? createNestedIdentifierScope('block', scopes) + : scopes + if (current.id) { + currentIdentifierScope(nestedScopes).bindings.add(current.id.name) + } + + walkIdentifierChildren(current, parent, nestedScopes, ids) + return + } + + if (t.isVariableDeclaration(current)) { + addIdentifierDeclarationBindings(current, scopes) + } else if (t.isVariableDeclarator(current)) { + const scope = + parent && t.isVariableDeclaration(parent) && parent.kind === 'var' + ? nearestFunctionIdentifierScope(scopes) + : currentIdentifierScope(scopes) + addIdentifierPatternBindings(current.id, scope) + } else if ( + t.isTSTypeAliasDeclaration(current) || + t.isTSInterfaceDeclaration(current) || + t.isTSEnumDeclaration(current) + ) { + currentIdentifierScope(scopes).bindings.add(current.id.name) + } + + walkIdentifierChildren(current, parent, scopes, ids) +} + +/** + * Recursively walk an AST node and collect referenced identifier-like names. + * This avoids Babel path/scope allocation for module-level dependency scans. + */ +export function collectIdentifiersFromNode(node: t.Node): Set { + const ids = new Set() + walkIdentifierNode( + node, + undefined, + undefined, + undefined, + [{ kind: 'program', bindings: new Set() }], + ids, + ) + return ids +} + +export function collectIdentifiersFromPattern( + node: t.LVal | t.Node | null | undefined, +): Array { + if (!node) { + return [] + } + + if (t.isIdentifier(node)) { + return [node.name] + } + + if (t.isAssignmentPattern(node)) { + return collectIdentifiersFromPattern(node.left) + } + + if (t.isRestElement(node)) { + return collectIdentifiersFromPattern(node.argument) + } + + if (t.isObjectPattern(node)) { + return node.properties.flatMap((prop) => { + if (t.isObjectProperty(prop)) { + return collectIdentifiersFromPattern(prop.value as t.LVal) + } + if (t.isRestElement(prop)) { + return collectIdentifiersFromPattern(prop.argument) + } + return [] + }) + } + + if (t.isArrayPattern(node)) { + return node.elements.flatMap((element) => + collectIdentifiersFromPattern(element), + ) + } + + return [] +} + +export function collectLocalBindingsFromStatement( + node: t.Statement | t.ModuleDeclaration, + bindings: Set, +) { + const declaration = + t.isExportNamedDeclaration(node) && node.declaration + ? node.declaration + : t.isExportDefaultDeclaration(node) + ? node.declaration + : node + + if (t.isVariableDeclaration(declaration)) { + for (const declarator of declaration.declarations) { + for (const name of collectIdentifiersFromPattern(declarator.id)) { + bindings.add(name) + } + } + } else if (t.isFunctionDeclaration(declaration) && declaration.id) { + bindings.add(declaration.id.name) + } else if (t.isClassDeclaration(declaration) && declaration.id) { + bindings.add(declaration.id.name) + } +} + +export function extractModuleInfoFromAst(ast: t.File): ExtractedModuleInfo { + const bindings = new Map() + const exportMap = new Map() + const reExportAllSources: Array = [] + + for (const node of ast.program.body) { + if (t.isImportDeclaration(node)) { + const source = node.source.value + for (const specifier of node.specifiers) { + if (t.isImportSpecifier(specifier)) { + bindings.set(specifier.local.name, { + type: 'import', + source, + importedName: getModuleExportName(specifier.imported), + }) + } else if (t.isImportDefaultSpecifier(specifier)) { + bindings.set(specifier.local.name, { + type: 'import', + source, + importedName: 'default', + }) + } else if (t.isImportNamespaceSpecifier(specifier)) { + bindings.set(specifier.local.name, { + type: 'import', + source, + importedName: '*', + }) + } + } + continue + } + + if (t.isVariableDeclaration(node)) { + addVariableDeclarationModuleInfo(node, bindings) + continue + } + + if (t.isFunctionDeclaration(node) || t.isClassDeclaration(node)) { + addDeclarationModuleInfo(node, bindings) + continue + } + + if (t.isExportNamedDeclaration(node)) { + if (node.declaration) { + addDeclarationModuleInfo(node.declaration, bindings, exportMap) + } + + for (const specifier of node.specifiers) { + if (t.isExportNamespaceSpecifier(specifier)) { + const exported = getModuleExportName(specifier.exported) + exportMap.set(exported, exported) + if (node.source) { + bindings.set(exported, { + type: 'import', + source: node.source.value, + importedName: '*', + }) + } + } else if (t.isExportSpecifier(specifier)) { + const local = getModuleExportName(specifier.local) + const exported = getModuleExportName(specifier.exported) + exportMap.set(exported, local) + + if (node.source) { + bindings.set(local, { + type: 'import', + source: node.source.value, + importedName: local, + }) + } + } + } + continue + } + + if (t.isExportDefaultDeclaration(node)) { + const declaration = node.declaration + if (t.isIdentifier(declaration)) { + exportMap.set('default', declaration.name) + } else if ( + (t.isFunctionDeclaration(declaration) || + t.isClassDeclaration(declaration)) && + declaration.id + ) { + bindings.set(declaration.id.name, { + type: 'var', + init: null, + }) + exportMap.set('default', declaration.id.name) + } else { + const synth = '__default_export__' + bindings.set(synth, { + type: 'var', + init: t.isExpression(declaration) ? declaration : null, + }) + exportMap.set('default', synth) + } + continue + } + + if (t.isExportAllDeclaration(node)) { + reExportAllSources.push(node.source.value) + } + } + + return { + bindings, + exports: exportMap, + reExportAllSources, + } +} + +export function buildDeclarationMap(ast: t.File): Map { + const map = new Map() + + for (const statement of ast.program.body) { + const declaration = + t.isExportNamedDeclaration(statement) && statement.declaration + ? statement.declaration + : t.isExportDefaultDeclaration(statement) + ? statement.declaration + : statement + + if (t.isVariableDeclaration(declaration)) { + for (const declarator of declaration.declarations) { + for (const name of collectIdentifiersFromPattern(declarator.id)) { + map.set(name, declarator) + } + } + } else if (t.isFunctionDeclaration(declaration) && declaration.id) { + map.set(declaration.id.name, declaration) + } else if (t.isClassDeclaration(declaration) && declaration.id) { + map.set(declaration.id.name, declaration) + } + } + + return map +} + +export function buildDependencyGraph( + declarationMap: Map, + localBindings: Set, +): Map> { + const graph = new Map>() + + for (const [name, declarationNode] of declarationMap) { + if (!localBindings.has(name)) continue + + const dependencies = new Set() + for (const id of collectIdentifiersFromNode(declarationNode)) { + if (id !== name && localBindings.has(id)) { + dependencies.add(id) + } + } + graph.set(name, dependencies) + } + + return graph +} + +export function collectModuleLevelRefsFromNode( + node: t.Node, + localModuleLevelBindings: Set, +): Set { + const refs = new Set() + + for (const name of collectIdentifiersFromNode(node)) { + if (localModuleLevelBindings.has(name)) { + refs.add(name) + } + } + + return refs +} + +export function expandTransitively( + bindings: Set, + dependencyGraph: Map>, +) { + const queue = [...bindings] + const visited = new Set() + + while (queue.length > 0) { + const name = queue.pop()! + if (visited.has(name)) continue + visited.add(name) + + const dependencies = dependencyGraph.get(name) + if (!dependencies) continue + + for (const dependency of dependencies) { + if (!bindings.has(dependency)) { + bindings.add(dependency) + queue.push(dependency) + } + } + } +} + +export function expandSharedDestructuredDeclarators( + ast: t.File, + refsByGroup: Map>, + sharedBindings: Set, +) { + for (const statement of ast.program.body) { + const declaration = + t.isExportNamedDeclaration(statement) && statement.declaration + ? statement.declaration + : statement + + if (!t.isVariableDeclaration(declaration)) continue + + for (const declarator of declaration.declarations) { + if ( + !t.isObjectPattern(declarator.id) && + !t.isArrayPattern(declarator.id) + ) { + continue + } + + const names = collectIdentifiersFromPattern(declarator.id) + const usedGroups = new Set() + + for (const name of names) { + const groups = refsByGroup.get(name) + if (!groups) continue + for (const group of groups) { + usedGroups.add(group) + } + } + + if (usedGroups.size >= 2) { + for (const name of names) { + sharedBindings.add(name) + } + } + } + } +} + +export function expandDestructuredDeclarations( + ast: t.File, + bindings: Set, +) { + for (const statement of ast.program.body) { + const declaration = + t.isExportNamedDeclaration(statement) && statement.declaration + ? statement.declaration + : statement + + if (!t.isVariableDeclaration(declaration)) continue + + for (const declarator of declaration.declarations) { + if ( + !t.isObjectPattern(declarator.id) && + !t.isArrayPattern(declarator.id) + ) { + continue + } + + const names = collectIdentifiersFromPattern(declarator.id) + if (names.some((name) => bindings.has(name))) { + for (const name of names) { + bindings.add(name) + } + } + } + } +} + +export function removeBindingsTransitivelyDependingOn( + bindings: Set, + dependencyGraph: Map>, + roots: Iterable, +) { + const reverseGraph = new Map>() + + for (const [name, dependencies] of dependencyGraph) { + for (const dependency of dependencies) { + let parents = reverseGraph.get(dependency) + if (!parents) { + parents = new Set() + reverseGraph.set(dependency, parents) + } + parents.add(name) + } + } + + const visited = new Set() + const queue = [...roots] + + while (queue.length > 0) { + const current = queue.pop()! + if (visited.has(current)) continue + visited.add(current) + + const parents = reverseGraph.get(current) + if (!parents) continue + + for (const parent of parents) { + if (!visited.has(parent)) { + queue.push(parent) + } + } + } + + for (const name of [...bindings]) { + if (visited.has(name)) { + bindings.delete(name) + } + } +} + +export function removeModuleLevelBindings( + ast: t.File, + namesToRemove: Set, +) { + ast.program.body = ast.program.body.filter((statement) => { + const declaration = + t.isExportNamedDeclaration(statement) && statement.declaration + ? statement.declaration + : statement + + if (t.isVariableDeclaration(declaration)) { + declaration.declarations = declaration.declarations.filter( + (declarator) => + !collectIdentifiersFromPattern(declarator.id).some((name) => + namesToRemove.has(name), + ), + ) + return declaration.declarations.length > 0 + } + + if (t.isFunctionDeclaration(declaration) && declaration.id) { + return !namesToRemove.has(declaration.id.name) + } + + if (t.isClassDeclaration(declaration) && declaration.id) { + return !namesToRemove.has(declaration.id.name) + } + + if (t.isExportDefaultDeclaration(statement)) { + const defaultDeclaration = statement.declaration + if ( + (t.isFunctionDeclaration(defaultDeclaration) || + t.isClassDeclaration(defaultDeclaration)) && + defaultDeclaration.id + ) { + return !namesToRemove.has(defaultDeclaration.id.name) + } + } + + return true + }) +} + +export function retainModuleLevelDeclarations( + ast: t.File, + bindingsToKeep: Set, +) { + ast.program.body = ast.program.body.filter((statement) => { + if (t.isImportDeclaration(statement)) return true + + const declaration = + t.isExportNamedDeclaration(statement) && statement.declaration + ? statement.declaration + : statement + + if (t.isVariableDeclaration(declaration)) { + declaration.declarations = declaration.declarations.filter((declarator) => + collectIdentifiersFromPattern(declarator.id).some((name) => + bindingsToKeep.has(name), + ), + ) + return declaration.declarations.length > 0 + } + + if (t.isFunctionDeclaration(declaration) && declaration.id) { + return bindingsToKeep.has(declaration.id.name) + } + + if (t.isClassDeclaration(declaration) && declaration.id) { + return bindingsToKeep.has(declaration.id.name) + } + + return false + }) +} + +export function unwrapExportedDeclarations(ast: t.File) { + const body: Array = [] + + for (const statement of ast.program.body) { + if (t.isExportNamedDeclaration(statement)) { + if (statement.declaration) { + body.push(statement.declaration) + } + continue + } + + if (t.isExportDefaultDeclaration(statement)) { + const declaration = statement.declaration + if ( + (t.isFunctionDeclaration(declaration) || + t.isClassDeclaration(declaration)) && + declaration.id + ) { + body.push(declaration) + } + continue + } + + if (t.isExportAllDeclaration(statement)) { + continue + } + + body.push(statement) + } + + ast.program.body = body +} + +export function stripUnreferencedTopLevelExpressionStatements(ast: t.File) { + const locallyBound = new Set() + + for (const statement of ast.program.body) { + collectLocalBindingsFromStatement(statement, locallyBound) + } + + ast.program.body = ast.program.body.filter((statement) => { + if (!t.isExpressionStatement(statement)) return true + + for (const name of collectIdentifiersFromNode(statement)) { + if (locallyBound.has(name)) { + return true + } + } + + return false + }) +} diff --git a/packages/router-utils/src/index.ts b/packages/router-utils/src/index.ts index 3b072ae419..ce0de90824 100644 --- a/packages/router-utils/src/index.ts +++ b/packages/router-utils/src/index.ts @@ -9,3 +9,24 @@ export type { ParseAstOptions, ParseAstResult, GeneratorResult } from './ast' export { logDiff } from './logger' export { copyFilesPlugin } from './copy-files-plugin' + +export { createIdentifier, decodeIdentifier } from './path-ids' + +export { + buildDeclarationMap, + buildDependencyGraph, + collectIdentifiersFromNode, + collectIdentifiersFromPattern, + collectLocalBindingsFromStatement, + collectModuleLevelRefsFromNode, + expandDestructuredDeclarations, + expandSharedDestructuredDeclarators, + expandTransitively, + extractModuleInfoFromAst, + removeBindingsTransitivelyDependingOn, + removeModuleLevelBindings, + retainModuleLevelDeclarations, + stripUnreferencedTopLevelExpressionStatements, + unwrapExportedDeclarations, +} from './compiler-helpers' +export type { ExtractedModuleInfo, ModuleInfoBinding } from './compiler-helpers' diff --git a/packages/router-plugin/src/core/code-splitter/path-ids.ts b/packages/router-utils/src/path-ids.ts similarity index 100% rename from packages/router-plugin/src/core/code-splitter/path-ids.ts rename to packages/router-utils/src/path-ids.ts diff --git a/packages/router-utils/tests/compiler-helpers.test.ts b/packages/router-utils/tests/compiler-helpers.test.ts new file mode 100644 index 0000000000..00b75d67e5 --- /dev/null +++ b/packages/router-utils/tests/compiler-helpers.test.ts @@ -0,0 +1,249 @@ +import * as t from '@babel/types' +import { describe, expect, test } from 'vitest' +import { + buildDeclarationMap, + collectIdentifiersFromNode, + collectLocalBindingsFromStatement, + extractModuleInfoFromAst, +} from '../src/compiler-helpers' +import { parseAst } from '../src/ast' + +function getVariableInit(code: string) { + const ast = parseAst({ code, filename: 'test.tsx' }) + const declaration = ast.program.body.find((node) => + t.isVariableDeclaration(node), + ) as t.VariableDeclaration + return declaration.declarations[0]!.init! +} + +function collectSortedIdentifiers(node: t.Node) { + return [...collectIdentifiersFromNode(node)].sort() +} + +function collectSortedStatementBindings(code: string) { + const ast = parseAst({ code, filename: 'test.tsx' }) + const bindings = new Set() + for (const statement of ast.program.body) { + collectLocalBindingsFromStatement(statement, bindings) + } + return [...bindings].sort() +} + +function collectSortedDeclarationMapEntries(code: string) { + const ast = parseAst({ code, filename: 'test.tsx' }) + return [...buildDeclarationMap(ast)] + .map(([name, node]): [string, string] => [name, node.type]) + .sort((left, right) => (left[0] < right[0] ? -1 : 1)) +} + +function collectModuleInfoSnapshot(code: string) { + const ast = parseAst({ code, filename: 'test.tsx' }) + const info = extractModuleInfoFromAst(ast) + return { + bindings: [...info.bindings] + .map(([name, binding]) => [ + name, + binding.type === 'import' + ? `${binding.source}:${binding.importedName}` + : (binding.init?.type ?? null), + ]) + .sort((left, right) => (left[0]! < right[0]! ? -1 : 1)), + exports: [...info.exports].sort((left, right) => + left[0] < right[0] ? -1 : 1, + ), + reExportAllSources: info.reExportAllSources, + } +} + +describe('collectIdentifiersFromNode', () => { + test('collects free identifiers without reporting nested local bindings', () => { + const init = getVariableInit(` +const value = outer + (() => { + const local = dep + + function nested(param = fallback) { + const Inner = () => + const LocalExpr = class NamedLocal { + method() { + return NamedLocal + local + param + } + } + + class LocalComponent {} + + return local + param + imported + Inner + LocalExpr + } + + return nested() +})() +`) + + expect(collectSortedIdentifiers(init)).toMatchInlineSnapshot(` + [ + "dep", + "fallback", + "imported", + "outer", + ] + `) + }) + + test('respects nested variable, parameter, catch, and import shadowing', () => { + const ast = parseAst({ + code: ` +import { external as localImport } from 'pkg' + +const value = (localParam = defaultValue) => { + const localShadow = factory(localImport) + + try { + throw thrown + } catch (thrown) { + const factory = () => localShadow + localParam + thrown + return factory() + } +} +`, + filename: 'test.ts', + }) + + expect(collectSortedIdentifiers(ast.program)).toMatchInlineSnapshot(` + [ + "defaultValue", + "factory", + "thrown", + ] + `) + }) +}) + +describe('collectLocalBindingsFromStatement', () => { + test('collects ids from named default function and class declarations', () => { + expect({ + class: collectSortedStatementBindings( + `export default class DefaultComponent {}`, + ), + function: collectSortedStatementBindings( + `export default function DefaultRoute() {}`, + ), + anonymous: collectSortedStatementBindings( + `export default function () {}`, + ), + }).toMatchInlineSnapshot(` + { + "anonymous": [], + "class": [ + "DefaultComponent", + ], + "function": [ + "DefaultRoute", + ], + } + `) + }) +}) + +describe('buildDeclarationMap', () => { + test('maps named default function and class declarations', () => { + expect({ + class: collectSortedDeclarationMapEntries( + `export default class DefaultComponent {}`, + ), + function: collectSortedDeclarationMapEntries( + `export default function DefaultRoute() {}`, + ), + anonymous: collectSortedDeclarationMapEntries(`export default class {}`), + }).toMatchInlineSnapshot(` + { + "anonymous": [], + "class": [ + [ + "DefaultComponent", + "ClassDeclaration", + ], + ], + "function": [ + [ + "DefaultRoute", + "FunctionDeclaration", + ], + ], + } + `) + }) +}) + +describe('extractModuleInfoFromAst', () => { + test('extracts imports, local exports, default exports, and re-export sources', () => { + expect( + collectModuleInfoSnapshot(` + import defaultImport, { named as localNamed } from 'pkg' + import * as ns from 'pkg-ns' + const local = localNamed + export const exported = local + export function loader() {} + export default class DefaultRoute {} + export { remote as renamed } from './remote' + export * from './all' + `), + ).toMatchInlineSnapshot(` + { + "bindings": [ + [ + "DefaultRoute", + null, + ], + [ + "defaultImport", + "pkg:default", + ], + [ + "exported", + "Identifier", + ], + [ + "loader", + null, + ], + [ + "local", + "Identifier", + ], + [ + "localNamed", + "pkg:named", + ], + [ + "ns", + "pkg-ns:*", + ], + [ + "remote", + "./remote:remote", + ], + ], + "exports": [ + [ + "default", + "DefaultRoute", + ], + [ + "exported", + "exported", + ], + [ + "loader", + "loader", + ], + [ + "renamed", + "remote", + ], + ], + "reExportAllSources": [ + "./all", + ], + } + `) + }) +}) diff --git a/packages/router-utils/tests/stripTypeExports.test.ts b/packages/router-utils/tests/stripTypeExports.test.ts index d0c6af3ad7..32d25f1cbe 100644 --- a/packages/router-utils/tests/stripTypeExports.test.ts +++ b/packages/router-utils/tests/stripTypeExports.test.ts @@ -123,7 +123,7 @@ type TypeOnly = string; export { value, type TypeOnly };` const result = transform(code) expect(result).toContain('export { value }') - expect(result).not.toContain('TypeOnly') + expect(result).toContain('type TypeOnly = string') }) test('removes entire export if all specifiers are type-only', () => { @@ -133,8 +133,8 @@ export { type Foo, type Bar }; export const value = 1;` const result = transform(code) expect(result).not.toContain('export { type Foo') - expect(result).not.toContain('Foo') - expect(result).not.toContain('Bar') + expect(result).toContain('type Foo = string') + expect(result).toContain('type Bar = number') expect(result).toContain('export const value = 1') }) }) @@ -233,9 +233,11 @@ export { helper, type HelperType };` expect(result).not.toContain('./types') expect(result).not.toContain('HelperType') - // Should remove type declarations - expect(result).not.toContain('type LocalType') - expect(result).not.toContain('interface LocalInterface') + // Should preserve local type declarations + expect(result).toContain('type LocalType = string') + expect(result).toContain('interface LocalInterface') + + // Should remove exported type declarations expect(result).not.toContain('type ExportedType') expect(result).not.toContain('interface ExportedInterface') diff --git a/packages/solid-router/src/ClientOnly.tsx b/packages/solid-router/src/ClientOnly.tsx index 6ed10d267b..a7c4b71819 100644 --- a/packages/solid-router/src/ClientOnly.tsx +++ b/packages/solid-router/src/ClientOnly.tsx @@ -56,10 +56,15 @@ export function ClientOnly(props: ClientOnlyProps) { * ``` * @returns True if the JS has been hydrated already, false otherwise. */ +let globalHydrated = false + export function useHydrated(): Solid.Accessor { - const [hydrated, setHydrated] = Solid.createSignal(false) + const [hydrated, setHydrated] = Solid.createSignal(globalHydrated) + Solid.onMount(() => { + globalHydrated = true setHydrated(true) }) + return hydrated } diff --git a/packages/solid-start-client/package.json b/packages/solid-start-client/package.json index 7bcb2876cd..b01b0a28af 100644 --- a/packages/solid-start-client/package.json +++ b/packages/solid-start-client/package.json @@ -48,6 +48,12 @@ "default": "./dist/esm/index.js" } }, + "./hydration": { + "import": { + "types": "./dist/esm/hydration.d.ts", + "default": "./dist/esm/hydration.js" + } + }, "./package.json": "./package.json" }, "sideEffects": false, diff --git a/packages/solid-start-client/src/GenericHydrate.tsx b/packages/solid-start-client/src/GenericHydrate.tsx new file mode 100644 index 0000000000..e23c057f34 --- /dev/null +++ b/packages/solid-start-client/src/GenericHydrate.tsx @@ -0,0 +1,376 @@ +import * as Solid from 'solid-js' +import { Dynamic } from 'solid-js/web' + +import { useHydrated } from '@tanstack/solid-router' +import { isServer } from '@tanstack/router-core/isServer' +import { + hydrateIdAttribute, + hydrateWhenAttribute, +} from '@tanstack/start-client-core/hydration/constants' +import { + createResolvedGate, + getFallbackHtml, + getOrCreateGate, + onGateResolve, + releaseGate, + runHydrationStrategyCleanup, + saveFallbackHtml, + waitForHydrationPrefetchStrategy, +} from '@tanstack/start-client-core/hydration/runtime' +import { listenForDelegatedHydrationIntent } from '@tanstack/start-client-core/hydration' +import type { + HydrationRuntimeContext, + HydrationStrategy, + HydrationWhen, +} from '@tanstack/start-client-core/hydration' +import type { HydrationGateRecord } from '@tanstack/start-client-core/hydration/runtime' +import type { InternalHydrateProps } from './Hydrate' +import type { DynamicProps } from 'solid-js/web' + +type HydrationFallbackDynamicProps = DynamicProps<'div'> +type HydrationMarkerDynamicProps = DynamicProps<'div'> & { + [hydrateIdAttribute]: string + [hydrateWhenAttribute]: HydrationWhen + [key: `data-${string}`]: string | undefined +} +type PrefetchController = { + abortController: AbortController + hydrationRequested: boolean + hydrationListeners: Set<() => void> + hydrationResolvePending: boolean + started: boolean + promise?: Promise +} + +const hydrateIdSelector = `[${hydrateIdAttribute}]` +const dynamicType = 'dynamic' +const dynamicHydrateStrategy = { + _t: dynamicType, + _d: () => true, +} satisfies HydrationStrategy + +function shouldDeferHydration(strategy: HydrationStrategy) { + return strategy._d ? strategy._d() : strategy._t !== 'load' +} + +/* @__NO_SIDE_EFFECTS__ */ +function HydratedBoundary(props: { + id: string + onHydrated?: () => void + onStrategyHydrated?: (id: string) => void + children: Solid.JSX.Element +}) { + let didHydrate = false + + Solid.onMount(() => { + if (didHydrate) return + didHydrate = true + props.onHydrated?.() + props.onStrategyHydrated?.(props.id) + }) + + return props.children +} + +/* @__NO_SIDE_EFFECTS__ */ +export function GenericHydrate(props: InternalHydrateProps) { + const when = props.when + const dynamicHydrate = typeof when === 'function' + const initialHydrateStrategy: HydrationStrategy = dynamicHydrate + ? // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + (isServer ?? typeof window === 'undefined') + ? dynamicHydrateStrategy + : when() + : when + const markerHydrateType: HydrationWhen = dynamicHydrate + ? dynamicType + : initialHydrateStrategy._t! + const prefetchStrategy = () => props.prefetch + const hydrated = useHydrated() + const uniqueId = Solid.createUniqueId() + const id = props.h ? `${props.h}${uniqueId}` : uniqueId + const initialHydrateType = initialHydrateStrategy._t! + const shouldPreserveServerHTML = + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + (isServer ?? typeof window === 'undefined') || !hydrated() + const shouldDeferInitialHydration = + !hydrated() && shouldDeferHydration(initialHydrateStrategy) + const gate: HydrationGateRecord = + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + (isServer ?? typeof window === 'undefined') + ? createResolvedGate(id, initialHydrateType) + : getOrCreateGate(id, initialHydrateType) + const [ready, setReady] = Solid.createSignal( + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + (isServer ?? typeof window === 'undefined') || + (!shouldDeferInitialHydration && initialHydrateType !== 'never'), + ) + const [prefetchError, setPrefetchError] = Solid.createSignal() + const controller: PrefetchController = { + abortController: new AbortController(), + hydrationRequested: false, + hydrationListeners: new Set<() => void>(), + hydrationResolvePending: false, + started: false, + } + let didPrefetch = false + let markerElement: HTMLDivElement | undefined + + if ( + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + !(isServer ?? typeof window === 'undefined') && + initialHydrateType !== 'never' && + (!shouldDeferInitialHydration || + !shouldDeferHydration(initialHydrateStrategy)) + ) { + gate.resolve() + } + + const onHydrate = (listener: () => void) => { + if (controller.hydrationRequested) { + listener() + return () => {} + } + + controller.hydrationListeners.add(listener) + return () => { + controller.hydrationListeners.delete(listener) + } + } + + const requestHydration = () => { + if (!controller.hydrationRequested) { + controller.hydrationRequested = true + controller.hydrationListeners.forEach((listener) => listener()) + controller.hydrationListeners.clear() + } + + if (!controller.promise) { + resolveGate() + return + } + if (controller.hydrationResolvePending) return + controller.hydrationResolvePending = true + + controller.promise.then( + () => resolveGate(), + (error) => { + if (!controller.abortController.signal.aborted) { + setPrefetchError(() => error) + } + }, + ) + } + const resolveGate = gate.resolve + + Solid.onMount(() => { + const currentHydrateStrategy = initialHydrateStrategy + const currentPrefetchStrategy = prefetchStrategy() + const currentHydrateType = currentHydrateStrategy._t! + gate.when = currentHydrateType + for (const element of document.querySelectorAll( + hydrateIdSelector, + )) { + if (element.getAttribute(hydrateIdAttribute) === id) { + markerElement = element + saveFallbackHtml(id, element) + break + } + } + + if ( + currentHydrateType === 'never' && + !shouldPreserveServerHTML && + markerElement + ) { + markerElement.replaceChildren() + } + + if (currentPrefetchStrategy && !controller.started) { + controller.started = true + const preload = () => props.p?.() ?? Promise.resolve() + + if (typeof currentPrefetchStrategy === 'function') { + const promise = Promise.resolve() + .then(() => + currentPrefetchStrategy({ + element: markerElement ?? null, + signal: controller.abortController.signal, + preload, + waitFor: (strategy) => + waitForHydrationPrefetchStrategy(strategy, { + element: markerElement ?? null, + signal: controller.abortController.signal, + onHydrate, + }), + }), + ) + .then(() => undefined) + + controller.promise = promise + promise.catch((error) => { + if (!controller.abortController.signal.aborted) { + setPrefetchError(() => error) + } + }) + } else if (props.p) { + const currentStrategy = currentPrefetchStrategy + const prefetch = () => { + if (didPrefetch) return + didPrefetch = true + void preload() + } + const cleanupPrefetch = runHydrationStrategyCleanup( + currentStrategy._s?.({ + element: markerElement ?? null, + prefetch, + }), + ) + if (cleanupPrefetch) Solid.onCleanup(cleanupPrefetch) + } + } + + if ( + currentHydrateType !== 'never' && + (!shouldDeferInitialHydration || + !shouldDeferHydration(currentHydrateStrategy)) + ) { + gate.resolve() + setReady(true) + } + + const cleanups: Array<() => void> = [] + let removeResolveListener = () => {} + let disposed = false + + const resolveBoundary = () => { + setReady(true) + } + + const cleanup = () => { + if (disposed) return + disposed = true + if (gate.resolve === requestHydration) { + gate.resolve = resolveGate + } + removeResolveListener() + cleanups.forEach((fn) => fn()) + } + + const addCleanup = (fn: void | (() => void)) => { + if (!fn) return + if (disposed || gate.resolved) { + fn() + return + } + cleanups.push(fn) + } + + Solid.onCleanup(() => { + controller.abortController.abort() + controller.hydrationListeners.clear() + cleanup() + releaseGate(gate) + }) + + removeResolveListener = onGateResolve(gate, () => { + cleanup() + resolveBoundary() + }) + + if ( + gate.resolved || + !shouldDeferInitialHydration || + currentHydrateType === 'never' + ) { + if (gate.resolved) resolveBoundary() + return + } + + gate.resolve = requestHydration + const context: HydrationRuntimeContext = { + element: markerElement ?? null, + gate, + } + addCleanup( + runHydrationStrategyCleanup(currentHydrateStrategy._s?.(context)), + ) + + if (currentHydrateStrategy._t !== 'interaction') { + addCleanup( + runHydrationStrategyCleanup( + markerElement + ? listenForDelegatedHydrationIntent(markerElement, context) + : undefined, + ), + ) + } + }) + + Solid.createRenderEffect(() => { + if ( + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + (isServer ?? typeof window === 'undefined') || + gate.resolved || + initialHydrateStrategy._t === 'never' || + shouldDeferHydration(initialHydrateStrategy) + ) { + return + } + + gate.resolve() + }) + + const markerAttributes = + markerHydrateType === dynamicType + ? undefined + : initialHydrateStrategy._a?.() + const markerProps: HydrationMarkerDynamicProps = { + component: 'div', + [hydrateIdAttribute]: id, + [hydrateWhenAttribute]: markerHydrateType, + ...markerAttributes, + } + const fallback = () => { + if (!shouldPreserveServerHTML) return props.fallback ?? null + + const html = getFallbackHtml(id) + if (!html) return null + + const fallbackProps: HydrationFallbackDynamicProps = { + component: 'div', + style: { display: 'contents' }, + innerHTML: html, + } + + return + } + + return ( + + {(() => { + const error = prefetchError() + if (error) throw error + return null + })()} + {initialHydrateType === 'never' && !shouldPreserveServerHTML ? ( + (props.fallback ?? null) + ) : ( + + + { + markerElement?.removeAttribute(hydrateWhenAttribute) + initialHydrateStrategy._o?.(id) + }} + > + {props.children} + + + + )} + + ) +} diff --git a/packages/solid-start-client/src/Hydrate.tsx b/packages/solid-start-client/src/Hydrate.tsx new file mode 100644 index 0000000000..1b52e643f2 --- /dev/null +++ b/packages/solid-start-client/src/Hydrate.tsx @@ -0,0 +1,75 @@ +import { GenericHydrate } from './GenericHydrate' +import type { + HydrationStrategy as CoreHydrationStrategy, + HydrationPrefetchFunction, + HydrationPrefetchStrategy, + HydrationWhen, +} from '@tanstack/start-client-core/hydration' +import type * as Solid from 'solid-js' + +export type { + HydrationInteractionEvent, + HydrationInteractionEvents, + HydrationPrefetchContext, + HydrationPrefetchFunction, + HydrationPrefetchStrategy, + HydrationPrefetchWaitReason, + HydrationWhen, +} from '@tanstack/start-client-core/hydration' + +export type SolidHydrationStrategy< + TWhen extends HydrationWhen = HydrationWhen, + TCanPrefetch extends boolean = boolean, +> = CoreHydrationStrategy & { + _h: (props: HydrateProps) => Solid.JSX.Element +} + +export type HydrationStrategy< + TWhen extends HydrationWhen = HydrationWhen, + TCanPrefetch extends boolean = boolean, +> = SolidHydrationStrategy + +export type HydrateWhen = + | SolidHydrationStrategy + | (() => SolidHydrationStrategy) + +type HydrateCommonOptions = { + when: HydrateWhen + fallback?: Solid.JSX.Element + onHydrated?: () => void +} + +export type HydrateOptions = + | (HydrateCommonOptions & { + prefetch?: never + split?: boolean + }) + | (HydrateCommonOptions & { + prefetch: HydrationPrefetchStrategy + split?: true + }) + | (HydrateCommonOptions & { + prefetch: HydrationPrefetchFunction + split?: boolean + }) + +export type HydrateProps = HydrateOptions & { + children: Solid.JSX.Element +} + +export type InternalHydrateProps = HydrateProps & { + h?: string + p?: () => Promise +} + +/* @__NO_SIDE_EFFECTS__ */ +export function Hydrate(props: HydrateProps) { + if ( + typeof props.when === 'function' || + typeof props.prefetch === 'function' + ) { + return + } + + return props.when._h(props) +} diff --git a/packages/solid-start-client/src/hydration.ts b/packages/solid-start-client/src/hydration.ts new file mode 100644 index 0000000000..bd875dcb0a --- /dev/null +++ b/packages/solid-start-client/src/hydration.ts @@ -0,0 +1,20 @@ +export { condition, interaction, media } from './hydration/generic' +export { idle } from './hydration/idle' +export { load } from './hydration/load' +export { never } from './hydration/never' +export { visible } from './hydration/visible' +export type { + HydrationCondition, + HydrationInteractionEvent, + HydrationInteractionEvents, + IdleHydrationOptions, + HydrationPrefetchContext, + HydrationPrefetchFunction, + HydrationPrefetchWhen, + HydrationPrefetchStrategy, + HydrationPrefetchWaitReason, + HydrationStrategyTypes, + HydrationWhen, + VisibleHydrationOptions, +} from '@tanstack/start-client-core/hydration' +export type { HydrationStrategy, SolidHydrationStrategy } from './Hydrate' diff --git a/packages/solid-start-client/src/hydration/generic.ts b/packages/solid-start-client/src/hydration/generic.ts new file mode 100644 index 0000000000..bfc1e8db9f --- /dev/null +++ b/packages/solid-start-client/src/hydration/generic.ts @@ -0,0 +1,41 @@ +import { + condition as coreCondition, + interaction as coreInteraction, + media as coreMedia, + withHydrationRenderer, +} from '@tanstack/start-client-core/hydration' +import { GenericHydrate } from '../GenericHydrate' +import type { + HydrationCondition, + HydrationInteractionEvents, + HydrationPrefetchStrategy, +} from '@tanstack/start-client-core/hydration' +import type { SolidHydrationStrategy } from '../Hydrate' + +/* @__NO_SIDE_EFFECTS__ */ +export function media( + query: string, +): SolidHydrationStrategy<'media', true> & HydrationPrefetchStrategy<'media'> { + return /* @__PURE__ */ withHydrationRenderer(coreMedia(query), GenericHydrate) +} + +/* @__NO_SIDE_EFFECTS__ */ +export function condition( + condition: HydrationCondition, +): SolidHydrationStrategy<'condition', false> { + return /* @__PURE__ */ withHydrationRenderer( + coreCondition(condition), + GenericHydrate, + ) +} + +/* @__NO_SIDE_EFFECTS__ */ +export function interaction(options?: { + events?: HydrationInteractionEvents +}): SolidHydrationStrategy<'interaction', true> & + HydrationPrefetchStrategy<'interaction'> { + return /* @__PURE__ */ withHydrationRenderer( + coreInteraction(options), + GenericHydrate, + ) +} diff --git a/packages/solid-start-client/src/hydration/idle.ts b/packages/solid-start-client/src/hydration/idle.ts new file mode 100644 index 0000000000..89282b0a95 --- /dev/null +++ b/packages/solid-start-client/src/hydration/idle.ts @@ -0,0 +1,20 @@ +import { + idle as coreIdle, + withHydrationRenderer, +} from '@tanstack/start-client-core/hydration' +import { GenericHydrate } from '../GenericHydrate' +import type { + HydrationPrefetchStrategy, + IdleHydrationOptions, +} from '@tanstack/start-client-core/hydration' +import type { SolidHydrationStrategy } from '../Hydrate' + +/* @__NO_SIDE_EFFECTS__ */ +export function idle( + options: IdleHydrationOptions = {}, +): SolidHydrationStrategy<'idle', true> & HydrationPrefetchStrategy<'idle'> { + return /* @__PURE__ */ withHydrationRenderer( + coreIdle(options), + GenericHydrate, + ) +} diff --git a/packages/solid-start-client/src/hydration/load.tsx b/packages/solid-start-client/src/hydration/load.tsx new file mode 100644 index 0000000000..a2836231e8 --- /dev/null +++ b/packages/solid-start-client/src/hydration/load.tsx @@ -0,0 +1,13 @@ +import { + load as coreLoad, + withHydrationRenderer, +} from '@tanstack/start-client-core/hydration' +import { GenericHydrate } from '../GenericHydrate' +import type { HydrationPrefetchStrategy } from '@tanstack/start-client-core/hydration' +import type { SolidHydrationStrategy } from '../Hydrate' + +/* @__NO_SIDE_EFFECTS__ */ +export function load(): SolidHydrationStrategy<'load', true> & + HydrationPrefetchStrategy<'load'> { + return /* @__PURE__ */ withHydrationRenderer(coreLoad(), GenericHydrate) +} diff --git a/packages/solid-start-client/src/hydration/never.ts b/packages/solid-start-client/src/hydration/never.ts new file mode 100644 index 0000000000..36513b95d4 --- /dev/null +++ b/packages/solid-start-client/src/hydration/never.ts @@ -0,0 +1,11 @@ +import { + never as coreNever, + withHydrationRenderer, +} from '@tanstack/start-client-core/hydration' +import { GenericHydrate } from '../GenericHydrate' +import type { SolidHydrationStrategy } from '../Hydrate' + +/* @__NO_SIDE_EFFECTS__ */ +export function never(): SolidHydrationStrategy<'never', false> { + return /* @__PURE__ */ withHydrationRenderer(coreNever(), GenericHydrate) +} diff --git a/packages/solid-start-client/src/hydration/visible.tsx b/packages/solid-start-client/src/hydration/visible.tsx new file mode 100644 index 0000000000..c747c236ec --- /dev/null +++ b/packages/solid-start-client/src/hydration/visible.tsx @@ -0,0 +1,21 @@ +import { + visible as coreVisible, + withHydrationRenderer, +} from '@tanstack/start-client-core/hydration' +import { GenericHydrate } from '../GenericHydrate' +import type { + HydrationPrefetchStrategy, + VisibleHydrationOptions, +} from '@tanstack/start-client-core/hydration' +import type { SolidHydrationStrategy } from '../Hydrate' + +/* @__NO_SIDE_EFFECTS__ */ +export function visible( + options?: VisibleHydrationOptions, +): SolidHydrationStrategy<'visible', true> & + HydrationPrefetchStrategy<'visible'> { + return /* @__PURE__ */ withHydrationRenderer( + coreVisible(options), + GenericHydrate, + ) +} diff --git a/packages/solid-start-client/src/index.tsx b/packages/solid-start-client/src/index.tsx index aa73990a57..2128ebcb01 100644 --- a/packages/solid-start-client/src/index.tsx +++ b/packages/solid-start-client/src/index.tsx @@ -1,2 +1,16 @@ export { StartClient } from './StartClient' export { hydrateStart } from './hydrateStart' +export { Hydrate } from './Hydrate' +export type { + HydrateOptions, + HydrateProps, + HydrateWhen, + HydrationInteractionEvent, + HydrationInteractionEvents, + HydrationPrefetchContext, + HydrationPrefetchFunction, + HydrationPrefetchStrategy, + HydrationPrefetchWaitReason, + HydrationStrategy, + HydrationWhen, +} from './Hydrate' diff --git a/packages/solid-start-client/src/tests/Hydrate.test-d.tsx b/packages/solid-start-client/src/tests/Hydrate.test-d.tsx new file mode 100644 index 0000000000..e5e13334f3 --- /dev/null +++ b/packages/solid-start-client/src/tests/Hydrate.test-d.tsx @@ -0,0 +1,147 @@ +import { expectTypeOf, test } from 'vitest' +import { visible } from '../hydration' +import { Hydrate } from '../Hydrate' +import type { + HydrateOptions, + HydrateProps, + HydrationPrefetchFunction, + HydrationPrefetchStrategy, + HydrationStrategy, +} from '../Hydrate' +import type { HydrationStrategy as CoreHydrationStrategy } from '@tanstack/start-client-core/hydration' +import type { JSX } from 'solid-js' + +type CommonHydrateProps = { + fallback?: JSX.Element + onHydrated?: () => void + children: JSX.Element +} + +type SplitHydrateProps = CommonHydrateProps & { + when: HydrationStrategy | (() => HydrationStrategy) + prefetch?: never + split?: boolean +} + +type PrefetchHydrateProps = CommonHydrateProps & { + when: HydrationStrategy | (() => HydrationStrategy) + prefetch: HydrationPrefetchStrategy + split?: true +} + +type FunctionPrefetchHydrateProps = CommonHydrateProps & { + when: HydrationStrategy | (() => HydrationStrategy) + prefetch: HydrationPrefetchFunction + split?: boolean +} + +test('Hydrate component accepts the public HydrateProps type', () => { + expectTypeOf(Hydrate).toBeFunction() + expectTypeOf(Hydrate).parameter(0).branded.toEqualTypeOf() +}) + +test('HydrateOptions supports reusable spread props', () => { + const belowFoldProps = { + when: () => visible({ rootMargin: '800px' }), + } satisfies HydrateOptions + + expectTypeOf(belowFoldProps).toMatchTypeOf() + + const withFunctionPrefetch = { + when: visible(), + split: false, + prefetch: (ctx) => { + expectTypeOf(ctx.element).toEqualTypeOf() + expectTypeOf(ctx.signal).toEqualTypeOf() + expectTypeOf(ctx.preload).returns.toEqualTypeOf>() + expectTypeOf(ctx.waitFor).returns.toEqualTypeOf< + Promise<'prefetch' | 'hydrate' | 'abort'> + >() + }, + } satisfies HydrateOptions + + expectTypeOf(withFunctionPrefetch).toMatchTypeOf() +}) + +test('Hydrate props are exact for strategy and prefetch forms', () => { + expectTypeOf< + Extract + >().branded.toEqualTypeOf() + expectTypeOf< + Extract + >().branded.toEqualTypeOf() + expectTypeOf< + Extract + >().branded.toEqualTypeOf() +}) + +test('Hydrate requires a strategy', () => { + expectTypeOf<{ + when: HydrationStrategy + children: JSX.Element + }>().toMatchTypeOf() + + expectTypeOf<{ + when: () => HydrationStrategy + children: JSX.Element + }>().toMatchTypeOf() + + expectTypeOf<{ + children: JSX.Element + }>().not.toMatchTypeOf() + + expectTypeOf<{ + when: () => true + children: JSX.Element + }>().not.toMatchTypeOf() + + expectTypeOf<{ + when: false + children: JSX.Element + }>().not.toMatchTypeOf() +}) + +test('Hydrate requires a framework-renderable strategy', () => { + expectTypeOf().not.toMatchTypeOf() + expectTypeOf>().toMatchTypeOf() + + expectTypeOf<{ + when: CoreHydrationStrategy + children: JSX.Element + }>().not.toMatchTypeOf() +}) + +test('Hydrate enforces prefetch only with split boundaries', () => { + expectTypeOf<{ + when: HydrationStrategy + prefetch: HydrationPrefetchStrategy + children: JSX.Element + }>().toMatchTypeOf() + + expectTypeOf<{ + when: HydrationStrategy + prefetch: HydrationPrefetchStrategy + split: true + children: JSX.Element + }>().toMatchTypeOf() + + expectTypeOf<{ + when: HydrationStrategy + prefetch: HydrationPrefetchStrategy + split: false + children: JSX.Element + }>().not.toMatchTypeOf() + + expectTypeOf<{ + when: HydrationStrategy + prefetch: HydrationPrefetchFunction + split: false + children: JSX.Element + }>().toMatchTypeOf() + + expectTypeOf<{ + when: HydrationStrategy + prefetch: HydrationPrefetchFunction + children: JSX.Element + }>().toMatchTypeOf() +}) diff --git a/packages/solid-start-client/vite.config.ts b/packages/solid-start-client/vite.config.ts index be71bab518..dbfb60ea03 100644 --- a/packages/solid-start-client/vite.config.ts +++ b/packages/solid-start-client/vite.config.ts @@ -20,7 +20,7 @@ export default mergeConfig( tanstackViteConfig({ tsconfigPath: './tsconfig.build.json', srcDir: './src', - entry: './src/index.tsx', + entry: ['./src/index.tsx', './src/Hydrate.tsx', './src/hydration.ts'], cjs: false, }), ) diff --git a/packages/solid-start/package.json b/packages/solid-start/package.json index de2ecd1c22..e902fe7abb 100644 --- a/packages/solid-start/package.json +++ b/packages/solid-start/package.json @@ -44,6 +44,12 @@ "default": "./dist/esm/client.js" } }, + "./hydration": { + "import": { + "types": "./dist/esm/hydration.d.ts", + "default": "./dist/esm/hydration.js" + } + }, "./client-rpc": { "import": { "types": "./dist/esm/client-rpc.d.ts", diff --git a/packages/solid-start/src/hydration.ts b/packages/solid-start/src/hydration.ts new file mode 100644 index 0000000000..fc660e9dc5 --- /dev/null +++ b/packages/solid-start/src/hydration.ts @@ -0,0 +1,18 @@ +export { + condition, + idle, + interaction, + load, + media, + never, + visible, +} from '@tanstack/solid-start-client/hydration' +export type { + HydrationCondition, + HydrationInteractionEvent, + HydrationInteractionEvents, + HydrationPrefetchStrategy, + HydrationStrategy, + HydrationWhen, + VisibleHydrationOptions, +} from '@tanstack/solid-start-client/hydration' diff --git a/packages/solid-start/src/index.ts b/packages/solid-start/src/index.ts index 8b51b6c783..0cdac87c81 100644 --- a/packages/solid-start/src/index.ts +++ b/packages/solid-start/src/index.ts @@ -1,2 +1,12 @@ export { useServerFn } from './useServerFn' export * from '@tanstack/start-client-core' +export { Hydrate } from '@tanstack/solid-start-client' +export type { + HydrateOptions, + HydrateProps, + HydrationInteractionEvent, + HydrationInteractionEvents, + HydrationPrefetchStrategy, + HydrationStrategy, + HydrationWhen, +} from '@tanstack/solid-start-client' diff --git a/packages/solid-start/vite.config.ts b/packages/solid-start/vite.config.ts index 262208de09..2c1a42d0e4 100644 --- a/packages/solid-start/vite.config.ts +++ b/packages/solid-start/vite.config.ts @@ -27,6 +27,7 @@ export default mergeConfig( entry: [ './src/index.ts', './src/client.tsx', + './src/hydration.ts', './src/client-rpc.ts', './src/ssr-rpc.ts', './src/server-rpc.ts', diff --git a/packages/start-client-core/package.json b/packages/start-client-core/package.json index 811c106ee2..ca7e9bd076 100644 --- a/packages/start-client-core/package.json +++ b/packages/start-client-core/package.json @@ -60,16 +60,37 @@ "default": "./dist/esm/client-rpc/index.js" } }, + "./hydration": { + "import": { + "types": "./dist/esm/hydration.d.ts", + "default": "./dist/esm/hydration.js" + } + }, + "./hydration/constants": { + "import": { + "types": "./dist/esm/hydration/constants.d.ts", + "default": "./dist/esm/hydration/constants.js" + } + }, + "./hydration/runtime": { + "import": { + "types": "./dist/esm/hydration/runtime.d.ts", + "default": "./dist/esm/hydration/runtime.js" + } + }, "./package.json": "./package.json" }, "imports": { "#tanstack-start-entry": { + "types": "./src/start-entry.d.ts", "default": "./dist/esm/fake-entries/start.js" }, "#tanstack-router-entry": { + "types": "./src/start-entry.d.ts", "default": "./dist/esm/fake-entries/router.js" }, "#tanstack-start-plugin-adapters": { + "types": "./src/start-entry.d.ts", "default": "./dist/esm/fake-entries/plugin-adapters.js" } }, diff --git a/packages/start-client-core/src/client/hydrateStart.ts b/packages/start-client-core/src/client/hydrateStart.ts index 206b70505c..83b9c468af 100644 --- a/packages/start-client-core/src/client/hydrateStart.ts +++ b/packages/start-client-core/src/client/hydrateStart.ts @@ -1,5 +1,4 @@ import { hydrate } from '@tanstack/router-core/ssr/client' - import { startInstance } from '#tanstack-start-entry' import { hasPluginAdapters, @@ -10,7 +9,19 @@ import { ServerFunctionSerializationAdapter } from './ServerFunctionSerializatio import type { AnyRouter, AnySerializationAdapter } from '@tanstack/router-core' import type { AnyStartInstanceOptions } from '../createStart' -export async function hydrateStart(): Promise { +type HotContext = { + data?: Record + dispose?: (cb: (data: Record) => void) => void +} + +declare global { + interface ImportMeta { + hot?: HotContext + webpackHot?: HotContext + } +} + +async function hydrateStart(): Promise { const router = await getRouter() let serializationAdapters: Array @@ -47,3 +58,38 @@ export async function hydrateStart(): Promise { return router } + +function hydrateStartWithHmr(): Promise { + const hot = import.meta.hot ?? import.meta.webpackHot + + if (!hot) { + return hydrateStart() + } + + const key = 'tss-hydrate-start-promise' + const hotData = (hot.data ??= {}) + let hydrationPromise = hotData[key] as Promise | undefined + + if (!hydrationPromise) { + hydrationPromise = hydrateStart().catch((error) => { + if (hotData[key] === hydrationPromise) { + hotData[key] = undefined + } + + throw error + }) + + hotData[key] = hydrationPromise + } + + hot.dispose?.((data) => { + data[key] = hotData[key] + }) + + return hydrationPromise +} + +const exportedHydrateStart = + process.env.NODE_ENV !== 'production' ? hydrateStartWithHmr : hydrateStart + +export { exportedHydrateStart as hydrateStart } diff --git a/packages/start-client-core/src/hydration.ts b/packages/start-client-core/src/hydration.ts new file mode 100644 index 0000000000..934b73116f --- /dev/null +++ b/packages/start-client-core/src/hydration.ts @@ -0,0 +1,50 @@ +import { hydrateIdAttribute } from './hydration/constants' + +export { condition } from './hydration/condition' +export type { HydrationCondition } from './hydration/condition' +export { + hydrateIdAttribute, + hydrateInteractionEventsAttribute, + hydrateWhenAttribute, +} from './hydration/constants' +export const hydrateIdSelector = `[${hydrateIdAttribute}]` +export { idle } from './hydration/idle' +export type { IdleHydrationOptions } from './hydration/idle' +export { interaction } from './hydration/interaction' +export { load } from './hydration/load' +export { media } from './hydration/media' +export { never } from './hydration/never' +export { + clearResolvedGateIdsInMarker, + createResolvedGate, + getFallbackHtml, + getMarkerGate, + getOrCreateGate, + onGateResolve, + releaseGate, + resolveHydrationMarker, + runHydrationStrategyCleanup, + saveFallbackHtml, + waitForHydrationPrefetchStrategy, +} from './hydration/runtime' +export { withHydrationRenderer } from './hydration/renderer' +export { visible } from './hydration/visible' +export { listenForDelegatedHydrationIntent } from './hydration/interaction' +export type { VisibleHydrationOptions } from './hydration/visible' +export type { HydrationGateRecord } from './hydration/runtime' +export type { HydrationStrategyWithRenderer } from './hydration/renderer' +export type { + HydrationInteractionEvent, + HydrationInteractionEvents, + HydrationMarkerAttributes, + HydrationPrefetchContext, + HydrationPrefetchFunction, + HydrationPrefetchWhen, + HydrationPrefetchStrategy, + HydrationPrefetchWaitReason, + HydrationRuntimeContext, + HydrationRuntimeGate, + HydrationStrategy, + HydrationStrategyTypes, + HydrationWhen, +} from './hydration/types' diff --git a/packages/start-client-core/src/hydration/condition.ts b/packages/start-client-core/src/hydration/condition.ts new file mode 100644 index 0000000000..6e640cc3ae --- /dev/null +++ b/packages/start-client-core/src/hydration/condition.ts @@ -0,0 +1,20 @@ +import type { HydrationStrategy } from './types' + +const conditionType = 'condition' + +export type HydrationCondition = boolean | (() => boolean) + +/* @__NO_SIDE_EFFECTS__ */ +export function condition( + condition: HydrationCondition, +): HydrationStrategy { + return { + _t: conditionType, + _d: () => !(typeof condition === 'function' ? condition() : condition), + _s: ({ gate }) => { + if (typeof condition === 'function' ? condition() : condition) { + gate!.resolve() + } + }, + } +} diff --git a/packages/start-client-core/src/hydration/constants.ts b/packages/start-client-core/src/hydration/constants.ts new file mode 100644 index 0000000000..4b7a29313d --- /dev/null +++ b/packages/start-client-core/src/hydration/constants.ts @@ -0,0 +1,4 @@ +export const hydrateIdAttribute = 'data-ts-hydrate-id' +export const hydrateWhenAttribute = 'data-ts-hydrate-when' +export const hydrateInteractionEventsAttribute = + 'data-ts-hydrate-interaction-events' diff --git a/packages/start-client-core/src/hydration/idle.ts b/packages/start-client-core/src/hydration/idle.ts new file mode 100644 index 0000000000..bf0dc71131 --- /dev/null +++ b/packages/start-client-core/src/hydration/idle.ts @@ -0,0 +1,35 @@ +import type { HydrationPrefetchStrategy } from './types' + +const idleType = 'idle' + +export type IdleHydrationOptions = { + timeout?: number +} + +export function idle( + options: IdleHydrationOptions = {}, +): HydrationPrefetchStrategy { + const timeout = options.timeout ?? 2000 + + return { + _t: idleType, + _s: ({ gate, prefetch }) => { + const schedule = globalThis as unknown as { + requestIdleCallback?: ( + callback: IdleRequestCallback, + options?: IdleRequestOptions, + ) => number + cancelIdleCallback?: (handle: number) => void + } + const callback = prefetch ?? gate!.resolve + + if (schedule.requestIdleCallback) { + const handle = schedule.requestIdleCallback(callback, { timeout }) + return () => schedule.cancelIdleCallback?.(handle) + } + + const timeoutId = globalThis.setTimeout(callback, timeout) + return () => globalThis.clearTimeout(timeoutId) + }, + } +} diff --git a/packages/start-client-core/src/hydration/interaction.ts b/packages/start-client-core/src/hydration/interaction.ts new file mode 100644 index 0000000000..d5d6886d36 --- /dev/null +++ b/packages/start-client-core/src/hydration/interaction.ts @@ -0,0 +1,342 @@ +import { + hydrateIdAttribute, + hydrateInteractionEventsAttribute, + hydrateWhenAttribute, +} from './constants' +import { + clearResolvedGateIdsInMarker, + getMarkerGate, + resolveHydrationMarker, +} from './runtime' +import type { + HydrationInteractionEvents, + HydrationPrefetchStrategy, + HydrationRuntimeContext, +} from './types' + +export type InteractionHydrationOptions = { + events?: HydrationInteractionEvents +} + +const hydrateIdSelector = `[${hydrateIdAttribute}]` + +type PendingReplayEvent = { + marker: Element + targetPath: Array + type: string + event: Event +} + +const defaultInteractionEvents = [ + 'pointerenter', + 'focusin', + 'pointerdown', + 'click', +] as const +const supportedInteractionEvents = [ + 'auxclick', + 'click', + 'contextmenu', + 'dblclick', + 'focusin', + 'keydown', + 'keyup', + 'mousedown', + 'mouseenter', + 'mouseover', + 'mouseup', + 'pointerdown', + 'pointerenter', + 'pointerover', + 'pointerup', +] as const +const interactionType = 'interaction' +const dynamicType = 'dynamic' +const interactionHydrateSelector = `[${hydrateWhenAttribute}="${interactionType}"]` +const delegatedHydrateSelector = `${interactionHydrateSelector},[${hydrateWhenAttribute}="${dynamicType}"]` +const replayEventsByGateId = /* @__PURE__ */ new Map< + string, + Array +>() + +function getIntentListenerEvents( + marker: Element, + events: ReadonlyArray, +) { + const listenerEvents = new Set(events) + + marker.querySelectorAll(delegatedHydrateSelector).forEach((childMarker) => { + if (childMarker.getAttribute(hydrateWhenAttribute) === dynamicType) { + supportedInteractionEvents.forEach((eventName) => { + listenerEvents.add(eventName) + }) + return + } + + const attr = childMarker.getAttribute(hydrateInteractionEventsAttribute) + for (const eventName of attr === null + ? defaultInteractionEvents + : attr.split(/\s+/).filter(Boolean)) { + listenerEvents.add(eventName) + } + }) + + return [...listenerEvents] +} + +function queueHydrationReplayEvent(marker: Element, event: Event) { + if (!event.bubbles) return + + const id = marker.getAttribute(hydrateIdAttribute) + const when = marker.getAttribute(hydrateWhenAttribute) + if (!id || !when || when === 'never') return + + const target = event.target + if (!target) return + + const gate = getMarkerGate(marker) + if (gate?.resolved) return + + event.preventDefault() + event.stopPropagation() + event.stopImmediatePropagation() + + let targetPath: Array = [] + if (target instanceof Node && marker.contains(target)) { + let node: Element | null = + target instanceof Element ? target : target.parentElement + + while (node && node !== marker) { + const parent = node.parentElement + if (!parent) { + targetPath = [] + break + } + targetPath.push(Array.prototype.indexOf.call(parent.children, node)) + node = parent + } + targetPath.reverse() + } + + const pendingEvents = replayEventsByGateId.get(id) ?? [] + pendingEvents.push({ + marker, + targetPath, + type: event.type, + event, + }) + replayEventsByGateId.set(id, pendingEvents) +} + +if (typeof document !== 'undefined') { + const onIntent = (event: Event) => { + const target = event.target + if (!(target instanceof Element)) return + + let marker: Element | null = target.closest(hydrateIdSelector) + const markers: Array = [] + let shouldHandle = false + + while (marker) { + markers.push(marker) + + const when = marker.getAttribute(hydrateWhenAttribute) + if (when === dynamicType) { + shouldHandle ||= event.type === 'click' + } else if (when === interactionType) { + const attr = marker.getAttribute(hydrateInteractionEventsAttribute) + const events: ReadonlyArray = + attr === null + ? defaultInteractionEvents + : attr.split(/\s+/).filter(Boolean) + shouldHandle ||= events.includes(event.type) + } + + marker = marker.parentElement?.closest(hydrateIdSelector) ?? null + } + + if (!shouldHandle) return + + markers.reverse() + if (markers.every((marker) => getMarkerGate(marker))) return + + markers.forEach((marker) => { + queueHydrationReplayEvent(marker, event) + resolveHydrationMarker(marker) + }) + } + + supportedInteractionEvents.forEach((eventName) => { + document.addEventListener(eventName, onIntent, true) + }) +} + +function listenForIntent( + element: Element, + events: ReadonlyArray, + context: HydrationRuntimeContext, +) { + const onIntent = (event: Event) => { + const target = event.target + let marker: Element | null + if (target instanceof Element) { + const closestMarker = target.closest(hydrateIdSelector) + marker = + closestMarker && element.contains(closestMarker) + ? closestMarker + : element + } else { + marker = element + } + + const markers: Array = [] + while (marker) { + if (marker.hasAttribute(hydrateIdAttribute)) { + markers.push(marker) + } + if (marker === element) break + marker = marker.parentElement + } + + if (!markers.includes(element)) { + markers.push(element) + } + + markers.reverse() + + if ( + context.delegated && + !markers.some( + (marker) => + marker.getAttribute(hydrateWhenAttribute) === interactionType || + marker.getAttribute(hydrateWhenAttribute) === dynamicType, + ) + ) { + return + } + + markers.forEach((marker) => { + queueHydrationReplayEvent(marker, event) + resolveHydrationMarker(marker) + }) + } + let disposed = false + + events.forEach((eventName) => { + element.addEventListener(eventName, onIntent, true) + }) + + return () => { + if (disposed) return + disposed = true + events.forEach((eventName) => { + element.removeEventListener(eventName, onIntent, true) + }) + } +} + +export function listenForDelegatedHydrationIntent( + element: Element, + context: HydrationRuntimeContext, +) { + const listenerEvents = getIntentListenerEvents(element, []) + if (!listenerEvents.length) return + + const cleanupIntent = listenForIntent(element, listenerEvents, { + ...context, + delegated: true, + }) + return () => { + cleanupIntent() + clearResolvedGateIdsInMarker(element) + } +} + +/* @__NO_SIDE_EFFECTS__ */ +export function interaction( + options: InteractionHydrationOptions = {}, +): HydrationPrefetchStrategy { + let events: ReadonlyArray = defaultInteractionEvents + if (options.events !== undefined) { + const eventList: ReadonlyArray = + typeof options.events === 'string' ? [options.events] : options.events + const normalizedEvents: Array = [] + const seen = new Set() + + for (const eventName of eventList) { + if (!eventName || seen.has(eventName)) continue + seen.add(eventName) + normalizedEvents.push(eventName) + } + + events = normalizedEvents + } + + const eventKey = events.join(' ') + + return { + _t: interactionType, + _s: (context) => { + const element = context.element + if (!element) return + const prefetch = context.prefetch + if (prefetch) { + if (!events.length) return + let disposed = false + + events.forEach((eventName) => { + element.addEventListener(eventName, prefetch, true) + }) + + return () => { + if (disposed) return + disposed = true + events.forEach((eventName) => { + element.removeEventListener(eventName, prefetch, true) + }) + } + } + + const listenerEvents = getIntentListenerEvents(element, events) + const cleanupIntent = listenerEvents.length + ? listenForIntent(element, listenerEvents, context) + : undefined + return () => { + cleanupIntent?.() + clearResolvedGateIdsInMarker(element) + } + }, + _o: (id) => { + globalThis.requestAnimationFrame(() => { + const pendingEvents = replayEventsByGateId.get(id) + if (!pendingEvents?.length) return + + replayEventsByGateId.delete(id) + + for (const pendingEvent of pendingEvents) { + let replayTarget: Element | null = pendingEvent.marker + for (const index of pendingEvent.targetPath) { + replayTarget = replayTarget.children[index] ?? null + if (!replayTarget) break + } + + const event = pendingEvent.event + replayTarget ??= pendingEvent.marker + replayTarget.dispatchEvent( + event instanceof MouseEvent + ? new MouseEvent(event.type, event) + : event instanceof FocusEvent + ? new FocusEvent(event.type, event) + : new Event(event.type, event), + ) + } + }) + }, + _a: () => + options.events === undefined + ? undefined + : { + [hydrateInteractionEventsAttribute]: eventKey, + }, + } +} diff --git a/packages/start-client-core/src/hydration/load.ts b/packages/start-client-core/src/hydration/load.ts new file mode 100644 index 0000000000..b78d6d6a42 --- /dev/null +++ b/packages/start-client-core/src/hydration/load.ts @@ -0,0 +1,16 @@ +import type { HydrationPrefetchStrategy } from './types' + +const loadType = 'load' + +const loadStrategy: HydrationPrefetchStrategy = { + _t: loadType, + _d: () => false, + _s: ({ gate, prefetch }) => { + ;(prefetch ?? gate!.resolve)() + }, +} + +/* @__NO_SIDE_EFFECTS__ */ +export function load(): HydrationPrefetchStrategy { + return loadStrategy +} diff --git a/packages/start-client-core/src/hydration/media.ts b/packages/start-client-core/src/hydration/media.ts new file mode 100644 index 0000000000..c2335b7e2f --- /dev/null +++ b/packages/start-client-core/src/hydration/media.ts @@ -0,0 +1,25 @@ +import type { HydrationPrefetchStrategy } from './types' + +const mediaType = 'media' + +/* @__NO_SIDE_EFFECTS__ */ +export function media( + query: string, +): HydrationPrefetchStrategy { + return { + _t: mediaType, + _s: ({ gate, prefetch }) => { + if (!query) return + + const callback = prefetch ?? gate!.resolve + const mediaQuery = window.matchMedia(query) + const onChange = () => { + if (mediaQuery.matches) callback() + } + mediaQuery.addEventListener('change', onChange) + onChange() + + return () => mediaQuery.removeEventListener('change', onChange) + }, + } +} diff --git a/packages/start-client-core/src/hydration/never.ts b/packages/start-client-core/src/hydration/never.ts new file mode 100644 index 0000000000..8ace129b5e --- /dev/null +++ b/packages/start-client-core/src/hydration/never.ts @@ -0,0 +1,13 @@ +import type { HydrationStrategy } from './types' + +const neverType = 'never' + +const neverStrategy: HydrationStrategy = { + _t: neverType, + _d: () => true, +} + +/* @__NO_SIDE_EFFECTS__ */ +export function never(): HydrationStrategy { + return neverStrategy +} diff --git a/packages/start-client-core/src/hydration/renderer.ts b/packages/start-client-core/src/hydration/renderer.ts new file mode 100644 index 0000000000..1a14ef9b46 --- /dev/null +++ b/packages/start-client-core/src/hydration/renderer.ts @@ -0,0 +1,21 @@ +import type { HydrationStrategy } from './types' + +export type HydrationStrategyWithRenderer< + TStrategy extends HydrationStrategy, + TRenderer, +> = TStrategy & { + _h: TRenderer +} + +/* @__NO_SIDE_EFFECTS__ */ +export function withHydrationRenderer< + TStrategy extends HydrationStrategy, + TRenderer, +>( + strategy: TStrategy, + renderer: TRenderer, +): HydrationStrategyWithRenderer { + return /* @__PURE__ */ Object.assign(strategy, { + _h: renderer, + }) +} diff --git a/packages/start-client-core/src/hydration/runtime.ts b/packages/start-client-core/src/hydration/runtime.ts new file mode 100644 index 0000000000..b1da55195d --- /dev/null +++ b/packages/start-client-core/src/hydration/runtime.ts @@ -0,0 +1,191 @@ +import { hydrateIdAttribute, hydrateWhenAttribute } from './constants' +import type { + HydrationPrefetchStrategy, + HydrationPrefetchWaitReason, + HydrationRuntimeGate, + HydrationWhen, +} from './types' + +const hydrateIdSelector = `[${hydrateIdAttribute}]` + +export type HydrationGateRecord = HydrationRuntimeGate & { + id: string + when: HydrationWhen + promise: Promise + consumers: number + resolveListeners: Set<() => void> +} + +const gateRegistry = /* @__PURE__ */ new Map() +const resolvedGateIds = /* @__PURE__ */ new Set() +const fallbackHtmlByGateId = /* @__PURE__ */ new Map() + +export function createResolvedGate( + id: string, + when: HydrationWhen, +): HydrationGateRecord { + return { + id, + when, + promise: Promise.resolve(), + resolve: () => {}, + resolved: true, + consumers: 0, + resolveListeners: new Set<() => void>(), + } +} + +export function getOrCreateGate( + id: string, + when: HydrationWhen, +): HydrationGateRecord { + const existing = gateRegistry.get(id) + if (existing?.when === when) { + existing.consumers++ + return existing + } + + let resolvePromise!: () => void + const promise = new Promise((resolve) => { + resolvePromise = resolve + }) + + const gate: HydrationGateRecord = { + id, + promise, + resolved: false, + consumers: 1, + when, + resolveListeners: new Set(), + resolve: () => { + if (gate.resolved) return + gate.resolved = true + resolvePromise() + gate.resolveListeners.forEach((listener) => listener()) + gate.resolveListeners.clear() + }, + } + + gateRegistry.set(id, gate) + if (when !== 'never' && resolvedGateIds.has(id)) { + resolvedGateIds.delete(id) + gate.resolve() + } + return gate +} + +export function releaseGate(gate: HydrationGateRecord) { + resolvedGateIds.delete(gate.id) + gate.consumers-- + if (gate.consumers > 0) return + if (gateRegistry.get(gate.id) === gate) { + gateRegistry.delete(gate.id) + fallbackHtmlByGateId.delete(gate.id) + gate.resolveListeners.clear() + } +} + +export function onGateResolve(gate: HydrationGateRecord, listener: () => void) { + if (gate.resolved) { + listener() + return () => {} + } + + gate.resolveListeners.add(listener) + return () => { + gate.resolveListeners.delete(listener) + } +} + +export function runHydrationStrategyCleanup(cleanup: void | (() => void)) { + if (typeof cleanup === 'function') return cleanup + return undefined +} + +export function waitForHydrationPrefetchStrategy( + strategy: HydrationPrefetchStrategy, + options: { + element: Element | null + signal: AbortSignal + onHydrate: (listener: () => void) => () => void + }, +): Promise { + if (options.signal.aborted) { + return Promise.resolve('abort') + } + + return new Promise((resolve) => { + const state = { disposed: false } + const cleanupStrategyRef: { current: void | (() => void) } = { + current: undefined, + } + let cleanupHydrate = () => {} + + const finish = (reason: HydrationPrefetchWaitReason) => { + if (state.disposed) return + state.disposed = true + options.signal.removeEventListener('abort', onAbort) + cleanupHydrate() + runHydrationStrategyCleanup(cleanupStrategyRef.current)?.() + resolve(reason) + } + + const onAbort = () => finish('abort') + + options.signal.addEventListener('abort', onAbort, { once: true }) + cleanupHydrate = options.onHydrate(() => finish('hydrate')) + const cleanupStrategy = strategy._s?.({ + element: options.element, + prefetch: () => finish('prefetch'), + }) + cleanupStrategyRef.current = cleanupStrategy + if (state.disposed) { + runHydrationStrategyCleanup(cleanupStrategy)?.() + } + }) +} + +export function getMarkerGate(marker: Element) { + const id = marker.getAttribute(hydrateIdAttribute) + return id ? gateRegistry.get(id) : undefined +} + +export function resolveHydrationMarker(marker: Element) { + const id = marker.getAttribute(hydrateIdAttribute) + const when = marker.getAttribute(hydrateWhenAttribute) + if (!id || !when || when === 'never') { + return + } + + const gate = gateRegistry.get(id) + if (gate) { + if (gate.when !== 'never') gate.resolve() + return + } + + resolvedGateIds.add(id) +} + +export function clearResolvedGateIdsInMarker(marker: Element) { + const ownId = marker.getAttribute(hydrateIdAttribute) + if (ownId) { + resolvedGateIds.delete(ownId) + } + + marker.querySelectorAll(hydrateIdSelector).forEach((childMarker) => { + const childId = childMarker.getAttribute(hydrateIdAttribute) + if (childId) { + resolvedGateIds.delete(childId) + } + }) +} + +export function saveFallbackHtml(id: string, element: Element) { + if (!fallbackHtmlByGateId.has(id)) { + fallbackHtmlByGateId.set(id, element.innerHTML) + } +} + +export function getFallbackHtml(id: string) { + return fallbackHtmlByGateId.get(id) +} diff --git a/packages/start-client-core/src/hydration/types.ts b/packages/start-client-core/src/hydration/types.ts new file mode 100644 index 0000000000..f4250067d6 --- /dev/null +++ b/packages/start-client-core/src/hydration/types.ts @@ -0,0 +1,90 @@ +export type HydrationWhen = + | 'load' + | 'idle' + | 'visible' + | 'media' + | 'interaction' + | 'condition' + | 'never' + | 'dynamic' + +export type HydrationInteractionEvent = + | 'auxclick' + | 'click' + | 'contextmenu' + | 'dblclick' + | 'focusin' + | 'keydown' + | 'keyup' + | 'mousedown' + | 'mouseenter' + | 'mouseover' + | 'mouseup' + | 'pointerdown' + | 'pointerenter' + | 'pointerover' + | 'pointerup' + +export type HydrationInteractionEvents = + | HydrationInteractionEvent + | ReadonlyArray + +export type HydrationMarkerAttributes = Record + +export type HydrationRuntimeGate = { + id?: string + when?: HydrationWhen + resolved: boolean + resolve: () => void +} + +export type HydrationRuntimeContext = { + element: Element | null + gate?: HydrationRuntimeGate + prefetch?: () => void + delegated?: boolean +} + +export type HydrationStrategyTypes< + TWhen extends HydrationWhen = HydrationWhen, + TCanPrefetch extends boolean = boolean, +> = { + when: TWhen + canPrefetch: TCanPrefetch +} + +export type HydrationStrategy< + TWhen extends HydrationWhen = HydrationWhen, + TCanPrefetch extends boolean = boolean, +> = { + _t?: TWhen + readonly '~types'?: HydrationStrategyTypes + _d?: () => boolean + _s?: (context: HydrationRuntimeContext) => void | (() => void) + _o?: (id: string) => void + _a?: () => HydrationMarkerAttributes | undefined +} + +export type HydrationPrefetchWhen = Exclude< + HydrationWhen, + 'condition' | 'never' | 'dynamic' +> + +export type HydrationPrefetchStrategy< + TWhen extends HydrationPrefetchWhen = HydrationPrefetchWhen, +> = HydrationStrategy + +export type HydrationPrefetchWaitReason = 'prefetch' | 'hydrate' | 'abort' + +export type HydrationPrefetchContext = { + element: Element | null + signal: AbortSignal + preload: () => Promise + waitFor: ( + strategy: HydrationPrefetchStrategy, + ) => Promise +} + +export type HydrationPrefetchFunction = ( + context: HydrationPrefetchContext, +) => void | Promise diff --git a/packages/start-client-core/src/hydration/visible.ts b/packages/start-client-core/src/hydration/visible.ts new file mode 100644 index 0000000000..3c3391b1de --- /dev/null +++ b/packages/start-client-core/src/hydration/visible.ts @@ -0,0 +1,90 @@ +import type { HydrationPrefetchStrategy } from './types' + +const visibleType = 'visible' + +export type VisibleHydrationOptions = { + rootMargin?: string + threshold?: number | Array +} + +type VisibleObserverEntry = { + key: string + observer: IntersectionObserver + elements: Map void>> +} + +const observerRegistry = /* @__PURE__ */ new Map() + +function cleanupVisibleObserverEntry(observerEntry: VisibleObserverEntry) { + if (observerEntry.elements.size > 0) return + observerEntry.observer.disconnect() + observerRegistry.delete(observerEntry.key) +} + +/* @__NO_SIDE_EFFECTS__ */ +export function visible( + options: VisibleHydrationOptions = {}, +): HydrationPrefetchStrategy { + const rootMargin = options.rootMargin ?? '600px' + const threshold = options.threshold ?? 0 + + return { + _t: visibleType, + _s: ({ element, gate, prefetch }) => { + const callback = prefetch ?? gate!.resolve + + if (!element) { + callback() + return + } + + const key = `${rootMargin}|${ + Array.isArray(threshold) ? threshold.join(',') : String(threshold) + }` + let observerEntry = observerRegistry.get(key) + + if (!observerEntry) { + const entry: VisibleObserverEntry = { + key, + elements: new Map void>>(), + observer: new IntersectionObserver( + (entries) => { + for (const intersectingEntry of entries) { + if (!intersectingEntry.isIntersecting) continue + + const callbacks = entry.elements.get(intersectingEntry.target) + if (!callbacks) continue + + callbacks.forEach((callback) => callback()) + entry.elements.delete(intersectingEntry.target) + entry.observer.unobserve(intersectingEntry.target) + cleanupVisibleObserverEntry(entry) + } + }, + { rootMargin, threshold }, + ), + } + observerRegistry.set(key, entry) + observerEntry = entry + } + + let callbacks = observerEntry.elements.get(element) + if (!callbacks) { + callbacks = new Set() + observerEntry.elements.set(element, callbacks) + observerEntry.observer.observe(element) + } + callbacks.add(callback) + + return () => { + const currentCallbacks = observerEntry.elements.get(element) + currentCallbacks?.delete(callback) + if (currentCallbacks?.size === 0) { + observerEntry.elements.delete(element) + observerEntry.observer.unobserve(element) + } + cleanupVisibleObserverEntry(observerEntry) + } + }, + } +} diff --git a/packages/start-client-core/vite.config.ts b/packages/start-client-core/vite.config.ts index e893ba2c8d..c17997fc31 100644 --- a/packages/start-client-core/vite.config.ts +++ b/packages/start-client-core/vite.config.ts @@ -2,33 +2,42 @@ import { defineConfig, mergeConfig } from 'vitest/config' import { tanstackViteConfig } from '@tanstack/vite-config' import packageJson from './package.json' -const config = defineConfig({ - test: { - typecheck: { enabled: true }, - name: packageJson.name, - watch: false, - environment: 'jsdom', - }, -}) - -export default mergeConfig( - config, - tanstackViteConfig({ - tsconfigPath: './tsconfig.build.json', - srcDir: './src', - entry: [ - './src/index.tsx', - './src/client/index.ts', - './src/client-rpc/index.ts', - './src/fake-entries/start.ts', - './src/fake-entries/router.ts', - './src/fake-entries/plugin-adapters.ts', - ], - cjs: false, - externalDeps: [ - '#tanstack-start-entry', - '#tanstack-router-entry', - '#tanstack-start-plugin-adapters', - ], - }), +export default defineConfig(({ command }) => + mergeConfig( + { + define: + command === 'build' + ? { + 'import.meta.hot': 'import.meta.hot', + } + : undefined, + test: { + typecheck: { enabled: true }, + name: packageJson.name, + watch: false, + environment: 'jsdom', + }, + }, + tanstackViteConfig({ + tsconfigPath: './tsconfig.build.json', + srcDir: './src', + entry: [ + './src/index.tsx', + './src/client/index.ts', + './src/client-rpc/index.ts', + './src/hydration/constants.ts', + './src/hydration.ts', + './src/hydration/runtime.ts', + './src/fake-entries/start.ts', + './src/fake-entries/router.ts', + './src/fake-entries/plugin-adapters.ts', + ], + cjs: false, + externalDeps: [ + '#tanstack-start-entry', + '#tanstack-router-entry', + '#tanstack-start-plugin-adapters', + ], + }), + ), ) diff --git a/packages/start-plugin-core/src/hydrate-when-transform.ts b/packages/start-plugin-core/src/hydrate-when-transform.ts new file mode 100644 index 0000000000..d88ddb60d0 --- /dev/null +++ b/packages/start-plugin-core/src/hydrate-when-transform.ts @@ -0,0 +1,1004 @@ +import { relative } from 'node:path' +import crypto from 'node:crypto' +import babel from '@babel/core' +import * as t from '@babel/types' +import { + buildDeclarationMap, + buildDependencyGraph, + collectIdentifiersFromNode, + collectIdentifiersFromPattern, + collectLocalBindingsFromStatement, + deadCodeElimination, + expandTransitively, + findReferencedIdentifiers, + generateFromAst, + parseAst, + removeModuleLevelBindings, + retainModuleLevelDeclarations, + stripUnreferencedTopLevelExpressionStatements, + unwrapExportedDeclarations, +} from '@tanstack/router-utils' +import { tssHydrate } from './hydration-constants' +import { cleanId, codeFrameError } from './start-compiler/utils' +import type { + CompileStartFrameworkOptions, + StartCompilerPlugin, + StartCompilerTransformResult, +} from './types' + +export class MissingHydrateSourceError extends Error { + constructor(id: string) { + super( + `Missing Hydrate source for virtual module ${id}. The parent module must be transformed before its Hydrate child chunk is loaded.`, + ) + } +} + +/** + * Detection pattern used by the transform code filter to pre-scan files for + * `` JSX before any AST parsing happens. + */ +const HYDRATE_DETECTION_PATTERN = /\bHydrate\b/ + +function createBoundaryId(root: string, sourceId: string) { + const normalized = relative(root, sourceId).replaceAll('\\', '/') + const sourceHash = crypto + .createHash('sha1') + .update(normalized) + .digest('hex') + .slice(0, 10) + + return (index: number) => { + return `${index.toString(36)}_${sourceHash}` + } +} + +function getJSXElementName(node: t.JSXElement) { + const name = node.openingElement.name + return t.isJSXIdentifier(name) ? name.name : undefined +} + +function getJSXAttribute(node: t.JSXOpeningElement, name: string) { + for (const item of node.attributes) { + if (t.isJSXAttribute(item) && t.isJSXIdentifier(item.name, { name })) { + return item + } + } + + return undefined +} + +function getBooleanProp(node: t.JSXOpeningElement, name: string) { + const attr = getJSXAttribute(node, name) + if (!attr) return undefined + if (!attr.value) return true + if (t.isStringLiteral(attr.value)) return attr.value.value !== 'false' + if (t.isJSXExpressionContainer(attr.value)) { + if (t.isBooleanLiteral(attr.value.expression)) { + return attr.value.expression.value + } + } + return undefined +} + +function parseHydrateVirtualId(id: string) { + const queryIndex = id.indexOf('?') + const sourceId = cleanId(queryIndex === -1 ? id : id.slice(0, queryIndex)) + if (queryIndex === -1) { + return { sourceId, splitId: null, boundaryIndex: -1 } + } + + const rawQuery = id.slice(queryIndex + 1) + const params = new URLSearchParams(rawQuery) + const splitId = params.get(tssHydrate) + let boundaryIndex = -1 + if (splitId) { + const separatorIndex = splitId.indexOf('_') + if (separatorIndex > 0) { + const parsedIndex = Number.parseInt(splitId.slice(0, separatorIndex), 36) + if (Number.isInteger(parsedIndex)) { + boundaryIndex = parsedIndex + } + } + } + + return { + sourceId, + splitId, + boundaryIndex, + } +} + +function isObjectPropertyName( + property: t.ObjectMethod | t.ObjectProperty, + name: string, +) { + if (t.isIdentifier(property.key) && !property.computed) { + return property.key.name === name + } + + return t.isStringLiteral(property.key) && property.key.value === name +} + +function isReferenceInsideAnyNode( + referencePath: babel.NodePath, + nodes: ReadonlySet, +) { + if (nodes.has(referencePath.node)) return true + return Boolean(referencePath.findParent((parent) => nodes.has(parent.node))) +} + +function stripBindingsOnlyReferencedBy( + path: babel.NodePath, + node: t.Node, + seen = new Set(), + preserve = new Set(), +) { + stripBindingsOnlyReferencedByNodes(path.scope, [node], seen, preserve) +} + +function stripBindingsOnlyReferencedByNodes( + scope: babel.NodePath['scope'], + nodes: ReadonlyArray, + seen = new Set(), + preserve = new Set(), +) { + const nodeSet = new Set(nodes) + const names = new Set() + nodes.forEach((node) => { + collectIdentifiersFromNode(node).forEach((name) => names.add(name)) + }) + + for (const name of names) { + if (seen.has(name)) continue + if (preserve.has(name)) continue + const binding = scope.getBinding(name) + if (!binding?.constant) continue + if ( + binding.path.findParent( + (parentPath) => + parentPath.isExportNamedDeclaration() || + parentPath.isExportDefaultDeclaration(), + ) + ) { + continue + } + if (binding.referencePaths.length === 0) continue + if ( + !binding.referencePaths.every((referencePath) => + isReferenceInsideAnyNode(referencePath, nodeSet), + ) + ) { + continue + } + + seen.add(name) + + const declarationPath = binding.path.isVariableDeclarator() + ? binding.path + : binding.path.findParent((parentPath) => + parentPath.isVariableDeclarator(), + ) + const patternHasExternalReferences = + declarationPath?.isVariableDeclarator() && + !t.isIdentifier(declarationPath.node.id) && + collectIdentifiersFromPattern(declarationPath.node.id).some( + (bindingName) => { + if (bindingName === binding.identifier.name) return false + + const siblingBinding = binding.scope.getBinding(bindingName) + return siblingBinding?.referencePaths.some( + (referencePath) => + !isReferenceInsideAnyNode(referencePath, nodeSet), + ) + }, + ) + + if (patternHasExternalReferences) { + continue + } + + const bindingNode = binding.path.node + if (t.isVariableDeclarator(bindingNode) && bindingNode.init) { + stripBindingsOnlyReferencedByNodes( + binding.scope, + [bindingNode.init], + seen, + preserve, + ) + } else if ( + t.isFunctionDeclaration(bindingNode) || + t.isClassDeclaration(bindingNode) + ) { + stripBindingsOnlyReferencedByNodes( + binding.scope, + [bindingNode], + seen, + preserve, + ) + } + + if (binding.path.isVariableDeclarator()) { + const declarationPath = binding.path.parentPath + if ( + declarationPath.isVariableDeclaration() && + declarationPath.node.declarations.length === 1 + ) { + declarationPath.remove() + continue + } + + binding.path.remove() + continue + } + + if ( + binding.path.isImportSpecifier() || + binding.path.isImportDefaultSpecifier() || + binding.path.isImportNamespaceSpecifier() + ) { + const importPath = binding.path.parentPath + if ( + importPath.isImportDeclaration() && + importPath.node.specifiers.length === 1 + ) { + importPath.remove() + continue + } + + binding.path.remove() + continue + } + + binding.path.remove() + } +} + +function getSingleUseObjectExpressionBinding( + path: babel.NodePath, + identifier: t.Identifier, +) { + const binding = path.scope.getBinding(identifier.name) + if (!binding?.constant) return undefined + if (binding.referencePaths.length !== 1) return undefined + if (binding.referencePaths[0]?.node !== identifier) return undefined + if (!binding.path.isVariableDeclarator()) return undefined + const init = binding.path.node.init + return t.isObjectExpression(init) ? init : undefined +} + +function objectExpressionMayHaveProperty( + node: t.ObjectExpression, + name: string, +) { + return node.properties.some((property) => { + if (t.isSpreadElement(property)) return true + if (!t.isObjectMethod(property) && !t.isObjectProperty(property)) { + return true + } + if (property.computed) return true + return isObjectPropertyName(property, name) + }) +} + +function stripObjectExpressionProperty( + path: babel.NodePath, + node: t.ObjectExpression, + name: string, +) { + let modified = false + + node.properties = node.properties.filter((property) => { + if ( + (t.isObjectMethod(property) || t.isObjectProperty(property)) && + isObjectPropertyName(property, name) + ) { + stripBindingsOnlyReferencedBy( + path, + t.isObjectProperty(property) ? property.value : property.body, + ) + modified = true + return false + } + + return true + }) + + return modified +} + +function throwBoundaryError( + code: string, + path: babel.NodePath, + message: string, +): never { + if (path.node.loc) { + throw codeFrameError(code, path.node.loc, message) + } + throw new Error(message) +} + +function inspectSplitBoundary(options: { + code: string + path: babel.NodePath + validate?: boolean + collectCaptured?: boolean + nestedHydrate?: { + localName: string + } +}) { + const { path } = options + const capturedNames = options.collectCaptured ? new Set() : undefined + const nestedHydrate = options.nestedHydrate + let nestedBoundaryCount = 0 + + if (options.validate) { + for (const child of path.node.children) { + if ( + t.isJSXExpressionContainer(child) && + (t.isFunctionExpression(child.expression) || + t.isArrowFunctionExpression(child.expression)) + ) { + throwBoundaryError( + options.code, + path, + 'Hydrate cannot code-split function-as-children. Use split={false} for this boundary.', + ) + } + } + } + + const rootVisitors = { + JSXOpeningElement(openingPath: babel.NodePath) { + if (openingPath.node === path.node.openingElement) { + openingPath.skip() + } + }, + JSXClosingElement(closingPath: babel.NodePath) { + closingPath.skip() + }, + } + + const validateVisitors = options.validate + ? { + CallExpression(callPath: babel.NodePath) { + if (!t.isIdentifier(callPath.node.callee)) return + if (!/^use[A-Z0-9]/.test(callPath.node.callee.name)) return + + throwBoundaryError( + options.code, + path, + 'Hydrate cannot code-split JSX that calls hooks during render. Move the hook call into a child component or use split={false}.', + ) + }, + ThisExpression(thisPath: babel.NodePath) { + void thisPath + throwBoundaryError( + options.code, + path, + 'Hydrate cannot code-split JSX that captures this.', + ) + }, + Super(superPath: babel.NodePath) { + void superPath + throwBoundaryError( + options.code, + path, + 'Hydrate cannot code-split JSX that captures super.', + ) + }, + } + : {} + + const nestedHydrateVisitors = nestedHydrate + ? { + JSXElement(nestedPath: babel.NodePath) { + if (getJSXElementName(nestedPath.node) !== nestedHydrate.localName) { + return + } + + const split = getBooleanProp(nestedPath.node.openingElement, 'split') + if (split === false) return + + nestedBoundaryCount++ + }, + } + : {} + + const captureVisitors = capturedNames + ? { + Identifier(identifierPath: babel.NodePath) { + const parent = identifierPath.parent + if ( + t.isJSXOpeningElement(parent) || + t.isJSXClosingElement(parent) || + (t.isObjectProperty(parent, { key: identifierPath.node }) && + !parent.computed && + !parent.shorthand) || + (t.isMemberExpression(parent, { + property: identifierPath.node, + }) && + !parent.computed) + ) { + return + } + + const binding = identifierPath.scope.getBinding( + identifierPath.node.name, + ) + if (!binding) return + if (t.isProgram(binding.scope.block)) return + if ( + path.node === binding.scope.block || + path.isAncestor(binding.path) + ) + return + + capturedNames.add(identifierPath.node.name) + }, + JSXIdentifier(identifierPath: babel.NodePath) { + if (identifierPath.parentKey !== 'name') return + const name = identifierPath.node.name + if (!/^[A-Z]/.test(name)) return + const binding = identifierPath.scope.getBinding(name) + if (!binding) return + if (t.isProgram(binding.scope.block)) return + + capturedNames.add(name) + }, + } + : {} + + path.traverse({ + ...rootVisitors, + ...validateVisitors, + ...nestedHydrateVisitors, + ...captureVisitors, + }) + + return { + captured: capturedNames ? [...capturedNames].sort() : [], + nestedBoundaryCount, + } +} + +function getHydrateImport( + ast: t.File, + framework: CompileStartFrameworkOptions, +) { + const hydrateImportSource = `@tanstack/${framework}-start` + + for (const node of ast.program.body) { + if (!t.isImportDeclaration(node)) continue + if (node.source.value !== hydrateImportSource) continue + + for (const specifier of node.specifiers) { + if ( + t.isImportSpecifier(specifier) && + t.isIdentifier(specifier.imported, { name: 'Hydrate' }) + ) { + return { + hydrateLocalName: specifier.local.name, + } + } + } + } + + return undefined +} + +function getMeaningfulChildren( + children: Array, +) { + return children.filter( + (child) => !(t.isJSXText(child) && child.value.trim() === ''), + ) +} + +function transformHydrateAst(options: { + ast: t.File + code: string + id: string + root: string + env: 'client' | 'server' + framework: CompileStartFrameworkOptions + indexOffset?: number +}) { + if (!options.code.includes('Hydrate')) return null + + const hydrateImport = getHydrateImport(options.ast, options.framework) + if (!hydrateImport) return null + const { hydrateLocalName: localName } = hydrateImport + const sourceId = cleanId(options.id) + const getBoundaryId = createBoundaryId(options.root, sourceId) + + let nextBoundaryIndex = options.indexOffset ?? 0 + const state = { + modified: false, + extractedChildNodes: [] as Array, + capturedNames: new Set(), + } + let lazyIdent: t.Identifier | undefined + + babel.traverse(options.ast, { + Program(programPath) { + programPath.traverse({ + JSXElement(path) { + if (getJSXElementName(path.node) !== localName) return + + if (options.env === 'server') { + path.node.openingElement.attributes = + path.node.openingElement.attributes.filter((item) => { + if ( + t.isJSXAttribute(item) && + t.isJSXIdentifier(item.name, { name: 'fallback' }) + ) { + if (item.value) { + stripBindingsOnlyReferencedBy(path, item.value) + } + state.modified = true + return false + } + + if ( + t.isJSXSpreadAttribute(item) && + t.isObjectExpression(item.argument) + ) { + if ( + stripObjectExpressionProperty( + path, + item.argument, + 'fallback', + ) + ) { + state.modified = true + } + return item.argument.properties.length > 0 + } + + if ( + t.isJSXSpreadAttribute(item) && + t.isIdentifier(item.argument) + ) { + const init = getSingleUseObjectExpressionBinding( + path, + item.argument, + ) + if ( + init && + stripObjectExpressionProperty(path, init, 'fallback') + ) { + state.modified = true + } + } + + return true + }) + } + + const split = getBooleanProp(path.node.openingElement, 'split') + if (split === false) return + + const boundaryInspection = inspectSplitBoundary({ + code: options.code, + path, + validate: true, + collectCaptured: options.env === 'client', + ...(options.env === 'client' + ? { + nestedHydrate: { + localName, + }, + } + : {}), + }) + + const index = nextBoundaryIndex + nextBoundaryIndex += 1 + boundaryInspection.nestedBoundaryCount + const id = getBoundaryId(index) + const exportName = `H${index}` + + const existingHydrateId = getJSXAttribute( + path.node.openingElement, + 'h', + ) + if (existingHydrateId) { + existingHydrateId.value = t.stringLiteral(id) + } else { + path.node.openingElement.attributes.push( + t.jsxAttribute(t.jsxIdentifier('h'), t.stringLiteral(id)), + ) + } + state.modified = true + + if (options.env === 'server') return + + const needsPreloadProp = path.node.openingElement.attributes.some( + (attribute) => { + if (t.isJSXAttribute(attribute)) { + return t.isJSXIdentifier(attribute.name, { name: 'prefetch' }) + } + + if (t.isJSXSpreadAttribute(attribute)) { + if (t.isObjectExpression(attribute.argument)) { + return objectExpressionMayHaveProperty( + attribute.argument, + 'prefetch', + ) + } + + if (t.isIdentifier(attribute.argument)) { + const init = getSingleUseObjectExpressionBinding( + path, + attribute.argument, + ) + return init + ? objectExpressionMayHaveProperty(init, 'prefetch') + : true + } + + return true + } + + return false + }, + ) + const childReferenceNodes = getMeaningfulChildren(path.node.children) + + state.extractedChildNodes.push(...childReferenceNodes) + boundaryInspection.captured.forEach((name) => { + state.capturedNames.add(name) + }) + + if (!lazyIdent) { + lazyIdent = + programPath.scope.generateUidIdentifier('lazyRouteComponent') + programPath.unshiftContainer('body', [ + t.importDeclaration( + [ + t.importSpecifier( + lazyIdent, + t.identifier('lazyRouteComponent'), + ), + ], + t.stringLiteral(`@tanstack/${options.framework}-router`), + ), + ]) + } + + const importIdParams = new URLSearchParams() + importIdParams.set(tssHydrate, id) + const componentIdent = + programPath.scope.generateUidIdentifier(exportName) + const declarations = [ + t.variableDeclarator( + componentIdent, + t.callExpression(lazyIdent, [ + t.arrowFunctionExpression( + [], + t.callExpression(t.import(), [ + t.stringLiteral(`${sourceId}?${importIdParams.toString()}`), + ]), + ), + t.stringLiteral(exportName), + ]), + ), + ] + + let preloadIdent: t.Identifier | undefined + if (needsPreloadProp) { + preloadIdent = programPath.scope.generateUidIdentifier( + `${exportName}_preload`, + ) + declarations.push( + t.variableDeclarator( + preloadIdent, + t.memberExpression(componentIdent, t.identifier('preload')), + ), + ) + } + + programPath.unshiftContainer('body', [ + t.variableDeclaration('const', declarations), + ]) + if (preloadIdent) { + path.node.openingElement.attributes.push( + t.jsxAttribute( + t.jsxIdentifier('p'), + t.jsxExpressionContainer(preloadIdent), + ), + ) + } + + path.node.children = [ + t.jsxText('\n'), + t.jsxExpressionContainer( + t.jsxElement( + t.jsxOpeningElement( + t.jsxIdentifier(componentIdent.name), + boundaryInspection.captured.map((name) => + t.jsxAttribute( + t.jsxIdentifier(name), + t.jsxExpressionContainer(t.identifier(name)), + ), + ), + true, + ), + null, + [], + true, + ), + ), + t.jsxText('\n'), + ] + path.skip() + }, + }) + + if (state.extractedChildNodes.length > 0) { + stripBindingsOnlyReferencedByNodes( + programPath.scope, + state.extractedChildNodes, + new Set(), + state.capturedNames, + ) + } + + programPath.skip() + }, + }) + + if (!state.modified) return null + + return true +} + +function loadHydrateVirtualModule(options: { + id: string + root: string + code: string + framework: CompileStartFrameworkOptions +}) { + const { sourceId, splitId, boundaryIndex } = parseHydrateVirtualId(options.id) + if (!splitId || boundaryIndex < 0) return null + const getBoundaryId = createBoundaryId(options.root, sourceId) + + const ast = parseAst({ code: options.code, sourceFilename: sourceId }) + const hydrateImport = getHydrateImport(ast, options.framework) + if (!hydrateImport) return null + const { hydrateLocalName: localName } = hydrateImport + + let target: t.JSXElement | undefined + let targetIndex = -1 + let targetCaptured: Array = [] + let index = 0 + + babel.traverse(ast, { + JSXElement(path) { + if (getJSXElementName(path.node) !== localName) return + const split = getBooleanProp(path.node.openingElement, 'split') + if (split === false) return + + if (index === boundaryIndex) { + const id = getBoundaryId(index) + if (id !== splitId) { + path.stop() + return + } + targetCaptured = inspectSplitBoundary({ + code: options.code, + path, + collectCaptured: true, + }).captured + target = t.cloneNode(path.node, true) + targetIndex = index + path.stop() + return + } + index++ + }, + }) + + if (!target || targetIndex < 0) return null + + const children = target.children + const exportName = `H${targetIndex}` + const refIdents = findReferencedIdentifiers(ast) + + removeModuleLevelBindings(ast, new Set(['Route'])) + const localBindings = new Set() + for (const node of ast.program.body) { + collectLocalBindingsFromStatement(node, localBindings) + } + + const keepBindings = new Set() + const meaningfulChildren = getMeaningfulChildren(children) + let returnExpression: t.Expression | t.JSXElement | t.JSXFragment = + t.nullLiteral() + + if (meaningfulChildren.length === 1) { + const child = meaningfulChildren[0]! + if (t.isJSXExpressionContainer(child)) { + returnExpression = t.isJSXEmptyExpression(child.expression) + ? t.nullLiteral() + : child.expression + } else if (t.isJSXElement(child) || t.isJSXFragment(child)) { + returnExpression = child + } else if (t.isJSXText(child)) { + returnExpression = t.stringLiteral(child.value) + } + } else if (meaningfulChildren.length > 1) { + returnExpression = t.jsxFragment( + t.jsxOpeningFragment(), + t.jsxClosingFragment(), + children, + ) + } + for (const name of collectIdentifiersFromNode(returnExpression)) { + if (localBindings.has(name)) { + keepBindings.add(name) + } + } + + if (keepBindings.size > 0) { + expandTransitively( + keepBindings, + buildDependencyGraph(buildDeclarationMap(ast), localBindings), + ) + } + + retainModuleLevelDeclarations(ast, keepBindings) + unwrapExportedDeclarations(ast) + + ast.program.body.push( + t.exportNamedDeclaration( + t.functionDeclaration( + t.identifier(exportName), + targetCaptured.length > 0 + ? [ + t.objectPattern( + targetCaptured.map((name) => + t.objectProperty( + t.identifier(name), + t.identifier(name), + false, + true, + ), + ), + ), + ] + : [], + t.blockStatement([t.returnStatement(returnExpression)]), + ), + ), + ) + + deadCodeElimination(ast, refIdents) + stripUnreferencedTopLevelExpressionStatements(ast) + + const result = generateFromAst(ast, { + sourceMaps: true, + sourceFileName: options.id, + filename: options.id, + }) + return result +} + +export function createHydrateCompilerPlugin(): StartCompilerPlugin { + type SourceEntry = { + code: string + framework: CompileStartFrameworkOptions + virtualModules: Map + } + + const sourcesByEnvironment = new Map>() + + const getEnvironmentSources = (envName: string) => { + let sources = sourcesByEnvironment.get(envName) + if (!sources) { + sources = new Map() + sourcesByEnvironment.set(envName, sources) + } + return sources + } + + const setSource = ( + envName: string, + id: string, + code: string, + framework: CompileStartFrameworkOptions, + ) => { + const sourceId = cleanId(id) + const sources = getEnvironmentSources(envName) + const existing = sources.get(sourceId) + if (existing?.code === code && existing.framework === framework) { + return existing + } + + const entry = { + code, + framework, + virtualModules: new Map(), + } + sources.set(sourceId, entry) + return entry + } + + const getSourceEntry = (envName: string, id: string) => + sourcesByEnvironment.get(envName)?.get(cleanId(id)) + + const deleteSource = (envName: string, id: string) => { + sourcesByEnvironment.get(envName)?.delete(cleanId(id)) + } + + return { + name: 'tanstack-start-core:hydrate', + detect: HYDRATE_DETECTION_PATTERN, + virtualModuleIdPattern: new RegExp(`[?&]${tssHydrate}=`), + transformAst(context) { + const virtualModule = parseHydrateVirtualId(context.id) + const indexOffset = + virtualModule.boundaryIndex < 0 + ? undefined + : virtualModule.boundaryIndex + 1 + const result = transformHydrateAst({ + ast: context.ast, + code: context.code, + id: context.id, + root: context.root, + env: context.env, + framework: context.framework, + indexOffset, + }) + + if (result && virtualModule.boundaryIndex < 0) { + setSource(context.envName, context.id, context.code, context.framework) + } + + return !!result + }, + loadVirtualModule(context) { + const virtualModule = parseHydrateVirtualId(context.id) + if (!virtualModule.splitId || virtualModule.boundaryIndex < 0) { + return null + } + + const existingSourceEntry = getSourceEntry( + context.envName, + virtualModule.sourceId, + ) + const sourceEntry = + context.code === undefined + ? existingSourceEntry + : setSource( + context.envName, + virtualModule.sourceId, + context.code, + existingSourceEntry?.framework ?? + (context.code.includes('@tanstack/solid-start') + ? 'solid' + : 'react'), + ) + + if (!sourceEntry) { + throw new MissingHydrateSourceError(context.id) + } + + if (sourceEntry.virtualModules.has(context.id)) { + return sourceEntry.virtualModules.get(context.id)! + } + + const result = loadHydrateVirtualModule({ + code: sourceEntry.code, + id: context.id, + root: context.root, + framework: sourceEntry.framework, + }) + sourceEntry.virtualModules.set(context.id, result) + return result + }, + invalidateModule(context) { + deleteSource(context.envName, context.id) + }, + } +} diff --git a/packages/start-plugin-core/src/hydration-constants.ts b/packages/start-plugin-core/src/hydration-constants.ts new file mode 100644 index 0000000000..b79c20ffd3 --- /dev/null +++ b/packages/start-plugin-core/src/hydration-constants.ts @@ -0,0 +1 @@ +export const tssHydrate = 'tss-hydrate' diff --git a/packages/start-plugin-core/src/rsbuild/normalized-client-build.ts b/packages/start-plugin-core/src/rsbuild/normalized-client-build.ts index b349b68040..60244fdca9 100644 --- a/packages/start-plugin-core/src/rsbuild/normalized-client-build.ts +++ b/packages/start-plugin-core/src/rsbuild/normalized-client-build.ts @@ -1,4 +1,5 @@ import { tsrSplit } from '@tanstack/router-plugin' +import { tssHydrate } from '../hydration-constants' import { getCssAssetSource } from '../start-manifest-plugin/inlineCss' import { RSBUILD_ENVIRONMENT_NAMES } from './planning' import type { RsbuildPluginAPI, Rspack } from '@rsbuild/core' @@ -57,6 +58,39 @@ function getRouteFilePathsFromModules( return routeFilePaths ?? [] } +function getHydrationIdsFromModules( + modules: Array, +): Array { + let hydrationIds: Array | undefined + let seen: Set | undefined + + for (const mod of modules) { + const identifier = mod.identifier() + const lastBangIndex = identifier.lastIndexOf('!') + const resourcePart = + lastBangIndex >= 0 ? identifier.slice(lastBangIndex + 1) : identifier + + const queryIndex = resourcePart.indexOf('?') + if (queryIndex < 0) continue + + const query = resourcePart.slice(queryIndex + 1) + if (!query.includes(tssHydrate)) continue + + const hydrationId = new URLSearchParams(query).get(tssHydrate) + if (!hydrationId || seen?.has(hydrationId)) continue + + if (!hydrationIds || !seen) { + hydrationIds = [] + seen = new Set() + } + + hydrationIds.push(hydrationId) + seen.add(hydrationId) + } + + return hydrationIds ?? [] +} + /** * Returns true for Rspack/webpack HMR runtime chunks that should never be * surfaced to the Start manifest. These files are emitted on every rebuild @@ -186,6 +220,7 @@ export function normalizeRspackClientBuild( for (const chunk of compilation.chunks) { const modules = compilation.chunkGraph.getChunkModules(chunk) const routeFilePaths = getRouteFilePathsFromModules(modules) + const hydrationIds = getHydrationIdsFromModules(modules) const cssFiles: Array = [] const seenCssFiles = new Set() @@ -242,6 +277,7 @@ export function normalizeRspackClientBuild( dynamicImports, css: [], routeFilePaths, + hydrationIds, } chunksByFileName.set(file, normalizedChunk) diff --git a/packages/start-plugin-core/src/rsbuild/start-compiler-host.ts b/packages/start-plugin-core/src/rsbuild/start-compiler-host.ts index 066d5b2867..d0ef77e34b 100644 --- a/packages/start-plugin-core/src/rsbuild/start-compiler-host.ts +++ b/packages/start-plugin-core/src/rsbuild/start-compiler-host.ts @@ -5,15 +5,19 @@ import { detectKindsInCode } from '../start-compiler/compiler' import { getTransformCodeFilterForEnv } from '../start-compiler/config' import { createStartCompiler, + loadCompilerVirtualModule, matchesCodeFilters, mergeServerFnsById, } from '../start-compiler/host' import { cleanId } from '../start-compiler/utils' +import { createHydrateCompilerPlugin } from '../hydrate-when-transform' import { RSBUILD_ENVIRONMENT_NAMES } from './planning' import type { RsbuildPluginAPI, Rspack } from '@rsbuild/core' import type { CompileStartFrameworkOptions, StartCompilerImportTransform, + StartCompilerPlugin, + StartCompilerTransformResult, } from '../types' import type { DevServerFnModuleSpecifierEncoder, @@ -27,7 +31,7 @@ type RsbuildTransformContext = Parameters< type RsbuildInputFileSystem = NonNullable /** - * Rsbuild dev server fn ref strategy: uses file:// URLs for absolute paths. + * Rsbuild dev server fn ref when: uses file:// URLs for absolute paths. * These are directly importable by Node's ESM VM runner without any bundler * path conventions (unlike Vite's /@id/ prefix). */ @@ -40,6 +44,7 @@ export interface StartCompilerHostOptions { providerEnvName: string generateFunctionId?: GenerateFunctionIdFnOptional compilerTransforms?: Array | undefined + compilerPlugins?: Array | undefined serverFnProviderModuleDirectives?: ReadonlyArray | undefined serverFnsById?: Record onServerFnsByIdChange?: () => void @@ -69,6 +74,10 @@ export function registerStartCompilerTransforms( mergeServerFnsById(serverFnsById, d) opts.onServerFnsByIdChange?.() } + const compilerPlugins = [ + createHydrateCompilerPlugin(), + ...(opts.compilerPlugins ?? []), + ] const isDev = api.context.action === 'dev' const mode = isDev ? 'dev' : 'build' @@ -83,9 +92,12 @@ export function registerStartCompilerTransforms( // Pre-compute code filter patterns per environment type const codeFilters: Record<'client' | 'server', Array> = { - client: getTransformCodeFilterForEnv('client'), + client: getTransformCodeFilterForEnv('client', { + compilerPlugins, + }), server: getTransformCodeFilterForEnv('server', { compilerTransforms: opts.compilerTransforms, + compilerPlugins, }), } @@ -109,17 +121,36 @@ export function registerStartCompilerTransforms( async (ctx: RsbuildTransformContext) => { return transformContextStorage.run(ctx, async () => { const code = ctx.code + let nextCode = code + let previousResult: { + code: string + map: StartCompilerTransformResult['map'] + } | null = null const id = ctx.resourcePath + (ctx.resourceQuery || '') + const root = getRoot() + + const virtualResult = loadCompilerVirtualModule(compilerPlugins, { + code, + id, + root, + env: env.type, + envName: env.name, + }) + if (virtualResult) { + nextCode = virtualResult.code + previousResult = { + code: virtualResult.code, + map: virtualResult.map ?? null, + } + } // Quick string-level check: does this file contain any patterns for this env? - if (!matchesCodeFilters(code, envCodeFilters)) { - return code + if (!matchesCodeFilters(nextCode, envCodeFilters)) { + return previousResult ?? nextCode } let compiler = compilers.get(env.name) if (!compiler) { - const root = getRoot() - compiler = createStartCompiler({ env: env.type, envName: env.name, @@ -129,6 +160,7 @@ export function registerStartCompilerTransforms( providerEnvName: opts.providerEnvName, generateFunctionId: opts.generateFunctionId, compilerTransforms, + compilerPlugins, serverFnProviderModuleDirectives, onServerFnsById, getKnownServerFns: () => serverFnsById, @@ -197,19 +229,23 @@ export function registerStartCompilerTransforms( compilers.set(env.name, compiler) } - const detectedKinds = detectKindsInCode(code, env.type, { + const detectedKinds = detectKindsInCode(nextCode, env.type, { compilerTransforms, }) - const result = await compiler.compile({ id, code, detectedKinds }) + const result = await compiler.compile({ + id, + code: nextCode, + detectedKinds, + }) - if (!result) { - return code + if (result) { + return { + code: result.code, + map: result.map ?? null, + } } - return { - code: result.code, - map: result.map ?? null, - } + return previousResult ?? nextCode }) }, ) diff --git a/packages/start-plugin-core/src/start-compiler/compiler.ts b/packages/start-plugin-core/src/start-compiler/compiler.ts index e742a75d41..458c467e4d 100644 --- a/packages/start-plugin-core/src/start-compiler/compiler.ts +++ b/packages/start-plugin-core/src/start-compiler/compiler.ts @@ -1,8 +1,8 @@ -/* eslint-disable import/no-commonjs */ import crypto from 'node:crypto' import * as t from '@babel/types' import { deadCodeElimination, + extractModuleInfoFromAst, findReferencedIdentifiers, generateFromAst, parseAst, @@ -21,28 +21,26 @@ import type { RewriteCandidate, ServerFn, } from './types' +import type { ModuleInfoBinding } from '@tanstack/router-utils' import type { CompileStartFrameworkOptions, StartCompilerEnvironment, StartCompilerImportTransform, + StartCompilerPlugin, + StartCompilerTransformResult, } from '../types' -type Binding = - | { - type: 'import' - source: string - importedName: string - resolvedKind?: Kind - } - | { - type: 'var' - init: t.Expression | null - resolvedKind?: Kind - } +type Binding = ModuleInfoBinding & { + resolvedKind?: Kind +} type ImportBinding = Extract type Kind = 'None' | `Root` | `Builder` | LookupKind +type ParsedAst = ReturnType +type StartCompilerAstPlugin = StartCompilerPlugin & { + transformAst: NonNullable +} export type BuiltInLookupKind = | 'ServerFn' @@ -86,11 +84,28 @@ export function isCompilerTransformEnabledForEnv( transform: StartCompilerImportTransform, env: StartCompilerEnvironment, ): boolean { - if (!transform.environment) return true - if (Array.isArray(transform.environment)) { - return transform.environment.includes(env) + return isStartCompilerEnvironmentEnabled(transform.environment, env) +} + +export function isStartCompilerPluginEnabledForEnv( + plugin: StartCompilerPlugin, + env: StartCompilerEnvironment, +): boolean { + return isStartCompilerEnvironmentEnabled(plugin.environment, env) +} + +function isStartCompilerEnvironmentEnabled( + environment: + | StartCompilerEnvironment + | Array + | undefined, + env: StartCompilerEnvironment, +): boolean { + if (!environment) return true + if (Array.isArray(environment)) { + return environment.includes(env) } - return transform.environment === env + return environment === env } const BuiltInLookupSetup: Record< @@ -219,13 +234,16 @@ export function detectKindsInCode( const validForEnv = getLookupKindsForEnv(env, opts) for (const kind of AllBuiltInLookupKinds) { - if (validForEnv.has(kind) && KindDetectionPatterns[kind].test(code)) { + const pattern = KindDetectionPatterns[kind] + pattern.lastIndex = 0 + if (validForEnv.has(kind) && pattern.test(code)) { detected.add(kind) } } for (const transform of opts?.compilerTransforms ?? []) { if (!isCompilerTransformEnabledForEnv(transform, env)) continue + transform.detect.lastIndex = 0 if (transform.detect.test(code)) { detected.add(getExternalLookupKind(transform)) } @@ -464,6 +482,7 @@ export class StartCompiler { StartCompilerImportTransform >() private externalLookupSetup = new Map() + private compilerPlugins: Array private externalDirectCallKindsBySource = new Map< string, Map @@ -517,6 +536,7 @@ export class StartCompiler { */ onServerFnsById?: (d: Record) => void compilerTransforms?: Array | undefined + compilerPlugins?: Array | undefined serverFnProviderModuleDirectives?: ReadonlyArray | undefined /** * Returns the currently known server functions from previous builds. @@ -527,6 +547,10 @@ export class StartCompiler { }, ) { this.validLookupKinds = options.lookupKinds + this.compilerPlugins = (options.compilerPlugins ?? []).filter((plugin) => + isStartCompilerPluginEnabledForEnv(plugin, options.env), + ) + for (const transform of options.compilerTransforms ?? []) { const kind = getExternalLookupKind(transform) if (!this.validLookupKinds.has(kind)) continue @@ -775,100 +799,13 @@ export class StartCompiler { ast: ReturnType, id: string, ): ModuleInfo { - const bindings = new Map() - const exports = new Map() - const reExportAllSources: Array = [] - - // we are only interested in top-level bindings, hence we don't traverse the AST - // instead we only iterate over the program body - for (const node of ast.program.body) { - if (t.isImportDeclaration(node)) { - const source = node.source.value - for (const s of node.specifiers) { - if (t.isImportSpecifier(s)) { - const importedName = t.isIdentifier(s.imported) - ? s.imported.name - : s.imported.value - bindings.set(s.local.name, { type: 'import', source, importedName }) - } else if (t.isImportDefaultSpecifier(s)) { - bindings.set(s.local.name, { - type: 'import', - source, - importedName: 'default', - }) - } else if (t.isImportNamespaceSpecifier(s)) { - bindings.set(s.local.name, { - type: 'import', - source, - importedName: '*', - }) - } - } - } else if (t.isVariableDeclaration(node)) { - for (const decl of node.declarations) { - if (t.isIdentifier(decl.id)) { - bindings.set(decl.id.name, { - type: 'var', - init: decl.init ?? null, - }) - } - } - } else if (t.isExportNamedDeclaration(node)) { - // export const foo = ... - if (node.declaration) { - if (t.isVariableDeclaration(node.declaration)) { - for (const d of node.declaration.declarations) { - if (t.isIdentifier(d.id)) { - exports.set(d.id.name, d.id.name) - bindings.set(d.id.name, { type: 'var', init: d.init ?? null }) - } - } - } - } - for (const sp of node.specifiers) { - if (t.isExportNamespaceSpecifier(sp)) { - exports.set(sp.exported.name, sp.exported.name) - } - // export { local as exported } - else if (t.isExportSpecifier(sp)) { - const local = sp.local.name - const exported = t.isIdentifier(sp.exported) - ? sp.exported.name - : sp.exported.value - exports.set(exported, local) - - // When re-exporting from another module (export { foo } from './module'), - // create an import binding so the server function can be resolved - if (node.source) { - bindings.set(local, { - type: 'import', - source: node.source.value, - importedName: local, - }) - } - } - } - } else if (t.isExportDefaultDeclaration(node)) { - const d = node.declaration - if (t.isIdentifier(d)) { - exports.set('default', d.name) - } else { - const synth = '__default_export__' - bindings.set(synth, { type: 'var', init: d as t.Expression }) - exports.set('default', synth) - } - } else if (t.isExportAllDeclaration(node)) { - // Handle `export * from './module'` syntax - // Track the source so we can look up exports from it when needed - reExportAllSources.push(node.source.value) - } - } + const extracted = extractModuleInfoFromAst(ast) const info: ModuleInfo = { id, - bindings, - exports, - reExportAllSources, + bindings: new Map(extracted.bindings), + exports: extracted.exports, + reExportAllSources: extracted.reExportAllSources, } this.moduleCache.set(id, info) return info @@ -889,13 +826,30 @@ export class StartCompiler { } public invalidateModule(id: string) { - const normalizedId = cleanId(id) - let hasCachedModule = false + return this.invalidateModules([id]).size > 0 + } + + public invalidateModules(ids: Iterable): Set { + const normalizedIds = new Set() + + for (const id of ids) { + normalizedIds.add(cleanId(id)) + + for (const plugin of this.compilerPlugins) { + plugin.invalidateModule?.({ id, envName: this.options.envName }) + } + } + + const deletedModuleIds = new Set() + if (normalizedIds.size === 0) { + return deletedModuleIds + } for (const moduleId of Array.from(this.moduleCache.keys())) { - if (cleanId(moduleId) === normalizedId) { + const normalizedModuleId = cleanId(moduleId) + if (normalizedIds.has(normalizedModuleId)) { this.moduleCache.delete(moduleId) - hasCachedModule = true + deletedModuleIds.add(normalizedModuleId) } } @@ -915,14 +869,20 @@ export class StartCompiler { this.resolveIdCache.clear() this.exportResolutionCache.clear() - return hasCachedModule + return deletedModuleIds } - public async getTransitiveImporters(id: string): Promise> { + public async getTransitiveImporters( + ids: string | Iterable, + ): Promise> { const discoveredImporters = new Set() - const pendingTargets = [cleanId(id)] + const pendingTargets = + typeof ids === 'string' + ? [cleanId(ids)] + : Array.from(ids, (id) => cleanId(id)) const visitedTargets = new Set() const resolveCache = new Map>() + const importersByTarget = new Map>() const resolveSource = (source: string, importer: string) => { const cacheKey = `${importer}::${source}` @@ -936,6 +896,40 @@ export class StartCompiler { return resolved } + await Promise.all( + Array.from(this.moduleCache.values()).map(async (moduleInfo) => { + if (this.knownRootImports.has(moduleInfo.id)) { + return + } + + const moduleId = cleanId(moduleInfo.id) + const importSources = new Set(moduleInfo.reExportAllSources) + + for (const binding of moduleInfo.bindings.values()) { + if (binding.type === 'import') { + importSources.add(binding.source) + } + } + + await Promise.all( + Array.from(importSources, async (source) => { + const resolved = await resolveSource(source, moduleInfo.id) + if (!resolved) return + + const targetId = cleanId(resolved) + if (targetId === moduleId) return + + let importers = importersByTarget.get(targetId) + if (!importers) { + importers = new Set() + importersByTarget.set(targetId, importers) + } + importers.add(moduleId) + }), + ) + }), + ) + while (pendingTargets.length > 0) { const targetId = pendingTargets.pop()! @@ -945,40 +939,8 @@ export class StartCompiler { visitedTargets.add(targetId) - const importerIds = await Promise.all( - Array.from(this.moduleCache.values()).map(async (moduleInfo) => { - if (this.knownRootImports.has(moduleInfo.id)) { - return null - } - - const moduleId = cleanId(moduleInfo.id) - - if (moduleId === targetId) { - return null - } - - const importSources = new Set(moduleInfo.reExportAllSources) - - for (const binding of moduleInfo.bindings.values()) { - if (binding.type === 'import') { - importSources.add(binding.source) - } - } - - for (const source of importSources) { - const resolved = await resolveSource(source, moduleInfo.id) - - if (resolved && cleanId(resolved) === targetId) { - return moduleId - } - } - - return null - }), - ) - - for (const importerId of importerIds) { - if (!importerId || discoveredImporters.has(importerId)) { + for (const importerId of importersByTarget.get(targetId) ?? []) { + if (discoveredImporters.has(importerId)) { continue } @@ -1011,408 +973,435 @@ export class StartCompiler { ? new Set([...detectedKinds].filter((k) => this.validLookupKinds.has(k))) : this.validLookupKinds - // Early exit if no kinds to process - if (fileKinds.size === 0) { - return null - } - - const hasExternalKinds = hasExternalLookupKinds(fileKinds) - const checkDirectCalls = - hasBuiltInDirectCallKinds(fileKinds) || - (fileKinds.has('ServerFn') && - !hasExternalKinds && - hasBuiltInDirectCallKinds(this.validLookupKinds)) - // Optimization: ServerFn is always a top-level declaration (must be assigned to a variable). - // If the file only has ServerFn, we can skip full AST traversal and only visit - // the specific top-level declarations that have candidates. - const canUseFastPath = areAllKindsTopLevelOnly(fileKinds) - + const astTransformPlugins = this.getAstTransformPluginsForCode(code) // Always parse and extract module info upfront. // This ensures the module is cached for import resolution even if no candidates are found. - const { ast } = this.ingestModule({ code, id, parserFilename }) + const ast = this.ingestModule({ code, id, parserFilename }).ast + let astHasChanges = false - // Single-pass traversal to: - // 1. Collect candidate paths (only candidates, not all CallExpressions) - // 2. Build a map for looking up paths of nested calls in method chains - const candidatePaths: Array = [] - // Map for nested chain lookup - only populated for CallExpressions that are - // part of a method chain (callee.object is a CallExpression) - const chainCallPaths = new Map< - t.CallExpression, - babel.NodePath - >() + builtInTransforms: { + // Early exit if no built-in or import transforms need this file. + if (fileKinds.size === 0) { + break builtInTransforms + } - // JSX candidates (e.g., ) - const jsxCandidatePaths: Array> = [] - const checkJSX = needsJSXDetection(fileKinds, this.externalLookupSetup) - // Get module info that was just cached by ingestModule - const moduleInfo = this.moduleCache.get(id)! - const externalDirectCallCandidates = this.getExternalDirectCallCandidates( - fileKinds, - moduleInfo, - ) - const checkExternalDirectCalls = hasExternalDirectCallCandidates( - externalDirectCallCandidates, - ) + const hasExternalKinds = hasExternalLookupKinds(fileKinds) + const checkDirectCalls = + hasBuiltInDirectCallKinds(fileKinds) || + (fileKinds.has('ServerFn') && + !hasExternalKinds && + hasBuiltInDirectCallKinds(this.validLookupKinds)) + // Optimization: ServerFn is always a top-level declaration (must be assigned to a variable). + // If the file only has ServerFn, we can skip full AST traversal and only visit + // the specific top-level declarations that have candidates. + const canUseFastPath = areAllKindsTopLevelOnly(fileKinds) - if (canUseFastPath) { - // Fast path: only visit top-level statements that have potential candidates + // Single-pass traversal to: + // 1. Collect candidate paths (only candidates, not all CallExpressions) + // 2. Build a map for looking up paths of nested calls in method chains + const candidatePaths: Array = [] + // Map for nested chain lookup - only populated for CallExpressions that are + // part of a method chain (callee.object is a CallExpression) + const chainCallPaths = new Map< + t.CallExpression, + babel.NodePath + >() - // Collect indices of top-level statements that contain candidates - const candidateIndices: Array = [] - for (let i = 0; i < ast.program.body.length; i++) { - const node = ast.program.body[i]! - let declarations: Array | undefined + // JSX candidates (e.g., ) + const jsxCandidatePaths: Array> = [] + const checkJSX = needsJSXDetection(fileKinds, this.externalLookupSetup) + // Get module info that was just cached by ingestModule + const moduleInfo = this.moduleCache.get(id)! + const externalDirectCallCandidates = this.getExternalDirectCallCandidates( + fileKinds, + moduleInfo, + ) + const checkExternalDirectCalls = hasExternalDirectCallCandidates( + externalDirectCallCandidates, + ) - if (t.isVariableDeclaration(node)) { - declarations = node.declarations - } else if (t.isExportNamedDeclaration(node) && node.declaration) { - if (t.isVariableDeclaration(node.declaration)) { - declarations = node.declaration.declarations + if (canUseFastPath) { + // Fast path: only visit top-level statements that have potential candidates + + // Collect indices of top-level statements that contain candidates + const candidateIndices: Array = [] + for (let i = 0; i < ast.program.body.length; i++) { + const node = ast.program.body[i]! + let declarations: Array | undefined + + if (t.isVariableDeclaration(node)) { + declarations = node.declarations + } else if (t.isExportNamedDeclaration(node) && node.declaration) { + if (t.isVariableDeclaration(node.declaration)) { + declarations = node.declaration.declarations + } } - } - if (declarations) { - for (const decl of declarations) { - if (decl.init && t.isCallExpression(decl.init)) { - if ( - isMethodChainCandidate(decl.init, fileKinds) || - (checkDirectCalls && - isTopLevelDirectCallCandidateNode(decl.init)) - ) { - candidateIndices.push(i) - break // Only need to mark this statement once + if (declarations) { + for (const decl of declarations) { + if (decl.init && t.isCallExpression(decl.init)) { + if ( + isMethodChainCandidate(decl.init, fileKinds) || + (checkDirectCalls && + isTopLevelDirectCallCandidateNode(decl.init)) + ) { + candidateIndices.push(i) + break // Only need to mark this statement once + } } } } } - } - // Early exit: no potential candidates found at top level - if (candidateIndices.length === 0) { - return null - } + // Early exit: no potential candidates found at top level + if (candidateIndices.length === 0) { + break builtInTransforms + } - // Targeted traversal: only visit the specific statements that have candidates - // This is much faster than traversing the entire AST - babel.traverse(ast, { - Program(programPath) { - const bodyPaths = programPath.get('body') - for (const idx of candidateIndices) { - const stmtPath = bodyPaths[idx] - if (!stmtPath) continue + // Targeted traversal: only visit the specific statements that have candidates + // This is much faster than traversing the entire AST + babel.traverse(ast, { + Program(programPath) { + const bodyPaths = programPath.get('body') + for (const idx of candidateIndices) { + const stmtPath = bodyPaths[idx] + if (!stmtPath) continue - // Traverse only this statement's subtree - stmtPath.traverse({ - CallExpression(path) { - const node = path.node - const parent = path.parent + // Traverse only this statement's subtree + stmtPath.traverse({ + CallExpression(path) { + const node = path.node + const parent = path.parent - // Check if this call is part of a larger chain (inner call) - if ( - t.isMemberExpression(parent) && - t.isCallExpression(path.parentPath.parent) - ) { - chainCallPaths.set(node, path) - return - } - - // Method chain pattern - if (isMethodChainCandidate(node, fileKinds)) { - candidatePaths.push({ path }) - return - } - - if (checkExternalDirectCalls) { - const kind = getExternalDirectCallCandidateKind( - path, - externalDirectCallCandidates, - ) - if (kind) { - candidatePaths.push({ path, kind }) + // Check if this call is part of a larger chain (inner call) + if ( + t.isMemberExpression(parent) && + t.isCallExpression(path.parentPath.parent) + ) { + chainCallPaths.set(node, path) return } - } - if (isTopLevelDirectCallCandidate(path)) { - candidatePaths.push({ path }) - } - }, - }) - } - // Stop traversal after processing Program - programPath.stop() - }, - }) - } else { - // Normal path: full traversal for non-fast-path kinds - babel.traverse(ast, { - CallExpression: (path) => { - const node = path.node - const parent = path.parent + // Method chain pattern + if (isMethodChainCandidate(node, fileKinds)) { + candidatePaths.push({ path }) + return + } - // Check if this call is part of a larger chain (inner call) - // If so, store it for method chain lookup but don't treat as candidate - if ( - t.isMemberExpression(parent) && - t.isCallExpression(path.parentPath.parent) - ) { - // This is an inner call in a chain - store for later lookup - chainCallPaths.set(node, path) - return - } + if (checkExternalDirectCalls) { + const kind = getExternalDirectCallCandidateKind( + path, + externalDirectCallCandidates, + ) + if (kind) { + candidatePaths.push({ path, kind }) + return + } + } - // Pattern 1: Method chain pattern (.handler(), .server(), .client(), etc.) - if (isMethodChainCandidate(node, fileKinds)) { - candidatePaths.push({ path }) - return - } + if (isTopLevelDirectCallCandidate(path)) { + candidatePaths.push({ path }) + } + }, + }) + } + // Stop traversal after processing Program + programPath.stop() + }, + }) + } else { + // Normal path: full traversal for non-fast-path kinds + babel.traverse(ast, { + CallExpression: (path) => { + const node = path.node + const parent = path.parent - // External direct-call transforms are import-bound. Direct imports - // already identify the transform kind, so skip async import tracing. - if (checkExternalDirectCalls) { - const kind = getExternalDirectCallCandidateKind( - path, - externalDirectCallCandidates, - ) - if (kind) { - candidatePaths.push({ path, kind }) + // Check if this call is part of a larger chain (inner call) + // If so, store it for method chain lookup but don't treat as candidate + if ( + t.isMemberExpression(parent) && + t.isCallExpression(path.parentPath.parent) + ) { + // This is an inner call in a chain - store for later lookup + chainCallPaths.set(node, path) return } - } - if (checkDirectCalls && isTopLevelDirectCallCandidate(path)) { - candidatePaths.push({ path }) - return - } - - // Pattern 2: Direct call pattern - if (checkDirectCalls) { - if ( - isNestedDirectCallCandidate( - node, - fileKinds, - this.externalLookupSetup, - ) - ) { + // Pattern 1: Method chain pattern (.handler(), .server(), .client(), etc.) + if (isMethodChainCandidate(node, fileKinds)) { candidatePaths.push({ path }) return } - } - }, - // Pattern 3: JSX element pattern (e.g., ) - // Collect JSX elements where the component is imported from a known package - // and resolves to a JSX kind (e.g., ClientOnly from @tanstack/react-router) - JSXElement: (path) => { - if (!checkJSX) return - const openingElement = path.node.openingElement - const nameNode = openingElement.name + // External direct-call transforms are import-bound. Direct imports + // already identify the transform kind, so skip async import tracing. + if (checkExternalDirectCalls) { + const kind = getExternalDirectCallCandidateKind( + path, + externalDirectCallCandidates, + ) + if (kind) { + candidatePaths.push({ path, kind }) + return + } + } - // Only handle simple identifier names (not namespaced or member expressions) - if (!t.isJSXIdentifier(nameNode)) return + if (checkDirectCalls && isTopLevelDirectCallCandidate(path)) { + candidatePaths.push({ path }) + return + } - const componentName = nameNode.name - const binding = moduleInfo.bindings.get(componentName) + // Pattern 2: Direct call pattern + if (checkDirectCalls) { + if ( + isNestedDirectCallCandidate( + node, + fileKinds, + this.externalLookupSetup, + ) + ) { + candidatePaths.push({ path }) + return + } + } + }, + // Pattern 3: JSX element pattern (e.g., ) + // Collect JSX elements where the component is imported from a known package + // and resolves to a JSX kind (e.g., ClientOnly from @tanstack/react-router) + JSXElement: (path) => { + if (!checkJSX) return - // Must be an import binding from a known package - if (!binding || binding.type !== 'import') return + const openingElement = path.node.openingElement + const nameNode = openingElement.name - // Verify the import source is a known TanStack router package - const knownExports = this.knownRootImports.get(binding.source) - if (!knownExports) return + // Only handle simple identifier names (not namespaced or member expressions) + if (!t.isJSXIdentifier(nameNode)) return - // Verify the imported name resolves to a JSX kind (e.g., ClientOnlyJSX) - const kind = knownExports.get(binding.importedName) - if (kind !== 'ClientOnlyJSX') return + const componentName = nameNode.name + const binding = moduleInfo.bindings.get(componentName) - jsxCandidatePaths.push(path) - }, - }) - } + // Must be an import binding from a known package + if (!binding || binding.type !== 'import') return - if (candidatePaths.length === 0 && jsxCandidatePaths.length === 0) { - return null - } + // Verify the import source is a known TanStack router package + const knownExports = this.knownRootImports.get(binding.source) + if (!knownExports) return - // Resolve only candidates whose import scan did not already prove the kind. - const resolvedCandidates: Array<{ - path: babel.NodePath - kind: Kind - }> = [] - const unresolvedCandidates: Array = [] + // Verify the imported name resolves to a JSX kind (e.g., ClientOnlyJSX) + const kind = knownExports.get(binding.importedName) + if (kind !== 'ClientOnlyJSX') return - for (const candidate of candidatePaths) { - if (candidate.kind) { - resolvedCandidates.push({ - path: candidate.path, - kind: candidate.kind, + jsxCandidatePaths.push(path) + }, }) - } else { - unresolvedCandidates.push(candidate) } - } - if (unresolvedCandidates.length > 0) { - resolvedCandidates.push( - ...(await Promise.all( - unresolvedCandidates.map(async (candidate) => ({ + if (candidatePaths.length === 0 && jsxCandidatePaths.length === 0) { + break builtInTransforms + } + + // Resolve only candidates whose import scan did not already prove the kind. + const resolvedCandidates: Array<{ + path: babel.NodePath + kind: Kind + }> = [] + const unresolvedCandidates: Array = [] + + for (const candidate of candidatePaths) { + if (candidate.kind) { + resolvedCandidates.push({ path: candidate.path, - kind: await this.resolveExprKind(candidate.path.node, id), - })), - )), - ) - } - - // Filter to valid candidates - const validCandidates = resolvedCandidates.filter(({ path, kind }) => { - if ( - !this.validLookupKinds.has(kind as Exclude) - ) { - return false + kind: candidate.kind, + }) + } else { + unresolvedCandidates.push(candidate) + } } - if ( - isLookupKind(kind) && - kind !== 'ClientOnlyJSX' && - !isMethodChainCandidate(path.node, fileKinds) - ) { - return isDirectCallCandidateForKind(kind, this.externalLookupSetup) + if (unresolvedCandidates.length > 0) { + resolvedCandidates.push( + ...(await Promise.all( + unresolvedCandidates.map(async (candidate) => ({ + path: candidate.path, + kind: await this.resolveExprKind(candidate.path.node, id), + })), + )), + ) } - return true - }) as Array<{ - path: babel.NodePath - kind: Exclude - }> - - if (validCandidates.length === 0 && jsxCandidatePaths.length === 0) { - return null - } - - // Process valid candidates to collect method chains - const pathsToRewrite: Array<{ - path: babel.NodePath - kind: Exclude - methodChain: MethodChainPaths - }> = [] - - for (const { path, kind } of validCandidates) { - const node = path.node - - // Collect method chain paths by walking DOWN from root through the chain - const methodChain: MethodChainPaths = { - middleware: null, - inputValidator: null, - handler: null, - server: null, - client: null, - } - - // Walk down the call chain using nodes, look up paths from map - let currentNode: t.CallExpression = node - let currentPath: babel.NodePath = path - - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - while (true) { - const callee = currentNode.callee - if (!t.isMemberExpression(callee)) { - break + // Filter to valid candidates + const validCandidates = resolvedCandidates.filter(({ path, kind }) => { + if ( + !this.validLookupKinds.has( + kind as Exclude, + ) + ) { + return false } - // Record method chain path if it's a known method - if (t.isIdentifier(callee.property)) { - const name = callee.property.name as keyof MethodChainPaths - if (name in methodChain) { - // Get first argument path - const args = currentPath.get('arguments') - const firstArgPath = - Array.isArray(args) && args.length > 0 ? (args[0] ?? null) : null - methodChain[name] = { - callPath: currentPath, - firstArgPath, + if ( + isLookupKind(kind) && + kind !== 'ClientOnlyJSX' && + !isMethodChainCandidate(path.node, fileKinds) + ) { + return isDirectCallCandidateForKind(kind, this.externalLookupSetup) + } + + return true + }) as Array<{ + path: babel.NodePath + kind: Exclude + }> + + if (validCandidates.length === 0 && jsxCandidatePaths.length === 0) { + break builtInTransforms + } + + // Process valid candidates to collect method chains + const pathsToRewrite: Array<{ + path: babel.NodePath + kind: Exclude + methodChain: MethodChainPaths + }> = [] + + for (const { path, kind } of validCandidates) { + const node = path.node + + // Collect method chain paths by walking DOWN from root through the chain + const methodChain: MethodChainPaths = { + middleware: null, + inputValidator: null, + handler: null, + server: null, + client: null, + } + + // Walk down the call chain using nodes, look up paths from map + let currentNode: t.CallExpression = node + let currentPath: babel.NodePath = path + + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + while (true) { + const callee = currentNode.callee + if (!t.isMemberExpression(callee)) { + break + } + + // Record method chain path if it's a known method + if (t.isIdentifier(callee.property)) { + const name = callee.property.name as keyof MethodChainPaths + if (name in methodChain) { + // Get first argument path + const args = currentPath.get('arguments') + const firstArgPath = + Array.isArray(args) && args.length > 0 + ? (args[0] ?? null) + : null + methodChain[name] = { + callPath: currentPath, + firstArgPath, + } } } + + // Move to the inner call (the object of the member expression) + if (!t.isCallExpression(callee.object)) { + break + } + currentNode = callee.object + // Look up path from chain map, or use candidate path if not found + const nextPath = chainCallPaths.get(currentNode) + if (!nextPath) { + break + } + currentPath = nextPath } - // Move to the inner call (the object of the member expression) - if (!t.isCallExpression(callee.object)) { - break - } - currentNode = callee.object - // Look up path from chain map, or use candidate path if not found - const nextPath = chainCallPaths.get(currentNode) - if (!nextPath) { - break - } - currentPath = nextPath + pathsToRewrite.push({ path, kind, methodChain }) } - pathsToRewrite.push({ path, kind, methodChain }) - } + const refIdents = findReferencedIdentifiers(ast) - const refIdents = findReferencedIdentifiers(ast) + const context: CompilationContext = { + ast, + id, + code, + env: this.options.env, + envName: this.options.envName, + mode: this.mode, + root: this.options.root, + framework: this.options.framework, + providerEnvName: this.options.providerEnvName, + types: t, + parseExpression: (expressionCode) => + babel.template.expression(expressionCode, { + placeholderPattern: false, + })() as t.Expression, - const context: CompilationContext = { - ast, - id, - code, - env: this.options.env, - envName: this.options.envName, - mode: this.mode, - root: this.options.root, - framework: this.options.framework, - providerEnvName: this.options.providerEnvName, - types: t, - parseExpression: (expressionCode) => - babel.template.expression(expressionCode, { - placeholderPattern: false, - })() as t.Expression, - - generateFunctionId: (opts) => this.generateFunctionId(opts), - getKnownServerFns: this.options.getKnownServerFns, - serverFnProviderModuleDirectives: - this.options.serverFnProviderModuleDirectives, - onServerFnsById: this.options.onServerFnsById, - } - - // Group candidates by kind for batch processing - const candidatesByKind = new Map< - Exclude, - Array - >() - - for (const { path: candidatePath, kind, methodChain } of pathsToRewrite) { - const candidate: RewriteCandidate = { path: candidatePath, methodChain } - const existing = candidatesByKind.get(kind) - if (existing) { - existing.push(candidate) - } else { - candidatesByKind.set(kind, [candidate]) + generateFunctionId: (opts) => this.generateFunctionId(opts), + getKnownServerFns: this.options.getKnownServerFns, + serverFnProviderModuleDirectives: + this.options.serverFnProviderModuleDirectives, + onServerFnsById: this.options.onServerFnsById, } + + // Group candidates by kind for batch processing + const candidatesByKind = new Map< + Exclude, + Array + >() + + for (const { path: candidatePath, kind, methodChain } of pathsToRewrite) { + const candidate: RewriteCandidate = { path: candidatePath, methodChain } + const existing = candidatesByKind.get(kind) + if (existing) { + existing.push(candidate) + } else { + candidatesByKind.set(kind, [candidate]) + } + } + + // External transforms run before built-ins by default so they can augment + // user handlers before server function extraction clones provider bodies. + this.runExternalTransforms('pre', candidatesByKind, context) + + for (const kind of BuiltInKindHandlerOrder) { + const candidates = candidatesByKind.get(kind) + if (!candidates) continue + const handler = BuiltInKindHandlers[kind] + handler(candidates, context, kind) + } + + this.runExternalTransforms('post', candidatesByKind, context) + + // Handle JSX candidates (e.g., ) + // Validation was already done during traversal - just call the handler + for (const jsxPath of jsxCandidatePaths) { + handleClientOnlyJSX(jsxPath, { env: 'server' }) + } + + deadCodeElimination(ast, refIdents) + astHasChanges = true } - // External transforms run before built-ins by default so they can augment - // user handlers before server function extraction clones provider bodies. - this.runExternalTransforms('pre', candidatesByKind, context) - - for (const kind of BuiltInKindHandlerOrder) { - const candidates = candidatesByKind.get(kind) - if (!candidates) continue - const handler = BuiltInKindHandlers[kind] - handler(candidates, context, kind) + if (astTransformPlugins.length > 0) { + astHasChanges = + this.runAstTransforms({ + ast, + code, + id, + transforms: astTransformPlugins, + }) || astHasChanges } - this.runExternalTransforms('post', candidatesByKind, context) - - // Handle JSX candidates (e.g., ) - // Validation was already done during traversal - just call the handler - for (const jsxPath of jsxCandidatePaths) { - handleClientOnlyJSX(jsxPath, { env: 'server' }) - } - - deadCodeElimination(ast, refIdents) + return astHasChanges ? this.generateResultFromAst(ast, code, id) : null + } + private generateResultFromAst( + ast: ParsedAst, + sourceCode: string, + id: string, + ): StartCompilerTransformResult { const result = generateFromAst(ast, { sourceMaps: true, sourceFileName: id, @@ -1420,17 +1409,66 @@ export class StartCompiler { }) // @babel/generator does not populate sourcesContent because it only has - // the AST, not the original text. Without this, Vite's composed - // sourcemap omits the original source, causing downstream consumers - // (e.g. import-protection snippet display) to fall back to the shorter - // compiled output and fail to resolve original line numbers. + // the AST, not the original text. Without this, Vite's composed sourcemap + // omits the original source, causing downstream consumers to fall back to + // the compiled output and fail to resolve original line numbers. if (result.map) { - result.map.sourcesContent = [code] + result.map.sourcesContent = [sourceCode] } return result } + private getAstTransformPluginsForCode( + code: string, + ): Array { + return this.compilerPlugins.filter( + (plugin): plugin is StartCompilerAstPlugin => { + if (!plugin.transformAst) return false + if (!plugin.detect) return true + plugin.detect.lastIndex = 0 + return plugin.detect.test(code) + }, + ) + } + + private runAstTransforms({ + ast, + code, + id, + transforms, + }: { + ast: ParsedAst + code: string + id: string + transforms: Array + }): boolean { + let modified = false + + for (const plugin of transforms) { + const context = { + ast, + code, + id, + env: this.options.env, + envName: this.options.envName, + mode: this.mode, + root: this.options.root, + framework: this.options.framework, + providerEnvName: this.options.providerEnvName, + types: t, + parseExpression: (expressionCode: string) => + babel.template.expression(expressionCode, { + placeholderPattern: false, + })() as t.Expression, + } + + modified = plugin.transformAst(context) || modified + } + + return modified + } + private runExternalTransforms( order: 'pre' | 'post', candidatesByKind: Map< @@ -1608,8 +1646,8 @@ export class StartCompiler { return 'None' } - for (const [source, exports] of this.knownRootImports) { - const kind = exports.get(binding.importedName) + for (const [source, rootExports] of this.knownRootImports) { + const kind = rootExports.get(binding.importedName) if (!kind) { continue } diff --git a/packages/start-plugin-core/src/start-compiler/config.ts b/packages/start-plugin-core/src/start-compiler/config.ts index e9d7d95e5e..387343bad9 100644 --- a/packages/start-plugin-core/src/start-compiler/config.ts +++ b/packages/start-plugin-core/src/start-compiler/config.ts @@ -3,17 +3,20 @@ import { getExternalLookupKind, getLookupKindsForEnv, isCompilerTransformEnabledForEnv, + isStartCompilerPluginEnabledForEnv, } from './compiler' import type { BuiltInLookupKind, LookupConfig } from './compiler' import type { CompileStartFrameworkOptions, StartCompilerImportTransform, + StartCompilerPlugin, } from '../types' export function getTransformCodeFilterForEnv( env: 'client' | 'server', opts?: { compilerTransforms?: Array | undefined + compilerPlugins?: Array | undefined }, ): Array { const validKinds = getLookupKindsForEnv(env, opts) @@ -33,6 +36,12 @@ export function getTransformCodeFilterForEnv( } } + for (const plugin of opts?.compilerPlugins ?? []) { + if (plugin.detect && isStartCompilerPluginEnabledForEnv(plugin, env)) { + patterns.push(plugin.detect) + } + } + return patterns } diff --git a/packages/start-plugin-core/src/start-compiler/host.ts b/packages/start-plugin-core/src/start-compiler/host.ts index e1da89d7f2..c225347dea 100644 --- a/packages/start-plugin-core/src/start-compiler/host.ts +++ b/packages/start-plugin-core/src/start-compiler/host.ts @@ -3,6 +3,9 @@ import { getLookupConfigurationsForEnv } from './config' import type { CompileStartFrameworkOptions, StartCompilerImportTransform, + StartCompilerPlugin, + StartCompilerTransformResult, + StartCompilerVirtualModuleContext, } from '../types' import type { DevServerFnModuleSpecifierEncoder, @@ -19,6 +22,7 @@ export interface CreateStartCompilerOptions { mode: 'dev' | 'build' generateFunctionId?: GenerateFunctionIdFnOptional compilerTransforms?: Array | undefined + compilerPlugins?: Array | undefined serverFnProviderModuleDirectives?: ReadonlyArray | undefined onServerFnsById?: (d: Record) => void getKnownServerFns: () => Record @@ -48,6 +52,7 @@ export function createStartCompiler( generateFunctionId: options.generateFunctionId, onServerFnsById: options.onServerFnsById, compilerTransforms: options.compilerTransforms, + compilerPlugins: options.compilerPlugins, serverFnProviderModuleDirectives: options.serverFnProviderModuleDirectives, getKnownServerFns: options.getKnownServerFns, devServerFnModuleSpecifierEncoder: options.encodeModuleSpecifierInDev, @@ -81,6 +86,7 @@ export function matchesCodeFilters( filters: ReadonlyArray, ): boolean { for (const pattern of filters) { + pattern.lastIndex = 0 if (pattern.test(code)) { return true } @@ -88,3 +94,43 @@ export function matchesCodeFilters( return false } + +export function createCompilerVirtualModuleIdPattern( + compilerPlugins: ReadonlyArray, +) { + const patterns = compilerPlugins + .map((plugin) => plugin.virtualModuleIdPattern) + .filter((pattern): pattern is RegExp => !!pattern) + + if (patterns.length === 0) { + return undefined + } + + return new RegExp( + patterns.map((pattern) => `(?:${pattern.source})`).join('|'), + ) +} + +export function loadCompilerVirtualModule( + compilerPlugins: ReadonlyArray, + context: StartCompilerVirtualModuleContext, +): StartCompilerTransformResult | null { + for (const compilerPlugin of compilerPlugins) { + const pattern = compilerPlugin.virtualModuleIdPattern + if (!pattern) { + continue + } + + pattern.lastIndex = 0 + if (!pattern.test(context.id)) { + continue + } + + const result = compilerPlugin.loadVirtualModule?.(context) + if (result) { + return result + } + } + + return null +} diff --git a/packages/start-plugin-core/src/start-manifest-plugin/manifestBuilder.ts b/packages/start-plugin-core/src/start-manifest-plugin/manifestBuilder.ts index a3c991c4c7..6f27f37d4d 100644 --- a/packages/start-plugin-core/src/start-manifest-plugin/manifestBuilder.ts +++ b/packages/start-plugin-core/src/start-manifest-plugin/manifestBuilder.ts @@ -484,10 +484,35 @@ export function buildRouteManifestRoutes(options: { getChunkCssAssets, getChunkPreloads: options.assetResolvers.getChunkPreloads, }) + + if (routeId !== rootRouteId) { + mergeReachableHydrationChunkData({ + route: targetRoute, + chunk, + chunksByFileName: options.chunksByFileName, + getChunkCssAssets, + }) + } } } const rootRoute = (routes[rootRouteId] = routes[rootRouteId] || {}) + const rootRouteTreeRoute = options.routeTreeRoutes[rootRouteId] + const rootRouteChunks = rootRouteTreeRoute?.filePath + ? options.routeChunksByFilePath.get(rootRouteTreeRoute.filePath) + : undefined + + if (rootRouteChunks) { + for (const chunk of rootRouteChunks) { + mergeReachableHydrationChunkData({ + route: rootRoute, + chunk, + chunksByFileName: options.chunksByFileName, + getChunkCssAssets, + }) + } + } + mergeRouteChunkData({ route: rootRoute, chunk: options.entryChunk, @@ -517,6 +542,54 @@ export function buildRouteManifestRoutes(options: { return routes } +function mergeReachableHydrationChunkData(options: { + route: RouteTreeRoute + chunk: NormalizedClientChunk + chunksByFileName: ReadonlyMap + getChunkCssAssets: (chunk: NormalizedClientChunk) => Array +}) { + const visitedStaticChunks = new Set() + const mergedHydrationChunks = new Set() + + const mergeHydrationChunk = (chunk: NormalizedClientChunk) => { + if (mergedHydrationChunks.has(chunk.fileName)) return + mergedHydrationChunks.add(chunk.fileName) + + options.route.assets = appendUniqueAssets( + options.route.assets, + options.getChunkCssAssets(chunk), + ) + + for (const dynamicImport of chunk.dynamicImports) { + const dynamicChunk = options.chunksByFileName.get(dynamicImport) + if (dynamicChunk?.hydrationIds.length) { + mergeHydrationChunk(dynamicChunk) + } + } + } + + const visitStaticChunk = (chunk: NormalizedClientChunk) => { + if (visitedStaticChunks.has(chunk.fileName)) return + visitedStaticChunks.add(chunk.fileName) + + for (const importedFileName of chunk.imports) { + const importedChunk = options.chunksByFileName.get(importedFileName) + if (importedChunk) { + visitStaticChunk(importedChunk) + } + } + + for (const dynamicImport of chunk.dynamicImports) { + const dynamicChunk = options.chunksByFileName.get(dynamicImport) + if (dynamicChunk?.hydrationIds.length) { + mergeHydrationChunk(dynamicChunk) + } + } + } + + visitStaticChunk(options.chunk) +} + export { getRouteFilePathsFromModuleIds, normalizeViteClientBuild, diff --git a/packages/start-plugin-core/src/types.ts b/packages/start-plugin-core/src/types.ts index bc76726875..f0acdbfe35 100644 --- a/packages/start-plugin-core/src/types.ts +++ b/packages/start-plugin-core/src/types.ts @@ -1,5 +1,6 @@ import type * as babel from '@babel/core' import type * as t from '@babel/types' +import type { GeneratorResult } from '@tanstack/router-utils' import type { TanStackStartOutputConfig } from './schema' export type CompileStartFrameworkOptions = 'react' | 'solid' | 'vue' @@ -62,6 +63,36 @@ export interface StartCompilerImportTransform { ) => void } +export interface StartCompilerTransformResult { + code: string + map?: GeneratorResult['map'] | null +} + +export interface StartCompilerVirtualModuleContext { + readonly id: string + readonly root: string + readonly env: StartCompilerEnvironment + readonly envName: string + readonly code?: string +} + +export interface StartCompilerPlugin { + name: string + environment?: + | StartCompilerEnvironment + | Array + | undefined + detect?: RegExp | undefined + virtualModuleIdPattern?: RegExp | undefined + transformAst?: ( + context: StartCompilerTransformContext, + ) => boolean | null | undefined + loadVirtualModule?: ( + context: StartCompilerVirtualModuleContext, + ) => StartCompilerTransformResult | null + invalidateModule?: (context: { id: string; envName: string }) => void +} + export interface NormalizedBasePaths { publicBase: string assetBase: { @@ -82,6 +113,7 @@ export interface NormalizedClientChunk { dynamicImports: Array css: Array routeFilePaths: Array + hydrationIds: Array } export interface NormalizedClientBuild { diff --git a/packages/start-plugin-core/src/vite/start-compiler-plugin/plugin.ts b/packages/start-plugin-core/src/vite/start-compiler-plugin/plugin.ts index 698ab5ae1a..7a2ddd9ff6 100644 --- a/packages/start-plugin-core/src/vite/start-compiler-plugin/plugin.ts +++ b/packages/start-plugin-core/src/vite/start-compiler-plugin/plugin.ts @@ -8,12 +8,18 @@ import { import { detectKindsInCode } from '../../start-compiler/compiler' import { getTransformCodeFilterForEnv } from '../../start-compiler/config' import { + createCompilerVirtualModuleIdPattern, createStartCompiler, + loadCompilerVirtualModule, mergeServerFnsById, } from '../../start-compiler/host' import { generateServerFnResolverModule } from '../../start-compiler/server-fn-resolver-module' import { cleanId } from '../../start-compiler/utils' import { createVirtualModule } from '../createVirtualModule' +import { + MissingHydrateSourceError, + createHydrateCompilerPlugin, +} from '../../hydrate-when-transform' import { resolveViteId } from '../../utils' import { createViteDevServerFnModuleSpecifierEncoder, @@ -23,12 +29,13 @@ import { mergeHotUpdateModules } from './hot-update' import type { CompileStartFrameworkOptions, StartCompilerImportTransform, + StartCompilerPlugin, } from '../../types' import type { GenerateFunctionIdFnOptional, ServerFn, } from '../../start-compiler/types' -import type { EnvironmentModuleNode, PluginOption } from 'vite' +import type { Environment, EnvironmentModuleNode, PluginOption } from 'vite' // Re-export from shared constants for backwards compatibility export { SERVER_FN_LOOKUP } @@ -46,6 +53,32 @@ type ModuleInvalidationEnvironment = { } } +type ViteModuleLoadOptions = { + devId?: string + load: (options: { id: string }) => Promise<{ code?: string | null } | null> + error: (message: string) => never +} + +async function loadViteModuleFromEnvironment( + environment: Environment, + id: string, + opts: ViteModuleLoadOptions, +): Promise { + if (environment.mode === 'build') { + const loaded = await opts.load({ id }) + return loaded?.code ?? '' + } + + if (environment.mode === 'dev') { + await environment.transformRequest(opts.devId ?? id) + return undefined + } + + opts.error( + `could not load module ${id}: unknown environment mode ${environment.mode}`, + ) +} + function invalidateMatchingFileModules( environment: ModuleInvalidationEnvironment, ids: Iterable, @@ -104,6 +137,25 @@ function invalidateServerFnLookupModules( ) } +function invalidateCompilerVirtualModules( + environment: ModuleInvalidationEnvironment, + ids: Iterable, + pattern: RegExp | undefined, +) { + if (!pattern) { + return [] + } + + return invalidateMatchingFileModules(environment, ids, (fileModule) => { + if (!fileModule.id) { + return false + } + + pattern.lastIndex = 0 + return pattern.test(fileModule.id) + }) +} + function getServerFnProviderIds(ids: Iterable) { const providerIds = new Set() @@ -170,6 +222,7 @@ export interface StartCompilerPluginOptions { */ generateFunctionId?: GenerateFunctionIdFnOptional compilerTransforms?: Array | undefined + compilerPlugins?: Array | undefined serverFnProviderModuleDirectives?: ReadonlyArray | undefined /** * The Vite environment name for the server function provider. @@ -181,6 +234,15 @@ export function startCompilerPlugin( opts: StartCompilerPluginOptions, ): PluginOption { const compilers = new Map>() + const compilerPlugins = [ + createHydrateCompilerPlugin(), + ...(opts.compilerPlugins ?? []), + ] + const compilerVirtualModuleIdPattern = + createCompilerVirtualModuleIdPattern(compilerPlugins) + const environmentByName = new Map( + opts.environments.map((environment) => [environment.name, environment]), + ) // Shared registry of server functions across all environments const serverFnsById: Record = {} @@ -218,6 +280,7 @@ export function startCompilerPlugin( // Derive transform code filter from KindDetectionPatterns (single source of truth) const transformCodeFilter = getTransformCodeFilterForEnv(environment.type, { compilerTransforms, + compilerPlugins, }) return { name: `tanstack-start-core::server-fn:${environment.name}`, @@ -262,6 +325,7 @@ export function startCompilerPlugin( providerEnvName: opts.providerEnvName, generateFunctionId: opts.generateFunctionId, compilerTransforms, + compilerPlugins, serverFnProviderModuleDirectives, onServerFnsById, getKnownServerFns: () => serverFnsById, @@ -270,23 +334,18 @@ export function startCompilerPlugin( ? createViteDevServerFnModuleSpecifierEncoder(root) : undefined, loadModule: async (id: string) => { - if (mode === 'build') { - const loaded = await this.load({ id }) - const code = loaded.code ?? '' - - compiler!.ingestModule({ code, id }) - return - } - - if (this.environment.mode !== 'dev') { - this.error( - `could not load module ${id}: unknown environment mode ${this.environment.mode}`, - ) - } - - await this.environment.transformRequest( - `${id}?${SERVER_FN_LOOKUP}`, + const code = await loadViteModuleFromEnvironment( + this.environment, + id, + { + load: (options) => this.load(options), + error: (message) => this.error(message), + devId: `${id}?${SERVER_FN_LOOKUP}`, + }, ) + if (code !== undefined) { + compiler!.ingestModule({ code, id }) + } }, resolveId: async (source: string, importer?: string) => { @@ -315,6 +374,7 @@ export function startCompilerPlugin( code, detectedKinds, }) + return result }, }, @@ -324,17 +384,22 @@ export function startCompilerPlugin( const idsToInvalidate = new Set() const transitiveCompilerImportersToInvalidate = new Set() const importerModulesToInvalidate = new Set() + const changedIds: Array = [] ctx.modules.forEach((m) => { if (m.id) { idsToInvalidate.add(m.id) - const deleted = compiler?.invalidateModule(m.id) + changedIds.push(m.id) + } + }) - if (deleted) { + const deletedIds = compiler?.invalidateModules(changedIds) ?? new Set() + + ctx.modules.forEach((m) => { + if (m.id) { + if (deletedIds.has(cleanId(m.id))) { transitiveCompilerImportersToInvalidate.add(cleanId(m.id)) - } - if (deleted) { m.importers.forEach((importer) => { if (importer.id) { idsToInvalidate.add(importer.id) @@ -349,54 +414,54 @@ export function startCompilerPlugin( }) const finishHotUpdate = async () => { - if (environment.type === 'server' && compiler) { - const pendingImporters = [ - ...transitiveCompilerImportersToInvalidate, - ] - const seenImporters = new Set(pendingImporters) + if ( + environment.type === 'server' && + compiler && + transitiveCompilerImportersToInvalidate.size > 0 + ) { + const seenImporters = new Set( + transitiveCompilerImportersToInvalidate, + ) + const nestedImporters = + await compiler.getTransitiveImporters(seenImporters) - while (pendingImporters.length > 0) { - const importerId = pendingImporters.pop()! - const nestedImporters = - await compiler.getTransitiveImporters(importerId) - - for (const nestedImporterId of nestedImporters) { - if (seenImporters.has(nestedImporterId)) { - continue - } - - seenImporters.add(nestedImporterId) - pendingImporters.push(nestedImporterId) - } + for (const nestedImporterId of nestedImporters) { + seenImporters.add(nestedImporterId) } for (const importerId of seenImporters) { idsToInvalidate.add(importerId) - compiler.invalidateModule(importerId) } + compiler.invalidateModules(seenImporters) } invalidateModuleNodes(this.environment, importerModulesToInvalidate) invalidateServerFnLookupModules(this.environment, idsToInvalidate) + const compilerVirtualModules = invalidateCompilerVirtualModules( + this.environment, + idsToInvalidate, + compilerVirtualModuleIdPattern, + ) if (environment.type !== 'server') { - return + return mergeHotUpdateModules(ctx.modules, compilerVirtualModules) } invalidateModuleNodes(this.environment, ctx.modules) const providerIdsToInvalidate = getServerFnProviderIds(idsToInvalidate) - for (const providerId of providerIdsToInvalidate) { - compiler?.invalidateModule(providerId) - } + compiler?.invalidateModules(providerIdsToInvalidate) const providerModules = invalidateServerFnProviderModules( this.environment, [...idsToInvalidate, ...providerIdsToInvalidate], ) - return mergeHotUpdateModules(ctx.modules, providerModules) + return mergeHotUpdateModules(ctx.modules, [ + ...compilerVirtualModules, + ...providerModules, + ]) } return finishHotUpdate() @@ -423,6 +488,45 @@ export function startCompilerPlugin( }, }, }, + { + name: 'tanstack-start-core:compiler-virtual-module', + enforce: 'pre', + load: { + filter: { + id: compilerVirtualModuleIdPattern ?? /$^/, + }, + async handler(id) { + const environment = environmentByName.get(this.environment.name) + if (!environment || !compilerVirtualModuleIdPattern) { + return null + } + + const loadVirtualModule = () => + loadCompilerVirtualModule(compilerPlugins, { + id, + root, + env: environment.type, + envName: this.environment.name, + }) + + try { + return loadVirtualModule() + } catch (error) { + if (!(error instanceof MissingHydrateSourceError)) { + throw error + } + } + + const sourceId = cleanId(id) + await loadViteModuleFromEnvironment(this.environment, sourceId, { + load: (options) => this.load(options), + error: (message) => this.error(message), + }) + + return loadVirtualModule() + }, + }, + }, // Validate server function ID in dev mode { name: 'tanstack-start-core:validate-server-fn-id', @@ -451,7 +555,7 @@ export function startCompilerPlugin( typeof decoded.file === 'string' && typeof decoded.export === 'string' ) { - // Use the Vite strategy to decode the module specifier + // Use the Vite when to decode the module specifier // back to the original source file path. const sourceFile = decodeViteDevServerModuleSpecifier( decoded.file, diff --git a/packages/start-plugin-core/src/vite/start-manifest-plugin/normalized-client-build.ts b/packages/start-plugin-core/src/vite/start-manifest-plugin/normalized-client-build.ts index 8ac7915ff0..c14609bc6a 100644 --- a/packages/start-plugin-core/src/vite/start-manifest-plugin/normalized-client-build.ts +++ b/packages/start-plugin-core/src/vite/start-manifest-plugin/normalized-client-build.ts @@ -1,4 +1,5 @@ import { tsrSplit } from '@tanstack/router-plugin' +import { tssHydrate } from '../../hydration-constants' import { getCssAssetSource } from '../../start-manifest-plugin/inlineCss' import type { Rollup } from 'vite' import type { NormalizedClientBuild, NormalizedClientChunk } from '../../types' @@ -13,6 +14,7 @@ export function normalizeViteClientChunk( dynamicImports: chunk.dynamicImports, css: Array.from(chunk.viteMetadata?.importedCss ?? []), routeFilePaths: getRouteFilePathsFromModuleIds(chunk.moduleIds), + hydrationIds: getHydrationIdsFromModuleIds(chunk.moduleIds), } } @@ -147,3 +149,38 @@ export function getRouteFilePathsFromModuleIds(moduleIds: Array) { return routeFilePaths ?? [] } + +export function getHydrationIdsFromModuleIds(moduleIds: Array) { + let hydrationIds: Array | undefined + let seen: Set | undefined + + for (const moduleId of moduleIds) { + const queryIndex = moduleId.indexOf('?') + + if (queryIndex < 0) { + continue + } + + const query = moduleId.slice(queryIndex + 1) + + if (!query.includes(tssHydrate)) { + continue + } + + const hydrationId = new URLSearchParams(query).get(tssHydrate) + + if (!hydrationId || seen?.has(hydrationId)) { + continue + } + + if (hydrationIds === undefined || seen === undefined) { + hydrationIds = [] + seen = new Set() + } + + hydrationIds.push(hydrationId) + seen.add(hydrationId) + } + + return hydrationIds ?? [] +} diff --git a/packages/start-plugin-core/tests/compiler.test.ts b/packages/start-plugin-core/tests/compiler.test.ts index e5c99fd257..94780d140b 100644 --- a/packages/start-plugin-core/tests/compiler.test.ts +++ b/packages/start-plugin-core/tests/compiler.test.ts @@ -185,6 +185,29 @@ describe('detectKindsInCode', () => { new Set(['ClientOnlyFn']), ) }) + + test('resets external transform regex state between detections', () => { + const compilerTransforms: Array = [ + { + name: 'global-detect', + environment: 'server', + imports: [{ libName: '@example/runtime', rootExport: 'renderThing' }], + detect: /\brenderThing\b/g, + transform: () => {}, + }, + ] + const code = ` + import { renderThing } from '@example/runtime' + renderThing() + ` + + expect(detectKindsInCode(code, 'server', { compilerTransforms })).toEqual( + new Set(['External:global-detect']), + ) + expect(detectKindsInCode(code, 'server', { compilerTransforms })).toEqual( + new Set(['External:global-detect']), + ) + }) }) describe('detects multiple kinds in same file', () => { @@ -611,6 +634,53 @@ test('ingestModule handles empty code gracefully', () => { }).not.toThrow() }) +test('compile caches modules without detected candidates for transitive importer traversal', async () => { + const compiler = new StartCompiler({ + env: 'client', + ...getDefaultTestOptions('client'), + lookupKinds: new Set(['ServerFn']), + lookupConfigurations: [], + getKnownServerFns: () => ({}), + loadModule: async () => {}, + resolveId: async (source, importer) => { + if (source === './leaf' && importer === '/src/plain.ts') { + return '/src/leaf.ts' + } + + if (source === './plain' && importer === '/src/parent.ts') { + return '/src/plain.ts' + } + + return null + }, + }) + + await compiler.compile({ + id: '/src/plain.ts', + code: ` + import { value } from './leaf' + export const plain = value + `, + detectedKinds: new Set(), + }) + + await compiler.compile({ + id: '/src/parent.ts', + code: ` + import { plain } from './plain' + export const parent = plain + `, + detectedKinds: new Set(), + }) + + expect(await compiler.getTransitiveImporters('/src/leaf.ts')).toEqual( + new Set(['/src/plain.ts', '/src/parent.ts']), + ) + expect(await compiler.getTransitiveImporters(['/src/leaf.ts'])).toEqual( + new Set(['/src/plain.ts', '/src/parent.ts']), + ) +}) + describe('calling result of createServerOnlyFn/createClientOnlyFn', () => { // This tests the fix for https://github.com/TanStack/router/issues/6643 // When a file has both createServerFn and createServerOnlyFn, and the result diff --git a/packages/start-plugin-core/tests/hydrate-when-transform.test.ts b/packages/start-plugin-core/tests/hydrate-when-transform.test.ts new file mode 100644 index 0000000000..13e1d909bd --- /dev/null +++ b/packages/start-plugin-core/tests/hydrate-when-transform.test.ts @@ -0,0 +1,618 @@ +import { mkdtempSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import * as t from '@babel/types' +import { generateFromAst, parseAst } from '@tanstack/router-utils' +import { describe, expect, test } from 'vitest' +import { createHydrateCompilerPlugin } from '../src/hydrate-when-transform' +import type { CompileStartFrameworkOptions } from '../src/types' + +const root = '/repo' +const id = '/repo/src/routes/about.tsx' + +type HydrateBoundary = { + id: string + exportName: string + index: number +} + +function getHydrateBoundariesFromCode(code: string): Array { + const boundaries: Array = [] + const hydrateImportPattern = + /import\("([^"]*[?&]tss-hydrate=[^"]*)"\),\s*"([^"]+)"/g + let match: RegExpExecArray | null + + while ((match = hydrateImportPattern.exec(code))) { + const importId = match[1]! + const queryIndex = importId.indexOf('?') + const params = new URLSearchParams(importId.slice(queryIndex + 1)) + const boundaryId = params.get('tss-hydrate') + const separatorIndex = boundaryId?.indexOf('_') ?? -1 + const index = + boundaryId && separatorIndex > 0 + ? Number.parseInt(boundaryId.slice(0, separatorIndex), 36) + : Number.NaN + + if (boundaryId && Number.isInteger(index)) { + boundaries.push({ + id: boundaryId, + exportName: match[2]!, + index, + }) + } + } + + return boundaries.sort((a, b) => a.index - b.index) +} + +function virtualHydrateId( + file: string, + boundary: Pick, +) { + const params = new URLSearchParams() + params.set('tss-hydrate', boundary.id) + return `${file}?${params.toString()}` +} + +function withSourceHash(id: string, sourceHash: string) { + const separatorIndex = id.indexOf('_') + return `${id.slice(0, separatorIndex + 1)}${sourceHash}` +} + +function compileHydrate(options: { + code: string + id: string + root: string + env: 'client' | 'server' + envName?: string + framework?: CompileStartFrameworkOptions + plugin?: ReturnType +}) { + const plugin = options.plugin ?? createHydrateCompilerPlugin() + const envName = options.envName ?? options.env + const ast = parseAst({ code: options.code, sourceFilename: options.id }) + const result = plugin.transformAst?.({ + ast, + code: options.code, + id: options.id, + root: options.root, + env: options.env, + envName, + mode: 'dev', + framework: options.framework ?? 'react', + providerEnvName: 'ssr', + types: t, + parseExpression: (expressionCode) => t.identifier(expressionCode), + }) + if (!result) return null + + const generated = generateFromAst(ast, { + sourceMaps: true, + sourceFileName: options.id, + filename: options.id, + }) + + return { + code: generated.code, + map: generated.map, + boundaries: getHydrateBoundariesFromCode(generated.code), + plugin, + } +} + +function loadVirtualHydrateModule(options: { + code: string + id: string + root: string + envName?: string +}) { + const plugin = createHydrateCompilerPlugin() + return plugin.loadVirtualModule?.({ + code: options.code, + id: options.id, + root: options.root, + env: 'client', + envName: options.envName ?? 'client', + }) +} + +describe('Hydrate compiler transform', () => { + test('splits Hydrate children behind a lazy import', () => { + const result = compileHydrate({ + code: ` + import { Hydrate } from '@tanstack/react-start' + import { visible } from '@tanstack/react-start/hydration' + + export function Page() { + return ( + + + + ) + } + + function Widget(props: { title: string }) { + return

{props.title}

+ } + `, + id, + root, + env: 'client', + }) + + expect(result?.code).toContain('lazyRouteComponent') + expect(result?.code).toContain('tss-hydrate=') + expect(result?.code).not.toContain('tss-hydrate-index') + expect(result?.code).not.toContain('createElement') + expect(result?.code).toContain('h=') + expect(result?.code).not.toContain('p=') + }) + + test('uses the Solid Router import source for Solid Hydrate boundaries', () => { + const result = compileHydrate({ + code: ` + import { Hydrate } from '@tanstack/solid-start' + import { visible } from '@tanstack/solid-start/hydration' + + export function Page() { + return ( + + + + ) + } + + function Widget(props: { title: string }) { + return

{props.title}

+ } + `, + id, + root, + env: 'client', + framework: 'solid', + }) + + expect(result?.code).toContain( + 'lazyRouteComponent } from "@tanstack/solid-router"', + ) + expect(result?.code).toContain('tss-hydrate=') + expect(result?.code).toContain('h=') + expect(result?.code).not.toContain('p=') + }) + + test('rejects function-as-children unless the boundary opts out of splitting', () => { + expect(() => + compileHydrate({ + code: ` + import { Hydrate } from '@tanstack/react-start' + import { idle } from '@tanstack/react-start/hydration' + + export function Page() { + return ( + + {() =>

child

} +
+ ) + } + `, + id, + root, + env: 'client', + }), + ).toThrow(/function-as-children/) + }) + + test('rejects hook calls that would be moved into an extracted component', () => { + expect(() => + compileHydrate({ + code: ` + import { Hydrate } from '@tanstack/react-start' + import { idle } from '@tanstack/react-start/hydration' + + function useThing() { + return 'thing' + } + + export function Page() { + return ( + +

{useThing()}

+
+ ) + } + `, + id, + root, + env: 'client', + }), + ).toThrow(/hooks/) + }) + + test('strips Hydrate fallback from the server transform', () => { + const result = compileHydrate({ + code: ` + import { Hydrate } from '@tanstack/react-start' + import { idle, visible } from '@tanstack/react-start/hydration' + + const spreadProps = { + when: visible(), + fallback:
bound
, + } + + export function Page() { + return ( + <> + fallback
} + > + + + inline} + > + + + spread, + }} + > + + + + + + + ) + } + + function Widget(props: { title: string }) { + return

{props.title}

+ } + `, + id, + root, + env: 'server', + }) + + expect(result?.code).not.toContain('fallback=') + expect(result?.code).not.toContain('fallback:') + expect(result?.code).not.toContain('server-fallback') + expect(result?.code).not.toContain('server-inline') + expect(result?.code).not.toContain('server-spread') + expect(result?.code).not.toContain('server-bound-spread') + expect(result?.code).toContain('h=') + expect(result?.code).toContain('') + expect(result?.code).toContain('') + expect(result?.code).toContain('') + expect(result?.code).toContain('') + }) + + test('supports nested Hydrate boundaries in extracted virtual modules', () => { + const dir = mkdtempSync(join(tmpdir(), 'hydrate-when-')) + const file = join(dir, 'route.tsx') + const code = ` + import { Hydrate } from '@tanstack/react-start' + import { interaction, visible } from '@tanstack/react-start/hydration' + + const unused = 'remove me' + + export function Page() { + return ( + +
+ + + +
+
+ ) + } + ` + const firstPass = compileHydrate({ + code, + id: file, + root: dir, + env: 'client', + }) + expect(firstPass?.boundaries).toHaveLength(1) + + const virtualId = virtualHydrateId(file, firstPass!.boundaries[0]!) + const virtualModule = loadVirtualHydrateModule({ + code, + id: virtualId, + root: dir, + }) + expect(virtualModule?.code).not.toContain('remove me') + + const boundaryIndex = firstPass!.boundaries[0]!.index + const nestedPass = compileHydrate({ + code: virtualModule!.code, + id: virtualId, + root: dir, + env: 'client', + }) + + expect(boundaryIndex).toBe(0) + expect(nestedPass?.code).toContain('H1') + expect(nestedPass?.code).toContain('tss-hydrate=') + }) + + test('keeps sibling boundary ids stable after nested boundaries', () => { + const dir = mkdtempSync(join(tmpdir(), 'hydrate-when-')) + const file = join(dir, 'route.tsx') + const code = ` + import { Hydrate } from '@tanstack/react-start' + import { idle, interaction, visible } from '@tanstack/react-start/hydration' + + export function Page() { + return ( + <> + +
+ + + +
+
+ +

Sibling

+
+ + ) + } + ` + const firstPass = compileHydrate({ + code, + id: file, + root: dir, + env: 'client', + }) + expect( + firstPass?.boundaries.map((boundary) => boundary.exportName), + ).toEqual(['H0', 'H2']) + + const siblingBoundary = firstPass!.boundaries[1]! + const virtualId = virtualHydrateId(file, siblingBoundary) + const boundaryIndex = siblingBoundary.index + const virtualModule = loadVirtualHydrateModule({ + code, + id: virtualId, + root: dir, + }) + const parentVirtualId = virtualHydrateId(file, firstPass!.boundaries[0]!) + const parentVirtualModule = loadVirtualHydrateModule({ + code, + id: parentVirtualId, + root: dir, + }) + const nestedPass = compileHydrate({ + code: parentVirtualModule!.code, + id: parentVirtualId, + root: dir, + env: 'client', + }) + const serverPass = compileHydrate({ + code, + id: file, + root: dir, + env: 'server', + }) + + expect(boundaryIndex).toBe(2) + expect(virtualModule?.code).toContain('Sibling') + expect(virtualModule?.code).not.toContain('Nested') + expect(nestedPass?.boundaries[0]?.exportName).toBe('H1') + expect(serverPass?.code).toContain(firstPass!.boundaries[0]!.id) + expect(serverPass?.code).toContain(nestedPass!.boundaries[0]!.id) + expect(serverPass?.code).toContain(siblingBoundary.id) + }) + + test('loads virtual modules from supplied bundler code instead of the filesystem', () => { + const dir = mkdtempSync(join(tmpdir(), 'hydrate-when-')) + const file = join(dir, 'route.tsx') + const oldCode = ` + import { Hydrate } from '@tanstack/react-start' + import { visible } from '@tanstack/react-start/hydration' + + export function Page() { + return

Old

+ } + ` + const nextCode = oldCode.replace('Old', 'New') + const firstPass = compileHydrate({ + code: oldCode, + id: file, + root: dir, + env: 'client', + }) + const virtualModule = loadVirtualHydrateModule({ + code: nextCode, + id: virtualHydrateId(file, firstPass!.boundaries[0]!), + root: dir, + }) + + expect(virtualModule?.code).toContain('New') + expect(virtualModule?.code).not.toContain('Old') + }) + + test('captures identifiers used by shorthand objects and computed members', () => { + const dir = mkdtempSync(join(tmpdir(), 'hydrate-when-')) + const file = join(dir, 'route.tsx') + const code = ` + import { Hydrate } from '@tanstack/react-start' + import { visible } from '@tanstack/react-start/hydration' + + export function Page() { + const key = 'name' + const items = { name: 'Ada' } + return ( + + + + ) + } + + function Widget(props: { data: { key: string; value: string } }) { + return

{props.data.value}

+ } + ` + const firstPass = compileHydrate({ + code, + id: file, + root: dir, + env: 'client', + }) + const virtualModule = loadVirtualHydrateModule({ + code, + id: virtualHydrateId(file, firstPass!.boundaries[0]!), + root: dir, + }) + + expect(virtualModule?.code).toContain('export function H0({') + expect(virtualModule?.code).toContain('items') + expect(virtualModule?.code).toContain('key') + expect(virtualModule?.code).toContain('items[key]') + }) + + test('unwraps exported declarations needed by extracted virtual modules', () => { + const dir = mkdtempSync(join(tmpdir(), 'hydrate-when-')) + const file = join(dir, 'route.tsx') + const code = ` + import { createFileRoute } from '@tanstack/react-router' + import { Hydrate } from '@tanstack/react-start' + import { visible } from '@tanstack/react-start/hydration' + + export const Route = createFileRoute('/test')({ + component: Page, + }) + + export const label = 'Ada' + + export const Widget = () => { + return

{label}

+ } + + function Page() { + return + } + ` + const firstPass = compileHydrate({ + code, + id: file, + root: dir, + env: 'client', + }) + const virtualModule = loadVirtualHydrateModule({ + code, + id: virtualHydrateId(file, firstPass!.boundaries[0]!), + root: dir, + }) + + expect(virtualModule?.code).toContain('const Widget') + expect(virtualModule?.code).toContain('const label') + expect(virtualModule?.code).toContain('') + expect(virtualModule?.code).not.toContain('export const Widget') + expect(virtualModule?.code).not.toContain('createFileRoute') + expect(virtualModule?.code).not.toContain('const Route') + }) + + test('invalidates cached Hydrate source for virtual module loads', () => { + const dir = mkdtempSync(join(tmpdir(), 'hydrate-when-')) + const file = join(dir, 'route.tsx') + const oldCode = ` + import { Hydrate } from '@tanstack/react-start' + import { visible } from '@tanstack/react-start/hydration' + + export function Page() { + return

Old

+ } + ` + const nextCode = oldCode.replace('Old', 'New') + const envName = 'client' + const plugin = createHydrateCompilerPlugin() + const transformed = compileHydrate({ + code: oldCode, + id: file, + root: dir, + env: 'client', + envName, + plugin, + }) + const virtualId = virtualHydrateId(file, transformed!.boundaries[0]!) + + expect( + transformed!.plugin.loadVirtualModule?.({ + id: virtualId, + root: dir, + env: 'client', + envName, + })?.code, + ).toContain('Old') + + transformed!.plugin.invalidateModule?.({ id: file, envName }) + expect(() => + transformed!.plugin.loadVirtualModule?.({ + id: virtualId, + root: dir, + env: 'client', + envName, + }), + ).toThrow(/Missing Hydrate source/) + + const updated = compileHydrate({ + code: nextCode, + id: file, + root: dir, + env: 'client', + envName, + plugin, + }) + + expect( + updated!.plugin.loadVirtualModule?.({ + id: virtualId, + root: dir, + env: 'client', + envName, + })?.code, + ).toContain('New') + }) + + test('rejects virtual module ids whose source hash does not match', () => { + const code = ` + import { Hydrate } from '@tanstack/react-start' + import { idle, visible } from '@tanstack/react-start/hydration' + + export function Page() { + return ( + <> +

First

+

Second

+ + ) + } + ` + const firstPass = compileHydrate({ + code, + id, + root, + env: 'client', + }) + const mismatchedId = virtualHydrateId(id, { + id: withSourceHash(firstPass!.boundaries[0]!.id, 'mismatch'), + index: firstPass!.boundaries[0]!.index, + }) + + expect( + new URLSearchParams(mismatchedId.split('?')[1]).get('tss-hydrate'), + ).toMatch(/_mismatch$/) + expect( + loadVirtualHydrateModule({ code, id: mismatchedId, root }), + ).toBeNull() + }) +}) diff --git a/packages/start-plugin-core/tests/hydrateWhen/error-files/hydrateWhenFunctionChild.tsx b/packages/start-plugin-core/tests/hydrateWhen/error-files/hydrateWhenFunctionChild.tsx new file mode 100644 index 0000000000..a2560a6197 --- /dev/null +++ b/packages/start-plugin-core/tests/hydrateWhen/error-files/hydrateWhenFunctionChild.tsx @@ -0,0 +1,6 @@ +import { Hydrate } from '@tanstack/react-start' +import { idle } from '@tanstack/react-start/hydration' + +export function Page() { + return {() =>

child

}
+} diff --git a/packages/start-plugin-core/tests/hydrateWhen/error-files/hydrateWhenHookCall.tsx b/packages/start-plugin-core/tests/hydrateWhen/error-files/hydrateWhenHookCall.tsx new file mode 100644 index 0000000000..1e89bb7303 --- /dev/null +++ b/packages/start-plugin-core/tests/hydrateWhen/error-files/hydrateWhenHookCall.tsx @@ -0,0 +1,14 @@ +import { Hydrate } from '@tanstack/react-start' +import { idle } from '@tanstack/react-start/hydration' + +function useThing() { + return 'thing' +} + +export function Page() { + return ( + +

{useThing()}

+
+ ) +} diff --git a/packages/start-plugin-core/tests/hydrateWhen/error-files/hydrateWhenSuperCapture.tsx b/packages/start-plugin-core/tests/hydrateWhen/error-files/hydrateWhenSuperCapture.tsx new file mode 100644 index 0000000000..63b91b0239 --- /dev/null +++ b/packages/start-plugin-core/tests/hydrateWhen/error-files/hydrateWhenSuperCapture.tsx @@ -0,0 +1,16 @@ +import { Hydrate } from '@tanstack/react-start' +import { idle } from '@tanstack/react-start/hydration' + +class Base { + title = 'super' +} + +export class Page extends Base { + render() { + return ( + +

{super.title}

+
+ ) + } +} diff --git a/packages/start-plugin-core/tests/hydrateWhen/error-files/hydrateWhenThisCapture.tsx b/packages/start-plugin-core/tests/hydrateWhen/error-files/hydrateWhenThisCapture.tsx new file mode 100644 index 0000000000..5f7b3df606 --- /dev/null +++ b/packages/start-plugin-core/tests/hydrateWhen/error-files/hydrateWhenThisCapture.tsx @@ -0,0 +1,14 @@ +import { Hydrate } from '@tanstack/react-start' +import { idle } from '@tanstack/react-start/hydration' + +export class Page { + title = 'this' + + render() { + return ( + +

{this.title}

+
+ ) + } +} diff --git a/packages/start-plugin-core/tests/hydrateWhen/hydrateWhen.test.ts b/packages/start-plugin-core/tests/hydrateWhen/hydrateWhen.test.ts new file mode 100644 index 0000000000..2d121539fe --- /dev/null +++ b/packages/start-plugin-core/tests/hydrateWhen/hydrateWhen.test.ts @@ -0,0 +1,241 @@ +import { readFile, readdir } from 'node:fs/promises' +import path from 'node:path' +import * as t from '@babel/types' +import { generateFromAst, parseAst } from '@tanstack/router-utils' +import { describe, expect, test } from 'vitest' +import { createHydrateCompilerPlugin } from '../../src/hydrate-when-transform' + +const fixtureRoot = path.resolve(import.meta.dirname, './test-files') +const errorRoot = path.resolve(import.meta.dirname, './error-files') + +function fixtureId(filename: string) { + return path.join(fixtureRoot, filename) +} + +function normalizeSnapshotCode(code: string) { + return code.split(fixtureRoot).join('') +} + +async function readFixture(filename: string) { + return await readFile(fixtureId(filename), 'utf8') +} + +async function getFilenames(dirname: string) { + return (await readdir(dirname)) + .filter((filename) => filename.endsWith('.tsx')) + .sort() +} + +type HydrateBoundary = { + id: string + exportName: string + index: number +} + +function getHydrateBoundariesFromCode(code: string): Array { + const boundaries: Array = [] + const hydrateImportPattern = + /import\("([^"]*[?&]tss-hydrate=[^"]*)"\),\s*"([^"]+)"/g + let match: RegExpExecArray | null + + while ((match = hydrateImportPattern.exec(code))) { + const importId = match[1]! + const queryIndex = importId.indexOf('?') + const params = new URLSearchParams(importId.slice(queryIndex + 1)) + const boundaryId = params.get('tss-hydrate') + const separatorIndex = boundaryId?.indexOf('_') ?? -1 + const index = + boundaryId && separatorIndex > 0 + ? Number.parseInt(boundaryId.slice(0, separatorIndex), 36) + : Number.NaN + + if (boundaryId && Number.isInteger(index)) { + boundaries.push({ + id: boundaryId, + exportName: match[2]!, + index, + }) + } + } + + return boundaries.sort((a, b) => a.index - b.index) +} + +function compile(opts: { + env: 'client' | 'server' + code: string + id: string + root?: string +}) { + const options = { + ...opts, + root: opts.root ?? fixtureRoot, + } + const plugin = createHydrateCompilerPlugin() + const ast = parseAst({ code: options.code, sourceFilename: options.id }) + const result = plugin.transformAst?.({ + ast, + code: options.code, + id: options.id, + root: options.root, + env: options.env, + envName: options.env, + mode: 'dev', + framework: 'react', + providerEnvName: 'ssr', + types: t, + parseExpression: (expressionCode) => t.identifier(expressionCode), + }) + if (!result) return null + + const generated = generateFromAst(ast, { + sourceMaps: true, + sourceFileName: options.id, + filename: options.id, + }) + + return { + code: generated.code, + map: generated.map, + boundaries: getHydrateBoundariesFromCode(generated.code), + } +} + +function loadVirtualHydrateModule(options: { + code: string + id: string + root: string +}) { + return createHydrateCompilerPlugin().loadVirtualModule?.({ + code: options.code, + id: options.id, + root: options.root, + env: 'client', + envName: 'client', + }) +} + +function virtualHydrateId( + file: string, + boundary: Pick, +) { + const params = new URLSearchParams() + params.set('tss-hydrate', boundary.id) + return `${file}?${params.toString()}` +} + +describe('Hydrate compiler transform fixtures', async () => { + const filenames = await getFilenames(fixtureRoot) + + describe.each(filenames)('should handle "%s"', async (filename) => { + const code = await readFixture(filename) + const id = fixtureId(filename) + + test(`should compile ${filename} for client`, async () => { + const result = compile({ env: 'client', code, id }) + + await expect( + normalizeSnapshotCode(result?.code ?? 'no-transform'), + ).toMatchFileSnapshot(`./snapshots/client/${filename}`) + }) + + test(`should compile ${filename} for server`, async () => { + const result = compile({ env: 'server', code, id }) + + await expect( + normalizeSnapshotCode(result?.code ?? 'no-transform'), + ).toMatchFileSnapshot(`./snapshots/server/${filename}`) + }) + }) + + test('should extract virtual modules and keep nested ids stable', async () => { + const filename = 'hydrateWhenNested.tsx' + const code = await readFixture(filename) + const id = fixtureId(filename) + const firstPass = compile({ env: 'client', code, id }) + + expect( + firstPass?.boundaries.map((boundary) => boundary.exportName), + ).toEqual(['H0', 'H2']) + + for (const boundary of firstPass!.boundaries) { + const virtualId = virtualHydrateId(id, boundary) + const loaded = loadVirtualHydrateModule({ + code, + id: virtualId, + root: fixtureRoot, + }) + + await expect( + normalizeSnapshotCode(loaded?.code ?? 'no-virtual-module'), + ).toMatchFileSnapshot( + `./snapshots/virtual/${filename}.${boundary.exportName}.tsx`, + ) + } + + const parentBoundary = firstPass!.boundaries[0]! + const parentVirtualId = virtualHydrateId(id, parentBoundary) + const parentVirtualModule = loadVirtualHydrateModule({ + code, + id: parentVirtualId, + root: fixtureRoot, + }) + const nestedPass = compile({ + code: parentVirtualModule!.code, + id: parentVirtualId, + env: 'client', + }) + + await expect( + normalizeSnapshotCode(nestedPass?.code ?? 'no-transform'), + ).toMatchFileSnapshot(`./snapshots/virtual/${filename}.H0.client.tsx`) + }) +}) + +describe('Hydrate compiler extraction errors', async () => { + const errorCases = [ + { + filename: 'hydrateWhenFunctionChild.tsx', + message: /function-as-children/, + }, + { + filename: 'hydrateWhenHookCall.tsx', + message: /hooks/, + }, + { + filename: 'hydrateWhenThisCapture.tsx', + message: /captures this/, + }, + { + filename: 'hydrateWhenSuperCapture.tsx', + message: /captures super/, + }, + ] as const + + describe.each(errorCases)('$filename', async ({ filename, message }) => { + const code = await readFile(path.join(errorRoot, filename), 'utf8') + const id = path.join(errorRoot, filename) + + test('should reject unsafe client extraction', () => { + expect(() => + compile({ + code, + id, + root: errorRoot, + env: 'client', + }), + ).toThrow(message) + }) + + test('should reject unsafe server extraction', () => { + expect(() => + compile({ + code, + id, + root: errorRoot, + env: 'server', + }), + ).toThrow(message) + }) + }) +}) diff --git a/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenBasic.tsx b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenBasic.tsx new file mode 100644 index 0000000000..c977cd70a2 --- /dev/null +++ b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenBasic.tsx @@ -0,0 +1,18 @@ +const _H = _lazyRouteComponent(() => import("/hydrateWhenBasic.tsx?tss-hydrate=0_3cf0187f82"), "H0"), + _H0_preload = _H.preload; +import { lazyRouteComponent as _lazyRouteComponent } from "@tanstack/react-router"; +import { Hydrate } from '@tanstack/react-start'; +import { idle, visible } from '@tanstack/react-start/hydration'; +import { FallbackPane } from './widgets'; +export function Page() { + return
+ } h="0_3cf0187f82" p={_H0_preload}> + {<_H />} + +
; +} \ No newline at end of file diff --git a/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenMultiple.tsx b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenMultiple.tsx new file mode 100644 index 0000000000..8a68575d69 --- /dev/null +++ b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenMultiple.tsx @@ -0,0 +1,19 @@ +const _H3 = _lazyRouteComponent(() => import("/hydrateWhenMultiple.tsx?tss-hydrate=2_21aa371e0f"), "H2"); +const _H2 = _lazyRouteComponent(() => import("/hydrateWhenMultiple.tsx?tss-hydrate=1_21aa371e0f"), "H1"); +const _H = _lazyRouteComponent(() => import("/hydrateWhenMultiple.tsx?tss-hydrate=0_21aa371e0f"), "H0"); +import { lazyRouteComponent as _lazyRouteComponent } from "@tanstack/react-router"; +import { Hydrate } from '@tanstack/react-start'; +import { load, media, visible } from '@tanstack/react-start/hydration'; +export function Page() { + return <> + + {<_H />} + + + {<_H2 />} + + + {<_H3 />} + + ; +} \ No newline at end of file diff --git a/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenNested.tsx b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenNested.tsx new file mode 100644 index 0000000000..97c3dba1a4 --- /dev/null +++ b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenNested.tsx @@ -0,0 +1,16 @@ +const _H2 = _lazyRouteComponent(() => import("/hydrateWhenNested.tsx?tss-hydrate=2_466696e41d"), "H2"); +const _H = _lazyRouteComponent(() => import("/hydrateWhenNested.tsx?tss-hydrate=0_466696e41d"), "H0"); +import { lazyRouteComponent as _lazyRouteComponent } from "@tanstack/react-router"; +import { Hydrate } from '@tanstack/react-start'; +import { idle, visible } from '@tanstack/react-start/hydration'; +const unused = 'remove me from virtual modules'; +export function Page() { + return <> + + {<_H />} + + + {<_H2 />} + + ; +} \ No newline at end of file diff --git a/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenNever.tsx b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenNever.tsx new file mode 100644 index 0000000000..426e83fa73 --- /dev/null +++ b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenNever.tsx @@ -0,0 +1,9 @@ +const _H = _lazyRouteComponent(() => import("/hydrateWhenNever.tsx?tss-hydrate=0_b752509d76"), "H0"); +import { lazyRouteComponent as _lazyRouteComponent } from "@tanstack/react-router"; +import { Hydrate } from '@tanstack/react-start'; +import { never } from '@tanstack/react-start/hydration'; +export function Page() { + return + {<_H />} + ; +} \ No newline at end of file diff --git a/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenNoImport.tsx b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenNoImport.tsx new file mode 100644 index 0000000000..b35c36ab1b --- /dev/null +++ b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenNoImport.tsx @@ -0,0 +1 @@ +no-transform \ No newline at end of file diff --git a/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenNotFromTanstack.tsx b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenNotFromTanstack.tsx new file mode 100644 index 0000000000..b35c36ab1b --- /dev/null +++ b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenNotFromTanstack.tsx @@ -0,0 +1 @@ +no-transform \ No newline at end of file diff --git a/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenObjectFallback.tsx b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenObjectFallback.tsx new file mode 100644 index 0000000000..1bbe2337d6 --- /dev/null +++ b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenObjectFallback.tsx @@ -0,0 +1,26 @@ +const _H3 = _lazyRouteComponent(() => import("/hydrateWhenObjectFallback.tsx?tss-hydrate=2_7f4dc3aa80"), "H2"); +const _H2 = _lazyRouteComponent(() => import("/hydrateWhenObjectFallback.tsx?tss-hydrate=1_7f4dc3aa80"), "H1"); +const _H = _lazyRouteComponent(() => import("/hydrateWhenObjectFallback.tsx?tss-hydrate=0_7f4dc3aa80"), "H0"); +import { lazyRouteComponent as _lazyRouteComponent } from "@tanstack/react-router"; +import { Hydrate } from '@tanstack/react-start'; +import { idle, visible } from '@tanstack/react-start/hydration'; +const spreadProps = { + when: visible(), + fallback:
Bound
+}; +export function Page() { + return <> + Direct} h="0_7f4dc3aa80"> + {<_H />} + + Inline + }} h="1_7f4dc3aa80"> + {<_H2 />} + + + {<_H3 />} + + ; +} \ No newline at end of file diff --git a/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenPrefetchState.tsx b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenPrefetchState.tsx new file mode 100644 index 0000000000..9961cdc3c9 --- /dev/null +++ b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenPrefetchState.tsx @@ -0,0 +1,19 @@ +const _H = _lazyRouteComponent(() => import("/hydrateWhenPrefetchState.tsx?tss-hydrate=0_24b5f958eb"), "H0"), + _H0_preload = _H.preload; +import { lazyRouteComponent as _lazyRouteComponent } from "@tanstack/react-router"; +import { useState } from 'react'; +import { Hydrate } from '@tanstack/react-start'; +import { interaction } from '@tanstack/react-start/hydration'; +export function Page() { + const [status, setStatus] = useState('idle'); + const [, setUnusedStatus] = useState('idle'); + return
+

{status}

+ { + setStatus('prefetched'); + setUnusedStatus('prefetched'); + }} h="0_24b5f958eb" p={_H0_preload}> + {<_H />} + +
; +} \ No newline at end of file diff --git a/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenRenamed.tsx b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenRenamed.tsx new file mode 100644 index 0000000000..9c24d8cbd3 --- /dev/null +++ b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenRenamed.tsx @@ -0,0 +1,11 @@ +const _H = _lazyRouteComponent(() => import("/hydrateWhenRenamed.tsx?tss-hydrate=0_f555ef3ac2"), "H0"); +import { lazyRouteComponent as _lazyRouteComponent } from "@tanstack/react-router"; +import { Hydrate as HW } from '@tanstack/react-start'; +import { interaction } from '@tanstack/react-start/hydration'; +export function Page() { + return + {<_H />} + ; +} \ No newline at end of file diff --git a/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenSplitFalse.tsx b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenSplitFalse.tsx new file mode 100644 index 0000000000..b35c36ab1b --- /dev/null +++ b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenSplitFalse.tsx @@ -0,0 +1 @@ +no-transform \ No newline at end of file diff --git a/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenSplitFalseFunctionChild.tsx b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenSplitFalseFunctionChild.tsx new file mode 100644 index 0000000000..b35c36ab1b --- /dev/null +++ b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenSplitFalseFunctionChild.tsx @@ -0,0 +1 @@ +no-transform \ No newline at end of file diff --git a/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenWrongImportName.tsx b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenWrongImportName.tsx new file mode 100644 index 0000000000..b35c36ab1b --- /dev/null +++ b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenWrongImportName.tsx @@ -0,0 +1 @@ +no-transform \ No newline at end of file diff --git a/packages/start-plugin-core/tests/hydrateWhen/snapshots/server/hydrateWhenBasic.tsx b/packages/start-plugin-core/tests/hydrateWhen/snapshots/server/hydrateWhenBasic.tsx new file mode 100644 index 0000000000..8bcf4099ca --- /dev/null +++ b/packages/start-plugin-core/tests/hydrateWhen/snapshots/server/hydrateWhenBasic.tsx @@ -0,0 +1,17 @@ +import { Hydrate } from '@tanstack/react-start'; +import { idle, visible } from '@tanstack/react-start/hydration'; +import { Chart } from './widgets'; +import { formatValue } from './format'; +const chartTitle = formatValue('Revenue'); +export function Page() { + return
+ + + +
; +} \ No newline at end of file diff --git a/packages/start-plugin-core/tests/hydrateWhen/snapshots/server/hydrateWhenMultiple.tsx b/packages/start-plugin-core/tests/hydrateWhen/snapshots/server/hydrateWhenMultiple.tsx new file mode 100644 index 0000000000..6959b25b3e --- /dev/null +++ b/packages/start-plugin-core/tests/hydrateWhen/snapshots/server/hydrateWhenMultiple.tsx @@ -0,0 +1,24 @@ +import { Hydrate } from '@tanstack/react-start'; +import { load, media, visible } from '@tanstack/react-start/hydration'; +function Summary() { + return
Summary
; +} +function Comments() { + return
Comments
; +} +function Footer() { + return
Footer
; +} +export function Page() { + return <> + + + + + + + +