From e9acd3a456277608563e37d622cf9369ee7d5051 Mon Sep 17 00:00:00 2001 From: Manuel Schiller <6340397+schiller-manuel@users.noreply.github.com> Date: Fri, 26 Jun 2026 00:07:12 +0200 Subject: [PATCH 01/54] fix: match loading fixes #7602 fixes #7210 fixes #7457 fixes #7673 fixes #6221 --- .changeset/violet-poets-wait.md | 17 + docs/router/api/router/RouteMatchType.md | 2 +- docs/router/api/router/RouterStateType.md | 6 - docs/router/how-to/debug-router-issues.md | 1 - .../basic-file-based/tests/app.spec.ts | 6 +- e2e/react-router/issue-7120/index.html | 12 + e2e/react-router/issue-7120/package.json | 26 + .../issue-7120/playwright.config.ts | 27 + e2e/react-router/issue-7120/src/main.tsx | 72 + .../issue-7120/src/posts.lazy.tsx | 25 + .../issue-7120/tests/issue-7120.repro.spec.ts | 28 + e2e/react-router/issue-7120/tsconfig.json | 15 + e2e/react-router/issue-7120/vite.config.js | 6 + e2e/react-router/issue-7457/index.html | 10 + e2e/react-router/issue-7457/package.json | 27 + .../issue-7457/playwright.config.ts | 27 + e2e/react-router/issue-7457/src/main.tsx | 28 + .../issue-7457/src/routeTree.gen.ts | 77 + .../issue-7457/src/routes/__root.tsx | 16 + .../issue-7457/src/routes/another.tsx | 9 + .../issue-7457/src/routes/index.tsx | 15 + e2e/react-router/issue-7457/src/vite-env.d.ts | 1 + .../issue-7457/tests/issue-7457.repro.spec.ts | 28 + e2e/react-router/issue-7457/tsconfig.json | 15 + e2e/react-router/issue-7457/vite.config.js | 10 + e2e/react-start/issue-6221/.gitignore | 3 + e2e/react-start/issue-6221/package.json | 31 + .../issue-6221/playwright.config.ts | 27 + .../issue-6221/src/routeTree.gen.ts | 122 + e2e/react-start/issue-6221/src/router.tsx | 8 + .../issue-6221/src/routes/__root.tsx | 38 + .../issue-6221/src/routes/article.$id.tsx | 50 + .../issue-6221/src/routes/dashboard.tsx | 16 + .../issue-6221/src/routes/index.tsx | 16 + .../issue-6221/src/routes/login.tsx | 29 + e2e/react-start/issue-6221/tests/head.spec.ts | 29 + e2e/react-start/issue-6221/tsconfig.json | 21 + e2e/react-start/issue-6221/vite.config.ts | 11 + .../selective-ssr/src/routeTree.gen.ts | 24 +- e2e/react-start/selective-ssr/src/router.tsx | 6 + .../src/routes/ssr-false-pending-min.tsx | 49 + .../selective-ssr/tests/app.spec.ts | 71 + e2e/solid-start/basic-auth/package.json | 2 +- .../selective-ssr/src/routeTree.gen.ts | 33 +- .../src/routes/ssr-false-pending-min.tsx | 48 + .../selective-ssr/tests/app.spec.ts | 71 + .../tests/view-transitions.spec.ts | 3 +- e2e/vue-start/basic-auth/package.json | 2 +- .../selective-ssr/src/routeTree.gen.ts | 24 +- .../src/routes/ssr-false-pending-min.tsx | 56 + e2e/vue-start/selective-ssr/tests/app.spec.ts | 71 + packages/react-router/src/Match.tsx | 231 +- .../src/ssr/renderRouterToStream.tsx | 4 +- .../src/ssr/renderRouterToString.tsx | 2 +- packages/react-router/tests/Matches.test.tsx | 479 +- packages/react-router/tests/Scripts.test.tsx | 76 + .../tests/errorComponent.test.tsx | 2 +- packages/react-router/tests/loaders.test.tsx | 35 +- .../react-router/tests/not-found.test.tsx | 88 + packages/react-router/tests/redirect.test.tsx | 14 +- .../tests/renderRouterToStream.test.tsx | 2 +- packages/react-router/tests/route.test-d.tsx | 3 - .../react-router/tests/routeContext.test.tsx | 416 + packages/react-router/tests/router.test.tsx | 70 +- .../store-updates-during-navigation.test.tsx | 10 +- .../react-router/tests/useParams.test.tsx | 60 +- packages/router-core/INTERNALS.md | 1075 ++ packages/router-core/src/Matches.ts | 29 +- packages/router-core/src/index.ts | 3 +- .../router-core/src/load-matches.client.ts | 1066 ++ .../router-core/src/load-matches.server.ts | 553 + packages/router-core/src/load-matches.ts | 1339 +- packages/router-core/src/location-change.ts | 19 + packages/router-core/src/redirect.ts | 27 +- .../router-core/src/route-assets.client.ts | 122 + .../router-core/src/route-assets.server.ts | 183 + packages/router-core/src/route-chunks.ts | 97 + .../router-core/src/router-load.client.ts | 258 + .../router-core/src/router-load.server.ts | 96 + .../router-core/src/router-preload.client.ts | 88 + packages/router-core/src/router.ts | 989 +- .../router-core/src/scroll-restoration.ts | 2 +- .../src/ssr/createRequestHandler.ts | 2 +- packages/router-core/src/ssr/ssr-client.ts | 425 +- packages/router-core/src/stores.ts | 21 +- packages/router-core/src/utils.ts | 16 +- .../router-core/tests/granular-stores.test.ts | 2 +- packages/router-core/tests/hydrate.test.ts | 1133 +- packages/router-core/tests/load.test.ts | 10498 +++++++++++++++- .../router-devtools-core/src/AgeTicker.tsx | 2 +- .../router-devtools-core/src/useStyles.tsx | 3 +- packages/router-devtools-core/src/utils.tsx | 1 - .../src/core/hmr/handle-route-update.ts | 5 +- packages/solid-router/src/Match.tsx | 177 +- .../src/ssr/renderRouterToStream.tsx | 2 +- .../src/ssr/renderRouterToString.tsx | 2 +- packages/solid-router/src/useMatch.tsx | 11 +- packages/solid-router/tests/Matches.test.tsx | 155 +- packages/solid-router/tests/loaders.test.tsx | 33 +- packages/solid-router/tests/redirect.test.tsx | 8 +- .../tests/renderRouterToStream.test.tsx | 2 +- packages/solid-router/tests/route.test-d.tsx | 3 - .../solid-router/tests/routeContext.test.tsx | 76 + packages/solid-router/tests/router.test.tsx | 64 +- .../tests/server/errorComponent.test.tsx | 2 +- .../store-updates-during-navigation.test.tsx | 11 +- .../src/createStartHandler.ts | 4 +- packages/vue-router/src/Match.tsx | 99 +- packages/vue-router/src/Transitioner.tsx | 37 +- .../src/ssr/renderRouterToStream.tsx | 4 +- .../src/ssr/renderRouterToString.tsx | 2 +- packages/vue-router/src/useMatch.tsx | 11 +- packages/vue-router/tests/Matches.test.tsx | 100 +- packages/vue-router/tests/link.test.tsx | 15 +- packages/vue-router/tests/loaders.test.tsx | 50 +- packages/vue-router/tests/redirect.test.tsx | 15 +- .../tests/renderRouterToStream.test.tsx | 2 +- packages/vue-router/tests/route.test-d.tsx | 3 - packages/vue-router/tests/router.test.tsx | 214 - .../store-updates-during-navigation.test.tsx | 26 +- pnpm-lock.yaml | 108 + skills/bundle-size-optimization/SKILL.md | 7 + 122 files changed, 18971 insertions(+), 3185 deletions(-) create mode 100644 .changeset/violet-poets-wait.md create mode 100644 e2e/react-router/issue-7120/index.html create mode 100644 e2e/react-router/issue-7120/package.json create mode 100644 e2e/react-router/issue-7120/playwright.config.ts create mode 100644 e2e/react-router/issue-7120/src/main.tsx create mode 100644 e2e/react-router/issue-7120/src/posts.lazy.tsx create mode 100644 e2e/react-router/issue-7120/tests/issue-7120.repro.spec.ts create mode 100644 e2e/react-router/issue-7120/tsconfig.json create mode 100644 e2e/react-router/issue-7120/vite.config.js create mode 100644 e2e/react-router/issue-7457/index.html create mode 100644 e2e/react-router/issue-7457/package.json create mode 100644 e2e/react-router/issue-7457/playwright.config.ts create mode 100644 e2e/react-router/issue-7457/src/main.tsx create mode 100644 e2e/react-router/issue-7457/src/routeTree.gen.ts create mode 100644 e2e/react-router/issue-7457/src/routes/__root.tsx create mode 100644 e2e/react-router/issue-7457/src/routes/another.tsx create mode 100644 e2e/react-router/issue-7457/src/routes/index.tsx create mode 100644 e2e/react-router/issue-7457/src/vite-env.d.ts create mode 100644 e2e/react-router/issue-7457/tests/issue-7457.repro.spec.ts create mode 100644 e2e/react-router/issue-7457/tsconfig.json create mode 100644 e2e/react-router/issue-7457/vite.config.js create mode 100644 e2e/react-start/issue-6221/.gitignore create mode 100644 e2e/react-start/issue-6221/package.json create mode 100644 e2e/react-start/issue-6221/playwright.config.ts create mode 100644 e2e/react-start/issue-6221/src/routeTree.gen.ts create mode 100644 e2e/react-start/issue-6221/src/router.tsx create mode 100644 e2e/react-start/issue-6221/src/routes/__root.tsx create mode 100644 e2e/react-start/issue-6221/src/routes/article.$id.tsx create mode 100644 e2e/react-start/issue-6221/src/routes/dashboard.tsx create mode 100644 e2e/react-start/issue-6221/src/routes/index.tsx create mode 100644 e2e/react-start/issue-6221/src/routes/login.tsx create mode 100644 e2e/react-start/issue-6221/tests/head.spec.ts create mode 100644 e2e/react-start/issue-6221/tsconfig.json create mode 100644 e2e/react-start/issue-6221/vite.config.ts create mode 100644 e2e/react-start/selective-ssr/src/routes/ssr-false-pending-min.tsx create mode 100644 e2e/solid-start/selective-ssr/src/routes/ssr-false-pending-min.tsx create mode 100644 e2e/vue-start/selective-ssr/src/routes/ssr-false-pending-min.tsx create mode 100644 packages/router-core/INTERNALS.md create mode 100644 packages/router-core/src/load-matches.client.ts create mode 100644 packages/router-core/src/load-matches.server.ts create mode 100644 packages/router-core/src/location-change.ts create mode 100644 packages/router-core/src/route-assets.client.ts create mode 100644 packages/router-core/src/route-assets.server.ts create mode 100644 packages/router-core/src/route-chunks.ts create mode 100644 packages/router-core/src/router-load.client.ts create mode 100644 packages/router-core/src/router-load.server.ts create mode 100644 packages/router-core/src/router-preload.client.ts diff --git a/.changeset/violet-poets-wait.md b/.changeset/violet-poets-wait.md new file mode 100644 index 0000000000..9cb332593a --- /dev/null +++ b/.changeset/violet-poets-wait.md @@ -0,0 +1,17 @@ +--- +'@tanstack/router-core': patch +'@tanstack/react-router': patch +'@tanstack/solid-router': patch +'@tanstack/vue-router': patch +'@tanstack/start-server-core': patch +--- + +Fix match loading consistency across client navigation, preloading, background reloads, server rendering, and hydration. + +- `beforeLoad` context is now propagated to descendant loaders and components during background reloads, preloaded navigation, route re-entry while background work is still in flight, and error or notFound states. +- Redirects no longer use a renderable `RouteMatch.status`; `RouteMatch.status` is now `'pending' | 'success' | 'error' | 'notFound'`. Abandoned, redirected, or failed matches are dropped from cache and their readiness promises are settled so stale suspense work cannot keep rendering suspended. +- Route assets from `head` and `scripts` are projected from the committed match lane after loader data is current, including preloaded navigations, background reloads, and SSR hydration. +- Pending UI and `pendingMinMs` now remain owned by match loading, so long-running `beforeLoad` or loader work does not prematurely clear pending fallbacks. +- SSR hydration now handles dehydrated and data-only matches in a dedicated hydration pass, restoring route context and assets without rerunning client loaders. +- Server loading now has a dedicated path for status codes, redirects, notFound and error responses. +- React, Solid, and Vue match rendering now consume the simplified match readiness model, including aborted loader errors, SSR/data-only pending fallbacks, and stale render snapshots. diff --git a/docs/router/api/router/RouteMatchType.md b/docs/router/api/router/RouteMatchType.md index 251c2c031e..67fe4f17f6 100644 --- a/docs/router/api/router/RouteMatchType.md +++ b/docs/router/api/router/RouteMatchType.md @@ -11,7 +11,7 @@ interface RouteMatch { routeId: string pathname: string params: Route['allParams'] - status: 'pending' | 'success' | 'error' | 'redirected' | 'notFound' + status: 'pending' | 'success' | 'error' | 'notFound' isFetching: false | 'beforeLoad' | 'loader' showPending: boolean error: unknown diff --git a/docs/router/api/router/RouterStateType.md b/docs/router/api/router/RouterStateType.md index a77f4e775f..f49ccb1a7c 100644 --- a/docs/router/api/router/RouterStateType.md +++ b/docs/router/api/router/RouterStateType.md @@ -9,7 +9,6 @@ The `RouterState` type represents shape of the internal state of the router. The type RouterState = { status: 'pending' | 'idle' isLoading: boolean - isTransitioning: boolean matches: Array location: ParsedLocation resolvedLocation: ParsedLocation @@ -30,11 +29,6 @@ The `RouterState` type contains all of the properties that are available on the - Type: `boolean` - `true` if the router is currently loading a route or waiting for a route to finish loading. -### `isTransitioning` property - -- Type: `boolean` -- `true` if the router is currently transitioning to a new route. - ### `matches` property - Type: [`Array`](./RouteMatchType.md) diff --git a/docs/router/how-to/debug-router-issues.md b/docs/router/how-to/debug-router-issues.md index b4d20ec72f..068cbfed1a 100644 --- a/docs/router/how-to/debug-router-issues.md +++ b/docs/router/how-to/debug-router-issues.md @@ -326,7 +326,6 @@ function DataLoadingDebug() { console.log('Route status:', { isLoading: location.isLoading, - isTransitioning: location.isTransitioning, }) return null diff --git a/e2e/react-router/basic-file-based/tests/app.spec.ts b/e2e/react-router/basic-file-based/tests/app.spec.ts index ae87d350ce..62ae2cfb73 100644 --- a/e2e/react-router/basic-file-based/tests/app.spec.ts +++ b/e2e/react-router/basic-file-based/tests/app.spec.ts @@ -246,7 +246,7 @@ async function getRenderCount(page: Page) { return renderCount } async function structuralSharingTest(page: Page, enabled: boolean) { - page.goto(`/structural-sharing/${enabled}/?foo=f1&bar=b1`) + await page.goto(`/structural-sharing/${enabled}/?foo=f1&bar=b1`) await expect(page.getByTestId('enabled')).toHaveText(JSON.stringify(enabled)) async function checkSearch({ foo, bar }: { foo: string; bar: string }) { @@ -268,9 +268,9 @@ async function structuralSharingTest(page: Page, enabled: boolean) { test('structural sharing disabled', async ({ page }) => { await structuralSharingTest(page, false) - expect(await getRenderCount(page)).toBe(2) + expect(await getRenderCount(page)).toBe(3) await page.getByTestId('link').click() - expect(await getRenderCount(page)).toBeGreaterThan(2) + expect(await getRenderCount(page)).toBeGreaterThan(3) }) test('structural sharing enabled', async ({ page }) => { diff --git a/e2e/react-router/issue-7120/index.html b/e2e/react-router/issue-7120/index.html new file mode 100644 index 0000000000..de92cad2a3 --- /dev/null +++ b/e2e/react-router/issue-7120/index.html @@ -0,0 +1,12 @@ + + + + + + Issue 7120 + + +
+ + + diff --git a/e2e/react-router/issue-7120/package.json b/e2e/react-router/issue-7120/package.json new file mode 100644 index 0000000000..da30014471 --- /dev/null +++ b/e2e/react-router/issue-7120/package.json @@ -0,0 +1,26 @@ +{ + "name": "tanstack-router-e2e-react-issue-7120", + "private": true, + "type": "module", + "scripts": { + "dev": "vite --port 3000", + "dev:e2e": "vite", + "build": "vite build && tsc --noEmit", + "preview": "vite preview", + "start": "vite", + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + }, + "dependencies": { + "@tanstack/react-router": "workspace:^", + "react": "^19.0.0", + "react-dom": "^19.0.0" + }, + "devDependencies": { + "@playwright/test": "^1.50.1", + "@tanstack/router-e2e-utils": "workspace:^", + "@types/react": "^19.0.8", + "@types/react-dom": "^19.0.3", + "@vitejs/plugin-react": "^6.0.1", + "vite": "^8.0.14" + } +} diff --git a/e2e/react-router/issue-7120/playwright.config.ts b/e2e/react-router/issue-7120/playwright.config.ts new file mode 100644 index 0000000000..6ba60eaff1 --- /dev/null +++ b/e2e/react-router/issue-7120/playwright.config.ts @@ -0,0 +1,27 @@ +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: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} pnpm build && pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, + stdout: 'pipe', + }, + projects: [ + { + name: 'chromium', + use: { ...devices['Desktop Chrome'] }, + }, + ], +}) diff --git a/e2e/react-router/issue-7120/src/main.tsx b/e2e/react-router/issue-7120/src/main.tsx new file mode 100644 index 0000000000..08c46f529a --- /dev/null +++ b/e2e/react-router/issue-7120/src/main.tsx @@ -0,0 +1,72 @@ +import ReactDOM from 'react-dom/client' +import { + Outlet, + RouterProvider, + createRootRoute, + createRoute, + createRouter, + redirect, +} from '@tanstack/react-router' + +const posts = [ + { + id: '1', + title: 'sunt aut facere repellat provident occaecati', + }, +] + +const rootRoute = createRootRoute({ + component: RootComponent, + pendingMs: 0, + pendingComponent: () => { + ;(globalThis as any).__pendingSeen = true + return
loading
+ }, + beforeLoad: async ({ matches }) => { + if (matches.find((match) => match.routeId === '/posts')) { + return + } + + await new Promise((resolve) => setTimeout(resolve, 1000)) + throw redirect({ to: '/posts' }) + }, +}) + +function RootComponent() { + return +} + +const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
Home
, +}) + +const postsRoute = createRoute({ + getParentRoute: () => rootRoute, + path: 'posts', + loader: async () => { + await new Promise((resolve) => setTimeout(resolve, 10)) + return posts + }, +}).lazy(() => import('./posts.lazy').then((d) => d.Route)) + +const routeTree = rootRoute.addChildren([indexRoute, postsRoute]) + +const router = createRouter({ + routeTree, + defaultViewTransition: true, +}) + +declare module '@tanstack/react-router' { + interface Register { + router: typeof router + } +} + +const rootElement = document.getElementById('app')! + +if (!rootElement.innerHTML) { + const root = ReactDOM.createRoot(rootElement) + root.render() +} diff --git a/e2e/react-router/issue-7120/src/posts.lazy.tsx b/e2e/react-router/issue-7120/src/posts.lazy.tsx new file mode 100644 index 0000000000..f2635f2e08 --- /dev/null +++ b/e2e/react-router/issue-7120/src/posts.lazy.tsx @@ -0,0 +1,25 @@ +import { Link, createLazyRoute } from '@tanstack/react-router' + +export const Route = createLazyRoute('/posts')({ + component: PostsComponent, +}) + +function PostsComponent() { + const posts = Route.useLoaderData() + + return ( +
+
    + {posts.map((post) => { + return ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ) + })} +
+
+ ) +} diff --git a/e2e/react-router/issue-7120/tests/issue-7120.repro.spec.ts b/e2e/react-router/issue-7120/tests/issue-7120.repro.spec.ts new file mode 100644 index 0000000000..3b4d9a65cb --- /dev/null +++ b/e2e/react-router/issue-7120/tests/issue-7120.repro.spec.ts @@ -0,0 +1,28 @@ +import { expect, test } from '@playwright/test' + +test('root beforeLoad redirect does not blank when pending UI and view transitions are enabled (https://github.com/TanStack/router/issues/7120)', async ({ + page, +}) => { + const pageErrors: Array = [] + const consoleErrors: Array = [] + + page.on('pageerror', (error) => { + pageErrors.push(error.message) + }) + page.on('console', (message) => { + if (message.type() === 'error') { + consoleErrors.push(message.text()) + } + }) + + await page.goto('/') + + await expect(page).toHaveURL(/\/posts$/) + await expect(page.getByText('sunt aut facere repe')).toBeVisible() + await expect + .poll(() => page.evaluate(() => (globalThis as any).__pendingSeen)) + .toBe(true) + await expect(page.getByTestId('root-pending')).not.toBeVisible() + expect(pageErrors).toEqual([]) + expect(consoleErrors).toEqual([]) +}) diff --git a/e2e/react-router/issue-7120/tsconfig.json b/e2e/react-router/issue-7120/tsconfig.json new file mode 100644 index 0000000000..4f6089bc08 --- /dev/null +++ b/e2e/react-router/issue-7120/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "jsx": "react-jsx", + "target": "ESNext", + "moduleResolution": "Bundler", + "module": "ESNext", + "resolveJsonModule": true, + "allowJs": true, + "skipLibCheck": true, + "types": ["vite/client"] + }, + "exclude": ["node_modules", "dist"] +} diff --git a/e2e/react-router/issue-7120/vite.config.js b/e2e/react-router/issue-7120/vite.config.js new file mode 100644 index 0000000000..9ffcc67574 --- /dev/null +++ b/e2e/react-router/issue-7120/vite.config.js @@ -0,0 +1,6 @@ +import { defineConfig } from 'vite' +import react from '@vitejs/plugin-react' + +export default defineConfig({ + plugins: [react()], +}) diff --git a/e2e/react-router/issue-7457/index.html b/e2e/react-router/issue-7457/index.html new file mode 100644 index 0000000000..76369b5957 --- /dev/null +++ b/e2e/react-router/issue-7457/index.html @@ -0,0 +1,10 @@ + + + + + + Issue 7457 + + + + diff --git a/e2e/react-router/issue-7457/package.json b/e2e/react-router/issue-7457/package.json new file mode 100644 index 0000000000..9d9413e213 --- /dev/null +++ b/e2e/react-router/issue-7457/package.json @@ -0,0 +1,27 @@ +{ + "name": "tanstack-router-e2e-react-issue-7457", + "private": true, + "type": "module", + "scripts": { + "dev": "vite --port 3000", + "dev:e2e": "vite", + "build": "vite build && tsc --noEmit", + "preview": "vite preview", + "start": "vite", + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + }, + "dependencies": { + "@tanstack/react-router": "workspace:^", + "@tanstack/router-plugin": "workspace:^", + "react": "^19.0.0", + "react-dom": "^19.0.0" + }, + "devDependencies": { + "@playwright/test": "^1.50.1", + "@tanstack/router-e2e-utils": "workspace:^", + "@types/react": "^19.0.8", + "@types/react-dom": "^19.0.3", + "@vitejs/plugin-react": "^6.0.1", + "vite": "^8.0.14" + } +} diff --git a/e2e/react-router/issue-7457/playwright.config.ts b/e2e/react-router/issue-7457/playwright.config.ts new file mode 100644 index 0000000000..6ba60eaff1 --- /dev/null +++ b/e2e/react-router/issue-7457/playwright.config.ts @@ -0,0 +1,27 @@ +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: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} pnpm build && pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, + stdout: 'pipe', + }, + projects: [ + { + name: 'chromium', + use: { ...devices['Desktop Chrome'] }, + }, + ], +}) diff --git a/e2e/react-router/issue-7457/src/main.tsx b/e2e/react-router/issue-7457/src/main.tsx new file mode 100644 index 0000000000..ccf8ec77b2 --- /dev/null +++ b/e2e/react-router/issue-7457/src/main.tsx @@ -0,0 +1,28 @@ +import { StrictMode } from 'react' +import { createRoot } from 'react-dom/client' +import { RouterProvider, createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +const router = createRouter({ + routeTree, + defaultPendingComponent: DefaultPendingComponent, + defaultPreloadStaleTime: 0, +}) + +declare module '@tanstack/react-router' { + interface Register { + router: typeof router + } +} + +function DefaultPendingComponent() { + ;(globalThis as any).__pendingSeen = true + + return
loading
+} + +createRoot(document.body).render( + + + , +) diff --git a/e2e/react-router/issue-7457/src/routeTree.gen.ts b/e2e/react-router/issue-7457/src/routeTree.gen.ts new file mode 100644 index 0000000000..72a8f23384 --- /dev/null +++ b/e2e/react-router/issue-7457/src/routeTree.gen.ts @@ -0,0 +1,77 @@ +/* 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 AnotherRouteImport } from './routes/another' +import { Route as IndexRouteImport } from './routes/index' + +const AnotherRoute = AnotherRouteImport.update({ + id: '/another', + path: '/another', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/another': typeof AnotherRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/another': typeof AnotherRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/another': typeof AnotherRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/another' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/another' + id: '__root__' | '/' | '/another' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + AnotherRoute: typeof AnotherRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/another': { + id: '/another' + path: '/another' + fullPath: '/another' + preLoaderRoute: typeof AnotherRouteImport + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + AnotherRoute: AnotherRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/e2e/react-router/issue-7457/src/routes/__root.tsx b/e2e/react-router/issue-7457/src/routes/__root.tsx new file mode 100644 index 0000000000..d3dced6736 --- /dev/null +++ b/e2e/react-router/issue-7457/src/routes/__root.tsx @@ -0,0 +1,16 @@ +import { Outlet, createRootRoute } from '@tanstack/react-router' + +export const Route = createRootRoute({ + beforeLoad: async () => { + await new Promise((resolve) => setTimeout(resolve, 1500)) + }, + component: RootComponent, +}) + +function RootComponent() { + return ( +
+ +
+ ) +} diff --git a/e2e/react-router/issue-7457/src/routes/another.tsx b/e2e/react-router/issue-7457/src/routes/another.tsx new file mode 100644 index 0000000000..2274ee634b --- /dev/null +++ b/e2e/react-router/issue-7457/src/routes/another.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/another')({ + component: RouteComponent, +}) + +function RouteComponent() { + return
Hello "/another"!
+} diff --git a/e2e/react-router/issue-7457/src/routes/index.tsx b/e2e/react-router/issue-7457/src/routes/index.tsx new file mode 100644 index 0000000000..91f9a1c4eb --- /dev/null +++ b/e2e/react-router/issue-7457/src/routes/index.tsx @@ -0,0 +1,15 @@ +import { createFileRoute, redirect } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + beforeLoad: () => { + throw redirect({ + to: '/another', + replace: true, + }) + }, + component: RouteComponent, +}) + +function RouteComponent() { + return
You should never see this!
+} diff --git a/e2e/react-router/issue-7457/src/vite-env.d.ts b/e2e/react-router/issue-7457/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/e2e/react-router/issue-7457/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/e2e/react-router/issue-7457/tests/issue-7457.repro.spec.ts b/e2e/react-router/issue-7457/tests/issue-7457.repro.spec.ts new file mode 100644 index 0000000000..fd1c582bcf --- /dev/null +++ b/e2e/react-router/issue-7457/tests/issue-7457.repro.spec.ts @@ -0,0 +1,28 @@ +import { expect, test } from '@playwright/test' + +test('initial child beforeLoad redirect after async root beforeLoad does not blank (https://github.com/TanStack/router/issues/7457)', async ({ + page, +}) => { + const pageErrors: Array = [] + const consoleErrors: Array = [] + + page.on('pageerror', (error) => { + pageErrors.push(error.message || String(error)) + }) + page.on('console', (message) => { + if (message.type() === 'error') { + consoleErrors.push(message.text()) + } + }) + + await page.goto('/') + + await expect(page).toHaveURL(/\/another$/) + await expect(page.getByText('Hello "/another"!')).toBeVisible() + await expect + .poll(() => page.evaluate(() => (globalThis as any).__pendingSeen)) + .toBe(true) + await expect(page.getByTestId('app-pending')).not.toBeVisible() + expect(pageErrors).toEqual([]) + expect(consoleErrors).toEqual([]) +}) diff --git a/e2e/react-router/issue-7457/tsconfig.json b/e2e/react-router/issue-7457/tsconfig.json new file mode 100644 index 0000000000..4f6089bc08 --- /dev/null +++ b/e2e/react-router/issue-7457/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "jsx": "react-jsx", + "target": "ESNext", + "moduleResolution": "Bundler", + "module": "ESNext", + "resolveJsonModule": true, + "allowJs": true, + "skipLibCheck": true, + "types": ["vite/client"] + }, + "exclude": ["node_modules", "dist"] +} diff --git a/e2e/react-router/issue-7457/vite.config.js b/e2e/react-router/issue-7457/vite.config.js new file mode 100644 index 0000000000..9e39ea83d9 --- /dev/null +++ b/e2e/react-router/issue-7457/vite.config.js @@ -0,0 +1,10 @@ +import { defineConfig } from 'vite' +import react from '@vitejs/plugin-react' +import { tanstackRouter } from '@tanstack/router-plugin/vite' + +export default defineConfig({ + plugins: [ + tanstackRouter({ target: 'react', autoCodeSplitting: true }), + react(), + ], +}) diff --git a/e2e/react-start/issue-6221/.gitignore b/e2e/react-start/issue-6221/.gitignore new file mode 100644 index 0000000000..528451b60c --- /dev/null +++ b/e2e/react-start/issue-6221/.gitignore @@ -0,0 +1,3 @@ +dist +port*.txt +test-results diff --git a/e2e/react-start/issue-6221/package.json b/e2e/react-start/issue-6221/package.json new file mode 100644 index 0000000000..c3330ecb52 --- /dev/null +++ b/e2e/react-start/issue-6221/package.json @@ -0,0 +1,31 @@ +{ + "name": "tanstack-react-start-e2e-issue-6221", + "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": "pnpm dlx srvx --prod -s ../client dist/server/server.js", + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + }, + "dependencies": { + "@tanstack/react-router": "workspace:^", + "@tanstack/react-start": "workspace:^", + "react": "^19.0.0", + "react-dom": "^19.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", + "srvx": "^0.11.9", + "typescript": "^6.0.2", + "vite": "^8.0.14" + } +} diff --git a/e2e/react-start/issue-6221/playwright.config.ts b/e2e/react-start/issue-6221/playwright.config.ts new file mode 100644 index 0000000000..2c2952c186 --- /dev/null +++ b/e2e/react-start/issue-6221/playwright.config.ts @@ -0,0 +1,27 @@ +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: `VITE_SERVER_PORT=${PORT} pnpm build && NODE_ENV=production PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, + url: baseURL, + reuseExistingServer: !process.env.CI, + stdout: 'pipe', + }, + projects: [ + { + name: 'chromium', + use: { ...devices['Desktop Chrome'] }, + }, + ], +}) diff --git a/e2e/react-start/issue-6221/src/routeTree.gen.ts b/e2e/react-start/issue-6221/src/routeTree.gen.ts new file mode 100644 index 0000000000..010acc5542 --- /dev/null +++ b/e2e/react-start/issue-6221/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 LoginRouteImport } from './routes/login' +import { Route as DashboardRouteImport } from './routes/dashboard' +import { Route as IndexRouteImport } from './routes/index' +import { Route as ArticleIdRouteImport } from './routes/article.$id' + +const LoginRoute = LoginRouteImport.update({ + id: '/login', + path: '/login', + getParentRoute: () => rootRouteImport, +} as any) +const DashboardRoute = DashboardRouteImport.update({ + id: '/dashboard', + path: '/dashboard', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const ArticleIdRoute = ArticleIdRouteImport.update({ + id: '/article/$id', + path: '/article/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/dashboard': typeof DashboardRoute + '/login': typeof LoginRoute + '/article/$id': typeof ArticleIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/dashboard': typeof DashboardRoute + '/login': typeof LoginRoute + '/article/$id': typeof ArticleIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/dashboard': typeof DashboardRoute + '/login': typeof LoginRoute + '/article/$id': typeof ArticleIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/dashboard' | '/login' | '/article/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/dashboard' | '/login' | '/article/$id' + id: '__root__' | '/' | '/dashboard' | '/login' | '/article/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + DashboardRoute: typeof DashboardRoute + LoginRoute: typeof LoginRoute + ArticleIdRoute: typeof ArticleIdRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/login': { + id: '/login' + path: '/login' + fullPath: '/login' + preLoaderRoute: typeof LoginRouteImport + parentRoute: typeof rootRouteImport + } + '/dashboard': { + id: '/dashboard' + path: '/dashboard' + fullPath: '/dashboard' + preLoaderRoute: typeof DashboardRouteImport + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/article/$id': { + id: '/article/$id' + path: '/article/$id' + fullPath: '/article/$id' + preLoaderRoute: typeof ArticleIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + DashboardRoute: DashboardRoute, + LoginRoute: LoginRoute, + ArticleIdRoute: ArticleIdRoute, +} +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/issue-6221/src/router.tsx b/e2e/react-start/issue-6221/src/router.tsx new file mode 100644 index 0000000000..191f74ee02 --- /dev/null +++ b/e2e/react-start/issue-6221/src/router.tsx @@ -0,0 +1,8 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + }) +} diff --git a/e2e/react-start/issue-6221/src/routes/__root.tsx b/e2e/react-start/issue-6221/src/routes/__root.tsx new file mode 100644 index 0000000000..8b60be2cb9 --- /dev/null +++ b/e2e/react-start/issue-6221/src/routes/__root.tsx @@ -0,0 +1,38 @@ +/// +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: 'Issue 6221' }, + ], + }), + shellComponent: RootDocument, + component: () => , +}) + +function RootDocument({ children }: { children: React.ReactNode }) { + return ( + + + + + + + {children} + + + + ) +} diff --git a/e2e/react-start/issue-6221/src/routes/article.$id.tsx b/e2e/react-start/issue-6221/src/routes/article.$id.tsx new file mode 100644 index 0000000000..3c1b8469e6 --- /dev/null +++ b/e2e/react-start/issue-6221/src/routes/article.$id.tsx @@ -0,0 +1,50 @@ +import { Link, createFileRoute } from '@tanstack/react-router' + +type ArticleData = { + title: string + body: string +} + +const loadArticle = async (id: string): Promise => { + await new Promise((resolve) => setTimeout(resolve, 100)) + + if (window.localStorage.getItem('issue-6221-auth') !== 'true') { + return null + } + + return { + title: `Article ${id} Title`, + body: `Article ${id} body`, + } +} + +export const Route = createFileRoute('/article/$id')({ + ssr: false, + loader: ({ params }) => loadArticle(params.id), + head: ({ loaderData }) => ({ + meta: [{ title: loaderData?.title ?? 'Article Not Found' }], + }), + component: Article, +}) + +function Article() { + const article = Route.useLoaderData() + + if (!article) { + return ( +
+

Article not found

+ + Go to login + +
+ ) + } + + return ( +
+

{article.title}

+

{article.body}

+
+ ) +} diff --git a/e2e/react-start/issue-6221/src/routes/dashboard.tsx b/e2e/react-start/issue-6221/src/routes/dashboard.tsx new file mode 100644 index 0000000000..dc03c1f4e1 --- /dev/null +++ b/e2e/react-start/issue-6221/src/routes/dashboard.tsx @@ -0,0 +1,16 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/dashboard')({ + head: () => ({ + meta: [{ title: 'Dashboard' }], + }), + component: Dashboard, +}) + +function Dashboard() { + return ( +
+

Dashboard

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

Issue 6221

+ + Article 123 + +
+ ) +} diff --git a/e2e/react-start/issue-6221/src/routes/login.tsx b/e2e/react-start/issue-6221/src/routes/login.tsx new file mode 100644 index 0000000000..7d07073ea4 --- /dev/null +++ b/e2e/react-start/issue-6221/src/routes/login.tsx @@ -0,0 +1,29 @@ +import { createFileRoute, useNavigate } from '@tanstack/react-router' + +export const Route = createFileRoute('/login')({ + ssr: false, + head: () => ({ + meta: [{ title: 'Login' }], + }), + component: Login, +}) + +function Login() { + const navigate = useNavigate() + + return ( +
+

Login

+ +
+ ) +} diff --git a/e2e/react-start/issue-6221/tests/head.spec.ts b/e2e/react-start/issue-6221/tests/head.spec.ts new file mode 100644 index 0000000000..679f059c01 --- /dev/null +++ b/e2e/react-start/issue-6221/tests/head.spec.ts @@ -0,0 +1,29 @@ +import { expect } from '@playwright/test' +import { test } from '@tanstack/router-e2e-utils' + +test('updates head after a stale cached loader refreshes in the background', async ({ + page, +}) => { + await page.goto('/') + await page.evaluate(() => window.localStorage.clear()) + + await page.goto('/article/123') + await expect(page.getByTestId('article-not-found')).toBeVisible() + await expect(page).toHaveTitle('Article Not Found') + + await page.getByTestId('login-link').click() + await expect(page.getByTestId('login-page')).toBeVisible() + await expect(page).toHaveTitle('Login') + + await page.getByTestId('login-button').click() + await expect(page.getByTestId('dashboard')).toBeVisible() + await expect(page).toHaveTitle('Dashboard') + + await page.goBack() + await expect(page.getByTestId('article-content')).toBeVisible() + await expect(page.getByTestId('article-title')).toHaveText( + 'Article 123 Title', + ) + + await expect(page).toHaveTitle('Article 123 Title') +}) diff --git a/e2e/react-start/issue-6221/tsconfig.json b/e2e/react-start/issue-6221/tsconfig.json new file mode 100644 index 0000000000..cef9369516 --- /dev/null +++ b/e2e/react-start/issue-6221/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/issue-6221/vite.config.ts b/e2e/react-start/issue-6221/vite.config.ts new file mode 100644 index 0000000000..c32652e9c8 --- /dev/null +++ b/e2e/react-start/issue-6221/vite.config.ts @@ -0,0 +1,11 @@ +import { defineConfig } from 'vite' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import viteReact from '@vitejs/plugin-react' + +export default defineConfig({ + resolve: { tsconfigPaths: true }, + server: { + port: 3000, + }, + plugins: [tanstackStart(), viteReact()], +}) diff --git a/e2e/react-start/selective-ssr/src/routeTree.gen.ts b/e2e/react-start/selective-ssr/src/routeTree.gen.ts index 188cd5c91a..39a0a971b9 100644 --- a/e2e/react-start/selective-ssr/src/routeTree.gen.ts +++ b/e2e/react-start/selective-ssr/src/routeTree.gen.ts @@ -9,10 +9,16 @@ // 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 SsrFalsePendingMinRouteImport } from './routes/ssr-false-pending-min' import { Route as PostsRouteImport } from './routes/posts' import { Route as IndexRouteImport } from './routes/index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +const SsrFalsePendingMinRoute = SsrFalsePendingMinRouteImport.update({ + id: '/ssr-false-pending-min', + path: '/ssr-false-pending-min', + getParentRoute: () => rootRouteImport, +} as any) const PostsRoute = PostsRouteImport.update({ id: '/posts', path: '/posts', @@ -32,34 +38,45 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ export interface FileRoutesByFullPath { '/': typeof IndexRoute '/posts': typeof PostsRouteWithChildren + '/ssr-false-pending-min': typeof SsrFalsePendingMinRoute '/posts/$postId': typeof PostsPostIdRoute } export interface FileRoutesByTo { '/': typeof IndexRoute '/posts': typeof PostsRouteWithChildren + '/ssr-false-pending-min': typeof SsrFalsePendingMinRoute '/posts/$postId': typeof PostsPostIdRoute } export interface FileRoutesById { __root__: typeof rootRouteImport '/': typeof IndexRoute '/posts': typeof PostsRouteWithChildren + '/ssr-false-pending-min': typeof SsrFalsePendingMinRoute '/posts/$postId': typeof PostsPostIdRoute } export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/posts' | '/posts/$postId' + fullPaths: '/' | '/posts' | '/ssr-false-pending-min' | '/posts/$postId' fileRoutesByTo: FileRoutesByTo - to: '/' | '/posts' | '/posts/$postId' - id: '__root__' | '/' | '/posts' | '/posts/$postId' + to: '/' | '/posts' | '/ssr-false-pending-min' | '/posts/$postId' + id: '__root__' | '/' | '/posts' | '/ssr-false-pending-min' | '/posts/$postId' fileRoutesById: FileRoutesById } export interface RootRouteChildren { IndexRoute: typeof IndexRoute PostsRoute: typeof PostsRouteWithChildren + SsrFalsePendingMinRoute: typeof SsrFalsePendingMinRoute } declare module '@tanstack/react-router' { interface FileRoutesByPath { + '/ssr-false-pending-min': { + id: '/ssr-false-pending-min' + path: '/ssr-false-pending-min' + fullPath: '/ssr-false-pending-min' + preLoaderRoute: typeof SsrFalsePendingMinRouteImport + parentRoute: typeof rootRouteImport + } '/posts': { id: '/posts' path: '/posts' @@ -97,6 +114,7 @@ const PostsRouteWithChildren = PostsRoute._addFileChildren(PostsRouteChildren) const rootRouteChildren: RootRouteChildren = { IndexRoute: IndexRoute, PostsRoute: PostsRouteWithChildren, + SsrFalsePendingMinRoute: SsrFalsePendingMinRoute, } export const routeTree = rootRouteImport ._addFileChildren(rootRouteChildren) diff --git a/e2e/react-start/selective-ssr/src/router.tsx b/e2e/react-start/selective-ssr/src/router.tsx index 82a730704a..24eb56ec3a 100644 --- a/e2e/react-start/selective-ssr/src/router.tsx +++ b/e2e/react-start/selective-ssr/src/router.tsx @@ -9,3 +9,9 @@ export function getRouter() { return router } + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} diff --git a/e2e/react-start/selective-ssr/src/routes/ssr-false-pending-min.tsx b/e2e/react-start/selective-ssr/src/routes/ssr-false-pending-min.tsx new file mode 100644 index 0000000000..64b8362a86 --- /dev/null +++ b/e2e/react-start/selective-ssr/src/routes/ssr-false-pending-min.tsx @@ -0,0 +1,49 @@ +import * as React from 'react' +import { createFileRoute } from '@tanstack/react-router' + +const pendingMinMs = 1500 + +function recordEvent(type: string) { + if (typeof window === 'undefined') { + return + } + + const global = window as any + global.__events ??= [] + global.__events.push({ type, t: performance.now() }) +} + +function Pending() { + React.useEffect(() => { + recordEvent('pending-mounted') + + return () => { + recordEvent('pending-unmounted') + } + }, []) + + return
Loading SSR false route...
+} + +function Target() { + React.useEffect(() => { + recordEvent('target-mounted') + }, []) + + return
SSR false route loaded
+} + +export const Route = createFileRoute('/ssr-false-pending-min')({ + ssr: false, + pendingMs: 0, + pendingMinMs, + pendingComponent: Pending, + loader: async () => { + recordEvent('loader-start') + await new Promise((resolve) => setTimeout(resolve, 50)) + recordEvent('loader-done') + + return { ok: true } + }, + component: Target, +}) diff --git a/e2e/react-start/selective-ssr/tests/app.spec.ts b/e2e/react-start/selective-ssr/tests/app.spec.ts index aea216d506..b14c7e028a 100644 --- a/e2e/react-start/selective-ssr/tests/app.spec.ts +++ b/e2e/react-start/selective-ssr/tests/app.spec.ts @@ -1,8 +1,73 @@ import { expect } from '@playwright/test' import { test } from '@tanstack/router-e2e-utils' +import type { Page } from '@playwright/test' const testCount = 7 +type BrowserEvent = { type: string; t: number } + +function findEvent(events: Array, type: string) { + const event = events.find((entry) => entry.type === type) + expect(event, `Expected browser event "${type}"`).toBeTruthy() + return event! +} + +function findLastEvent(events: Array, type: string) { + let event: BrowserEvent | undefined + for (let index = events.length - 1; index >= 0; index--) { + if (events[index]!.type === type) { + event = events[index] + break + } + } + expect(event, `Expected browser event "${type}"`).toBeTruthy() + return event! +} + +async function expectSsrFalsePendingMin(page: Page) { + const errors: Array = [] + + page.on('pageerror', (err) => { + errors.push(err.message) + }) + page.on('console', (msg) => { + if (msg.type() === 'error') { + errors.push(msg.text()) + } + }) + + await page.goto('/ssr-false-pending-min') + + const pending = page.getByTestId('ssr-false-pending') + const visiblePending = page.locator( + '[data-testid="ssr-false-pending"]:visible', + ) + const target = page.getByTestId('ssr-false-target') + + await expect(visiblePending).toHaveCount(1) + + await page.waitForTimeout(500) + + await expect(visiblePending).toHaveCount(1) + await expect(target).toBeHidden() + + await expect(target).toBeVisible() + await expect(pending).toHaveCount(0) + + const events = await page.evaluate>( + () => (window as any).__events ?? [], + ) + const pendingMounted = findEvent(events, 'pending-mounted') + const pendingUnmounted = findLastEvent(events, 'pending-unmounted') + const targetMounted = findEvent(events, 'target-mounted') + const loaderDone = findEvent(events, 'loader-done') + + expect(loaderDone.t - pendingMounted.t).toBeLessThan(500) + expect(pendingUnmounted.t - pendingMounted.t).toBeGreaterThanOrEqual(1400) + expect(targetMounted.t - pendingMounted.t).toBeGreaterThanOrEqual(1400) + expect(errors).toEqual([]) +} + test.describe('selective ssr', () => { test('testcount matches', async ({ page }) => { await page.goto('/') @@ -38,4 +103,10 @@ test.describe('selective ssr', () => { await expect(page.getByTestId('router-status')).toContainText('idle') }) } + + test('direct ssr false hydration keeps pending visible for pendingMinMs', async ({ + page, + }) => { + await expectSsrFalsePendingMin(page) + }) }) diff --git a/e2e/solid-start/basic-auth/package.json b/e2e/solid-start/basic-auth/package.json index dc99d114fe..12ac82d514 100644 --- a/e2e/solid-start/basic-auth/package.json +++ b/e2e/solid-start/basic-auth/package.json @@ -10,7 +10,7 @@ "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", "prisma-generate": "prisma generate", - "test:e2e": "rm -rf port*.txt; mkdir -p .tmp; rm -f .tmp/dev.db .tmp/dev.db-journal .tmp/dev.db-wal .tmp/dev.db-shm; export DATABASE_URL=file:./.tmp/dev.db; pnpm run prisma-generate && pnpm exec prisma migrate deploy && playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; mkdir -p .tmp; rm -f .tmp/dev.db .tmp/dev.db-journal .tmp/dev.db-wal .tmp/dev.db-shm; touch .tmp/dev.db; export DATABASE_URL=file:./.tmp/dev.db; pnpm run prisma-generate && pnpm exec prisma migrate deploy && playwright test --project=chromium" }, "dependencies": { "@libsql/client": "^0.15.15", diff --git a/e2e/solid-start/selective-ssr/src/routeTree.gen.ts b/e2e/solid-start/selective-ssr/src/routeTree.gen.ts index df2b865e51..8fb128de38 100644 --- a/e2e/solid-start/selective-ssr/src/routeTree.gen.ts +++ b/e2e/solid-start/selective-ssr/src/routeTree.gen.ts @@ -9,11 +9,17 @@ // 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 SsrFalsePendingMinRouteImport } from './routes/ssr-false-pending-min' import { Route as PostsRouteImport } from './routes/posts' import { Route as DataOnlyPendingComponentRouteImport } from './routes/data-only-pending-component' import { Route as IndexRouteImport } from './routes/index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +const SsrFalsePendingMinRoute = SsrFalsePendingMinRouteImport.update({ + id: '/ssr-false-pending-min', + path: '/ssr-false-pending-min', + getParentRoute: () => rootRouteImport, +} as any) const PostsRoute = PostsRouteImport.update({ id: '/posts', path: '/posts', @@ -40,12 +46,14 @@ export interface FileRoutesByFullPath { '/': typeof IndexRoute '/data-only-pending-component': typeof DataOnlyPendingComponentRoute '/posts': typeof PostsRouteWithChildren + '/ssr-false-pending-min': typeof SsrFalsePendingMinRoute '/posts/$postId': typeof PostsPostIdRoute } export interface FileRoutesByTo { '/': typeof IndexRoute '/data-only-pending-component': typeof DataOnlyPendingComponentRoute '/posts': typeof PostsRouteWithChildren + '/ssr-false-pending-min': typeof SsrFalsePendingMinRoute '/posts/$postId': typeof PostsPostIdRoute } export interface FileRoutesById { @@ -53,18 +61,30 @@ export interface FileRoutesById { '/': typeof IndexRoute '/data-only-pending-component': typeof DataOnlyPendingComponentRoute '/posts': typeof PostsRouteWithChildren + '/ssr-false-pending-min': typeof SsrFalsePendingMinRoute '/posts/$postId': typeof PostsPostIdRoute } export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/data-only-pending-component' | '/posts' | '/posts/$postId' + fullPaths: + | '/' + | '/data-only-pending-component' + | '/posts' + | '/ssr-false-pending-min' + | '/posts/$postId' fileRoutesByTo: FileRoutesByTo - to: '/' | '/data-only-pending-component' | '/posts' | '/posts/$postId' + to: + | '/' + | '/data-only-pending-component' + | '/posts' + | '/ssr-false-pending-min' + | '/posts/$postId' id: | '__root__' | '/' | '/data-only-pending-component' | '/posts' + | '/ssr-false-pending-min' | '/posts/$postId' fileRoutesById: FileRoutesById } @@ -72,10 +92,18 @@ export interface RootRouteChildren { IndexRoute: typeof IndexRoute DataOnlyPendingComponentRoute: typeof DataOnlyPendingComponentRoute PostsRoute: typeof PostsRouteWithChildren + SsrFalsePendingMinRoute: typeof SsrFalsePendingMinRoute } declare module '@tanstack/solid-router' { interface FileRoutesByPath { + '/ssr-false-pending-min': { + id: '/ssr-false-pending-min' + path: '/ssr-false-pending-min' + fullPath: '/ssr-false-pending-min' + preLoaderRoute: typeof SsrFalsePendingMinRouteImport + parentRoute: typeof rootRouteImport + } '/posts': { id: '/posts' path: '/posts' @@ -121,6 +149,7 @@ const rootRouteChildren: RootRouteChildren = { IndexRoute: IndexRoute, DataOnlyPendingComponentRoute: DataOnlyPendingComponentRoute, PostsRoute: PostsRouteWithChildren, + SsrFalsePendingMinRoute: SsrFalsePendingMinRoute, } export const routeTree = rootRouteImport ._addFileChildren(rootRouteChildren) diff --git a/e2e/solid-start/selective-ssr/src/routes/ssr-false-pending-min.tsx b/e2e/solid-start/selective-ssr/src/routes/ssr-false-pending-min.tsx new file mode 100644 index 0000000000..82425f9575 --- /dev/null +++ b/e2e/solid-start/selective-ssr/src/routes/ssr-false-pending-min.tsx @@ -0,0 +1,48 @@ +import { onCleanup, onMount } from 'solid-js' +import { createFileRoute } from '@tanstack/solid-router' + +const pendingMinMs = 1500 + +function recordEvent(type: string) { + if (typeof window === 'undefined') { + return + } + + const global = window as any + global.__events ??= [] + global.__events.push({ type, t: performance.now() }) +} + +function Pending() { + onMount(() => { + recordEvent('pending-mounted') + }) + onCleanup(() => { + recordEvent('pending-unmounted') + }) + + return
Loading SSR false route...
+} + +function Target() { + onMount(() => { + recordEvent('target-mounted') + }) + + return
SSR false route loaded
+} + +export const Route = createFileRoute('/ssr-false-pending-min')({ + ssr: false, + pendingMs: 0, + pendingMinMs, + pendingComponent: Pending, + loader: async () => { + recordEvent('loader-start') + await new Promise((resolve) => setTimeout(resolve, 50)) + recordEvent('loader-done') + + return { ok: true } + }, + component: Target, +}) diff --git a/e2e/solid-start/selective-ssr/tests/app.spec.ts b/e2e/solid-start/selective-ssr/tests/app.spec.ts index aea216d506..b14c7e028a 100644 --- a/e2e/solid-start/selective-ssr/tests/app.spec.ts +++ b/e2e/solid-start/selective-ssr/tests/app.spec.ts @@ -1,8 +1,73 @@ import { expect } from '@playwright/test' import { test } from '@tanstack/router-e2e-utils' +import type { Page } from '@playwright/test' const testCount = 7 +type BrowserEvent = { type: string; t: number } + +function findEvent(events: Array, type: string) { + const event = events.find((entry) => entry.type === type) + expect(event, `Expected browser event "${type}"`).toBeTruthy() + return event! +} + +function findLastEvent(events: Array, type: string) { + let event: BrowserEvent | undefined + for (let index = events.length - 1; index >= 0; index--) { + if (events[index]!.type === type) { + event = events[index] + break + } + } + expect(event, `Expected browser event "${type}"`).toBeTruthy() + return event! +} + +async function expectSsrFalsePendingMin(page: Page) { + const errors: Array = [] + + page.on('pageerror', (err) => { + errors.push(err.message) + }) + page.on('console', (msg) => { + if (msg.type() === 'error') { + errors.push(msg.text()) + } + }) + + await page.goto('/ssr-false-pending-min') + + const pending = page.getByTestId('ssr-false-pending') + const visiblePending = page.locator( + '[data-testid="ssr-false-pending"]:visible', + ) + const target = page.getByTestId('ssr-false-target') + + await expect(visiblePending).toHaveCount(1) + + await page.waitForTimeout(500) + + await expect(visiblePending).toHaveCount(1) + await expect(target).toBeHidden() + + await expect(target).toBeVisible() + await expect(pending).toHaveCount(0) + + const events = await page.evaluate>( + () => (window as any).__events ?? [], + ) + const pendingMounted = findEvent(events, 'pending-mounted') + const pendingUnmounted = findLastEvent(events, 'pending-unmounted') + const targetMounted = findEvent(events, 'target-mounted') + const loaderDone = findEvent(events, 'loader-done') + + expect(loaderDone.t - pendingMounted.t).toBeLessThan(500) + expect(pendingUnmounted.t - pendingMounted.t).toBeGreaterThanOrEqual(1400) + expect(targetMounted.t - pendingMounted.t).toBeGreaterThanOrEqual(1400) + expect(errors).toEqual([]) +} + test.describe('selective ssr', () => { test('testcount matches', async ({ page }) => { await page.goto('/') @@ -38,4 +103,10 @@ test.describe('selective ssr', () => { await expect(page.getByTestId('router-status')).toContainText('idle') }) } + + test('direct ssr false hydration keeps pending visible for pendingMinMs', async ({ + page, + }) => { + await expectSsrFalsePendingMin(page) + }) }) diff --git a/e2e/vue-router/view-transitions/tests/view-transitions.spec.ts b/e2e/vue-router/view-transitions/tests/view-transitions.spec.ts index 31d8b12b04..d38e059360 100644 --- a/e2e/vue-router/view-transitions/tests/view-transitions.spec.ts +++ b/e2e/vue-router/view-transitions/tests/view-transitions.spec.ts @@ -20,7 +20,8 @@ test.beforeEach(async ({ page }) => { // ignore } - return { finished: Promise.resolve() } + const updateCallbackDone = Promise.resolve() + return { finished: updateCallbackDone, updateCallbackDone } } }) diff --git a/e2e/vue-start/basic-auth/package.json b/e2e/vue-start/basic-auth/package.json index 3a572536e9..cb3b0cd166 100644 --- a/e2e/vue-start/basic-auth/package.json +++ b/e2e/vue-start/basic-auth/package.json @@ -10,7 +10,7 @@ "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", "prisma-generate": "prisma generate", - "test:e2e": "rm -rf port*.txt; mkdir -p .tmp; rm -f .tmp/dev.db .tmp/dev.db-journal .tmp/dev.db-wal .tmp/dev.db-shm; export DATABASE_URL=file:./.tmp/dev.db; pnpm run prisma-generate && pnpm exec prisma migrate deploy && playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; mkdir -p .tmp; rm -f .tmp/dev.db .tmp/dev.db-journal .tmp/dev.db-wal .tmp/dev.db-shm; touch .tmp/dev.db; export DATABASE_URL=file:./.tmp/dev.db; pnpm run prisma-generate && pnpm exec prisma migrate deploy && playwright test --project=chromium" }, "dependencies": { "@libsql/client": "^0.15.15", diff --git a/e2e/vue-start/selective-ssr/src/routeTree.gen.ts b/e2e/vue-start/selective-ssr/src/routeTree.gen.ts index 474705b7e7..217a30eb9f 100644 --- a/e2e/vue-start/selective-ssr/src/routeTree.gen.ts +++ b/e2e/vue-start/selective-ssr/src/routeTree.gen.ts @@ -9,10 +9,16 @@ // 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 SsrFalsePendingMinRouteImport } from './routes/ssr-false-pending-min' import { Route as PostsRouteImport } from './routes/posts' import { Route as IndexRouteImport } from './routes/index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +const SsrFalsePendingMinRoute = SsrFalsePendingMinRouteImport.update({ + id: '/ssr-false-pending-min', + path: '/ssr-false-pending-min', + getParentRoute: () => rootRouteImport, +} as any) const PostsRoute = PostsRouteImport.update({ id: '/posts', path: '/posts', @@ -32,34 +38,45 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ export interface FileRoutesByFullPath { '/': typeof IndexRoute '/posts': typeof PostsRouteWithChildren + '/ssr-false-pending-min': typeof SsrFalsePendingMinRoute '/posts/$postId': typeof PostsPostIdRoute } export interface FileRoutesByTo { '/': typeof IndexRoute '/posts': typeof PostsRouteWithChildren + '/ssr-false-pending-min': typeof SsrFalsePendingMinRoute '/posts/$postId': typeof PostsPostIdRoute } export interface FileRoutesById { __root__: typeof rootRouteImport '/': typeof IndexRoute '/posts': typeof PostsRouteWithChildren + '/ssr-false-pending-min': typeof SsrFalsePendingMinRoute '/posts/$postId': typeof PostsPostIdRoute } export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/posts' | '/posts/$postId' + fullPaths: '/' | '/posts' | '/ssr-false-pending-min' | '/posts/$postId' fileRoutesByTo: FileRoutesByTo - to: '/' | '/posts' | '/posts/$postId' - id: '__root__' | '/' | '/posts' | '/posts/$postId' + to: '/' | '/posts' | '/ssr-false-pending-min' | '/posts/$postId' + id: '__root__' | '/' | '/posts' | '/ssr-false-pending-min' | '/posts/$postId' fileRoutesById: FileRoutesById } export interface RootRouteChildren { IndexRoute: typeof IndexRoute PostsRoute: typeof PostsRouteWithChildren + SsrFalsePendingMinRoute: typeof SsrFalsePendingMinRoute } declare module '@tanstack/vue-router' { interface FileRoutesByPath { + '/ssr-false-pending-min': { + id: '/ssr-false-pending-min' + path: '/ssr-false-pending-min' + fullPath: '/ssr-false-pending-min' + preLoaderRoute: typeof SsrFalsePendingMinRouteImport + parentRoute: typeof rootRouteImport + } '/posts': { id: '/posts' path: '/posts' @@ -97,6 +114,7 @@ const PostsRouteWithChildren = PostsRoute._addFileChildren(PostsRouteChildren) const rootRouteChildren: RootRouteChildren = { IndexRoute: IndexRoute, PostsRoute: PostsRouteWithChildren, + SsrFalsePendingMinRoute: SsrFalsePendingMinRoute, } export const routeTree = rootRouteImport ._addFileChildren(rootRouteChildren) diff --git a/e2e/vue-start/selective-ssr/src/routes/ssr-false-pending-min.tsx b/e2e/vue-start/selective-ssr/src/routes/ssr-false-pending-min.tsx new file mode 100644 index 0000000000..17bbd702ab --- /dev/null +++ b/e2e/vue-start/selective-ssr/src/routes/ssr-false-pending-min.tsx @@ -0,0 +1,56 @@ +import { defineComponent, onMounted, onUnmounted } from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const pendingMinMs = 1500 + +function recordEvent(type: string) { + if (typeof window === 'undefined') { + return + } + + const global = window as any + global.__events ??= [] + global.__events.push({ type, t: performance.now() }) +} + +const Pending = defineComponent({ + setup() { + onMounted(() => { + recordEvent('pending-mounted') + }) + onUnmounted(() => { + recordEvent('pending-unmounted') + }) + + return () => ( +
Loading SSR false route...
+ ) + }, +}) + +const Target = defineComponent({ + setup() { + onMounted(() => { + recordEvent('target-mounted') + }) + + return () => ( +
SSR false route loaded
+ ) + }, +}) + +export const Route = createFileRoute('/ssr-false-pending-min')({ + ssr: false, + pendingMs: 0, + pendingMinMs, + pendingComponent: Pending, + loader: async () => { + recordEvent('loader-start') + await new Promise((resolve) => setTimeout(resolve, 50)) + recordEvent('loader-done') + + return { ok: true } + }, + component: Target, +}) diff --git a/e2e/vue-start/selective-ssr/tests/app.spec.ts b/e2e/vue-start/selective-ssr/tests/app.spec.ts index aea216d506..b14c7e028a 100644 --- a/e2e/vue-start/selective-ssr/tests/app.spec.ts +++ b/e2e/vue-start/selective-ssr/tests/app.spec.ts @@ -1,8 +1,73 @@ import { expect } from '@playwright/test' import { test } from '@tanstack/router-e2e-utils' +import type { Page } from '@playwright/test' const testCount = 7 +type BrowserEvent = { type: string; t: number } + +function findEvent(events: Array, type: string) { + const event = events.find((entry) => entry.type === type) + expect(event, `Expected browser event "${type}"`).toBeTruthy() + return event! +} + +function findLastEvent(events: Array, type: string) { + let event: BrowserEvent | undefined + for (let index = events.length - 1; index >= 0; index--) { + if (events[index]!.type === type) { + event = events[index] + break + } + } + expect(event, `Expected browser event "${type}"`).toBeTruthy() + return event! +} + +async function expectSsrFalsePendingMin(page: Page) { + const errors: Array = [] + + page.on('pageerror', (err) => { + errors.push(err.message) + }) + page.on('console', (msg) => { + if (msg.type() === 'error') { + errors.push(msg.text()) + } + }) + + await page.goto('/ssr-false-pending-min') + + const pending = page.getByTestId('ssr-false-pending') + const visiblePending = page.locator( + '[data-testid="ssr-false-pending"]:visible', + ) + const target = page.getByTestId('ssr-false-target') + + await expect(visiblePending).toHaveCount(1) + + await page.waitForTimeout(500) + + await expect(visiblePending).toHaveCount(1) + await expect(target).toBeHidden() + + await expect(target).toBeVisible() + await expect(pending).toHaveCount(0) + + const events = await page.evaluate>( + () => (window as any).__events ?? [], + ) + const pendingMounted = findEvent(events, 'pending-mounted') + const pendingUnmounted = findLastEvent(events, 'pending-unmounted') + const targetMounted = findEvent(events, 'target-mounted') + const loaderDone = findEvent(events, 'loader-done') + + expect(loaderDone.t - pendingMounted.t).toBeLessThan(500) + expect(pendingUnmounted.t - pendingMounted.t).toBeGreaterThanOrEqual(1400) + expect(targetMounted.t - pendingMounted.t).toBeGreaterThanOrEqual(1400) + expect(errors).toEqual([]) +} + test.describe('selective ssr', () => { test('testcount matches', async ({ page }) => { await page.goto('/') @@ -38,4 +103,10 @@ test.describe('selective ssr', () => { await expect(page.getByTestId('router-status')).toContainText('idle') }) } + + test('direct ssr false hydration keeps pending visible for pendingMinMs', async ({ + page, + }) => { + await expectSsrFalsePendingMin(page) + }) }) diff --git a/packages/react-router/src/Match.tsx b/packages/react-router/src/Match.tsx index 5de5546aeb..c6f0e7a2e4 100644 --- a/packages/react-router/src/Match.tsx +++ b/packages/react-router/src/Match.tsx @@ -3,11 +3,9 @@ import * as React from 'react' import { useStore } from '@tanstack/react-store' import { - createControlledPromise, getLocationChangeInfo, invariant, isNotFound, - isRedirect, rootRouteId, } from '@tanstack/router-core' import { isServer } from '@tanstack/router-core/isServer' @@ -33,13 +31,41 @@ type OutletMatchSelection = [ ] const matchViewFieldsEqual = (a: AnyRouteMatch, b: AnyRouteMatch) => - a.routeId === b.routeId && a._displayPending === b._displayPending + a.routeId === b.routeId && + a.ssr === b.ssr && + a._displayPending === b._displayPending const outletMatchSelectionEqual = ( a: OutletMatchSelection, b: OutletMatchSelection, ) => a[0] === b[0] && a[1] === b[1] +const getLoadPromise = ( + router: ReturnType, + match: AnyRouteMatch, +) => { + const localPromise = match._.loadPromise + const promise = + localPromise?.status === 'pending' + ? localPromise + : // React may render a stale match snapshot after its + // match-local promise was settled/removed but before + // the newer lane commits. Suspend that stale render on + // the current router load so it can be replaced safely. + router.latestLoadPromise + if (!promise) { + if (process.env.NODE_ENV !== 'production') { + throw new Error( + `Invariant failed: pending match "${match.id}" has no loadPromise`, + ) + } + + invariant() + } + + return promise +} + export const Match = React.memo(function MatchImpl({ matchId, }: { @@ -59,30 +85,18 @@ export const Match = React.memo(function MatchImpl({ invariant() } - const routeId = match.routeId as string - const parentRouteId = (router.routesById[routeId] as AnyRoute).parentRoute - ?.id - return ( ) } - // Subscribe directly to the match store from the pool. - // The matchId prop is stable for this component's lifetime (set by Outlet), - // and reconcileMatchPool reuses stores for the same matchId. - const matchStore = router.stores.matchStores.get(matchId) + if (!matchStore) { if (process.env.NODE_ENV !== 'production') { throw new Error( @@ -92,53 +106,36 @@ export const Match = React.memo(function MatchImpl({ invariant() } + // eslint-disable-next-line react-hooks/rules-of-hooks const resetKey = useStore(router.stores.loadedAt, (loadedAt) => loadedAt) // eslint-disable-next-line react-hooks/rules-of-hooks const match = useStore(matchStore, (value) => value, matchViewFieldsEqual) - // eslint-disable-next-line react-hooks/rules-of-hooks - const matchState = React.useMemo(() => { - const routeId = match.routeId as string - const parentRouteId = (router.routesById[routeId] as AnyRoute).parentRoute - ?.id - - return { - routeId, - ssr: match.ssr, - _displayPending: match._displayPending, - parentRouteId: parentRouteId as string | undefined, - } satisfies MatchViewState - }, [match._displayPending, match.routeId, match.ssr, router.routesById]) return ( ) }) -type MatchViewState = { - routeId: string - ssr: boolean | 'data-only' | undefined - _displayPending: boolean | undefined - parentRouteId: string | undefined -} - function MatchView({ router, matchId, resetKey, - matchState, + match, }: { router: ReturnType matchId: string resetKey: number - matchState: MatchViewState + match: AnyRouteMatch }) { - const route: AnyRoute = router.routesById[matchState.routeId] + const routeId = match.routeId as string + const route: AnyRoute = router.routesById[routeId] + const parentRouteId = route.parentRoute?.id const PendingComponent = route.options.pendingComponent ?? router.options.defaultPendingComponent @@ -156,8 +153,7 @@ function MatchView({ router.options.notFoundRoute?.options.component) : route.options.notFoundComponent - const resolvedNoSsr = - matchState.ssr === false || matchState.ssr === 'data-only' + const resolvedNoSsr = match.ssr === false || match.ssr === 'data-only' const ResolvedSuspenseBoundary = // If we're on the root route, allow forcefully wrapping in suspense (!route.isRoot || route.options.wrapInSuspense || resolvedNoSsr) && @@ -188,7 +184,7 @@ function MatchView({ onCatch={(error, errorInfo) => { // Forward not found errors (we don't want to show the error component for these) if (isNotFound(error)) { - error.routeId ??= matchState.routeId as any + error.routeId ??= routeId as any throw error } if (process.env.NODE_ENV !== 'production') { @@ -199,21 +195,24 @@ function MatchView({ > { - error.routeId ??= matchState.routeId as any + error.routeId ??= routeId as any // If the current not found handler doesn't exist or it has a // route ID which doesn't match the current route, rethrow the error if ( !routeNotFoundComponent || - (error.routeId && error.routeId !== matchState.routeId) || + (error.routeId && error.routeId !== routeId) || (!error.routeId && !route.isRoot) - ) + ) { throw error + } return React.createElement(routeNotFoundComponent, error as any) }} > - {resolvedNoSsr || matchState._displayPending ? ( + {match._displayPending ? ( + pendingElement + ) : resolvedNoSsr ? ( @@ -224,10 +223,10 @@ function MatchView({ - {matchState.parentRouteId === rootRouteId ? ( + {parentRouteId === rootRouteId ? ( <> - {router.options.scrollRestoration && (isServer ?? router.isServer) ? ( + {(isServer ?? router.isServer) && router.options.scrollRestoration ? ( ) : null} @@ -294,22 +293,6 @@ export const MatchInner = React.memo(function MatchInnerImpl({ }): any { const router = useRouter() - const getMatchPromise = ( - match: { - id: string - _nonReactive: { - displayPendingPromise?: Promise - minPendingPromise?: Promise - loadPromise?: Promise - } - }, - key: 'displayPendingPromise' | 'minPendingPromise' | 'loadPromise', - ) => { - return ( - router.getMatch(match.id)?._nonReactive[key] ?? match._nonReactive[key] - ) - } - if (isServer ?? router.isServer) { const match = router.stores.matchStores.get(matchId)?.get() if (!match) { @@ -324,9 +307,9 @@ export const MatchInner = React.memo(function MatchInnerImpl({ const routeId = match.routeId as string const route = router.routesById[routeId] as AnyRoute + const routeOptions = route.options const remountFn = - (router.routesById[routeId] as AnyRoute).options.remountDeps ?? - router.options.defaultRemountDeps + routeOptions.remountDeps ?? router.options.defaultRemountDeps const remountDeps = remountFn?.({ routeId, loaderDeps: match.loaderDeps, @@ -334,19 +317,11 @@ export const MatchInner = React.memo(function MatchInnerImpl({ search: match._strictSearch, }) const key = remountDeps ? JSON.stringify(remountDeps) : undefined - const Comp = route.options.component ?? router.options.defaultComponent + const Comp = routeOptions.component ?? router.options.defaultComponent const out = Comp ? : - if (match._displayPending) { - throw getMatchPromise(match, 'displayPendingPromise') - } - - if (match._forcePending) { - throw getMatchPromise(match, 'minPendingPromise') - } - if (match.status === 'pending') { - throw getMatchPromise(match, 'loadPromise') + throw getLoadPromise(router, match) } if (match.status === 'notFound') { @@ -360,21 +335,9 @@ export const MatchInner = React.memo(function MatchInnerImpl({ return renderRouteNotFound(router, route, match.error) } - if (match.status === 'redirected') { - if (!isRedirect(match.error)) { - if (process.env.NODE_ENV !== 'production') { - throw new Error('Invariant failed: Expected a redirect error') - } - - invariant() - } - throw getMatchPromise(match, 'loadPromise') - } - if (match.status === 'error') { const RouteErrorComponent = - (route.options.errorComponent ?? - router.options.defaultErrorComponent) || + (routeOptions.errorComponent ?? router.options.defaultErrorComponent) || ErrorComponent return ( value) const routeId = match.routeId as string const route = router.routesById[routeId] as AnyRoute + const routeOptions = route.options // eslint-disable-next-line react-hooks/rules-of-hooks const key = React.useMemo(() => { const remountFn = - (router.routesById[routeId] as AnyRoute).options.remountDeps ?? - router.options.defaultRemountDeps + routeOptions.remountDeps ?? router.options.defaultRemountDeps const remountDeps = remountFn?.({ routeId, loaderDeps: match.loaderDeps, @@ -421,50 +385,36 @@ export const MatchInner = React.memo(function MatchInnerImpl({ match.loaderDeps, match._strictParams, match._strictSearch, + routeOptions.remountDeps, router.options.defaultRemountDeps, - router.routesById, ]) + const Comp = routeOptions.component ?? router.options.defaultComponent + // eslint-disable-next-line react-hooks/rules-of-hooks const out = React.useMemo(() => { - const Comp = route.options.component ?? router.options.defaultComponent if (Comp) { return } return - }, [key, route.options.component, router.options.defaultComponent]) + }, [key, Comp]) - if (match._displayPending) { - throw getMatchPromise(match, 'displayPendingPromise') - } - - if (match._forcePending) { - throw getMatchPromise(match, 'minPendingPromise') - } - - // see also hydrate() in packages/router-core/src/ssr/ssr-client.ts if (match.status === 'pending') { - // We're pending, and if we have a minPendingMs, we need to wait for it - const pendingMinMs = - route.options.pendingMinMs ?? router.options.defaultPendingMinMs - if (pendingMinMs) { - const routerMatch = router.getMatch(match.id) - if (routerMatch && !routerMatch._nonReactive.minPendingPromise) { - // Create a promise that will resolve after the minPendingMs - if (!(isServer ?? router.isServer)) { - const minPendingPromise = createControlledPromise() - - routerMatch._nonReactive.minPendingPromise = minPendingPromise - - setTimeout(() => { - minPendingPromise.resolve() - // We've handled the minPendingPromise, so we can delete it - routerMatch._nonReactive.minPendingPromise = undefined - }, pendingMinMs) - } - } + const PendingComponent = + routeOptions.pendingComponent ?? router.options.defaultPendingComponent + const pendingMinMs = PendingComponent + ? (routeOptions.pendingMinMs ?? router.options.defaultPendingMinMs) + : undefined + const localPromise = match._.loadPromise + if ( + !(isServer ?? router.isServer) && + localPromise?.status === 'pending' && + pendingMinMs + ) { + localPromise.pendingUntil ??= Date.now() + pendingMinMs } - throw getMatchPromise(match, 'loadPromise') + + throw getLoadPromise(router, match) } if (match.status === 'notFound') { @@ -478,32 +428,10 @@ export const MatchInner = React.memo(function MatchInnerImpl({ return renderRouteNotFound(router, route, match.error) } - if (match.status === 'redirected') { - // A match can be observed as redirected during an in-flight transition, - // especially when pending UI is already rendering. Suspend on the match's - // load promise so React can abandon this stale render and continue the - // redirect transition. - if (!isRedirect(match.error)) { - if (process.env.NODE_ENV !== 'production') { - throw new Error('Invariant failed: Expected a redirect error') - } - - invariant() - } - - throw getMatchPromise(match, 'loadPromise') - } - if (match.status === 'error') { - // If we're on the server, we need to use React's new and super - // wonky api for throwing errors from a server side render inside - // of a suspense boundary. This is the only way to get - // renderToPipeableStream to not hang indefinitely. - // We'll serialize the error and rethrow it on the client. if (isServer ?? router.isServer) { const RouteErrorComponent = - (route.options.errorComponent ?? - router.options.defaultErrorComponent) || + (routeOptions.errorComponent ?? router.options.defaultErrorComponent) || ErrorComponent return ( { - const index = ids.findIndex((id) => id === matchId) + const index = ids.indexOf(matchId!) return ids[index + 1] }) } const route = routeId ? router.routesById[routeId] : undefined - const pendingElement = router.options.defaultPendingComponent ? ( - + const DefaultPendingComponent = router.options.defaultPendingComponent + const pendingElement = DefaultPendingComponent ? ( + ) : null if (parentGlobalNotFound) { diff --git a/packages/react-router/src/ssr/renderRouterToStream.tsx b/packages/react-router/src/ssr/renderRouterToStream.tsx index 46275a5421..1117836c2c 100644 --- a/packages/react-router/src/ssr/renderRouterToStream.tsx +++ b/packages/react-router/src/ssr/renderRouterToStream.tsx @@ -76,7 +76,7 @@ export const renderRouterToStream = async ({ return createSsrStreamResponse( router, new Response(responseStream as any, { - status: router.stores.statusCode.get(), + status: router.statusCode, headers: responseHeaders, }), ) @@ -199,7 +199,7 @@ export const renderRouterToStream = async ({ return createSsrStreamResponse( router, new Response(responseStream as any, { - status: router.stores.statusCode.get(), + status: router.statusCode, headers: responseHeaders, }), ) diff --git a/packages/react-router/src/ssr/renderRouterToString.tsx b/packages/react-router/src/ssr/renderRouterToString.tsx index e9fe4ec779..ebb2c71790 100644 --- a/packages/react-router/src/ssr/renderRouterToString.tsx +++ b/packages/react-router/src/ssr/renderRouterToString.tsx @@ -21,7 +21,7 @@ export const renderRouterToString = async ({ } return new Response(`${html}`, { - status: router.stores.statusCode.get(), + status: router.statusCode, headers: responseHeaders, }) } catch (error) { diff --git a/packages/react-router/tests/Matches.test.tsx b/packages/react-router/tests/Matches.test.tsx index dd3ca3dfa6..8ab0c21f07 100644 --- a/packages/react-router/tests/Matches.test.tsx +++ b/packages/react-router/tests/Matches.test.tsx @@ -1,9 +1,12 @@ -import { afterEach, describe, expect, test } from 'vitest' +import { afterEach, describe, expect, test, vi } from 'vitest' +import * as React from 'react' import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' import { createMemoryHistory } from '@tanstack/history' +import { createControlledPromise } from '@tanstack/router-core' import { Link, Outlet, + RouterContextProvider, RouterProvider, createRootRoute, createRoute, @@ -12,6 +15,7 @@ import { useMatchRoute, useMatches, } from '../src' +import { Match, MatchInner } from '../src/Match' const rootRoute = createRootRoute() @@ -145,6 +149,479 @@ test('should show pendingComponent of root route', async () => { expect(await rendered.findByTestId('root-content')).toBeInTheDocument() }) +test('pending fallback remains visible through pendingMinMs', async () => { + vi.useFakeTimers() + + try { + let navigation!: Promise + const root = createRootRoute({ + component: () => , + }) + const index = createRoute({ + getParentRoute: () => root, + path: '/', + component: () =>
Index
, + }) + const slow = createRoute({ + getParentRoute: () => root, + path: '/slow', + pendingMs: 0, + pendingMinMs: 100, + pendingComponent: () =>
Slow pending
, + loader: async () => { + await new Promise((resolve) => setTimeout(resolve, 10)) + }, + component: () =>
Slow content
, + }) + const router = createRouter({ + routeTree: root.addChildren([index, slow]), + history: createMemoryHistory({ initialEntries: ['/'] }), + defaultPendingMs: 0, + }) + + await router.load() + render() + expect(screen.getByText('Index')).toBeInTheDocument() + + await act(async () => { + navigation = router.navigate({ to: '/slow' }) + await vi.advanceTimersByTimeAsync(0) + }) + expect(screen.getByText('Slow pending')).toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(99) + }) + expect(screen.getByText('Slow pending')).toBeInTheDocument() + expect(screen.queryByText('Slow content')).not.toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(1) + await navigation + }) + expect(screen.getByText('Slow content')).toBeInTheDocument() + } finally { + cleanup() + vi.useRealTimers() + } +}) + +test('pending fallback remains visible while beforeLoad outlives pending timers', async () => { + vi.useFakeTimers() + + try { + let navigation!: Promise + const beforeLoadGate = createControlledPromise() + const root = createRootRoute({ + component: () => , + }) + const index = createRoute({ + getParentRoute: () => root, + path: '/', + component: () =>
Index
, + }) + const slow = createRoute({ + getParentRoute: () => root, + path: '/slow', + pendingMs: 10, + pendingMinMs: 50, + pendingComponent: () =>
Slow pending
, + beforeLoad: () => beforeLoadGate, + component: () =>
Slow content
, + }) + const router = createRouter({ + routeTree: root.addChildren([index, slow]), + history: createMemoryHistory({ initialEntries: ['/'] }), + defaultPendingMs: 0, + }) + + await router.load() + render() + expect(screen.getByText('Index')).toBeInTheDocument() + + await act(async () => { + navigation = router.navigate({ to: '/slow' }) + await vi.advanceTimersByTimeAsync(9) + }) + expect(screen.queryByText('Slow pending')).not.toBeInTheDocument() + expect(screen.queryByText('Slow content')).not.toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(1) + }) + expect(screen.getByText('Slow pending')).toBeInTheDocument() + expect(screen.queryByText('Slow content')).not.toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(50) + }) + expect(screen.getByText('Slow pending')).toBeInTheDocument() + expect(screen.queryByText('Slow content')).not.toBeInTheDocument() + + await act(async () => { + beforeLoadGate.resolve() + await navigation + }) + expect(screen.queryByText('Slow pending')).not.toBeInTheDocument() + expect(screen.getByText('Slow content')).toBeInTheDocument() + } finally { + cleanup() + vi.useRealTimers() + } +}) + +test('hidden child pending fallback does not delay parent pending completion', async () => { + vi.useFakeTimers() + + try { + let resolveParent!: () => void + let resolveChild!: () => void + let navigation!: Promise + const ChildPending = vi.fn(() =>
Child pending
) + + const root = createRootRoute({ + component: () => , + }) + const index = createRoute({ + getParentRoute: () => root, + path: '/', + component: () =>
Index
, + }) + const parent = createRoute({ + getParentRoute: () => root, + path: '/parent', + pendingMs: 0, + pendingMinMs: 50, + pendingComponent: () =>
Parent pending
, + loader: () => + new Promise((resolve) => { + resolveParent = resolve + }), + component: () => , + }) + const child = createRoute({ + getParentRoute: () => parent, + path: '/child', + pendingMs: 0, + pendingMinMs: 5000, + pendingComponent: ChildPending, + loader: () => + new Promise((resolve) => { + resolveChild = resolve + }), + component: () =>
Child content
, + }) + + const router = createRouter({ + routeTree: root.addChildren([index, parent.addChildren([child])]), + history: createMemoryHistory({ initialEntries: ['/'] }), + defaultPendingMs: 0, + }) + + render() + + await act(async () => { + navigation = router.navigate({ to: '/parent/child' }) + await vi.advanceTimersByTimeAsync(0) + }) + + expect(screen.getByText('Parent pending')).toBeInTheDocument() + expect(screen.queryByText('Child pending')).not.toBeInTheDocument() + expect(ChildPending).not.toHaveBeenCalled() + + resolveParent() + resolveChild() + + await act(async () => { + await vi.advanceTimersByTimeAsync(49) + }) + expect(screen.queryByText('Child content')).not.toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(1) + await navigation + }) + + expect(screen.getByText('Child content')).toBeInTheDocument() + expect(ChildPending).not.toHaveBeenCalled() + } finally { + cleanup() + vi.useRealTimers() + } +}) + +test('pending match without fallback does not arm pendingMinMs', async () => { + vi.useFakeTimers() + + try { + const loaderGate = createControlledPromise() + const root = createRootRoute({ + component: () => , + }) + const slow = createRoute({ + getParentRoute: () => root, + path: '/slow', + wrapInSuspense: true, + pendingMinMs: 100, + loader: async () => { + await loaderGate + }, + component: () =>
Slow content
, + }) + const router = createRouter({ + routeTree: root.addChildren([slow]), + history: createMemoryHistory({ initialEntries: ['/slow'] }), + defaultPendingMs: 0, + }) + router.stores.setMatches(router.matchRoutes(router.latestLocation)) + + render() + + await act(async () => { + await vi.advanceTimersByTimeAsync(0) + }) + + const slowMatch = router.state.matches.find( + (match) => match.routeId === slow.id, + )! + const loadPromise = slowMatch._.loadPromise + + expect(slowMatch.status).toBe('pending') + expect(loadPromise?.pendingUntil).toBeUndefined() + + loaderGate.resolve() + + await act(async () => { + await vi.advanceTimersByTimeAsync(0) + await router.latestLoadPromise + }) + + expect(screen.getByText('Slow content')).toBeInTheDocument() + } finally { + cleanup() + vi.useRealTimers() + } +}) + +test('stale pending render ignores a resolved local promise and waits for latestLoadPromise', async () => { + const latestLoadPromise = createControlledPromise() + const root = createRootRoute() + const slow = createRoute({ + getParentRoute: () => root, + path: '/slow', + loader: () => latestLoadPromise, + component: () =>
Slow content
, + }) + const router = createRouter({ + routeTree: root.addChildren([slow]), + history: createMemoryHistory({ initialEntries: ['/slow'] }), + }) + const matches = router.matchRoutes(router.latestLocation) + router.stores.setMatches(matches) + const slowMatch = matches.find((match) => match.routeId === slow.id)! + const localPromise = slowMatch._.loadPromise! + localPromise.resolve() + router.latestLoadPromise = latestLoadPromise + + render( + + Fallback}> + + + , + ) + + expect(screen.getByText('Fallback')).toBeInTheDocument() + expect(screen.queryByText('Slow content')).not.toBeInTheDocument() + + await act(async () => { + router.updateMatch(slowMatch.id, (prev) => ({ + ...prev, + status: 'success', + _: { + ...prev._, + loadPromise: undefined, + }, + })) + router.latestLoadPromise = undefined + latestLoadPromise.resolve() + await latestLoadPromise + }) + + expect(screen.getByText('Slow content')).toBeInTheDocument() +}) + +test('Match view does not re-render for non-view match updates', () => { + const shellRender = vi.fn() + const root = createRootRoute({ + shellComponent: function ShellComponent({ + children, + }: { + children: React.ReactNode + }) { + shellRender() + return <>{children} + }, + component: () =>
Root content
, + }) + const router = createRouter({ + routeTree: root, + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + const matches = router.matchRoutes(router.latestLocation) + router.stores.setMatches(matches) + const rootMatch = matches[0]! + + const rendered = render( + + + , + ) + + expect(rendered.container).toHaveTextContent('Root content') + expect(shellRender).toHaveBeenCalledTimes(1) + + act(() => { + router.updateMatch(rootMatch.id, (prev) => ({ + ...prev, + loaderData: { updated: true }, + })) + }) + + expect(shellRender).toHaveBeenCalledTimes(1) +}) + +test('MatchInner does not re-render route component for non-rendering match updates', () => { + const routeRender = vi.fn() + const root = createRootRoute({ + component: function RootComponent() { + routeRender() + return
Root content
+ }, + }) + const router = createRouter({ + routeTree: root, + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + const matches = router.matchRoutes(router.latestLocation) + router.stores.setMatches(matches) + const rootMatch = matches[0]! + + const rendered = render( + + + , + ) + + expect(rendered.container).toHaveTextContent('Root content') + expect(routeRender).toHaveBeenCalledTimes(1) + + act(() => { + router.updateMatch(rootMatch.id, (prev) => ({ + ...prev, + loaderData: { updated: true }, + })) + }) + + expect(routeRender).toHaveBeenCalledTimes(1) + rendered.unmount() +}) + +test('Match view re-renders when same-id ssr field changes', () => { + const shellRender = vi.fn() + const root = createRootRoute({ + shellComponent: function ShellComponent({ + children, + }: { + children: React.ReactNode + }) { + shellRender() + return <>{children} + }, + component: () =>
Root content
, + }) + const router = createRouter({ + routeTree: root, + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + const matches = router.matchRoutes(router.latestLocation) + matches[0]!.ssr = true + router.stores.setMatches(matches) + const rootMatch = matches[0]! + + const rendered = render( + + + , + ) + + expect(rendered.container).toHaveTextContent('Root content') + expect(shellRender).toHaveBeenCalledTimes(1) + ;([false, 'data-only', true] as const).forEach((ssr, index) => { + act(() => { + router.updateMatch(rootMatch.id, (prev) => ({ + ...prev, + ssr, + })) + }) + + expect(shellRender).toHaveBeenCalledTimes(index + 2) + }) + rendered.unmount() +}) + +test('fast load before pendingMs does not arm pendingUntil', async () => { + vi.useFakeTimers() + + try { + let navigation!: Promise + const root = createRootRoute({ + component: () => , + }) + const index = createRoute({ + getParentRoute: () => root, + path: '/', + component: () =>
Index
, + }) + const fast = createRoute({ + getParentRoute: () => root, + path: '/fast', + pendingMs: 100, + pendingMinMs: 10_000, + pendingComponent: () =>
Fast pending
, + loader: async () => { + await new Promise((resolve) => setTimeout(resolve, 10)) + }, + component: () =>
Fast content
, + }) + const router = createRouter({ + routeTree: root.addChildren([index, fast]), + history: createMemoryHistory({ initialEntries: ['/'] }), + defaultPendingMs: 0, + }) + + await router.load() + render() + expect(screen.getByText('Index')).toBeInTheDocument() + + await act(async () => { + navigation = router.navigate({ to: '/fast' }) + await vi.advanceTimersByTimeAsync(10) + await navigation + }) + + expect(screen.queryByText('Fast pending')).not.toBeInTheDocument() + expect(screen.getByText('Fast content')).toBeInTheDocument() + const fastMatch = router.state.matches.find( + (match) => match.routeId === fast.id, + )! + expect(fastMatch._.loadPromise?.pendingUntil).toBeUndefined() + } finally { + cleanup() + vi.useRealTimers() + } +}) + describe('matching on different param types', () => { const testCases = [ { diff --git a/packages/react-router/tests/Scripts.test.tsx b/packages/react-router/tests/Scripts.test.tsx index b7605c9402..8422b1d29f 100644 --- a/packages/react-router/tests/Scripts.test.tsx +++ b/packages/react-router/tests/Scripts.test.tsx @@ -508,6 +508,82 @@ describe('ssr HeadContent', () => { ).toHaveLength(1) }) + test('removes stale child title when parent beforeLoad throws', async () => { + const history = createMemoryHistory({ + initialEntries: ['/parent/child?fail=false'], + }) + + const rootRoute = createRootRoute({ + component: () => { + return ( + <> + {createPortal(, document.head)} + + + ) + }, + }) + + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + validateSearch: (search: Record) => ({ + fail: search.fail === true || search.fail === 'true', + }), + beforeLoad: ({ search }) => { + if (search.fail) { + throw new Error('Parent beforeLoad failed') + } + }, + head: ({ match }) => ({ + meta: [ + { + title: match.error ? 'Parent error title' : 'Parent success title', + }, + ], + }), + errorComponent: () =>
Parent error boundary
, + component: () => , + }) + + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + head: () => ({ + meta: [{ title: 'Child success title' }], + }), + component: () =>
Child success
, + }) + + const router = createRouter({ + history, + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + }) + + await act(() => render()) + + expect(await screen.findByText('Child success')).toBeInTheDocument() + await waitFor(() => { + expect(document.title).toBe('Child success title') + }) + + await act(() => + router.navigate({ + to: '/parent/child', + search: { fail: true }, + } as never), + ) + + expect(await screen.findByText('Parent error boundary')).toBeInTheDocument() + expect(router.state.matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + parentRoute.id, + ]) + await waitFor(() => { + expect(document.title).toBe('Parent error title') + }) + }) + test('applies assetCrossOrigin to manifest stylesheets and preloads', async () => { const history = createTestBrowserHistory() const stylesheetHref = '/asset-cross-origin.css' diff --git a/packages/react-router/tests/errorComponent.test.tsx b/packages/react-router/tests/errorComponent.test.tsx index 0779c2e8c4..48df51be63 100644 --- a/packages/react-router/tests/errorComponent.test.tsx +++ b/packages/react-router/tests/errorComponent.test.tsx @@ -338,7 +338,7 @@ test('SSR errorComponent receives primitive errors thrown from beforeLoad', asyn await router.load() - expect(router.state.statusCode).toBe(500) + expect(router.statusCode).toBe(500) const html = ReactDOMServer.renderToString() expect(html).toContain('Error:') expect(html).toContain('primitive error thrown') diff --git a/packages/react-router/tests/loaders.test.tsx b/packages/react-router/tests/loaders.test.tsx index d9b5968d72..c9a800a735 100644 --- a/packages/react-router/tests/loaders.test.tsx +++ b/packages/react-router/tests/loaders.test.tsx @@ -647,7 +647,7 @@ test('reproducer #4546', async () => { } }) -test('clears pendingTimeout when match resolves', async () => { +test('does not show pending fallback when match resolves before pendingMs', async () => { const defaultPendingComponentOnMountMock = vi.fn() const nestedPendingComponentOnMountMock = vi.fn() const fooPendingComponentOnMountMock = vi.fn() @@ -751,12 +751,39 @@ test('throw abortError from loader upon initial load with basepath', async () => render() - const indexElement = await screen.findByText('Index route content') - expect(indexElement).toBeInTheDocument() - expect(screen.queryByTestId('index-error')).not.toBeInTheDocument() + const errorElement = await screen.findByTestId('index-error') + expect(errorElement).toBeInTheDocument() + expect(screen.queryByText('Index route content')).not.toBeInTheDocument() expect(window.location.pathname.startsWith('/app')).toBe(true) }) +test('aborted loader does not render the route component with undefined loaderData', async () => { + const rootRoute = createRootRoute({}) + + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + loader: async (): Promise<{ value: string }> => { + return Promise.reject(new DOMException('Aborted', 'AbortError')) + }, + component: () => { + const data = indexRoute.useLoaderData() + return
value: {data.value}
+ }, + errorComponent: () => ( +
indexErrorComponent
+ ), + }) + + const routeTree = rootRoute.addChildren([indexRoute]) + const router = createRouter({ routeTree, history }) + + render() + + expect(await screen.findByTestId('index-error')).toBeInTheDocument() + expect(screen.queryByTestId('index-content')).not.toBeInTheDocument() +}) + test('cancelMatches after pending timeout', async () => { function getPendingComponent(onMount: () => void) { const PendingComponent = () => { diff --git a/packages/react-router/tests/not-found.test.tsx b/packages/react-router/tests/not-found.test.tsx index 3754785d35..4ea1f00ae9 100644 --- a/packages/react-router/tests/not-found.test.tsx +++ b/packages/react-router/tests/not-found.test.tsx @@ -409,6 +409,94 @@ test('beforeLoad notFound with routeId targets parent boundary and preserves par expect(screen.queryByTestId('child-component')).not.toBeInTheDocument() }) +test('loader notFound with routeId preserves parent route context for notFoundComponent', async () => { + const rootRoute = createRootRoute({ + component: () => , + }) + + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + beforeLoad: () => ({ number: 42 }), + component: () => , + notFoundComponent: () => { + const context = parentRoute.useRouteContext() + return ( + {context.number} + ) + }, + }) + + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: () => { + throw notFound({ routeId: parentRoute.id }) + }, + component: () => Child, + }) + + const router = createRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history, + notFoundMode: 'fuzzy', + }) + + render() + await router.navigate({ to: '/parent/child' }) + + expect( + await screen.findByTestId('parent-not-found-context'), + ).toHaveTextContent('42') + expect(screen.queryByTestId('child-component')).not.toBeInTheDocument() +}) + +test('beforeLoad notFound clears stale context before rendering own notFoundComponent', async () => { + let shouldThrow = false + + const rootRoute = createRootRoute({ + component: () => , + }) + + const childRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/child', + beforeLoad: () => { + if (shouldThrow) { + throw notFound() + } + + return { number: 42 } + }, + component: () => Child, + notFoundComponent: () => { + const context = childRoute.useRouteContext() + return ( + + {String(context.number)} + + ) + }, + }) + + const router = createRouter({ + routeTree: rootRoute.addChildren([childRoute]), + history, + notFoundMode: 'fuzzy', + }) + + render() + await router.navigate({ to: '/child' }) + expect(await screen.findByTestId('child-component')).toBeInTheDocument() + + shouldThrow = true + await router.invalidate() + + expect( + await screen.findByTestId('child-not-found-context'), + ).toHaveTextContent('undefined') +}) + test('beforeLoad notFound with non-exact routeId falls back to root notFoundComponent', async () => { const rootRoute = createRootRoute({ component: () => , diff --git a/packages/react-router/tests/redirect.test.tsx b/packages/react-router/tests/redirect.test.tsx index cc15f0da36..06a716e316 100644 --- a/packages/react-router/tests/redirect.test.tsx +++ b/packages/react-router/tests/redirect.test.tsx @@ -152,7 +152,11 @@ describe('redirect', () => { // The lazy target route adds the async boundary that exposes the stale // redirected-match render path this regression is guarding. - expect(await screen.findByTestId('lazy-route-page')).toBeInTheDocument() + expect( + await screen.findByTestId('lazy-route-page', undefined, { + timeout: 5_000, + }), + ).toBeInTheDocument() expect(screen.queryByTestId('pending')).not.toBeInTheDocument() expect(router.state.location.href).toBe('/posts') expect(router.state.status).toBe('idle') @@ -345,9 +349,9 @@ describe('redirect', () => { await router.load() - expect(router.state.redirect).toBeDefined() - expect(router.state.redirect).toBeInstanceOf(Response) - const redirectResponse = router.state.redirect! + expect(router.redirect).toBeDefined() + expect(router.redirect).toBeInstanceOf(Response) + const redirectResponse = router.redirect! expect(redirectResponse.options).toEqual({ _fromLocation: expect.objectContaining({ @@ -395,7 +399,7 @@ describe('redirect', () => { await router.load() - const currentRedirect = router.state.redirect + const currentRedirect = router.redirect expect(currentRedirect).toBeDefined() expect(currentRedirect).toBeInstanceOf(Response) diff --git a/packages/react-router/tests/renderRouterToStream.test.tsx b/packages/react-router/tests/renderRouterToStream.test.tsx index 74e180a552..eb4dc7aeed 100644 --- a/packages/react-router/tests/renderRouterToStream.test.tsx +++ b/packages/react-router/tests/renderRouterToStream.test.tsx @@ -24,9 +24,9 @@ async function buildRouter() { const rootRoute = createRootRoute({ component: () => null }) const router = createRouter({ history: createMemoryHistory({ initialEntries: ['/'] }), + isServer: true, routeTree: rootRoute, }) - router.isServer = true attachRouterServerSsrUtils({ router, manifest: undefined }) await router.load() await router.serverSsr!.dehydrate() diff --git a/packages/react-router/tests/route.test-d.tsx b/packages/react-router/tests/route.test-d.tsx index 41b003e5d1..6466c2c2df 100644 --- a/packages/react-router/tests/route.test-d.tsx +++ b/packages/react-router/tests/route.test-d.tsx @@ -8,7 +8,6 @@ import { } from '../src' import type { BuildLocationFn, - ControlledPromise, NavigateFn, NavigateOptions, SearchSchemaInput, @@ -1328,8 +1327,6 @@ test('when creating a child route with context, search, params, loader, loaderDe search: TExpectedSearch context: TExpectedContext loaderDeps: { detailPage: number; invoicePage: number } - beforeLoadPromise?: ControlledPromise - loaderPromise?: ControlledPromise componentsPromise?: Promise> loaderData?: TExpectedLoaderData } diff --git a/packages/react-router/tests/routeContext.test.tsx b/packages/react-router/tests/routeContext.test.tsx index d11f86420e..a9c8b0f1ec 100644 --- a/packages/react-router/tests/routeContext.test.tsx +++ b/packages/react-router/tests/routeContext.test.tsx @@ -2796,6 +2796,422 @@ describe('useRouteContext in the component', () => { expect(content).toBeInTheDocument() }) + test('context value from beforeLoad is propagated to a sub-route while its loader reloads in the background', async () => { + let sawUndefinedContext = false + + const rootRoute = createRootRoute({ + component: () => , + }) + const homeRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
Home page
, + }) + const contextPropagationRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/context-propagation', + beforeLoad: () => ({ number: 42 }), + component: () => , + }) + const contextPropagationIndexRoute = createRoute({ + getParentRoute: () => contextPropagationRoute, + path: '/', + staleTime: 0, + loader: async () => { + await sleep(WAIT_TIME) + }, + component: () => { + const { number } = contextPropagationIndexRoute.useRouteContext() + sawUndefinedContext ||= number === undefined + + return ( +
+ number = {String(number)}, saw undefined ={' '} + {String(sawUndefinedContext)} +
+ ) + }, + }) + + const routeTree = rootRoute.addChildren([ + homeRoute, + contextPropagationRoute.addChildren([contextPropagationIndexRoute]), + ]) + const router = createRouter({ routeTree, history }) + + render() + + await act(() => router.navigate({ to: '/context-propagation' })) + + expect( + await screen.findByText('number = 42, saw undefined = false'), + ).toBeInTheDocument() + + await act(() => router.navigate({ to: '/' })) + + expect(await screen.findByText('Home page')).toBeInTheDocument() + + act(() => router.history.back()) + + expect( + await screen.findByText('number = 42, saw undefined = false'), + ).toBeInTheDocument() + + // let the background reload settle, the context must survive the + // loader's success update + await act(() => sleep(WAIT_TIME + 50)) + + expect( + await screen.findByText('number = 42, saw undefined = false'), + ).toBeInTheDocument() + }) + + test('context value from beforeLoad is propagated to a sub-route when it is re-entered while its loader is still reloading in the background', async () => { + let sawUndefinedContext = false + const loaderTime = WAIT_TIME * 3 + + const rootRoute = createRootRoute({ + component: () => , + }) + const homeRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
Home page
, + }) + const reloadInFlightRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/reload-in-flight', + beforeLoad: () => ({ number: 42 }), + component: () => , + }) + const reloadInFlightIndexRoute = createRoute({ + getParentRoute: () => reloadInFlightRoute, + path: '/', + staleTime: 0, + loader: async () => { + await sleep(loaderTime) + }, + component: () => { + const { number } = reloadInFlightIndexRoute.useRouteContext() + sawUndefinedContext ||= number === undefined + + return ( +
+ number = {String(number)}, saw undefined ={' '} + {String(sawUndefinedContext)} +
+ ) + }, + }) + + const routeTree = rootRoute.addChildren([ + homeRoute, + reloadInFlightRoute.addChildren([reloadInFlightIndexRoute]), + ]) + const router = createRouter({ routeTree, history }) + + render() + + await act(() => router.navigate({ to: '/reload-in-flight' })) + + expect( + await screen.findByText('number = 42, saw undefined = false'), + ).toBeInTheDocument() + + // re-entering the route starts a background reload of the sub-route + await act(() => router.navigate({ to: '/' })) + expect(await screen.findByText('Home page')).toBeInTheDocument() + act(() => router.history.back()) + + expect( + await screen.findByText('number = 42, saw undefined = false'), + ).toBeInTheDocument() + + // re-enter once more while that background reload is still in flight + await act(() => router.navigate({ to: '/' })) + expect(await screen.findByText('Home page')).toBeInTheDocument() + act(() => router.history.back()) + + expect( + await screen.findByText('number = 42, saw undefined = false'), + ).toBeInTheDocument() + + // let the in-flight reload settle, the context must survive its completion + await act(() => sleep(loaderTime + 50)) + + expect( + await screen.findByText('number = 42, saw undefined = false'), + ).toBeInTheDocument() + }) + + test('context value from beforeLoad is kept when the background reload of a sub-route is aborted', async () => { + let sawUndefinedContext = false + let loaderRuns = 0 + + const rootRoute = createRootRoute({ + component: () => , + }) + const homeRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
Home page
, + }) + const reloadAbortRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/reload-abort', + beforeLoad: () => ({ number: 42 }), + component: () => , + }) + const reloadAbortIndexRoute = createRoute({ + getParentRoute: () => reloadAbortRoute, + path: '/', + staleTime: 0, + loader: async () => { + loaderRuns++ + await sleep(WAIT_TIME) + if (loaderRuns > 1) { + const error = new Error('aborted') + error.name = 'AbortError' + throw error + } + }, + component: () => { + const { number } = reloadAbortIndexRoute.useRouteContext() + sawUndefinedContext ||= number === undefined + + return ( +
+ number = {String(number)}, saw undefined ={' '} + {String(sawUndefinedContext)} +
+ ) + }, + }) + + const routeTree = rootRoute.addChildren([ + homeRoute, + reloadAbortRoute.addChildren([reloadAbortIndexRoute]), + ]) + const router = createRouter({ routeTree, history }) + + render() + + await act(() => router.navigate({ to: '/reload-abort' })) + + expect( + await screen.findByText('number = 42, saw undefined = false'), + ).toBeInTheDocument() + + // re-entering the route starts a background reload which gets aborted + await act(() => router.navigate({ to: '/' })) + expect(await screen.findByText('Home page')).toBeInTheDocument() + act(() => router.history.back()) + + expect( + await screen.findByText('number = 42, saw undefined = false'), + ).toBeInTheDocument() + + // let the aborted reload settle, the context must survive the abort + await act(() => sleep(WAIT_TIME + 50)) + + expect( + await screen.findByText('number = 42, saw undefined = false'), + ).toBeInTheDocument() + }) + + test("context value from beforeLoad is available in a sub-route's errorComponent when its background reload fails", async () => { + let loaderRuns = 0 + + const rootRoute = createRootRoute({ + component: () => , + }) + const homeRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
Home page
, + }) + const reloadErrorRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/reload-error', + beforeLoad: () => ({ number: 42 }), + component: () => , + }) + const reloadErrorIndexRoute = createRoute({ + getParentRoute: () => reloadErrorRoute, + path: '/', + staleTime: 0, + loader: async () => { + loaderRuns++ + await sleep(WAIT_TIME) + if (loaderRuns > 1) { + throw new Error('loader failed') + } + }, + component: () => { + const { number } = reloadErrorIndexRoute.useRouteContext() + + return
number = {String(number)}
+ }, + errorComponent: () => { + const { number } = reloadErrorIndexRoute.useRouteContext() + + return
error number = {String(number)}
+ }, + }) + + const routeTree = rootRoute.addChildren([ + homeRoute, + reloadErrorRoute.addChildren([reloadErrorIndexRoute]), + ]) + const router = createRouter({ routeTree, history }) + + render() + + await act(() => router.navigate({ to: '/reload-error' })) + + expect(await screen.findByText('number = 42')).toBeInTheDocument() + + // re-entering the route starts a background reload which fails + await act(() => router.navigate({ to: '/' })) + expect(await screen.findByText('Home page')).toBeInTheDocument() + act(() => router.history.back()) + + expect(await screen.findByText('number = 42')).toBeInTheDocument() + + // once the failed reload settles, the errorComponent must still see + // the context value provided by the parent's beforeLoad + await act(() => sleep(WAIT_TIME + 50)) + + expect(await screen.findByText('error number = 42')).toBeInTheDocument() + }) + + test("context value from beforeLoad is available in a sub-route's errorComponent when the sub-route's beforeLoad throws", async () => { + const rootRoute = createRootRoute({ + component: () => , + }) + const homeRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
Home page
, + }) + const beforeLoadErrorRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/before-load-error', + beforeLoad: () => ({ number: 42 }), + component: () => , + }) + const beforeLoadErrorIndexRoute = createRoute({ + getParentRoute: () => beforeLoadErrorRoute, + path: '/', + beforeLoad: () => { + throw new Error('beforeLoad failed') + }, + component: () =>
never rendered
, + errorComponent: () => { + const { number } = beforeLoadErrorIndexRoute.useRouteContext() + + return
error number = {String(number)}
+ }, + }) + + const routeTree = rootRoute.addChildren([ + homeRoute, + beforeLoadErrorRoute.addChildren([beforeLoadErrorIndexRoute]), + ]) + const router = createRouter({ routeTree, history }) + + render() + + await act(() => router.navigate({ to: '/before-load-error' })) + + expect(await screen.findByText('error number = 42')).toBeInTheDocument() + }) + + test('updated context value from beforeLoad is committed atomically with a blocking reload of the sub-route', async () => { + let sawUndefinedContext = false + let beforeLoadRuns = 0 + let loaderRuns = 0 + let releaseLoader!: () => void + const loaderGate = new Promise((resolve) => { + releaseLoader = resolve + }) + + const rootRoute = createRootRoute({ + component: () => , + }) + const homeRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
Home page
, + }) + const blockingReloadRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/blocking-reload', + beforeLoad: () => ({ number: ++beforeLoadRuns }), + component: () => , + }) + const blockingReloadIndexRoute = createRoute({ + getParentRoute: () => blockingReloadRoute, + path: '/', + loader: async () => { + loaderRuns++ + if (loaderRuns > 1) { + await loaderGate + } + }, + component: () => { + const { number } = blockingReloadIndexRoute.useRouteContext() + sawUndefinedContext ||= number === undefined + + return ( +
+ number = {String(number)}, saw undefined ={' '} + {String(sawUndefinedContext)} +
+ ) + }, + }) + + const routeTree = rootRoute.addChildren([ + homeRoute, + blockingReloadRoute.addChildren([blockingReloadIndexRoute]), + ]) + const router = createRouter({ + routeTree, + history, + defaultStaleReloadMode: 'blocking', + }) + + render() + + await act(() => router.navigate({ to: '/blocking-reload' })) + + expect( + await screen.findByText('number = 1, saw undefined = false'), + ).toBeInTheDocument() + + // invalidating re-runs beforeLoad and blocks on the gated loader + act(() => { + void router.invalidate() + }) + + // while the blocking reload is in flight, the visible UI must keep the + // old, consistent pass: updates of the in-progress pass stay isolated + // in the pending match pool until the whole pass commits + await act(() => sleep(25)) + expect( + screen.getByText('number = 1, saw undefined = false'), + ).toBeInTheDocument() + + // releasing the loader commits the pass: the updated context must become + // visible together with the reload result + act(() => releaseLoader()) + + expect( + await screen.findByText('number = 2, saw undefined = false'), + ).toBeInTheDocument() + }) + // Check if context that is updated at the root, is the same in the root route test('modified route context, present in the root route', async () => { const rootRoute = createRootRoute({ diff --git a/packages/react-router/tests/router.test.tsx b/packages/react-router/tests/router.test.tsx index cf3b1c11fe..ebd445e89c 100644 --- a/packages/react-router/tests/router.test.tsx +++ b/packages/react-router/tests/router.test.tsx @@ -2205,46 +2205,9 @@ describe('does not strip search params if search validation fails', () => { }) }) -describe('statusCode', () => { - it('should reset statusCode to 200 when navigating from 404 to valid route', async () => { - const history = createMemoryHistory({ initialEntries: ['/'] }) - - const rootRoute = createRootRoute() - - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: () =>
Home
, - }) - - const validRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/valid', - component: () =>
Valid Route
, - }) - - const routeTree = rootRoute.addChildren([indexRoute, validRoute]) - const router = createRouter({ routeTree, history }) - - render() - - expect(router.state.statusCode).toBe(200) - - await act(() => router.navigate({ to: '/' })) - expect(router.state.statusCode).toBe(200) - - await act(() => router.navigate({ to: '/non-existing' })) - expect(router.state.statusCode).toBe(404) - - await act(() => router.navigate({ to: '/valid' })) - expect(router.state.statusCode).toBe(200) - - await act(() => router.navigate({ to: '/another-non-existing' })) - expect(router.state.statusCode).toBe(404) - }) - +describe('route error rendering', () => { describe.each([true, false])( - 'status code is set when loader/beforeLoad throws (isAsync=%s)', + 'loader/beforeLoad errors render the matching boundary (isAsync=%s)', async (isAsync) => { const throwingFun = isAsync ? (toThrow: () => void) => async () => { @@ -2259,7 +2222,7 @@ describe('statusCode', () => { const throwError = throwingFun(() => { throw new Error('test-error') }) - it('should set statusCode to 404 when a route loader throws a notFound()', async () => { + it('renders notFound when a route loader throws a notFound()', async () => { const history = createMemoryHistory({ initialEntries: ['/'] }) const rootRoute = createRootRoute() @@ -2287,17 +2250,14 @@ describe('statusCode', () => { render() - expect(router.state.statusCode).toBe(200) - await act(() => router.navigate({ to: '/loader-throws-not-found' })) - expect(router.state.statusCode).toBe(404) expect( await screen.findByTestId('not-found-component'), ).toBeInTheDocument() expect(screen.queryByTestId('route-component')).not.toBeInTheDocument() }) - it('should set statusCode to 404 when a route beforeLoad throws a notFound()', async () => { + it('renders notFound when a route beforeLoad throws a notFound()', async () => { const history = createMemoryHistory({ initialEntries: ['/'] }) const rootRoute = createRootRoute({ @@ -2332,17 +2292,14 @@ describe('statusCode', () => { render() - expect(router.state.statusCode).toBe(200) - await act(() => router.navigate({ to: '/beforeload-throws-not-found' })) - expect(router.state.statusCode).toBe(404) expect( await screen.findByTestId('not-found-component'), ).toBeInTheDocument() expect(screen.queryByTestId('route-component')).not.toBeInTheDocument() }) - it('should set statusCode to 500 when a route loader throws an Error', async () => { + it('renders error when a route loader throws an Error', async () => { const history = createMemoryHistory({ initialEntries: ['/'] }) const rootRoute = createRootRoute() @@ -2368,15 +2325,12 @@ describe('statusCode', () => { render() - expect(router.state.statusCode).toBe(200) - await act(() => router.navigate({ to: '/loader-throws-error' })) - expect(router.state.statusCode).toBe(500) expect(await screen.findByTestId('error-component')).toBeInTheDocument() expect(screen.queryByTestId('route-component')).not.toBeInTheDocument() }) - it('should set statusCode to 500 when a route beforeLoad throws an Error', async () => { + it('renders error when a route beforeLoad throws an Error', async () => { const history = createMemoryHistory({ initialEntries: ['/'] }) const rootRoute = createRootRoute() @@ -2405,10 +2359,7 @@ describe('statusCode', () => { render() - expect(router.state.statusCode).toBe(200) - await act(() => router.navigate({ to: '/beforeload-throws-error' })) - expect(router.state.statusCode).toBe(500) expect(await screen.findByTestId('error-component')).toBeInTheDocument() expect(screen.queryByTestId('route-component')).not.toBeInTheDocument() }) @@ -2484,8 +2435,6 @@ describe('notFound in beforeLoad with pendingComponent', () => { await waitFor(() => { expect(router.state.status).toBe('idle') }) - - expect(router.state.statusCode).toBe(404) }) it('should transition router.state.status to idle when child beforeLoad throws notFound and parent has NO pendingComponent', async () => { @@ -2529,8 +2478,6 @@ describe('notFound in beforeLoad with pendingComponent', () => { await waitFor(() => { expect(router.state.status).toBe('idle') }) - - expect(router.state.statusCode).toBe(404) }) it('should transition router.state.status to idle when nested child beforeLoad throws notFound WITHOUT pendingComponent', async () => { @@ -2588,8 +2535,6 @@ describe('notFound in beforeLoad with pendingComponent', () => { await waitFor(() => { expect(router.state.status).toBe('idle') }) - - expect(router.state.statusCode).toBe(404) }) it('should transition router.state.status to idle when child async beforeLoad throws notFound and parent has pendingComponent with pendingMs: 0', async () => { @@ -2660,8 +2605,6 @@ describe('notFound in beforeLoad with pendingComponent', () => { await waitFor(() => { expect(router.state.status).toBe('idle') }) - - expect(router.state.statusCode).toBe(404) }) }) @@ -3612,7 +3555,6 @@ describe('basepath', () => { }) expect(router.state.location.pathname).toBe('/') - expect(router.state.statusCode).toBe(200) }, ) diff --git a/packages/react-router/tests/store-updates-during-navigation.test.tsx b/packages/react-router/tests/store-updates-during-navigation.test.tsx index 0c4c1b4146..5713e3bcd3 100644 --- a/packages/react-router/tests/store-updates-during-navigation.test.tsx +++ b/packages/react-router/tests/store-updates-during-navigation.test.tsx @@ -136,7 +136,7 @@ describe("Store doesn't update *too many* times during navigation", () => { // This number should be as small as possible to minimize the amount of work // that needs to be done during a navigation. // Any change that increases this number should be investigated. - expect(updates).toBe(8) + expect(updates).toBe(4) }) test('redirection in preload', async () => { @@ -146,6 +146,8 @@ describe("Store doesn't update *too many* times during navigation", () => { }, }) + await waitFor(() => expect(router.stores.status.get()).toBe('idle')) + const before = select.mock.calls.length await router.preloadRoute({ to: '/posts' }) const after = select.mock.calls.length @@ -154,7 +156,7 @@ describe("Store doesn't update *too many* times during navigation", () => { // This number should be as small as possible to minimize the amount of work // that needs to be done during a navigation. // Any change that increases this number should be investigated. - expect(updates).toBe(1) + expect(updates).toBe(0) }) test('sync beforeLoad', async () => { @@ -170,7 +172,7 @@ describe("Store doesn't update *too many* times during navigation", () => { // This number should be as small as possible to minimize the amount of work // that needs to be done during a navigation. // Any change that increases this number should be investigated. - expect(updates).toBe(5) + expect(updates).toBe(4) }) test('nothing', async () => { @@ -196,7 +198,7 @@ describe("Store doesn't update *too many* times during navigation", () => { // This number should be as small as possible to minimize the amount of work // that needs to be done during a navigation. // Any change that increases this number should be investigated. - expect(updates).toBe(4) + expect(updates).toBe(3) }) test('hover preload, then navigate, w/ async loaders', async () => { diff --git a/packages/react-router/tests/useParams.test.tsx b/packages/react-router/tests/useParams.test.tsx index 19cf096ea0..7a63d62a02 100644 --- a/packages/react-router/tests/useParams.test.tsx +++ b/packages/react-router/tests/useParams.test.tsx @@ -1,5 +1,6 @@ +import { useEffect } from 'react' import { expect, test, vi } from 'vitest' -import { act, fireEvent, render, screen } from '@testing-library/react' +import { act, fireEvent, render, screen, waitFor } from '@testing-library/react' import { Link, Outlet, @@ -10,6 +11,63 @@ import { useParams, } from '../src' +test('keeps a params reference stable across search updates by default', async () => { + const effectSpy = vi.fn() + const paramSelections: Array<{ postId?: string }> = [] + + const rootRoute = createRootRoute({ + component: () => , + }) + + const postRoute = createRoute({ + getParentRoute: () => rootRoute, + path: 'posts/$postId', + component: PostComponent, + }) + + function PostComponent() { + const params = useParams({ strict: false }) + + useEffect(() => { + effectSpy(params) + paramSelections.push(params) + }, [params]) + + return
{params.postId}
+ } + + window.history.replaceState({}, '', '/posts/1?foo=one') + + const router = createRouter({ + routeTree: rootRoute.addChildren([postRoute]), + }) + + render() + + await act(() => router.load()) + + expect(await screen.findByTestId('post-id')).toHaveTextContent('1') + await waitFor(() => expect(effectSpy).toHaveBeenCalledTimes(1)) + + const initialParamsSelection = paramSelections[0] + + await act(() => + router.navigate({ + to: postRoute.fullPath, + params: { postId: '1' }, + search: { foo: 'two' }, + }), + ) + + await waitFor(() => { + expect(router.state.location.search).toEqual({ foo: 'two' }) + expect(effectSpy).toHaveBeenCalledTimes(1) + }) + + expect(paramSelections).toHaveLength(1) + expect(paramSelections[0]).toBe(initialParamsSelection) +}) + test('useParams must return parsed result if applicable.', async () => { const posts = [ { diff --git a/packages/router-core/INTERNALS.md b/packages/router-core/INTERNALS.md new file mode 100644 index 0000000000..d6559c3aa7 --- /dev/null +++ b/packages/router-core/INTERNALS.md @@ -0,0 +1,1075 @@ +# Router Core Match Loading Internals + +This document explains how router-core match loading works. It is written for +maintainers changing `src/router.ts`, `src/router-load.*.ts`, +`src/load-matches*.ts`, `src/route-assets.*.ts`, or the framework pending UI +integration. + +Match loading is intentionally split between server and client builds. The +server path is request-local and mostly linear. The client path has to handle +navigation cancellation, pending UI, preloads, background stale reloads, route +asset projection, and hydration handoff. + +## File Map + +- `src/router.ts` + - Dispatches `router.load()` and `router.preloadRoute()` to server or client + implementations. + - Builds route match arrays in `matchRoutesInternal`. + - Owns `cancelMatches()`, `getMatch()`, `updateMatch()`, cache APIs, and public + router state. `updateMatch()` patches only live active/pending match stores; + cache validity is owned by `setCached()` / `clearCache()` / cache + reconciliation, not by `updateMatch()`. +- `src/router-load.client.ts` + - Top-level client navigation load orchestration. + - Publishes pending matches, runs `loadClientMatches`, projects assets, and + performs the final active-lane commit. +- `src/router-load.server.ts` + - Top-level server load orchestration. + - Matches the request location, runs `loadServerMatches`, sets status code and + redirect state. +- `src/load-matches.ts` + - Shared types and small helpers for lane context, notFound boundary + selection, failure normalization, context merging, and promise settlement. +- `src/load-matches.client.ts` + - Client beforeLoad, loader, preload joining, pending UI, background reload, + route failure, and lane trimming logic. +- `src/load-matches.server.ts` + - Server beforeLoad, SSR eligibility, loader, route failure, and server asset + projection logic. +- `src/router-preload.client.ts` + - Client route preload entry point. Owns preload cancellation, route-control + recursion, asset projection, and owned-match cache insertion. +- `src/route-assets.client.ts` + - Client `head()` and `scripts()` projection for a finished lane. +- `src/route-assets.server.ts` + - Server `head()`, `scripts()`, and `headers()` projection. +- `src/stores.ts` + - Active, pending, and cached match pools. The compatibility `__store` + exposes only public client state (`status`, `isLoading`, `matches`, + `location`, and `resolvedLocation`). +- `src/ssr/ssr-client.ts` + - One-shot hydration reconstruction before falling back to normal + `router.load()` when needed. + +## Terminology + +### Match + +A match is an `AnyRouteMatch` for one route in the matched branch. Important +runtime fields: + +- `id`: stable identity built from route id, interpolated pathname, and loader + deps hash. +- `routeId`: route definition id. +- `index`: position in the matched branch. +- `status`: `pending`, `success`, `error`, or `notFound`. +- `isFetching`: `false`, `beforeLoad`, or `loader`. +- `context`: merged parent context, route context, and beforeLoad context. +- `abortController`: per-generation abort controller. Client work uses it as an + ownership/currentness token; server `beforeLoad` and loader contexts also + receive one. +- `_.loadPromise`: private readiness promise used by Suspense, + pending UI, preloads, and cancellation cleanup. +- `_.dehydrated`: client hydration marker. +- `_.error`: private redirect marker used by preload borrowing. + notFound and regular error outcomes live on public match state. +- `_displayPending`: hydration-only flag that asks frameworks to render pending + UI for a hydration display match. The display match can be the SPA fallback or + the first `ssr: false`/`data-only` match, so it is not always dehydrated. + +### Lane + +A lane is an ordered array of matches that represents one possible renderable +branch for one location. + +The same route branch can exist in several lanes at once: + +- **Active lane**: `router.stores.matches`. This is the current rendered router + state. +- **Pending lane**: `router.stores.pendingMatches`. This is the lane currently + being navigated to and exposed to readers as pending work. +- **Render-ready pending lane**: a private lane copy that was published into + `router.stores.matches` by `onReady()` so pending UI can render before the + final commit. +- **Cached lane entries**: `router.stores.cachedMatches`. These are inactive + finalized success snapshots from navigation/preload cache ownership. Public + invalidation may mark them `invalid: true`, but cached entries should remain + `status: 'success'` until they are reused, expired, or explicitly cleared. +- **Private load lane**: `InnerLoadContext.matches`. This is a mutable array + owned by one load pass. It is not necessarily published. +- **Preload lane**: a private load pass created with `preload: true`. Owned + entries have `match.preload === true`; borrowed active/pending entries keep + their original flag. If a borrowed owner disappears or owns a route-control / + error outcome, the preload returns without projecting assets or caching owned + speculative descendants. +- **Background lane**: a private copy of the active lane used for client + non-blocking reloads. Same-href loads can sometimes skip the foreground final + commit and become background-only. + +The store layer stores lanes as ids plus per-match stores: + +```mermaid +flowchart LR + subgraph "Router stores" + AM["matchStores"] + AI["matchesId"] + PM["pendingMatchStores"] + PI["pendingIds"] + CM["cachedMatchStores"] + CI["cachedIds"] + end + + A["active lane = readPoolMatches(matchStores, matchesId)"] + P["pending lane = readPoolMatches(pendingMatchStores, pendingIds)"] + C["cached entries = readPoolMatches(cachedMatchStores, cachedIds)"] + + AM --> A + AI --> A + PM --> P + PI --> P + CM --> C + CI --> C +``` + +`router.updateMatch(id, updater)` intentionally targets only active or pending +match stores. It does not mutate `cachedMatchStores`, and it is not responsible +for evicting invalid cache entries. Cache publication and eviction go through +`stores.setCached()` and `router.clearCache()` so the cache invariant stays +centralized. + +### Commit + +There are several kinds of commit. Keep them separate: + +- **Private match commit**: `commitMatch(inner, index, patch)` replaces one + entry in a private lane. This does not publish router state by itself. +- **Pending publication**: `onReady(matches)` publishes a render-ready pending + lane into active matches so frameworks can render pending UI. It does not run + route lifecycle hooks, cache reconciliation, `loadedAt`, or the final view + transition. It also clears the pending match pool for that load pass. +- **Final client commit**: `commitFinalMatches()` publishes the final active + lane, reconciles cache, clears pending state, updates `loadedAt`, and runs + `onLeave`, `onStay`, and `onEnter`. +- **Background commit**: `startBackgroundLoad()` publishes a completed client + non-blocking reload lane with `stores.setMatches(matches)`. It is atomic for + data and assets, but it does not run navigation lifecycle hooks. +- **Server commit**: `loadServerRouter()` writes the server lane into + `stores.matches` and updates server status/redirect properties. + +### Current + +"Current" means "this async work still owns the state it wants to mutate". + +Client match work is current when all of these hold: + +- `inner.matches[index]` still exists. +- `inner.matches[index].abortController` is the controller captured by this + async pass. +- The controller signal has not been aborted. +- If `router.pendingBuiltLocation` exists, its public browser href still equals + the load context public href. + +The helper `requireCurrentMatch(inner, index, controller)` checks those +conditions. It throws `inner` as a private sentinel when ownership is lost. +`loadClientMatches()` recognizes that sentinel and rethrows it so route-error +reduction does not run. The entry point that owns the pass then treats it as +cancellation: foreground navigation cleanup resolves the public load, while +preloads return without projecting assets or caching speculative matches. + +Top-level client navigation is current when +`router.latestLoadPromise === loadPromise`. + +Background work is current when: + +- `router._backgroundLoad === token`. +- The token controller is not aborted. +- The active store location still has the token href. +- There is no `pendingBuiltLocation`. + +## Server vs Client Split + +`router.ts` chooses the implementation at module initialization: + +```mermaid +flowchart TD + L["router.load(opts)"] --> D{"isServer export"} + D -->|"true"| S["loadServerRouter(router, opts)"] + D -->|"false"| C["loadClientRouter(router, opts)"] + D -->|"undefined in tests/dev"| R{"router.isServer"} + R -->|"true"| S + R -->|"false"| C + + P["router.preloadRoute(opts)"] --> PD{"server?"} + PD -->|"yes"| PN["return undefined"] + PD -->|"no"| PC["preloadClientRoute(router, opts)"] +``` + +The split is not just an optimization. The two runtimes have different +contracts. + +Server match loading: + +- Is intended for request-local router instances and assumes no client + interleaving. +- Does not inspect `router.load(opts)`: `sync`, `action`, request signals, + preloads, background work, and client currentness are client-side semantics in + this implementation. +- Does not publish pending UI. +- Does not run client preloads. +- Does not run background stale reloads. +- Does not need foreground current-load checks. +- Does not use stale-time reload decisions. +- Owns status code and redirect response metadata. +- Keeps status code and redirect response metadata as router instance + properties, not reactive client stores. +- Projects server assets, including headers. + +Client match loading: + +- Can have overlapping navigations, preloads, background reloads, and hydration + fallback loads. +- Can publish pending UI before final navigation commit when a pending match's + pending timer fires. +- Uses `AbortController`, `latestLoadPromise`, and background tokens to reject + stale async work. +- Projects foreground/background assets with currentness guards, and projects + successful preload assets only for owned preload entries. +- Caches successful owned preloads and eligible old active matches. + +## Match Creation + +Both server and client call `router.matchRoutes(location)`. The same function +creates the initial lane. + +`matchRoutesInternal()`: + +1. Finds matched routes. +2. Handles unmatched/global notFound routing. +3. Validates search params; for new matches, extracts and validates strict path + params. +4. Computes loader deps and the match id. +5. Reuses an existing match by id when possible. +6. Creates a fresh `AbortController`. +7. Sets `cause` to `preload`, `stay`, or `enter`. +8. Runs route `context()` for new matches. +9. Merges route context and existing beforeLoad context. + +New client matches start as `pending` when the route has work that can block +rendering: + +- `loader` +- `beforeLoad` +- `lazyFn` +- a component preload (`component`, `errorComponent`, `pendingComponent`, + `notFoundComponent`) + +Server-created matches do not use client pending status for this decision. + +Existing matches are shallow-copied into the new lane with fresh +params/search/preload/cause/controller. The private `_` bucket preserves an +existing `_.loadPromise` first, because hydration and pending owners can keep +readiness ownership across rematching. If there is no load promise, the copy +preserves only the dehydrated marker. That copy is a new generation. The old +match may still exist in an active, pending, or cached pool. + +## Client Top-Level Navigation Load + +`loadClientRouter()` owns the public navigation workflow. + +```mermaid +sequenceDiagram + participant App + participant Router + participant Stores + participant Loader as loadClientMatches + participant Assets as projectClientRouteAssets + participant Commit as commitFinalMatches + participant Bg as startBackgroundLoad + + App->>Router: router.load(opts) + Router->>Router: create loadPromise + Router->>Router: latestLoadPromise = loadPromise + Router->>Router: abort active background load if any + Router->>Router: cancelMatches() + Router->>Router: updateLatestLocation() + Router->>Router: matchRoutes(latestLocation) + Router->>Stores: status=pending, isLoading=true, location=next + Router->>Stores: setPending(pendingMatches), evict overlapping cache + Router->>Loader: loadClientMatches(loadContext) + Loader-->>Router: loaded private lane + alt foreground commit required + Router->>Assets: project assets for loaded lane + Assets-->>Router: assets written into private lane + Router->>Router: startViewTransition(...) + Router->>Router: startTransition(...) + Router->>Commit: publish final lane + Commit->>Stores: setMatches, clear pending, set cached, loadedAt + Commit->>Router: run onLeave/onStay/onEnter + else pure same-href background only + Router->>Stores: isLoading=false, clear pending + end + opt stale matches selected for background reload + Router->>Bg: startBackgroundLoad(next, loadedMatches, indices) + end + Router->>Router: resolve commitLocationPromise and loadPromise + opt background was started + Router->>Router: yield one microtask for sync background commit + end +``` + +Core sets `status` to `pending` at the start. Normal final commits and +background-only exits clear `isLoading`/pending; foreground redirects clear +pending and start a replacement navigation, whose load later clears +`isLoading`. Framework transitioners are responsible for later marking the +router status idle and updating `resolvedLocation`. + +### Background-only foreground pass + +When a same-href load finds only non-blocking stale reloads, the foreground pass +does not final-commit. `loadClientRouter()` first filters the selected +background indices against the finalized loaded lane. Only matches that still +exist, are `success`, and are not `globalNotFound` can stay in that list. This +is the `backgroundOnly` case: + +- The target href equals the resolved/current href. +- The filtered background list is non-empty. +- No route work set `requiresCommit`. +- No pending UI was published. + +The foreground pass clears pending/isLoading and then starts the background +reload. If a background load was started, `loadClientRouter()` yields one +microtask after resolving its public load promise so synchronous background work +can publish its final state before callers observe a transient fetching marker. + +## Client Match Loading + +`loadClientMatches(inner)` owns the private client lane. + +It has two large phases: + +1. Run `beforeLoad` serially from root to leaf. +2. Run loader/chunk work in parallel for the renderable prefix. + +The serial phase matters because child contexts depend on parent contexts. +The loader phase can be parallel because loader contexts receive a +`parentMatchPromise`. + +```mermaid +flowchart TD + Start["loadClientMatches(inner)"] --> BL["serial beforeLoad pass"] + BL --> BF{"beforeLoad failure?"} + BF -->|"redirect"| Prefix0["loader prefix length = 0"] + BF -->|"notFound"| NFPrefix["prefix = min(boundary + 1, failing index)"] + BF -->|"regular error"| ErrPrefix["prefix ends before failing route"] + BF -->|"none"| FullPrefix["prefix = full lane or first bad index"] + + Prefix0 --> Loaders["start loader/chunk promises for prefix"] + NFPrefix --> Loaders + ErrPrefix --> Loaders + FullPrefix --> Loaders + + Loaders --> FinalizeBL["append beforeLoad failure finalizer if any"] + FinalizeBL --> Reduce["reduce all promises together"] + Reduce --> Stale{"lost ownership sentinel?"} + Stale -->|"yes"| ThrowStale["throw sentinel to caller"] + Stale -->|"no"| Redirect{"redirect?"} + Redirect -->|"yes"| ThrowRedirect["throw redirect"] + Redirect -->|"no"| Fatal{"unhandled fatal rejection?"} + Fatal -->|"yes"| ThrowFatal["throw fatal rejection"] + Fatal -->|"no"| NotFound{"notFound?"} + NotFound -->|"yes"| CommitBoundary["commit notFound boundary and pop descendants"] + NotFound -->|"no"| ErrorIndex{"badIndex?"} + ErrorIndex -->|"yes"| PopAfterError["pop descendants after error index"] + ErrorIndex -->|"no"| Done["return private lane"] + CommitBoundary --> Done + PopAfterError --> Done +``` + +### beforeLoad on the client + +`handleClientBeforeLoad()`: + +- Creates a load promise when the match has `beforeLoad`, `loader`, or a serial + validation error. +- Arms the pending timer after serial validation succeeds, when the route can + show pending UI and the match is still pending. +- Commits `isFetching: 'beforeLoad'` for async beforeLoad, serial validation + errors, and thrown synchronous beforeLoad failures. +- Calls `beforeLoad` with parent context, params, search, location, navigate, + `abortController`, and current lane matches. +- Commits `__beforeLoadContext` and merged `context` only after `beforeLoad` + resolves. +- Converts thrown/returned redirects and notFounds into a serial failure record. + +This is why a child loader never sees a half-finished parent beforeLoad context. +When the serial phase records a beforeLoad failure, retained ancestor prefix +loaders run with `inner.background` temporarily disabled. Those reloads belong +to the foreground failure lane and must not be deferred into a background batch +that may be discarded by the boundary trim. + +### loader and chunk work on the client + +`loadClientRouteMatch()` handles one match: + +1. Hydrated matches finish immediately after reconstructing context. +2. Preload-disabled matches finish without running work. +3. Successful matches are checked for invalidation, staleness, or + `shouldReload`. +4. Non-blocking reloads are selected for background work. +5. Otherwise route chunks and loader run. +6. Loader data is committed into the private lane. If a loader exists, its + result is written even when the value is `undefined`; a reload that returns + `undefined` clears stale `loaderData` instead of preserving the previous + value. +7. `shouldReload` and loader failures are normalized and finalized. Serial + `beforeLoad` failures are finalized by `loadClientMatches()` using the same + finalizer. Route chunk failures are committed directly. +8. `pendingMinMs` is honored if pending UI was rendered. +9. Success clears error/fetching, sets `updatedAt`, and settles load promise. + +`parentMatchPromise` points at `matchPromises[index - 1]`, so loaders can wait +for parent work without forcing the whole route branch to become serial. + +Lost ownership is not a route outcome. If route work catches `err === inner`, it +rethrows the sentinel instead of reducing it as a route error. The path that +owns the abandoned work is responsible for promise settlement or cleanup before +the pass is dropped. + +## Pending UI and pendingMinMs + +Pending UI has two timers: + +- `pendingMs`: when the route is allowed to publish pending UI. +- `pendingMinMs`: once pending UI is rendered, how long it must remain visible. + +Core owns `pendingMs`. Framework match components own `pendingMinMs` by writing +`loadPromise.pendingUntil` only when a pending fallback actually renders for a +still-pending local load promise. Core later observes `pendingUntil` before +committing success/error/notFound/redirect. + +```mermaid +sequenceDiagram + participant Load as loadClientMatches + participant Timer as pendingMs timer + participant Router as loadClientRouter + participant FW as framework Match + participant Work as beforeLoad/loader/chunk + + Load->>Timer: set pendingTimeout on loadPromise + Load->>Work: continue route work + Timer-->>Router: onReady(private lane copy) + Router->>Router: stores.setMatches(render-ready lane) + Router->>Router: stores.setPending([]) + FW->>FW: render pendingComponent + FW->>Load: loadPromise.pendingUntil = now + pendingMinMs + Work-->>Load: resolves or fails + Load->>Load: wait until pendingUntil if needed + Load-->>Router: final private lane or thrown outcome + Router->>Router: final commit or redirect +``` + +Important invariants: + +- Pending publication is not final commit. +- Pending publication does not run lifecycle hooks. +- Pending publication does not reconcile cache. +- Pending publication does not consume the final view transition. +- After pending UI, a renderable same-href outcome still needs a final commit. + Redirect control flow waits any pending minimum and then navigates instead. + +Tests that anchor this behavior include: + +- `pending publication runs no lifecycle or cache reconciliation before beforeLoad error final commit` +- `pending publication does not consume the final view transition` +- `visible pending remains until beforeLoad settles after pendingMs plus pendingMinMs` +- `pendingMin wait does not throw after its match is canceled` + +## Failure Finalization and Lane Shortening + +Route failures can change the size of the lane. + +### Regular error + +A regular route error commits on the failing match and marks `inner.badIndex`. +Descendants after that match are removed after the promise reduction. Core does +not select an ancestor error boundary for route loading errors; framework error +boundaries handle render-time propagation later. + +### notFound + +A notFound chooses a notFound boundary with `getNotFoundBoundaryIndex()`. That +boundary may be the throwing route, an ancestor, or root. The final lane is +trimmed to include only matches up to the selected boundary. Non-root boundaries +become `status: 'notFound'`; root/global notFound uses `globalNotFound: true` +on a success root match. + +### redirect + +A redirect is terminal control flow. In foreground loads, it is resolved by +`router.resolveRedirect` and thrown to `loadClientRouter()`, which calls +`router.navigate()` with `replace: true` and `ignoreBlocker: true`. Background +redirects are handled inside `startBackgroundLoad()`. + +### Component/chunk failure while handling another failure + +If loading an `errorComponent` or `notFoundComponent` fails, the component/chunk +failure replaces the original route failure and is committed directly as an +error. It must not recursively try to load another boundary component. + +```mermaid +flowchart TD + F["loader/beforeLoad throws"] --> N["normalizeRouteFailure"] + Chunk["route/component chunk throws"] --> Direct + N --> R{"redirect?"} + R -->|"yes"| RT["settle source match and throw resolved redirect"] + R -->|"no"| NF{"notFound?"} + NF -->|"yes"| B["choose notFound boundary"] + B --> LNF["load notFoundComponent chunk"] + LNF --> NFCommit["commit temporary notFound and throw notFound"] + NF -->|"no"| LE["load errorComponent chunk"] + LE --> ErrCommit["commit error and mark badIndex"] + LNF --> CFail["component/chunk failure"] + LE --> CFail + CFail --> Direct["commit chunk/component failure as error"] +``` + +The lane can also change size before loaders start. A serial beforeLoad failure +limits the loader prefix so descendants that cannot render will not run. + +## How Lanes Change Size + +A lane is an array, and the array length is allowed to change at specific +boundaries. + +| Moment | How size changes | Why it is allowed | +| ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | +| `matchRoutes()` | The lane length follows the matched URL branch. Unmatched paths can add a notFound route or mark a global notFound boundary. | This is initial route matching, before any async work owns the lane. | +| New navigation | The new pending lane can be shorter, longer, or share a prefix with the active lane. | A different URL can match a different branch. | +| beforeLoad serial failure | The loader prefix is shortened before loader promises are started. For notFound, the prefix is capped at the smaller of `selectedBoundaryIndex + 1` and the throwing route index: ancestor/root boundary loaders may run, but the throwing route and its descendants do not run during the prefix. | Descendants below a redirect/error/notFound outcome cannot render correctly. | +| Loader or chunk error | Descendants after `inner.badIndex` are popped. | The failing match owns the route-loading error state below that point. | +| notFound | Descendants after the selected notFound boundary are popped. | The chosen boundary is the renderable leaf for this outcome. | +| Background error/notFound | The copied background lane is trimmed before atomic publication. | Active state must not see partial stale data or stale head output. | +| Final commit | Replaced active matches are moved into cache if eligible. | The new active lane owns rendering; old successful loader matches may be reused later. | +| Preload finish | Borrowed matches are not cached; owned successful preload matches may be cached. | A preload must not take ownership of active or pending foreground matches. | + +Lane shortening must settle load promises for removed matches. Otherwise +Suspense/preload waiters can remain pending after the match is no longer +reachable. + +## Preloads and Match Borrowing + +`router.preloadRoute()` is client-only. It builds a preload lane with +`matchRoutes(next, { preload: true, throwOnError: true })`, then calls +`loadClientMatches()` with a list of active and pending match ids that may be +borrowed. + +Preloading has two kinds of matches: + +- **Borrowed matches**: ids already present in the active or pending lanes. + The preload observes these read-only and does not cache them as its own work. +- **Owned preload matches**: `match.preload` entries that are not active or + pending when the successful preload is cached. + +```mermaid +sequenceDiagram + participant P as preloadClientRoute + participant R as Router + participant L as loadClientMatches + participant J as joinPreloadedActiveMatch + participant F as foreground owner + participant C as cache + + P->>R: matchRoutes(next, preload=true) + P->>R: collect active + pending ids + P->>L: loadClientMatches(preload ids) + L->>J: matched id is borrowable + J->>R: getMatch(id, includeCached=false) + alt borrowed loadPromise pending + J->>F: await borrowed loadPromise + end + alt borrowed match still in pending store + J->>F: await router.latestLoadPromise + end + J->>R: re-read owner match + alt owner missing/aborted + J-->>L: throw inner sentinel + else owner renderable + J-->>L: install borrowed match read-only in preload lane + opt borrowed owner has route-control/error ownership + J-->>L: throw inner sentinel + end + end + alt lane lost ownership + L-->>P: throw loadContext sentinel + P-->>P: return without assets/cache + else lane completed + L-->>P: loaded preload lane + end + alt every match success + P->>P: project and await preload assets + P->>C: cache owned preload matches only + end + P->>P: settle preload-owned load promises +``` + +Why wait for both `loadPromise` and sometimes `latestLoadPromise`? + +- `loadPromise` says the borrowed match's local work has reached a terminal + render state. +- `latestLoadPromise` says the foreground owner has actually committed or + disappeared from the pending store. + +Without the foreground wait, a preload can observe a transient pending-store +owner and start descendant work before the navigation that owns the parent has +finished. Tests anchor this with: + +- `joined preload waits for borrowed parent success while a sibling is still loading` +- `joined preload waits for borrowed terminal error to commit` +- `joined preload waits for borrowed notFound to commit` +- `preload canceled by borrowed owner disappearance projects no assets and caches nothing` + +Preload route-control behavior: + +- A private preload redirect recursively preloads the redirect target. It does + not navigate the active app, and it stops if `reloadDocument` is required. +- A preload notFound or regular error is not fatal to the app. +- Borrowed active redirect/notFound/error stops descendant preload work because + the active foreground owner already owns that outcome. +- Borrowed matches must re-read as present, un-aborted, and `status: 'success'` + after any waits. Otherwise the preload throws its private sentinel, projects + no assets, and caches nothing for speculative descendants. + +Cache invariant: + +- Pending preload work is private and does not enter `cachedMatches`. +- Failed, redirected, notFound, loaderless transient, and pending speculative + results should not be cached through public flows. +- `invalidate({ forcePending: true })` keeps cached entries as invalid success + snapshots instead of turning cached entries into pending matches. +- `clearCache()` is the explicit cleanup path for cached entries and only owns + cache membership. Public cache entries are written after match readiness has + settled, so cache removal does not settle synthetic private promises. + +## Background Stale Reloads + +Background reloads happen only on the client for invalid, stale, or +`shouldReload` successful loader matches whose stale reload mode is not +`blocking`. + +The foreground pass selects background indices inside `loadClientRouteMatch()`. +If a same-href load can background every necessary reload without any required +foreground commit or pending publication, `loadClientRouter()` skips final +foreground commit and starts `startBackgroundLoad()`. Other loads can still +start background work after their foreground commit. + +Background work is token-owned: + +- Starting a new background load aborts the old token. +- Starting a foreground load aborts any active background token and clears + fetching markers. +- A background token is current only while the active location href still + matches and no foreground pending location exists. +- Once a worker observes that the token is stale, cancellation is sticky: the + token is aborted and later workers, asset projection, and publication all stop. +- Background startup rewrites fetching markers across the whole active base lane: + selected indices become `isFetching: 'loader'`, and non-selected entries are + reset to `false`. + +```mermaid +sequenceDiagram + participant R as loadClientRouter + participant S as Stores + participant B as startBackgroundLoad + participant L1 as loader A + participant L2 as loader B + participant A as projectClientRouteAssets + + R->>R: load selects non-blocking stale/invalid/shouldReload indices + opt same-href background-only + R->>S: clear pending/isLoading without final commit + end + R->>B: start token-owned background lane + B->>S: selected active matches fetching, non-selected false + par selected loader A + B->>L1: run with copied lane + and selected loader B + B->>L2: run with copied lane + end + opt any worker observes stale token + B->>B: abort token and stop publication + end + B->>B: wait for all selected work + B->>B: reduce route-order outcomes + alt redirect + B->>R: navigate(replace=true, ignoreBlocker=true) + else error or notFound + B->>B: load selected failure component and trim lane + B->>A: project assets for trimmed lane + B->>S: setMatches(background lane) + else success + B->>A: project assets after all fresh loader data exists + B->>S: setMatches(background lane) + end + B->>S: if token still registered and not committed, clear fetching markers +``` + +Outcome priority for background batches: + +1. Redirect wins over notFound and regular errors. +2. If no redirect wins, the shallowest regular error wins. +3. If there is no regular error, the first selected notFound wins. + +Background asset projection waits until all selected loader work has settled. +That keeps data and head coherent. A parent-only background reload can still +republish child head because the child head may derive from parent loader data. +Selected background loaders own their `loaderData` field just like foreground +loaders: an `undefined` result is written into the copied background lane and +asset projection sees that cleared value before the atomic `setMatches()`. + +Tests that anchor this behavior include: + +- `same-url background beforeLoad context remains private until the atomic background commit` +- `pure same-url background revalidation does not perform a foreground commit` +- `multiple async background loaders flush heads after parent then child resolve` +- `background child redirect waits for parent error and then wins when ... settles first` +- `background parent error waits for child notFound and then wins when ... settles first` +- `background shallow regular error waits for deep regular error and then wins when ... settles first` +- `newer background batch supersedes older batch for the same lane` +- `foreground navigation clears an active background fetching marker before commit` +- `background batch that observed a pending navigation cannot later commit` +- `successful background commit performs one active match publication` + +## Route Asset Projection + +Route asset projection means executing route `head()`, `scripts()`, and on the +server `headers()`, then writing those results into the match lane. + +Projection always uses the lane it is handed. This matters because `head()` can +read `matches`, `match`, params, and loaderData. + +Client projection: + +- Runs after foreground match loading and before final commit. +- Runs after successful preloads, but only for `match.preload` entries. +- Runs after background loader work completes and before the background atomic + `setMatches()`. +- Foreground and background projection pass `isCurrent()` checks so stale lanes + do not mutate or publish assets. +- Preload projection filters to `match.preload` entries and relies on + owned-match cache checks instead of an `isCurrent()` callback. +- Handles `head()` and `scripts()`, not headers. +- If ownership is lost after an async `head()` or `scripts()` was started, the + projector observes the abandoned promise with `Promise.allSettled()` before + returning. This prevents unhandled rejections without committing stale assets + or continuing to later route asset hooks. +- If `scripts()` throws synchronously after an async `head()` started, client + projection observes that `head()` promise for the same reason, even when the + lane is still current. + +Server projection: + +- After reduction, redirects throw before asset projection. For non-redirect + outcomes, server projection runs over the trimmed/current lane before + throwing notFound or route errors. Unhandled fatal rejections project the + current lane before being rethrown; they may not have a committed error match. +- Handles `head()`, `scripts()`, and `headers()`. +- Does not need currentness checks. +- If `scripts()` or `headers()` throws synchronously after an earlier async asset + hook started, server projection observes the abandoned earlier promises. Async + server projection uses `Promise.allSettled()` so one rejected asset hook does + not leave another hook unobserved. + +Hydration projection: + +- Is not the same function as normal client projection. +- `ssr-client.ts` waits for route chunks first because lazy chunks can install + route context, head, and scripts. +- It reconstructs route context from dehydrated data where available, then + executes head and scripts for each match in the initial hydration lane. +- A `notFound()` thrown by hydration head/scripts records a notFound-shaped + match error and continues. Other hydration asset/context errors reject, + settle matches, and clear display pending. + +## Currentness and Cancellation + +Client currentness exists because async work can resolve after it no longer +owns the lane. + +```mermaid +stateDiagram-v2 + [*] --> Current + Current --> Current: await returns and owner still matches + Current --> Stale: controller identity changed + Current --> Stale: controller aborted + Current --> Stale: match removed from private lane + Current --> Stale: pendingBuiltLocation publicHref changed + Current --> Stale: background token replaced + Current --> Stale: latestLoadPromise replaced + Stale --> [*]: throw private sentinel or return without publishing + Current --> Mutated: private match commit + Current --> Published: pending publication / final commit / background setMatches +``` + +`cancelMatches()` aborts and settles pending and active matches. It skips active +matches that are also in the pending pool so the same match is not canceled +twice. Settling clears `loadPromise`, clears pending timeout, and resolves the +promise if it is still pending. + +After foreground/background work detects ownership loss, it must not: + +- run route error handling, +- commit or publish asset results, or continue to later asset hooks after + currentness is lost, +- publish route results into active stores. + +Cleanup mutations are different: stale/canceled background work is allowed, and +sometimes required, to clear active `isFetching` markers. + +Separately, preload completion must not cache borrowed active/pending matches. + +Cancellation and lane-shortening paths must settle removed or canceled load +promises. + +Tests that anchor this include: + +- `cancelMatches settles pending match load promises immediately` +- `cancelMatches after pending timeout` +- `pending timeout stays scoped to the current load pass` +- `pendingMin wait does not throw after its match is canceled` +- `background reload resolving after route exit does not execute head` +- `background redirect is ignored while a newer navigation is pending` + +## Final Client Commit + +`commitFinalMatches(router, baseMatches, nextMatches)` is the only normal +navigation final commit. + +It does three things: + +1. Cache eligible old active matches that were replaced. +2. Publish the next active lane and clear pending state. +3. Run lifecycle diffs. + +```mermaid +flowchart TD + Start["commitFinalMatches(base, next)"] --> CacheOld["push replaced base matches into cached candidates"] + CacheOld --> GC["filter cache by loader, gcTime/preloadGcTime, and success status"] + GC --> Stores["batch: isLoading=false, setMatches(next), clear pending, set loadedAt, set cached"] + Stores --> Diff["diff base vs next by index"] + Diff --> Leave["onLeave for old routeId not present at same index"] + Diff --> StayEnter["onStay if same routeId else onEnter"] +``` + +The final commit is intentionally separate from pending publication. Pending UI +is presentation; final commit is router state ownership. + +## Server Match Loading + +The server path is simpler because there is no client interleaving. + +```mermaid +sequenceDiagram + participant Req as request handler + participant R as loadServerRouter + participant M as matchRoutes + participant L as loadServerMatches + participant A as projectServerRouteAssets + participant S as stores/status + + Req->>R: router.load() + R->>R: choose latest/pendingBuilt location + R->>R: rebuild canonical location + alt canonical publicHref differs + R-->>Req: redirect + else canonical + R->>M: matchRoutes(next) + R->>S: statusCode=200, location=next + R->>L: loadServerMatches(matches) + L->>L: serial SSR decision + beforeLoad + L->>L: parallel loaders/chunks for renderable prefix + L->>L: reduce redirect/notFound/error + opt non-redirect outcome + L->>A: project head/scripts/headers + end + L-->>R: loaded lane or throws redirect/notFound/route error + R->>S: loadedAt, setMatches + end + alt non-redirect error/notFound after matching + R->>S: commit mutated matched lane, then set statusCode + else redirect + R->>S: set redirect/statusCode + end +``` + +Server beforeLoad differs from client beforeLoad: + +- It also computes SSR eligibility (`true`, `false`, or `data-only`). +- `ssr: false` skips server beforeLoad, loader, and route-chunk work for that + match. +- `data-only` still runs server beforeLoad and loader work, but skips route + chunk loading. +- Shell mode only SSR-loads the root. +- Parent `ssr: false` forces descendants to `ssr: false`. +- Preload is always false in server loader context. + +Server route failure handling: + +- Redirects update response redirect metadata and status code. +- For non-redirect errors and notFounds, `loadServerMatches()` mutates and + trims the matched lane before throwing; `loadServerRouter()` commits that lane + from its catch path and then derives the final status code. +- notFound commits the selected boundary. Non-root boundaries use + `status: 'notFound'`; root/global notFound uses `globalNotFound: true`, and + server status later becomes 404. +- Committed regular route errors use `status: 'error'` and later set status + code 500. +- Lane trimming mirrors client behavior, but without pending/currentness + machinery. + +## Hydration Handoff + +Hydration is a one-shot client path in `src/ssr/ssr-client.ts`. It keeps SSR +hydration reconstruction out of normal client match loading. The normal client +loader only retains a minimal dehydrated fast path for the fallback case where +hydration still needs to call `router.load()`. + +Hydration flow: + +1. Read `window.$_TSR.router`. +2. Install serialization adapters and SSR manifest. +3. Run custom `router.options.hydrate()` before matching routes. +4. Match the current client location. +5. Copy dehydrated status, data, errors, `ssr`, `updatedAt`, beforeLoad + context, and `globalNotFound` when present into matching client matches. + Mark unmatched client matches as `ssr: false`. +6. Mark matches as dehydrated unless `ssr === false`. +7. Start route chunk loading while copying those match payloads. +8. Publish initial matches. +9. Wait for route chunks before reconstructing route context and assets. Lazy + chunks can install route context, head, scripts, and `ssr` options. +10. Restore `route.options.ssr = match.ssr` during the reconstruction pass, then + rerun route context and execute head/scripts for the hydration lane. +11. If there are no `ssr: false` matches and this is not SPA mode, clear + dehydrated markers, settle load promises, set `resolvedLocation`, and stop. +12. Otherwise call normal `router.load()` to fill SPA or `ssr: false` holes. + +```mermaid +flowchart TD + H["hydrate(router)"] --> Data["read TSR bootstrap data"] + Data --> Hook["run user hydrate hook"] + Hook --> Match["match current location"] + Match --> Copy["copy dehydrated match payloads"] + Copy --> ChunksStarted["start route chunks"] + ChunksStarted --> Display{"display pending needed?"} + Display -->|"yes"| Pending["mark _displayPending and settle display match"] + Display -->|"no"| SetInitial["setMatches(matches)"] + Pending --> SetInitial + SetInitial --> Chunks["await all route chunks"] + Chunks --> Rebuild["restore ssr, rebuild route context and head/scripts"] + Rebuild --> Full{"no ssr:false and not SPA mode?"} + Full -->|"yes"| Done["settle, clear dehydrated, set resolvedLocation"] + Full -->|"no"| Load["Promise.resolve().then(router.load) for SPA/ssr:false matches"] +``` + +Hydration display pending uses `_displayPending`, not the normal client pending +timer. It applies to the SPA fallback match, or to the first non-fully-rendered +match (`ssr: false` or `data-only`) when pending UI/minimum timing applies. It +is cleared only after route chunks/context/head/scripts work, any required +`pendingMinMs`, and any follow-up SPA/`ssr:false` client load has left that +display match's pending state. If the marker is still present on a pending match +while the router is loading, hydration waits for `router.latestLoadPromise` and +tries again. After the follow-up load, hydration also repairs a still-pending +router status by setting `status: 'idle'` and `resolvedLocation` to the current +location; this covers synchronous loads that finish before framework +transitioners can observe them. Hydration failure cleanup settles matches and +clears the marker early. + +## Route Outcome Ordering + +When several route tasks settle, reduction order matters. + +Foreground client loader reduction: + +- Redirect throws immediately and wins. +- notFound is remembered if no redirect wins. +- The first unhandled non-route-control rejection is thrown. +- If no fatal rejection wins, notFound commits its boundary or root/global state + and trims descendants. +- If an error match was committed, descendants after `badIndex` are removed. + +Background reduction: + +- Waits for all selected background loaders. +- Redirect wins. +- If no redirect wins, the shallowest regular error wins. +- If there is no regular error, the first selected notFound wins. + +Server reduction: + +- Waits for all renderable-prefix promises. +- Redirect wins. +- Redirects throw before server asset projection. +- If no fatal rejection wins, notFound can commit its selected boundary. +- Committed route errors trim to `badIndex`, project assets, and then throw the + committed `errorMatch.error`. +- Unhandled fatal rejections throw after asset projection, but may not have a + committed error match. + +## Why Lanes Are Private First + +Most match loading work mutates a private lane before publication. This gives +the router a place to build a coherent result while async work interleaves. + +Private lanes let us: + +- Run beforeLoad serially and loaders in parallel. +- Keep background data private until all selected loaders and assets are + coherent. +- Publish pending UI without running final lifecycle hooks. +- Trim descendants after error/notFound without temporarily exposing invalid + active state. +- Let preloads borrow active matches without owning or caching them. +- Abandon stale async work by throwing a private sentinel. + +The rule of thumb: + +> Async route work may mutate only the private lane it owns. It may publish only +> after proving it is still current. + +## Common Change Checklist + +When changing match loading, check these invariants: + +- Does every async foreground/background continuation prove currentness before + mutating or publishing? +- If a lane can be shortened, are removed matches' load promises settled? +- Does pending publication remain separate from final commit? +- Does route asset projection see the final coherent lane for that path? +- Does any client reload path that runs a loader write `loaderData`, including + `undefined`, so a reload can clear previous data? +- Does cache mutation happen through cache APIs instead of `updateMatch()`? +- Can preload projection or caching accidentally treat a borrowed active/pending + match as owned? +- Can background work publish after a foreground navigation starts? +- Does a redirect bypass source head execution? +- Does notFound choose the same boundary on client and server? +- Are server-only status code and headers kept out of client-only paths? +- Do component/chunk failures replace the original route failure without + recursively trying to load another boundary component? +- Are `pendingMs` and `pendingMinMs` both honored when pending UI renders? + +Useful test anchors: + +- `packages/router-core/tests/load.test.ts` + - preload borrowing and owner disappearance tests + - pending publication and pendingMinMs tests + - background stale reload and superseding-token tests + - loader-returning-undefined foreground/background client tests + - client/server notFound boundary trimming tests + - redirect ownership tests + - route asset projection tests +- `packages/router-core/tests/hydrate.test.ts` + - dehydrated match reconstruction tests + - route-chunk-before-head hydration tests + - display pending cleanup tests diff --git a/packages/router-core/src/Matches.ts b/packages/router-core/src/Matches.ts index 852d186b67..eac88656a2 100644 --- a/packages/router-core/src/Matches.ts +++ b/packages/router-core/src/Matches.ts @@ -11,6 +11,11 @@ import type { import type { AnyRouter, RegisteredRouter, SSROption } from './router' import type { Constrain, ControlledPromise } from './utils' +type MatchLoadPromise = ControlledPromise & { + pendingTimeout?: ReturnType + pendingUntil?: number +} + export type AnyMatchAndValue = { match: any; value: any } export type FindValueByIndex< @@ -131,35 +136,28 @@ export interface RouteMatch< pathname: string params: TAllParams _strictParams: TAllParams - status: 'pending' | 'success' | 'error' | 'redirected' | 'notFound' + status: 'pending' | 'success' | 'error' | 'notFound' isFetching: false | 'beforeLoad' | 'loader' error: unknown paramsError: unknown searchError: unknown updatedAt: number - _nonReactive: { - /** @internal */ - beforeLoadPromise?: ControlledPromise - /** @internal */ - loaderPromise?: ControlledPromise - /** @internal */ - pendingTimeout?: ReturnType - loadPromise?: ControlledPromise - displayPendingPromise?: Promise - minPendingPromise?: ControlledPromise + /** Internal non-reactive match lifecycle bucket. */ + _: { + loadPromise?: MatchLoadPromise + /** Internal: true while this match is using SSR-hydrated data. */ dehydrated?: boolean - /** @internal */ + /** Internal loader error used by match loading. */ error?: unknown } loaderData?: TLoaderData - /** @internal */ + /** Internal route context scratch value. */ __routeContext?: Record - /** @internal */ + /** Internal beforeLoad context scratch value. */ __beforeLoadContext?: Record context: TAllContext search: TFullSearchSchema _strictSearch: TFullSearchSchema - fetchCount: number abortController: AbortController cause: 'preload' | 'enter' | 'stay' loaderDeps: TLoaderDeps @@ -170,7 +168,6 @@ export interface RouteMatch< staticData: StaticDataRouteOption /** This attribute is not reactive */ ssr?: SSROption - _forcePending?: boolean _displayPending?: boolean } diff --git a/packages/router-core/src/index.ts b/packages/router-core/src/index.ts index fd673ca410..471a17f97d 100644 --- a/packages/router-core/src/index.ts +++ b/packages/router-core/src/index.ts @@ -236,15 +236,14 @@ export type { } from './stores' export { defaultSerializeError, - getLocationChangeInfo, RouterCore, lazyFn, SearchParamError, PathParamError, - getInitialRouterState, getMatchedRoutes, trailingSlashOptions, } from './router' +export { getLocationChangeInfo } from './location-change' export type { ViewTransitionOptions, diff --git a/packages/router-core/src/load-matches.client.ts b/packages/router-core/src/load-matches.client.ts new file mode 100644 index 0000000000..02645044cd --- /dev/null +++ b/packages/router-core/src/load-matches.client.ts @@ -0,0 +1,1066 @@ +import { createControlledPromise, isPromise } from './utils' +import { isNotFound } from './not-found' +import { isRedirect } from './redirect' +import { loadRouteChunk } from './route-chunks' +import { projectClientRouteAssets } from './route-assets.client' +import { + getMatchContext, + getNotFoundBoundaryIndex, + getNotFoundBoundaryPatch, + markError, + normalizeRouteFailure, + settleMatchLoad, +} from './load-matches' +import type { NotFoundError } from './not-found' +import type { + AnyRoute, + BeforeLoadContextOptions, + LoaderFnContext, +} from './route' +import type { AnyRouteMatch, MakeRouteMatch } from './Matches' +import type { AnyRouter } from './router' +import type { InnerLoadContext, SerialFailure } from './load-matches' + +const isRouteControl = (error: unknown) => + isRedirect(error) || isNotFound(error) + +const getLoader = (loaderOption: AnyRoute['options']['loader']) => + typeof loaderOption === 'function' ? loaderOption : loaderOption?.handler + +// Route work may only commit while it still owns the lane entry it is about to +// mutate. Each client load pass stamps its matches with an AbortController: +// starting a newer load replaces the controller, cancellation aborts its signal, +// and a different pending public location means this pass no longer represents +// the browser target. Compare publicHref, not href, because href may be the +// router-internal path while publicHref includes basepath/rewrite output. Any +// of those cases makes continuing unsafe because stale beforeLoad/loader/chunk +// work could write into the current lane. +// +// Throwing `inner` is intentional. `loadClientMatches` catches that exact object +// as the private "lost ownership" sentinel, so abandoned work stops without +// becoming a user-visible route error or triggering route error handling. +const requireCurrentMatch = ( + inner: InnerLoadContext, + index: number, + abortController: AbortController, +): AnyRouteMatch => { + const match = inner.matches[index] + const pendingLocation = inner.router.pendingBuiltLocation + if ( + !match || + match.abortController !== abortController || + abortController.signal.aborted || + (pendingLocation && + pendingLocation.publicHref !== inner.location.publicHref) + ) { + throw inner + } + + return match +} + +const commitMatch = ( + inner: InnerLoadContext, + index: number, + patch: Partial, +): AnyRouteMatch => { + return (inner.matches[index] = { + ...inner.matches[index]!, + ...patch, + }) +} + +function getNavigate(inner: InnerLoadContext) { + return (opts: any) => + inner.router.navigate({ + ...opts, + _fromLocation: inner.location, + }) +} + +const joinPreloadedActiveMatch = async ( + inner: InnerLoadContext, + index: number, +): Promise => { + const matchId = inner.matches[index]!.id + + // A preload can reuse an active/pending match by ID, but it does not own that + // match. If the foreground owner is already gone or aborted, this speculative + // preload pass has nothing safe to borrow. + let match = inner.router.getMatch(matchId, false) + if (!match) { + throw inner + } + if (match.abortController.signal.aborted) { + throw inner + } + + // Wait for the borrowed match's own beforeLoad/loader/component work to reach + // a terminal render state before copying it into the private preload lane. + if (match._.loadPromise?.status === 'pending') { + await match._.loadPromise + } + + // If the borrowed match still lives in the pending store, its local readiness + // may have settled before the foreground load committed the lane. Wait for the + // foreground load so the preload observes the committed owner, not a transient + // pending-store snapshot. + if (inner.router.stores.pendingMatchStores.has(matchId)) { + await inner.router.latestLoadPromise + } + + // Re-read after the waits because the owner may have committed, redirected, + // disappeared, or been aborted while this preload was observing it. + match = inner.router.getMatch(matchId, false) + if (!match || match.abortController.signal.aborted) { + throw inner + } + + // From here the preload lane uses the owner match read-only. It must not clone + // or cache a borrowed active match as if the preload generated it itself. + inner.matches[index] = match + const error = match._.error ?? match.error + + if (isRouteControl(error)) { + // Borrowed active matches keep ownership of their route outcomes. Preloads + // only observe the active lane; they must not chase a redirect/notFound that + // the foreground navigation is already handling. + throw inner + } + + if (match.status !== 'success') { + throw inner + } + + return match +} + +function waitPendingMin(match: AnyRouteMatch): Promise | undefined { + const remaining = (match._.loadPromise?.pendingUntil ?? 0) - Date.now() + if (remaining > 0) { + return new Promise((resolve) => setTimeout(resolve, remaining)) + } + return undefined +} + +const finalizeRouteFailure = async ( + inner: InnerLoadContext, + index: number, + error: unknown, + abortController: AbortController, + componentFailure?: boolean, +): Promise => { + let errorIndex = index + + let currentMatch = requireCurrentMatch(inner, index, abortController) + + if (!componentFailure) { + try { + if (isNotFound(error)) { + errorIndex = getNotFoundBoundaryIndex(inner, error) + const boundaryMatch = inner.matches[errorIndex]! + + if (inner.preload?.includes(boundaryMatch.id)) { + // The selected boundary is owned by an active/pending route match. + // A speculative preload must not load its boundary component or mutate it. + throw inner + } + await loadRouteChunk( + inner.router.routesById[boundaryMatch.routeId], + 'notFoundComponent', + ) + } else if (!isRedirect(error)) { + await loadRouteChunk( + inner.router.routesById[currentMatch.routeId], + 'errorComponent', + ) + } + } catch (chunkError) { + if (chunkError === inner) { + // Preserve the stale-pass sentinel from the borrowed-boundary branch; + // it is not a component preload failure. + throw inner + } + // This error already came from component/chunk loading, so commit it + // directly instead of trying to load another boundary component. + error = chunkError + componentFailure = true + } + + currentMatch = requireCurrentMatch(inner, index, abortController) + } + + const pendingWait = waitPendingMin(currentMatch) + if (pendingWait) { + await pendingWait + currentMatch = requireCurrentMatch(inner, index, abortController) + } + + if (!componentFailure) { + if (isRedirect(error)) { + currentMatch._.error = error + settleMatchLoad(currentMatch) + + error.options._fromLocation = inner.location + // Redirects are terminal control flow for this pass, not renderable match + // state. Throw the resolved redirect so navigation can take over. + throw inner.router.resolveRedirect(error) + } + + if (isNotFound(error)) { + inner.requiresCommit = true + + commitMatch(inner, index, { + status: 'notFound', + error, + isFetching: false, + }) + + // notFound is also terminal for this phase. The later allSettled reduction + // chooses the render boundary and trims the final lane. + throw error + } + } + + const matchToCommit = inner.matches[errorIndex] + if (!matchToCommit) { + // The lane was shortened by a newer outcome before this finalizer could + // commit. Cancel this stale finalizer. + throw inner + } + + inner.requiresCommit = true + markError(inner, errorIndex) + + commitMatch(inner, errorIndex, { + error, + status: 'error' as const, + isFetching: false as const, + context: getMatchContext( + inner, + errorIndex, + matchToCommit.__beforeLoadContext, + ), + updatedAt: Date.now(), + }) + finishMatchLoad(inner, errorIndex) +} + +const recordBeforeLoadFailure = ( + inner: InnerLoadContext, + index: number, + error: unknown, +): SerialFailure => { + const abortController = inner.matches[index]!.abortController + requireCurrentMatch(inner, index, abortController) + error = normalizeRouteFailure(inner, index, error) + requireCurrentMatch(inner, index, abortController).__beforeLoadContext = + undefined + + return [index, error] +} + +const setupPendingTimeout = ( + inner: InnerLoadContext, + routeOptions: AnyRoute['options'], + index: number, + match: AnyRouteMatch, +): void => { + const onReady = inner.onReady + if ( + match.status === 'pending' && + onReady && + !inner.pendingPublished && + (routeOptions.pendingComponent ?? + (inner.router.options as any).defaultPendingComponent) + ) { + const pendingMs = + routeOptions.pendingMs ?? inner.router.options.defaultPendingMs + const promise = match._.loadPromise + if ( + (pendingMs as number) < Infinity && + promise && + !promise.pendingTimeout + ) { + promise.pendingTimeout = setTimeout(() => { + const current = inner.matches[index] + if ( + !inner.pendingPublished && + current?._.loadPromise === promise && + current.status === 'pending' + ) { + // Publish the current render-ready lane so pending UI can render while + // beforeLoad/loader work continues. + inner.pendingPublished = true + inner.rendered ||= onReady(inner.matches.slice()) ?? true + } + }, pendingMs) + } + } +} + +const handleClientBeforeLoad = ( + inner: InnerLoadContext, + index: number, +): void | SerialFailure | Promise => { + const existingMatch = inner.matches[index]! + + const { preload, routeId } = existingMatch + const routeOptions = inner.router.routesById[routeId]!.options + const abortController = existingMatch.abortController + const pending = () => { + commitMatch(inner, index, { + isFetching: 'beforeLoad', + // Note: We intentionally don't update context here. + // Context should only be updated after beforeLoad resolves to avoid + // components seeing incomplete context during async beforeLoad execution. + }) + } + + const serialError = + existingMatch.paramsError !== undefined + ? existingMatch.paramsError + : existingMatch.searchError + const beforeLoad = routeOptions.beforeLoad + if (beforeLoad || routeOptions.loader || serialError !== undefined) { + existingMatch._.loadPromise ||= createControlledPromise() + } + + if (serialError !== undefined) { + pending() + return recordBeforeLoadFailure(inner, index, serialError) + } + + setupPendingTimeout(inner, routeOptions, index, existingMatch) + + const commitBeforeLoad = (beforeLoadContext: any) => { + commitMatch(inner, index, { + isFetching: false as const, + __beforeLoadContext: beforeLoadContext, + context: getMatchContext(inner, index, beforeLoadContext), + }) + } + + // Routes without beforeLoad still need to pick up parent beforeLoad context + // before descendants run their loaders. + if (!beforeLoad) { + commitBeforeLoad(undefined) + return + } + + // commits the result of the beforeLoad phase and settles its promise + const updateContext = (beforeLoadContext: any): void | SerialFailure => { + requireCurrentMatch(inner, index, abortController) + + if (isRouteControl(beforeLoadContext)) { + return recordBeforeLoadFailure(inner, index, beforeLoadContext) + } + + commitBeforeLoad(beforeLoadContext) + } + + // Exclude the current beforeLoad context while invoking beforeLoad for this generation. + const context = getMatchContext(inner, index, undefined) + const { search, params, cause } = existingMatch + const beforeLoadFnContext: BeforeLoadContextOptions< + any, + any, + any, + any, + any, + any, + any, + any, + any + > = { + search, + abortController, + params, + preload, + context, + location: inner.location, + navigate: getNavigate(inner), + buildLocation: inner.router.buildLocation, + cause, + matches: inner.matches, + routeId, + ...inner.router.options.additionalContext, + } + + let beforeLoadContext + try { + requireCurrentMatch(inner, index, abortController) + beforeLoadContext = beforeLoad(beforeLoadFnContext) + if (isPromise(beforeLoadContext)) { + requireCurrentMatch(inner, index, abortController) + pending() + return beforeLoadContext.then(updateContext, (err) => { + requireCurrentMatch(inner, index, abortController) + return recordBeforeLoadFailure(inner, index, err) + }) + } + } catch (err) { + if (err === inner) { + throw err + } + + pending() + return recordBeforeLoadFailure(inner, index, err) + } + + return updateContext(beforeLoadContext) +} + +const getLoaderContext = ( + inner: InnerLoadContext, + matchPromises: Array>, + index: number, + route: AnyRoute, +): LoaderFnContext => { + const { params, loaderDeps, abortController, cause, context, preload } = + inner.matches[index]! + + return { + params, + deps: loaderDeps, + preload, + parentMatchPromise: matchPromises[index - 1] as any, + abortController, + context, + location: inner.location, + navigate: getNavigate(inner), + cause, + route, + ...inner.router.options.additionalContext, + } +} + +const finishMatchLoad = ( + inner: InnerLoadContext, + index: number, +): AnyRouteMatch => { + const match = inner.matches[index]! + + match._.dehydrated = undefined + settleMatchLoad(match) + + return match.isFetching || match.invalid + ? commitMatch(inner, index, { + isFetching: false, + invalid: false, + }) + : match +} + +const loadClientRouteMatch = async ( + inner: InnerLoadContext, + matchPromises: Array>, + index: number, +): Promise => { + const { router, matches } = inner + const initialMatch = matches[index]! + const { routeId } = initialMatch + const route = router.routesById[routeId]! + const routeOptions = route.options + const loaderOption = routeOptions.loader + const loader = getLoader(loaderOption) + + let match = initialMatch + const { preload } = match + + if (match._.dehydrated) { + commitMatch(inner, index, { + invalid: false, + context: getMatchContext(inner, index, match.__beforeLoadContext), + }) + + // Hydrated client matches are already loaded. Finish by clearing stale + // fetching/invalid flags and resolving their load promises. + return finishMatchLoad(inner, index) + } + + if (preload && routeOptions.preload === false) { + // Route-level preload opt-out still needs promise cleanup for the lane entry. + return finishMatchLoad(inner, index) + } + + const passController = match.abortController + + if (match.status === 'success') { + const activeMatch = router.stores.matches.get()[index] + const staleAge = preload + ? (routeOptions.preloadStaleTime ?? + router.options.defaultPreloadStaleTime ?? + 30_000) // 30 seconds for preloads by default + : (routeOptions.staleTime ?? router.options.defaultStaleTime ?? 0) + const shouldReloadOption = routeOptions.shouldReload + let shouldReload = shouldReloadOption + if (typeof shouldReloadOption === 'function') { + try { + requireCurrentMatch(inner, index, passController) + shouldReload = shouldReloadOption( + getLoaderContext(inner, matchPromises, index, route), + ) + } catch (err) { + requireCurrentMatch(inner, index, passController) + // shouldReload runs inside the route outcome lifecycle. If it throws, + // commit that failure like a loader error and return the finalized lane. + await finalizeRouteFailure( + inner, + index, + normalizeRouteFailure(inner, index, err), + passController, + ) + return matches[index]! + } + } + match = requireCurrentMatch(inner, index, passController) + + if ( + !match.invalid && + !( + shouldReload ?? + (Date.now() - match.updatedAt >= staleAge && + (inner.forceStaleReload || + match.cause !== 'stay' || + (activeMatch && + activeMatch.routeId === routeId && + activeMatch.id !== match.id))) + ) + ) { + // Fresh enough, not invalid, and shouldReload did not request work: settle + // the match without creating a loader generation. + return finishMatchLoad(inner, index) + } + + if ( + loader && + inner.background && + (loaderOption?.staleReloadMode ?? + router.options.defaultStaleReloadMode) !== 'blocking' + ) { + inner.background.push(index) + return finishMatchLoad(inner, index) + } + } + + if (loader || match.status === 'pending' || match.invalid) { + inner.requiresCommit = true + } + + await (async (): Promise => { + const routeChunkPromise = loadRouteChunk(route) + void routeChunkPromise?.catch(() => {}) + + // Actually run the loader and handle the result + try { + // Kick off the loader! + const loaderResult = loader?.( + getLoaderContext(inner, matchPromises, index, route), + ) + const loaderResultIsPromise = isPromise(loaderResult) + if (loaderResultIsPromise || routeChunkPromise) { + commitMatch(inner, index, { + isFetching: 'loader', + }) + } + + if (loader) { + const loaderData = loaderResultIsPromise + ? await loaderResult + : loaderResult + + requireCurrentMatch(inner, index, passController) + + if (isRouteControl(loaderData)) { + throw loaderData + } + + commitMatch(inner, index, { + loaderData, + }) + } + } catch (error) { + if (error === inner) { + // `inner` is cancellation. Re-throw it instead of wrapping it as a + // route error. + throw error + } + + if ( + (error as any)?.name === 'AbortError' && + requireCurrentMatch(inner, index, passController).status !== 'pending' + ) { + // The route already has a renderable result, so an AbortError here is + // a stale-while-revalidate abort. Clear fetching/invalid state and + // settle readiness without turning the abort into a route error. + finishMatchLoad(inner, index) + return + } else if (preload && isRedirect(error)) { + settleMatchLoad(match) + throw error + } + + // Pending AbortErrors have no previous loaderData to keep, so they share + // the normal route-error finalization path with other loader failures. + requireCurrentMatch(inner, index, passController) + return finalizeRouteFailure( + inner, + index, + normalizeRouteFailure(inner, index, error), + passController, + ) + } + + try { + if (routeChunkPromise) { + await routeChunkPromise + } + } catch (chunkError) { + // A route/component chunk failure replaces the loader result and is committed + // as the route error for this loader generation. + return finalizeRouteFailure( + inner, + index, + chunkError, + passController, + true, + ) + } + + const pendingWait = waitPendingMin( + requireCurrentMatch(inner, index, passController), + ) + if (pendingWait) { + await pendingWait + requireCurrentMatch(inner, index, passController) + } + + commitMatch(inner, index, { + error: undefined, + status: 'success', + isFetching: false, + updatedAt: Date.now(), + }) + finishMatchLoad(inner, index) + })().catch((error) => { + if (error === inner) { + settleMatchLoad(match) + } + throw error + }) + + requireCurrentMatch(inner, index, passController) + + return matches[index]! +} + +export const clearBackgroundFetching = (router: AnyRouter): void => { + router.batch(() => { + for (const matchId of router.stores.matchesId.get()) { + router.updateMatch(matchId, (match) => + match.isFetching + ? { + ...match, + isFetching: false, + } + : match, + ) + } + }) +} + +export function startBackgroundLoad( + router: AnyRouter, + location: InnerLoadContext['location'], + base: Array, + indices: Array, +): void { + router._backgroundLoad?.controller.abort() + const token = (router._backgroundLoad = { + href: location.href, + controller: new AbortController(), + }) + + const matches = base.slice() + let committed = false + const cancelBatch = () => { + token.controller.abort() + } + const isCurrent = () => + router._backgroundLoad === token && + !token.controller.signal.aborted && + router.stores.location.get().href === token.href && + !router.pendingBuiltLocation + const isCurrentOrCancel = () => { + if (isCurrent()) { + return true + } + cancelBatch() + return false + } + const requireCurrent = () => { + if (!isCurrent()) { + throw token + } + } + + router.batch(() => { + for (let i = 0; i < base.length; i++) { + const match = base[i]! + const isFetching = indices.includes(i) ? 'loader' : false + router.updateMatch(match.id, (previous) => + previous.isFetching === isFetching + ? previous + : { + ...previous, + isFetching, + }, + ) + } + }) + + const inner: InnerLoadContext = { + router, + location, + matches, + } + + void (async (): Promise => { + const matchPromises = matches.map((match) => Promise.resolve(match)) + // Sparse entries preserve `throw undefined`: a missing index means no + // failure, while an own index with value `undefined` is still a failure. + const failures: Array = [] + + for (const index of indices) { + let match = (matches[index] = { + ...base[index]!, + abortController: token.controller, + }) + + matchPromises[index] = (async (): Promise => { + const route = router.routesById[match.routeId]! + const loader = getLoader(route.options.loader)! + + try { + requireCurrent() + let loaderData = loader( + getLoaderContext(inner, matchPromises, index, route), + ) + requireCurrent() + if (isPromise(loaderData)) { + loaderData = await loaderData + requireCurrent() + } + + if (isRouteControl(loaderData)) { + throw loaderData + } + + match = { + ...match, + loaderData, + } + } catch (error) { + if (error === token) { + throw error + } + + requireCurrent() + if ((error as any)?.name === 'AbortError') { + return match + } + + // eslint-disable-next-line no-ex-assign + error = normalizeRouteFailure(inner, index, error) + requireCurrent() + throw error + } + + requireCurrent() + return (matches[index] = { + ...match, + isFetching: false, + updatedAt: Date.now(), + }) + })().catch((error) => { + if (error === token) { + cancelBatch() + } else { + failures[index] = error + } + return matches[index]! + }) + } + + await Promise.all(matchPromises) + + if (!isCurrentOrCancel()) { + return + } + + let redirectError: unknown + let notFoundError: NotFoundError | undefined + let failure: [number, unknown] | undefined + + for (let index = 0; index < failures.length; index++) { + if (!(index in failures)) { + continue + } + const error = failures[index] + + if (isRedirect(error)) { + redirectError ||= error + } else if (isNotFound(error)) { + notFoundError ||= error + } else { + failure ||= [index, error] + } + } + + if (redirectError) { + if (isCurrent()) { + void router.navigate({ + ...(redirectError as any).options, + replace: true, + ignoreBlocker: true, + }) + } + return + } + + if (failure) { + // eslint-disable-next-line prefer-const + let [index, error] = failure + try { + requireCurrent() + await loadRouteChunk( + router.routesById[matches[index]!.routeId], + 'errorComponent', + ) + requireCurrent() + } catch (componentError) { + if (componentError === token) { + cancelBatch() + return + } + if (!isCurrentOrCancel()) { + return + } + error = componentError + } + + matches[index] = { + ...matches[index]!, + error, + status: 'error', + isFetching: false, + updatedAt: Date.now(), + } + matches.length = index + 1 + } else if (notFoundError) { + const index = getNotFoundBoundaryIndex(inner, notFoundError) + const match = matches[index]! + try { + requireCurrent() + await loadRouteChunk( + router.routesById[match.routeId], + 'notFoundComponent', + ) + requireCurrent() + matches[index] = { + ...match, + ...getNotFoundBoundaryPatch(inner, index, notFoundError), + invalid: false, + } + } catch (componentError) { + if (componentError === token) { + cancelBatch() + return + } + if (!isCurrentOrCancel()) { + return + } + matches[index] = { + ...matches[index]!, + error: componentError, + status: 'error', + isFetching: false, + updatedAt: Date.now(), + } + } + matches.length = index + 1 + } + + const assets = projectClientRouteAssets( + router, + matches, + undefined, + isCurrentOrCancel, + ) + if (isPromise(assets)) { + await assets + } + + if (isCurrentOrCancel()) { + router.stores.setMatches(matches) + committed = true + } + })().finally(() => { + if (router._backgroundLoad === token) { + router._backgroundLoad = undefined + if (!committed) { + clearBackgroundFetching(router) + } + } + }) +} + +export async function loadClientMatches( + inner: InnerLoadContext, +): Promise> { + const matchPromises: Array> = [] + + let firstNotFound: NotFoundError | undefined + let failure: SerialFailure | undefined + + for ( + let i = 0; + i < inner.matches.length && !failure && inner.badIndex === undefined; + i++ + ) { + try { + if (inner.preload?.includes(inner.matches[i]!.id)) { + await (matchPromises[i] = joinPreloadedActiveMatch(inner, i)) + continue + } + + if (inner.matches[i]!._.dehydrated) { + matchPromises[i] = loadClientRouteMatch(inner, matchPromises, i) + continue + } + + const beforeLoadResult = handleClientBeforeLoad(inner, i) + if (isPromise(beforeLoadResult)) { + failure = (await beforeLoadResult) as SerialFailure | undefined + } else { + failure = beforeLoadResult as SerialFailure | undefined + } + } catch (err) { + if (err === inner) { + // This pass lost ownership before serial loading reached a route outcome. + throw err + } + if (isNotFound(err)) { + firstNotFound ||= err + } else if (isRedirect(err) || !inner.preload) { + throw err + } + break + } + } + + let maxIndexExclusive = inner.badIndex ?? inner.matches.length + if (failure) { + const [index, error] = failure + maxIndexExclusive = Math.min( + maxIndexExclusive, + isRedirect(error) + ? 0 + : isNotFound(error) + ? Math.min(getNotFoundBoundaryIndex(inner, error) + 1, index) + : index, + ) + } + + const background = inner.background + if (failure) { + // A serial failure is part of the foreground render lane. Retained + // ancestors must honor shouldReload/staleTime in that lane instead of + // being deferred into background work that may be discarded by the boundary. + inner.background = undefined + } + for (let i = 0; i < maxIndexExclusive; i++) { + matchPromises[i] ||= loadClientRouteMatch(inner, matchPromises, i) + } + inner.background = background + + if (failure) { + const [index, error] = failure + matchPromises.push( + finalizeRouteFailure( + inner, + index, + error, + inner.matches[index]!.abortController, + ) as any, + ) + } + + let fatalError: unknown + let hasFatalError = false + for (const result of await Promise.allSettled(matchPromises)) { + if (result.status === 'fulfilled') { + continue + } + + const reason = + process.env.NODE_ENV !== 'production' && result.reason === undefined + ? new Error('Route load failed with undefined') + : result.reason + if (reason === inner) { + // `inner` means "this pass lost ownership". Stop reducing outcomes and + // leave the current lane untouched for the newer owner. + throw reason + } + if (isRedirect(reason)) { + // Redirects outrank notFound and regular errors; let navigation handle it. + throw reason + } else if (isNotFound(reason)) { + firstNotFound ||= reason + } else if (!hasFatalError) { + fatalError = reason + hasFatalError = true + } + } + + if (hasFatalError) { + // Non-route-control failures are fatal to this load call. + throw fatalError + } + + const errorIndex = inner.badIndex + + if (firstNotFound) { + // Determine once which matched route will actually render the + // notFoundComponent, then pass this precomputed index through the remaining + // finalization steps. + // This can differ from the throwing route when routeId targets an ancestor + // boundary (or when bubbling resolves to a parent/root boundary). + const index = getNotFoundBoundaryIndex(inner, firstNotFound) + if (inner.preload?.includes(inner.matches[index]!.id)) { + return inner.matches + } + + const patch = getNotFoundBoundaryPatch(inner, index, firstNotFound) + commitMatch(inner, index, patch) + finishMatchLoad(inner, index) + while (inner.matches.length > index + 1) { + settleMatchLoad(inner.matches.pop()!) + } + } else if (errorIndex !== undefined) { + while (inner.matches.length > errorIndex + 1) { + settleMatchLoad(inner.matches.pop()!) + } + } + + if (inner.rendered && inner.rendered !== true) { + await inner.rendered + } + + if (firstNotFound) { + throw firstNotFound + } + + return inner.matches +} diff --git a/packages/router-core/src/load-matches.server.ts b/packages/router-core/src/load-matches.server.ts new file mode 100644 index 0000000000..b207157169 --- /dev/null +++ b/packages/router-core/src/load-matches.server.ts @@ -0,0 +1,553 @@ +import { isPromise } from './utils' +import { isNotFound } from './not-found' +import { rootRouteId } from './root' +import { isRedirect } from './redirect' +import { loadRouteChunk } from './route-chunks' +import { projectServerRouteAssets } from './route-assets.server' +import { + getMatchContext, + getNotFoundBoundaryIndex, + markError, + normalizeRouteFailure, +} from './load-matches' +import type { NotFoundError } from './not-found' +import type { + AnyRoute, + BeforeLoadContextOptions, + LoaderFnContext, + SsrContextOptions, +} from './route' +import type { AnyRouteMatch, MakeRouteMatch } from './Matches' +import type { SSROption } from './router' +import type { InnerLoadContext, LoadMatchesArg } from './load-matches' + +const commitMatch = ( + inner: InnerLoadContext, + index: number, + patch: Partial, +): AnyRouteMatch => { + return (inner.matches[index] = { + ...inner.matches[index]!, + ...patch, + }) +} + +const handleServerRedirectOrNotFound = ( + inner: InnerLoadContext, + index: number, + match: AnyRouteMatch, + err: unknown, +): void => { + if (isRedirect(err)) { + if (err.redirectHandled && !err.options.reloadDocument) { + throw err + } + + match._.error = err + + err.options._fromLocation = inner.location + err.redirectHandled = true + throw inner.router.resolveRedirect(err) + } + + if (isNotFound(err)) { + commitMatch(inner, index, { + status: 'notFound', + error: err, + }) + throw err + } +} + +const recordServerBeforeLoadFailure = ( + inner: InnerLoadContext, + index: number, + error: unknown, +): void => { + const match = inner.matches[index]! + error = normalizeRouteFailure(inner, index, error) + match.__beforeLoadContext = undefined + inner.serialFailure = [index, error] +} + +const finalizeServerRouteFailure = async ( + inner: InnerLoadContext, + index: number, + error: unknown, + componentError?: boolean, +): Promise => { + const routesById = inner.router.routesById + let errorIndex = index + + if (!componentError) { + try { + if (isNotFound(error)) { + errorIndex = getNotFoundBoundaryIndex(inner, error) + await loadRouteChunk( + routesById[inner.matches[errorIndex]!.routeId], + 'notFoundComponent', + ) + } else if (!isRedirect(error)) { + await loadRouteChunk( + routesById[inner.matches[index]!.routeId], + 'errorComponent', + ) + } + } catch (chunkError) { + error = chunkError + componentError = true + } + } + + if (!componentError) { + handleServerRedirectOrNotFound(inner, index, inner.matches[index]!, error) + } + + const matchToCommit = inner.matches[errorIndex] + if (!matchToCommit) { + return + } + + markError(inner, errorIndex) + commitMatch(inner, errorIndex, { + error, + status: 'error' as const, + context: getMatchContext( + inner, + errorIndex, + matchToCommit.__beforeLoadContext, + ), + updatedAt: Date.now(), + }) +} + +const runServerBeforeLoad = ( + inner: InnerLoadContext, + index: number, + route: AnyRoute, +): void | Promise => { + const match = inner.matches[index]! + const { abortController } = match + + const serialError = + match.paramsError !== undefined ? match.paramsError : match.searchError + if (serialError !== undefined) { + return recordServerBeforeLoadFailure(inner, index, serialError) + } + + const beforeLoad = route.options.beforeLoad + const commitBeforeLoad = (beforeLoadContext: any): void => { + commitMatch(inner, index, { + __beforeLoadContext: beforeLoadContext, + context: getMatchContext(inner, index, beforeLoadContext), + }) + } + + if (!beforeLoad) { + commitBeforeLoad(undefined) + return + } + + const updateContext = (beforeLoadContext: any): void => { + if (isRedirect(beforeLoadContext) || isNotFound(beforeLoadContext)) { + return recordServerBeforeLoadFailure(inner, index, beforeLoadContext) + } + + commitBeforeLoad(beforeLoadContext) + } + + const context = getMatchContext(inner, index, undefined) + const { search, params, cause } = match + const beforeLoadFnContext = { + search, + abortController, + params, + context, + location: inner.location, + navigate: (opts: any) => + inner.router.navigate({ + ...opts, + _fromLocation: inner.location, + }), + buildLocation: inner.router.buildLocation, + cause, + matches: inner.matches, + routeId: route.id, + ...inner.router.options.additionalContext, + } as BeforeLoadContextOptions + + try { + const beforeLoadContext = beforeLoad(beforeLoadFnContext) + if (isPromise(beforeLoadContext)) { + return beforeLoadContext.then(updateContext, (err) => + recordServerBeforeLoadFailure(inner, index, err), + ) + } + return updateContext(beforeLoadContext) + } catch (err) { + return recordServerBeforeLoadFailure(inner, index, err) + } +} + +const handleServerBeforeLoad = ( + inner: InnerLoadContext, + index: number, +): false | void | Promise => { + const { routeId } = inner.matches[index]! + const route = inner.router.routesById[routeId]! + const existingMatch = inner.matches[index]! + const parentMatch = inner.matches[index - 1] + + const queueServerBeforeLoad = (): + | false + | void + | Promise => { + if (existingMatch.ssr === false) { + return false + } + + return runServerBeforeLoad(inner, index, route) + } + + if (inner.router.isShell()) { + existingMatch.ssr = route.id === rootRouteId + return queueServerBeforeLoad() + } + + if (parentMatch?.ssr === false) { + existingMatch.ssr = false + return false + } + + const parentOverride = (tempSsr: SSROption) => { + if (tempSsr === true && parentMatch?.ssr === 'data-only') { + return 'data-only' + } + return tempSsr + } + + const defaultSsr = inner.router.options.defaultSsr ?? true + + if (route.options.ssr === undefined) { + existingMatch.ssr = parentOverride(defaultSsr) + return queueServerBeforeLoad() + } + + if (typeof route.options.ssr !== 'function') { + existingMatch.ssr = parentOverride(route.options.ssr) + return queueServerBeforeLoad() + } + + const { search, params } = existingMatch + const ssrFnContext: SsrContextOptions = { + search: makeMaybe(search, existingMatch.searchError), + params: makeMaybe(params, existingMatch.paramsError), + location: inner.location, + matches: inner.matches.map((match) => ({ + index: match.index, + pathname: match.pathname, + fullPath: match.fullPath, + staticData: match.staticData, + id: match.id, + routeId: match.routeId, + search: makeMaybe(match.search, match.searchError), + params: makeMaybe(match.params, match.paramsError), + ssr: match.ssr, + })), + } + + const tempSsr = route.options.ssr(ssrFnContext) + if (isPromise(tempSsr)) { + return tempSsr.then((ssr) => { + existingMatch.ssr = parentOverride(ssr ?? defaultSsr) + return queueServerBeforeLoad() as any + }) as Promise + } + + existingMatch.ssr = parentOverride(tempSsr ?? defaultSsr) + return queueServerBeforeLoad() +} + +const getServerLoaderContext = ( + inner: InnerLoadContext, + matchPromises: Array>, + index: number, + route: AnyRoute, +): LoaderFnContext => { + const { params, loaderDeps, abortController, cause, context } = + inner.matches[index]! + + return { + params, + deps: loaderDeps, + preload: false, + parentMatchPromise: matchPromises[index - 1] as any, + abortController, + context, + location: inner.location, + navigate: (opts: any) => + inner.router.navigate({ + ...opts, + _fromLocation: inner.location, + }), + cause, + route, + ...inner.router.options.additionalContext, + } +} + +const finishServerSkippedMatch = ( + inner: InnerLoadContext, + index: number, +): AnyRouteMatch => { + commitMatch(inner, index, { + context: getMatchContext( + inner, + index, + inner.matches[index]!.__beforeLoadContext, + ), + }) + return inner.matches[index]! +} + +const commitServerNotFoundBoundary = ( + inner: InnerLoadContext, + err: NotFoundError, +): number => { + const index = getNotFoundBoundaryIndex(inner, err) + const match = inner.matches[index]! + const routeId = match.routeId + + err.routeId = routeId + commitMatch( + inner, + index, + routeId === rootRouteId + ? { + status: 'success', + error: undefined, + globalNotFound: true, + context: getMatchContext(inner, index, match.__beforeLoadContext), + } + : { + status: 'notFound', + error: err, + context: getMatchContext(inner, index, match.__beforeLoadContext), + }, + ) + return index +} + +const loadServerRouteMatch = async ( + inner: InnerLoadContext, + matchPromises: Array>, + index: number, +): Promise => { + const initialMatch = inner.matches[index]! + const { routeId } = initialMatch + const route = inner.router.routesById[routeId]! + const loaderOption = route.options.loader + const loader = + typeof loaderOption === 'function' ? loaderOption : loaderOption?.handler + + const routeChunkPromise = + initialMatch.ssr === true ? loadRouteChunk(route) : undefined + void routeChunkPromise?.catch(() => {}) + + try { + const loaderResult = loader?.( + getServerLoaderContext(inner, matchPromises, index, route), + ) + const loaderResultIsPromise = isPromise(loaderResult) + + if (loader) { + const loaderData = loaderResultIsPromise + ? await loaderResult + : loaderResult + + if (isRedirect(loaderData) || isNotFound(loaderData)) { + throw loaderData + } + + commitMatch(inner, index, { + loaderData, + }) + } + } catch (loaderError) { + if (isRedirect(loaderError) && loaderError.redirectHandled) { + throw loaderError + } + + await finalizeServerRouteFailure( + inner, + index, + normalizeRouteFailure(inner, index, loaderError), + ) + return inner.matches[index]! + } + + try { + if (routeChunkPromise) { + await routeChunkPromise + } + } catch (chunkError) { + await finalizeServerRouteFailure(inner, index, chunkError, true) + return inner.matches[index]! + } + + commitMatch(inner, index, { + error: undefined, + status: 'success', + updatedAt: Date.now(), + }) + + return inner.matches[index]! +} + +export const loadServerMatches = async ( + arg: LoadMatchesArg, +): Promise> => { + const inner: InnerLoadContext = { + router: arg.router, + location: arg.location, + matches: arg.matches, + preload: arg.preload, + forceStaleReload: arg.forceReload, + background: arg.background, + onReady: arg.onReady, + } + const matchPromises: Array> = [] + + let firstNotFound: NotFoundError | undefined + + for (let i = 0; i < inner.matches.length && !inner.serialFailure; i++) { + try { + let beforeLoadResult: + | false + | void + | AnyRouteMatch + | Promise = handleServerBeforeLoad( + inner, + i, + ) + if (isPromise(beforeLoadResult)) { + beforeLoadResult = await beforeLoadResult + } + if (beforeLoadResult === false) { + matchPromises[i] = Promise.resolve(finishServerSkippedMatch(inner, i)) + } + } catch (err) { + if (isNotFound(err)) { + firstNotFound ||= err + } else { + throw err + } + break + } + } + + const failure = inner.serialFailure + let maxIndexExclusive = inner.matches.length + if (failure) { + const [index, error] = failure + maxIndexExclusive = isRedirect(error) + ? 0 + : isNotFound(error) + ? Math.min(getNotFoundBoundaryIndex(inner, error) + 1, index) + : index + } + + for (let i = 0; i < maxIndexExclusive; i++) { + matchPromises[i] ||= loadServerRouteMatch(inner, matchPromises, i) + } + + if (failure) { + const [index, error] = failure + matchPromises.push(finalizeServerRouteFailure(inner, index, error) as any) + } + + let firstRedirect: unknown + let fatalError: unknown + let hasFatalError = false + + const results = await Promise.all( + matchPromises.map((promise) => + promise.then( + () => ({ ok: true as const }), + (reason) => ({ + ok: false as const, + error: + process.env.NODE_ENV !== 'production' && reason === undefined + ? new Error('Route load failed with undefined') + : reason, + }), + ), + ), + ) + + for (const result of results) { + if (result.ok) { + continue + } + const reason = result.error + if (isRedirect(reason)) { + firstRedirect ||= reason + } else if (isNotFound(reason)) { + firstNotFound ||= reason + } else if (!hasFatalError) { + fatalError = reason + hasFatalError = true + } + } + + if (firstRedirect) { + throw firstRedirect + } + + const notFoundToThrow = firstNotFound + const errorIndex = inner.badIndex + + if (!hasFatalError && notFoundToThrow) { + const index = commitServerNotFoundBoundary(inner, notFoundToThrow) + while (inner.matches.length > index + 1) { + inner.matches.pop() + } + } else if (!hasFatalError) { + while (errorIndex != null && inner.matches.length > errorIndex + 1) { + inner.matches.pop() + } + } + + const assets = projectServerRouteAssets(inner.router, inner.matches) + + if (isPromise(assets)) { + await assets + } + + if (hasFatalError) { + throw fatalError + } + + if (notFoundToThrow) { + throw notFoundToThrow + } + + if (errorIndex != null) { + const errorMatch = inner.matches[errorIndex]! + if (errorMatch.status === 'error') { + throw errorMatch.error + } + } + + return inner.matches +} + +function makeMaybe( + value: TValue, + error: TError, +): { status: 'success'; value: TValue } | { status: 'error'; error: TError } { + if (error !== undefined) { + return { status: 'error' as const, error } + } + return { status: 'success' as const, value } +} diff --git a/packages/router-core/src/load-matches.ts b/packages/router-core/src/load-matches.ts index f901a0c97d..f5e77df2b9 100644 --- a/packages/router-core/src/load-matches.ts +++ b/packages/router-core/src/load-matches.ts @@ -1,1278 +1,165 @@ -import { isServer } from '@tanstack/router-core/isServer' -import { invariant } from './invariant' -import { createControlledPromise, isPromise } from './utils' import { isNotFound } from './not-found' -import { rootRouteId } from './root' import { isRedirect } from './redirect' +import { rootRouteId } from './root' import type { NotFoundError } from './not-found' import type { ParsedLocation } from './location' -import type { - AnyRoute, - BeforeLoadContextOptions, - LoaderFnContext, - SsrContextOptions, -} from './route' -import type { AnyRouteMatch, MakeRouteMatch } from './Matches' -import type { AnyRouter, SSROption, UpdateMatchFn } from './router' +import type { AnyRouteMatch } from './Matches' +import type { AnyRouter } from './router' -/** - * An object of this shape is created when calling `loadMatches`. - * It contains everything we need for all other functions in this file - * to work. (It's basically the function's argument, plus a few mutable states) - */ -type InnerLoadContext = { - /** the calling router instance */ +export type InnerLoadContext = { + /** Router for this private load lane. */ + router: AnyRouter + /** Target location for this private load lane. */ + location: ParsedLocation + /** Framework render promise returned by pending publication. */ + rendered?: true | Promise + /** Pending lane was published for presentation; final commit still owns effects. */ + pendingPublished?: true + /** Private match lane being loaded. */ + matches: Array + /** + * Set only for preload passes. Contains active/pending match IDs that + * this pass borrows read-only instead of owning in the cache. + */ + preload?: Array + /** Earliest route index with a committed route error. */ + badIndex?: number + /** Same-href client load should revalidate stale matches. */ + forceStaleReload?: boolean + /** Callback that publishes pending UI when the lane becomes renderable. */ + onReady?: (matches: Array) => void | Promise + /** Server beforeLoad failure captured during the serial phase. */ + serialFailure?: SerialFailure + /** Client background reload indices selected during foreground matching. */ + background?: Array + /** Foreground load must commit even if same-href background reloads exist. */ + requiresCommit?: boolean +} + +export type SerialFailure = [index: number, error: unknown] + +export type LoadMatchesArg = { router: AnyRouter location: ParsedLocation - /** mutable state, scoped to a `loadMatches` call */ - firstBadMatchIndex?: number - /** mutable state, scoped to a `loadMatches` call */ - rendered?: boolean - serialError?: unknown - updateMatch: UpdateMatchFn matches: Array - preload?: boolean - forceStaleReload?: boolean - onReady?: () => Promise - sync?: boolean + preload?: Array + forceReload?: boolean + background?: Array + onReady?: (matches: Array) => void | Promise } -const triggerOnReady = (inner: InnerLoadContext): void | Promise => { - if (!inner.rendered) { - inner.rendered = true - return inner.onReady?.() - } +export type BackgroundLoad = { + href: string + controller: AbortController } -const hasForcePendingActiveMatch = (router: AnyRouter): boolean => { - return router.stores.matchesId.get().some((matchId) => { - return router.stores.matchStores.get(matchId)?.get()._forcePending - }) +export const markError = (inner: InnerLoadContext, index: number) => { + inner.badIndex = Math.min(inner.badIndex ?? index, index) } -const resolvePreload = (inner: InnerLoadContext, matchId: string): boolean => { - return !!(inner.preload && !inner.router.stores.matchStores.has(matchId)) -} - -/** - * Builds the accumulated context from router options and all matches up to (and optionally including) the given index. - * Merges __routeContext and __beforeLoadContext from each match. - */ -const buildMatchContext = ( - inner: InnerLoadContext, +export const getMatchContext = ( + inner: Pick, index: number, - includeCurrentMatch: boolean = true, + beforeLoadContext: unknown, ): Record => { - const context: Record = { - ...(inner.router.options.context ?? {}), - } - const end = includeCurrentMatch ? index : index - 1 - for (let i = 0; i <= end; i++) { - const innerMatch = inner.matches[i] - if (!innerMatch) continue - const m = inner.router.getMatch(innerMatch.id) - if (!m) continue - Object.assign(context, m.__routeContext, m.__beforeLoadContext) - } - return context + const parentContext = + inner.matches[index - 1]?.context ?? inner.router.options.context ?? {} + const routeContext = inner.matches[index]!.__routeContext + return routeContext || beforeLoadContext + ? { + ...parentContext, + ...routeContext, + ...(beforeLoadContext as Record), + } + : parentContext } -const getNotFoundBoundaryIndex = ( +export const settleMatchLoad = (match: AnyRouteMatch): void => { + const promise = match._.loadPromise + match._.loadPromise = undefined + clearTimeout(promise?.pendingTimeout) + + if (promise?.status === 'pending') { + promise.resolve() + } +} + +export const getNotFoundBoundaryIndex = ( inner: InnerLoadContext, err: NotFoundError, -): number | undefined => { - if (!inner.matches.length) { - return undefined - } - +): number => { const requestedRouteId = err.routeId - const matchedRootIndex = inner.matches.findIndex( - (m) => m.routeId === inner.router.routeTree.id, - ) - const rootIndex = matchedRootIndex >= 0 ? matchedRootIndex : 0 let startIndex = requestedRouteId ? inner.matches.findIndex((match) => match.routeId === requestedRouteId) - : (inner.firstBadMatchIndex ?? inner.matches.length - 1) + : inner.matches.length - 1 - if (startIndex < 0) { - startIndex = rootIndex + if (startIndex === -1) { + startIndex = 0 } for (let i = startIndex; i >= 0; i--) { - const match = inner.matches[i]! - const route = inner.router.looseRoutesById[match.routeId]! - if (route.options.notFoundComponent) { + if ( + inner.router.routesById[inner.matches[i]!.routeId]!.options + .notFoundComponent + ) { return i } } // If no boundary component is found, preserve explicit routeId targeting behavior, // otherwise default to root for untargeted notFounds. - return requestedRouteId ? startIndex : rootIndex + return requestedRouteId ? startIndex : 0 } -const handleRedirectAndNotFound = ( - inner: InnerLoadContext, - match: AnyRouteMatch | undefined, - err: unknown, -): void => { - if (!isRedirect(err) && !isNotFound(err)) return - - if (isRedirect(err) && err.redirectHandled && !err.options.reloadDocument) { - throw err - } - - // in case of a redirecting match during preload, the match does not exist - if (match) { - match._nonReactive.beforeLoadPromise?.resolve() - match._nonReactive.loaderPromise?.resolve() - match._nonReactive.beforeLoadPromise = undefined - match._nonReactive.loaderPromise = undefined - - match._nonReactive.error = err - - inner.updateMatch(match.id, (prev) => ({ - ...prev, - status: isRedirect(err) - ? 'redirected' - : isNotFound(err) - ? 'notFound' - : prev.status === 'pending' - ? 'success' - : prev.status, - context: buildMatchContext(inner, match.index), - isFetching: false, - error: err, - })) - - if (isNotFound(err) && !err.routeId) { - // Stamp the throwing match's routeId so that the finalization step in - // loadMatches knows where the notFound originated. The actual boundary - // resolution (walking up to the nearest notFoundComponent) is deferred to - // the finalization step, where firstBadMatchIndex is stable and - // headMaxIndex can be capped correctly. - err.routeId = match.routeId - } - - match._nonReactive.loadPromise?.resolve() - } - - if (isRedirect(err)) { - inner.rendered = true - err.options._fromLocation = inner.location - err.redirectHandled = true - err = inner.router.resolveRedirect(err) - } - - throw err -} - -const shouldSkipLoader = ( - inner: InnerLoadContext, - matchId: string, -): boolean => { - const match = inner.router.getMatch(matchId) - if (!match) { - return true - } - // upon hydration, we skip the loader if the match has been dehydrated on the server - if (!(isServer ?? inner.router.isServer) && match._nonReactive.dehydrated) { - return true - } - - if ((isServer ?? inner.router.isServer) && match.ssr === false) { - return true - } - - return false -} - -const syncMatchContext = ( - inner: InnerLoadContext, - matchId: string, - index: number, -): void => { - const nextContext = buildMatchContext(inner, index) - - inner.updateMatch(matchId, (prev) => { - return { - ...prev, - context: nextContext, - } - }) -} - -const handleSerialError = ( +export const normalizeRouteFailure = ( inner: InnerLoadContext, index: number, - err: any, -): void => { - const { id: matchId, routeId } = inner.matches[index]! - const route = inner.router.looseRoutesById[routeId]! - - // Much like suspense, we use a promise here to know if - // we've been outdated by a new loadMatches call and - // should abort the current async operation - if (err instanceof Promise) { - throw err + error: unknown, +): unknown => { + if (process.env.NODE_ENV !== 'production' && error === undefined) { + error = new Error('Route load failed with undefined') } - inner.firstBadMatchIndex ??= index - handleRedirectAndNotFound(inner, inner.router.getMatch(matchId), err) - - try { - route.options.onError?.(err) - } catch (errorHandlerErr) { - err = errorHandlerErr - handleRedirectAndNotFound(inner, inner.router.getMatch(matchId), err) - } - - inner.updateMatch(matchId, (prev) => { - prev._nonReactive.beforeLoadPromise?.resolve() - prev._nonReactive.beforeLoadPromise = undefined - prev._nonReactive.loadPromise?.resolve() - - return { - ...prev, - error: err, - status: 'error', - isFetching: false, - updatedAt: Date.now(), - abortController: new AbortController(), - } - }) - - if (!inner.preload && !isRedirect(err) && !isNotFound(err)) { - inner.serialError ??= err - } -} - -const isBeforeLoadSsr = ( - inner: InnerLoadContext, - matchId: string, - index: number, - route: AnyRoute, -): void | Promise => { - const existingMatch = inner.router.getMatch(matchId)! - const parentMatchId = inner.matches[index - 1]?.id - const parentMatch = parentMatchId - ? inner.router.getMatch(parentMatchId)! - : undefined - - // in SPA mode, only SSR the root route - if (inner.router.isShell()) { - existingMatch.ssr = route.id === rootRouteId - return - } - - if (parentMatch?.ssr === false) { - existingMatch.ssr = false - return - } - - const parentOverride = (tempSsr: SSROption) => { - if (tempSsr === true && parentMatch?.ssr === 'data-only') { - return 'data-only' - } - return tempSsr - } - - const defaultSsr = inner.router.options.defaultSsr ?? true - - if (route.options.ssr === undefined) { - existingMatch.ssr = parentOverride(defaultSsr) - return - } - - if (typeof route.options.ssr !== 'function') { - existingMatch.ssr = parentOverride(route.options.ssr) - return - } - const { search, params } = existingMatch - - const ssrFnContext: SsrContextOptions = { - search: makeMaybe(search, existingMatch.searchError), - params: makeMaybe(params, existingMatch.paramsError), - location: inner.location, - matches: inner.matches.map((match) => ({ - index: match.index, - pathname: match.pathname, - fullPath: match.fullPath, - staticData: match.staticData, - id: match.id, - routeId: match.routeId, - search: makeMaybe(match.search, match.searchError), - params: makeMaybe(match.params, match.paramsError), - ssr: match.ssr, - })), - } - - const tempSsr = route.options.ssr(ssrFnContext) - if (isPromise(tempSsr)) { - return tempSsr.then((ssr) => { - existingMatch.ssr = parentOverride(ssr ?? defaultSsr) - }) - } - - existingMatch.ssr = parentOverride(tempSsr ?? defaultSsr) - return -} - -const setupPendingTimeout = ( - inner: InnerLoadContext, - matchId: string, - route: AnyRoute, - match: AnyRouteMatch, -): void => { - if (match._nonReactive.pendingTimeout !== undefined) return - - const pendingMs = - route.options.pendingMs ?? inner.router.options.defaultPendingMs - const shouldPending = !!( - inner.onReady && - !(isServer ?? inner.router.isServer) && - !resolvePreload(inner, matchId) && - (route.options.loader || - route.options.beforeLoad || - routeNeedsPreload(route)) && - typeof pendingMs === 'number' && - pendingMs !== Infinity && - (route.options.pendingComponent ?? - (inner.router.options as any)?.defaultPendingComponent) - ) - - if (shouldPending) { - const pendingTimeout = setTimeout(() => { - // Update the match and prematurely resolve the loadMatches promise so that - // the pending component can start rendering - triggerOnReady(inner) - }, pendingMs) - match._nonReactive.pendingTimeout = pendingTimeout - } -} - -const preBeforeLoadSetup = ( - inner: InnerLoadContext, - matchId: string, - route: AnyRoute, -): void | Promise => { - const existingMatch = inner.router.getMatch(matchId)! - - // If we are in the middle of a load, either of these will be present - // (not to be confused with `loadPromise`, which is always defined) - if ( - !existingMatch._nonReactive.beforeLoadPromise && - !existingMatch._nonReactive.loaderPromise - ) - return - - setupPendingTimeout(inner, matchId, route, existingMatch) - - const then = () => { - const match = inner.router.getMatch(matchId)! - if ( - match.preload && - (match.status === 'redirected' || match.status === 'notFound') - ) { - handleRedirectAndNotFound(inner, match, match.error) - } - } - - // Wait for the previous beforeLoad to resolve before we continue - return existingMatch._nonReactive.beforeLoadPromise - ? existingMatch._nonReactive.beforeLoadPromise.then(then) - : then() -} - -const executeBeforeLoad = ( - inner: InnerLoadContext, - matchId: string, - index: number, - route: AnyRoute, -): void | Promise => { - const match = inner.router.getMatch(matchId)! - - // explicitly capture the previous loadPromise - let prevLoadPromise = match._nonReactive.loadPromise - match._nonReactive.loadPromise = createControlledPromise(() => { - prevLoadPromise?.resolve() - prevLoadPromise = undefined - }) - - const { paramsError, searchError } = match - - if (paramsError) { - handleSerialError(inner, index, paramsError) - } - - if (searchError) { - handleSerialError(inner, index, searchError) - } - - setupPendingTimeout(inner, matchId, route, match) - - const abortController = new AbortController() - - let isPending = false - const pending = () => { - if (isPending) return - isPending = true - inner.updateMatch(matchId, (prev) => ({ - ...prev, - isFetching: 'beforeLoad', - fetchCount: prev.fetchCount + 1, - abortController, - // Note: We intentionally don't update context here. - // Context should only be updated after beforeLoad resolves to avoid - // components seeing incomplete context during async beforeLoad execution. - })) - } - - const resolve = () => { - match._nonReactive.beforeLoadPromise?.resolve() - match._nonReactive.beforeLoadPromise = undefined - inner.updateMatch(matchId, (prev) => ({ - ...prev, - isFetching: false, - })) - } - - // if there is no `beforeLoad` option, just mark as pending and resolve - // Context will be updated later in loadRouteMatch after loader completes - if (!route.options.beforeLoad) { - inner.router.batch(() => { - pending() - resolve() - }) - return - } - - match._nonReactive.beforeLoadPromise = createControlledPromise() - - // Build context from all parent matches, excluding current match's __beforeLoadContext - // (since we're about to execute beforeLoad for this match) - const context = { - ...buildMatchContext(inner, index, false), - ...match.__routeContext, - } - const { search, params, cause } = match - const preload = resolvePreload(inner, matchId) - const beforeLoadFnContext: BeforeLoadContextOptions< - any, - any, - any, - any, - any, - any, - any, - any, - any - > = { - search, - abortController, - params, - preload, - context, - location: inner.location, - navigate: (opts: any) => - inner.router.navigate({ - ...opts, - _fromLocation: inner.location, - }), - buildLocation: inner.router.buildLocation, - cause: preload ? 'preload' : cause, - matches: inner.matches, - routeId: route.id, - ...inner.router.options.additionalContext, - } - - const updateContext = (beforeLoadContext: any) => { - if (beforeLoadContext === undefined) { - inner.router.batch(() => { - pending() - resolve() - }) - return - } - if (isRedirect(beforeLoadContext) || isNotFound(beforeLoadContext)) { - pending() - handleSerialError(inner, index, beforeLoadContext) - } - - inner.router.batch(() => { - pending() - inner.updateMatch(matchId, (prev) => ({ - ...prev, - __beforeLoadContext: beforeLoadContext, - })) - resolve() - }) - } - - let beforeLoadContext - try { - beforeLoadContext = route.options.beforeLoad(beforeLoadFnContext) - if (isPromise(beforeLoadContext)) { - pending() - return beforeLoadContext - .catch((err) => { - handleSerialError(inner, index, err) - }) - .then(updateContext) - } - } catch (err) { - pending() - handleSerialError(inner, index, err) - } - - updateContext(beforeLoadContext) - return -} - -const handleBeforeLoad = ( - inner: InnerLoadContext, - index: number, -): void | Promise => { - const { id: matchId, routeId } = inner.matches[index]! - const route = inner.router.looseRoutesById[routeId]! - - const serverSsr = () => { - // on the server, determine whether SSR the current match or not - if (isServer ?? inner.router.isServer) { - const maybePromise = isBeforeLoadSsr(inner, matchId, index, route) - if (isPromise(maybePromise)) return maybePromise.then(queueExecution) - } - return queueExecution() - } - - const execute = () => executeBeforeLoad(inner, matchId, index, route) - - const queueExecution = () => { - if (shouldSkipLoader(inner, matchId)) return - const result = preBeforeLoadSetup(inner, matchId, route) - return isPromise(result) ? result.then(execute) : execute() - } - - return serverSsr() -} - -const executeHead = ( - inner: InnerLoadContext, - matchId: string, - route: AnyRoute, -): void | Promise< - Pick< - AnyRouteMatch, - 'meta' | 'links' | 'headScripts' | 'headers' | 'scripts' | 'styles' - > -> => { - const match = inner.router.getMatch(matchId) - // in case of a redirecting match during preload, the match does not exist - if (!match) { - return - } - if (!route.options.head && !route.options.scripts && !route.options.headers) { - return - } - const assetContext = { - ssr: inner.router.options.ssr, - matches: inner.matches, - match, - params: match.params, - loaderData: match.loaderData, - } - - return Promise.all([ - route.options.head?.(assetContext), - route.options.scripts?.(assetContext), - route.options.headers?.(assetContext), - ]).then(([headFnContent, scripts, headers]) => { - const meta = headFnContent?.meta - const links = headFnContent?.links - const headScripts = headFnContent?.scripts - const styles = headFnContent?.styles - - return { - meta, - links, - headScripts, - headers, - scripts, - styles, - } - }) -} - -const getLoaderContext = ( - inner: InnerLoadContext, - matchPromises: Array>, - matchId: string, - index: number, - route: AnyRoute, -): LoaderFnContext => { - const parentMatchPromise = matchPromises[index - 1] as any - const { params, loaderDeps, abortController, cause } = - inner.router.getMatch(matchId)! - - const context = buildMatchContext(inner, index) - - const preload = resolvePreload(inner, matchId) - - return { - params, - deps: loaderDeps, - preload: !!preload, - parentMatchPromise, - abortController, - context, - location: inner.location, - navigate: (opts) => - inner.router.navigate({ - ...opts, - _fromLocation: inner.location, - }), - cause: preload ? 'preload' : cause, - route, - ...inner.router.options.additionalContext, - } -} - -const runLoader = async ( - inner: InnerLoadContext, - matchPromises: Array>, - matchId: string, - index: number, - route: AnyRoute, -): Promise => { - try { - // If the Matches component rendered - // the pending component and needs to show it for - // a minimum duration, we''ll wait for it to resolve - // before committing to the match and resolving - // the loadPromise - - const match = inner.router.getMatch(matchId)! - - // Actually run the loader and handle the result + const match = inner.matches[index]! + if (!isRedirect(error) && !isNotFound(error)) { try { - if (!(isServer ?? inner.router.isServer) || match.ssr === true) { - loadRouteChunk(route) - } - - // Kick off the loader! - const routeLoader = route.options.loader - const loader = - typeof routeLoader === 'function' ? routeLoader : routeLoader?.handler - const loaderResult = loader?.( - getLoaderContext(inner, matchPromises, matchId, index, route), - ) - const loaderResultIsPromise = !!loader && isPromise(loaderResult) - - const willLoadSomething = !!( - loaderResultIsPromise || - route._lazyPromise || - route._componentsPromise || - route.options.head || - route.options.scripts || - route.options.headers || - match._nonReactive.minPendingPromise - ) - - if (willLoadSomething) { - inner.updateMatch(matchId, (prev) => ({ - ...prev, - isFetching: 'loader', - })) - } - - if (loader) { - const loaderData = loaderResultIsPromise - ? await loaderResult - : loaderResult - - handleRedirectAndNotFound( - inner, - inner.router.getMatch(matchId), - loaderData, - ) - if (loaderData !== undefined) { - inner.updateMatch(matchId, (prev) => ({ - ...prev, - loaderData, - })) - } - } - - // Lazy option can modify the route options, - // so we need to wait for it to resolve before - // we can use the options - if (route._lazyPromise) await route._lazyPromise - const pendingPromise = match._nonReactive.minPendingPromise - if (pendingPromise) await pendingPromise - - // Last but not least, wait for the components - // to be preloaded before we resolve the match - if (route._componentsPromise) await route._componentsPromise - inner.updateMatch(matchId, (prev) => ({ - ...prev, - error: undefined, - context: buildMatchContext(inner, index), - status: 'success', - isFetching: false, - updatedAt: Date.now(), - })) - } catch (e) { - let error = e - - if ((error as any)?.name === 'AbortError') { - if (match.abortController.signal.aborted) { - match._nonReactive.loaderPromise?.resolve() - match._nonReactive.loaderPromise = undefined - return - } - inner.updateMatch(matchId, (prev) => ({ - ...prev, - status: prev.status === 'pending' ? 'success' : prev.status, - isFetching: false, - context: buildMatchContext(inner, index), - })) - return - } - - const pendingPromise = match._nonReactive.minPendingPromise - if (pendingPromise) await pendingPromise - - if (isNotFound(e)) { - await (route.options.notFoundComponent as any)?.preload?.() - } - - handleRedirectAndNotFound(inner, inner.router.getMatch(matchId), e) - - try { - route.options.onError?.(e) - } catch (onErrorError) { - error = onErrorError - handleRedirectAndNotFound( - inner, - inner.router.getMatch(matchId), - onErrorError, - ) - } - if (!isRedirect(error) && !isNotFound(error)) { - await loadRouteChunk(route, ['errorComponent']) - } - - inner.updateMatch(matchId, (prev) => ({ - ...prev, - error, - context: buildMatchContext(inner, index), - status: 'error', - isFetching: false, - })) + inner.router.routesById[match.routeId]!.options.onError?.(error) + } catch (onErrorError) { + error = onErrorError } - } catch (err) { - const match = inner.router.getMatch(matchId) - // in case of a redirecting match during preload, the match does not exist - if (match) { - match._nonReactive.loaderPromise = undefined - } - handleRedirectAndNotFound(inner, match, err) } + + if (isNotFound(error)) { + error.routeId ||= match.routeId + } + + return error } -const loadRouteMatch = async ( +export const getNotFoundBoundaryPatch = ( inner: InnerLoadContext, - matchPromises: Array>, index: number, -): Promise => { - async function handleLoader( - preload: boolean, - prevMatch: AnyRouteMatch, - previousRouteMatchId: string | undefined, - match: AnyRouteMatch, - route: AnyRoute, - ) { - const age = Date.now() - prevMatch.updatedAt + err: NotFoundError, +): Partial => { + const match = inner.matches[index]! - const staleAge = preload - ? (route.options.preloadStaleTime ?? - inner.router.options.defaultPreloadStaleTime ?? - 30_000) // 30 seconds for preloads by default - : (route.options.staleTime ?? inner.router.options.defaultStaleTime ?? 0) - - const shouldReloadOption = route.options.shouldReload - - // Default to reloading the route all the time - // Allow shouldReload to get the last say, - // if provided. - const shouldReload = - typeof shouldReloadOption === 'function' - ? shouldReloadOption( - getLoaderContext(inner, matchPromises, matchId, index, route), - ) - : shouldReloadOption - - // If the route is successful and still fresh, just resolve - const { status, invalid } = match - const staleMatchShouldReload = - age >= staleAge && - (!!inner.forceStaleReload || - match.cause === 'enter' || - (previousRouteMatchId !== undefined && - previousRouteMatchId !== match.id)) - loaderShouldRunAsync = - status === 'success' && - (invalid || (shouldReload ?? staleMatchShouldReload)) - if (preload && route.options.preload === false) { - // Do nothing - } else if ( - loaderShouldRunAsync && - !inner.sync && - shouldReloadInBackground - ) { - loaderIsRunningAsync = true - ;(async () => { - try { - await runLoader(inner, matchPromises, matchId, index, route) - const match = inner.router.getMatch(matchId)! - match._nonReactive.loaderPromise?.resolve() - match._nonReactive.loadPromise?.resolve() - match._nonReactive.loaderPromise = undefined - match._nonReactive.loadPromise = undefined - } catch (err) { - if (isRedirect(err)) { - await inner.router.navigate(err.options) - } - } - })() - } else if (status !== 'success' || loaderShouldRunAsync) { - await runLoader(inner, matchPromises, matchId, index, route) - } else { - syncMatchContext(inner, matchId, index) - } - } - - const { id: matchId, routeId } = inner.matches[index]! - let loaderShouldRunAsync = false - let loaderIsRunningAsync = false - const route = inner.router.looseRoutesById[routeId]! - const routeLoader = route.options.loader - const shouldReloadInBackground = - ((typeof routeLoader === 'function' - ? undefined - : routeLoader?.staleReloadMode) ?? - inner.router.options.defaultStaleReloadMode) !== 'blocking' - - if (shouldSkipLoader(inner, matchId)) { - const match = inner.router.getMatch(matchId) - if (!match) { - return inner.matches[index]! - } - - syncMatchContext(inner, matchId, index) - - if (isServer ?? inner.router.isServer) { - return inner.router.getMatch(matchId)! - } - } else { - const prevMatch = inner.router.getMatch(matchId)! // This is where all of the stale-while-revalidate magic happens - const activeIdAtIndex = inner.router.stores.matchesId.get()[index] - const activeAtIndex = - (activeIdAtIndex && - inner.router.stores.matchStores.get(activeIdAtIndex)) || - null - const previousRouteMatchId = - activeAtIndex?.routeId === routeId - ? activeIdAtIndex - : inner.router.stores.matches.get().find((d) => d.routeId === routeId) - ?.id - const preload = resolvePreload(inner, matchId) - - // there is a loaderPromise, so we are in the middle of a load - if (prevMatch._nonReactive.loaderPromise) { - // do not block if we already have stale data we can show - // but only if the ongoing load is not a preload since error handling is different for preloads - // and we don't want to swallow errors - if ( - prevMatch.status === 'success' && - !inner.sync && - !prevMatch.preload && - shouldReloadInBackground - ) { - return prevMatch - } - await prevMatch._nonReactive.loaderPromise - const match = inner.router.getMatch(matchId)! - const error = match._nonReactive.error || match.error - if (error) { - handleRedirectAndNotFound(inner, match, error) - } - - if (match.status === 'pending') { - await handleLoader( - preload, - prevMatch, - previousRouteMatchId, - match, - route, - ) - } - } else { - const nextPreload = - preload && !inner.router.stores.matchStores.has(matchId) - const match = inner.router.getMatch(matchId)! - match._nonReactive.loaderPromise = createControlledPromise() - if (nextPreload !== match.preload) { - inner.updateMatch(matchId, (prev) => ({ - ...prev, - preload: nextPreload, - })) - } - - await handleLoader(preload, prevMatch, previousRouteMatchId, match, route) - } - } - const match = inner.router.getMatch(matchId)! - if (!loaderIsRunningAsync) { - match._nonReactive.loaderPromise?.resolve() - match._nonReactive.loadPromise?.resolve() - match._nonReactive.loadPromise = undefined - } - - clearTimeout(match._nonReactive.pendingTimeout) - match._nonReactive.pendingTimeout = undefined - if (!loaderIsRunningAsync) match._nonReactive.loaderPromise = undefined - match._nonReactive.dehydrated = undefined - - const nextIsFetching = loaderIsRunningAsync ? match.isFetching : false - if (nextIsFetching !== match.isFetching || match.invalid !== false) { - inner.updateMatch(matchId, (prev) => ({ - ...prev, - isFetching: nextIsFetching, - invalid: false, - })) - return inner.router.getMatch(matchId)! - } else { - return match - } -} - -export async function loadMatches(arg: { - router: AnyRouter - location: ParsedLocation - matches: Array - preload?: boolean - forceStaleReload?: boolean - onReady?: () => Promise - updateMatch: UpdateMatchFn - sync?: boolean -}): Promise> { - const inner: InnerLoadContext = arg - const matchPromises: Array> = [] - - // make sure the pending component is immediately rendered when hydrating a match that is not SSRed - // the pending component was already rendered on the server and we want to keep it shown on the client until minPendingMs is reached - if ( - !(isServer ?? inner.router.isServer) && - hasForcePendingActiveMatch(inner.router) - ) { - triggerOnReady(inner) - } - - let beforeLoadNotFound: NotFoundError | undefined - - // Execute all beforeLoads one by one - for (let i = 0; i < inner.matches.length; i++) { - try { - const beforeLoad = handleBeforeLoad(inner, i) - if (isPromise(beforeLoad)) await beforeLoad - } catch (err) { - if (isRedirect(err)) { - throw err - } - if (isNotFound(err)) { - beforeLoadNotFound = err - } else { - if (!inner.preload) throw err - } - break - } - - if (inner.serialError || inner.firstBadMatchIndex != null) { - break - } - } - - // Execute loaders once, with max index adapted for beforeLoad notFound handling. - const baseMaxIndexExclusive = inner.firstBadMatchIndex ?? inner.matches.length - - const boundaryIndex = - beforeLoadNotFound && !inner.preload - ? getNotFoundBoundaryIndex(inner, beforeLoadNotFound) - : undefined - - const maxIndexExclusive = - beforeLoadNotFound && inner.preload - ? 0 - : boundaryIndex !== undefined - ? Math.min(boundaryIndex + 1, baseMaxIndexExclusive) - : baseMaxIndexExclusive - - let firstNotFound: NotFoundError | undefined - let firstUnhandledRejection: unknown - - for (let i = 0; i < maxIndexExclusive; i++) { - matchPromises.push(loadRouteMatch(inner, matchPromises, i)) - } - - try { - await Promise.all(matchPromises) - } catch { - const settled = await Promise.allSettled(matchPromises) - - for (const result of settled) { - if (result.status !== 'rejected') continue - - const reason = result.reason - if (isRedirect(reason)) { - throw reason - } - if (isNotFound(reason)) { - firstNotFound ??= reason - } else { - firstUnhandledRejection ??= reason - } - } - - if (firstUnhandledRejection !== undefined) { - throw firstUnhandledRejection - } - } - - const notFoundToThrow = - firstNotFound ?? - (beforeLoadNotFound && !inner.preload ? beforeLoadNotFound : undefined) - - let headMaxIndex = - inner.firstBadMatchIndex !== undefined - ? inner.firstBadMatchIndex - : inner.matches.length - 1 - - if (!notFoundToThrow && beforeLoadNotFound && inner.preload) { - return inner.matches - } - - if (notFoundToThrow) { - // Determine once which matched route will actually render the - // notFoundComponent, then pass this precomputed index through the remaining - // finalization steps. - // This can differ from the throwing route when routeId targets an ancestor - // boundary (or when bubbling resolves to a parent/root boundary). - const renderedBoundaryIndex = getNotFoundBoundaryIndex( - inner, - notFoundToThrow, - ) - - if (renderedBoundaryIndex === undefined) { - if (process.env.NODE_ENV !== 'production') { - throw new Error( - 'Invariant failed: Could not find match for notFound boundary', - ) - } - - invariant() - } - const boundaryMatch = inner.matches[renderedBoundaryIndex]! - - const boundaryRoute = inner.router.looseRoutesById[boundaryMatch.routeId]! - const defaultNotFoundComponent = (inner.router.options as any) - ?.defaultNotFoundComponent - - // Ensure a notFoundComponent exists on the boundary route - if (!boundaryRoute.options.notFoundComponent && defaultNotFoundComponent) { - boundaryRoute.options.notFoundComponent = defaultNotFoundComponent - } - - notFoundToThrow.routeId = boundaryMatch.routeId - - const boundaryIsRoot = boundaryMatch.routeId === inner.router.routeTree.id - - inner.updateMatch(boundaryMatch.id, (prev) => ({ - ...prev, - ...(boundaryIsRoot - ? // For root boundary, use globalNotFound so the root component's - // shell still renders and handles the not-found display, - // instead of replacing the entire root shell via status='notFound'. - { status: 'success' as const, globalNotFound: true, error: undefined } - : // For non-root boundaries, set status:'notFound' so MatchInner - // renders the notFoundComponent directly. - { status: 'notFound' as const, error: notFoundToThrow }), - isFetching: false, - })) - - headMaxIndex = renderedBoundaryIndex - - // Ensure the rendering boundary route chunk (and its lazy components, including - // lazy notFoundComponent) is loaded before we continue to head execution/render. - await loadRouteChunk(boundaryRoute, ['notFoundComponent']) - } else if (!inner.preload) { - // Clear stale root global-not-found state on normal navigations that do not - // throw notFound. This must live here (instead of only in runLoader success) - // because the root loader may be skipped when data is still fresh. - const rootMatch = inner.matches[0]! - // `rootMatch` is the next match for this navigation. If it is not global - // not-found, then any currently stored root global-not-found is stale. - if (!rootMatch.globalNotFound) { - // `currentRootMatch` is the current store state (from the previous - // navigation/load). Update only when a stale flag is actually present. - const currentRootMatch = inner.router.getMatch(rootMatch.id) - if (currentRootMatch?.globalNotFound) { - inner.updateMatch(rootMatch.id, (prev) => ({ - ...prev, - globalNotFound: false, + err.routeId = match.routeId + const patch: Partial = + match.routeId === rootRouteId + ? { + status: 'success', error: undefined, - })) - } - } - } + isFetching: false, + globalNotFound: true, + } + : { + status: 'notFound', + error: err, + isFetching: false, + } - // When a serial error occurred (e.g. beforeLoad threw a regular Error), - // the erroring route's lazy chunk wasn't loaded because loaders were skipped. - // We need to load it so the code-split errorComponent is available for rendering. - if (inner.serialError && inner.firstBadMatchIndex !== undefined) { - const errorRoute = - inner.router.looseRoutesById[ - inner.matches[inner.firstBadMatchIndex]!.routeId - ]! - await loadRouteChunk(errorRoute, ['errorComponent']) - } + patch.context = getMatchContext(inner, index, match.__beforeLoadContext) - // serially execute heads once after loaders/notFound handling, ensuring - // all head functions get a chance even if one throws. - for (let i = 0; i <= headMaxIndex; i++) { - const match = inner.matches[i]! - const { id: matchId, routeId } = match - const route = inner.router.looseRoutesById[routeId]! - try { - const headResult = executeHead(inner, matchId, route) - if (headResult) { - const head = await headResult - inner.updateMatch(matchId, (prev) => ({ - ...prev, - ...head, - })) - } - } catch (err) { - console.error(`Error executing head for route ${routeId}:`, err) - } - } - - const readyPromise = triggerOnReady(inner) - if (isPromise(readyPromise)) { - await readyPromise - } - - if (notFoundToThrow) { - throw notFoundToThrow - } - - if (inner.serialError && !inner.preload && !inner.onReady) { - throw inner.serialError - } - - return inner.matches + return patch } - -export type RouteComponentType = - | 'component' - | 'errorComponent' - | 'pendingComponent' - | 'notFoundComponent' - -function preloadRouteComponents( - route: AnyRoute, - componentTypesToLoad: Array, -): Promise | undefined { - const preloads = componentTypesToLoad - .map((type) => (route.options[type] as any)?.preload?.()) - .filter(Boolean) - - if (preloads.length === 0) return undefined - - return Promise.all(preloads) as any as Promise -} - -export function loadRouteChunk( - route: AnyRoute, - componentTypesToLoad: Array = componentTypes, -) { - if (!route._lazyLoaded && route._lazyPromise === undefined) { - if (route.lazyFn) { - route._lazyPromise = route.lazyFn().then((lazyRoute) => { - // explicitly don't copy over the lazy route's id - const { id: _id, ...options } = lazyRoute.options - Object.assign(route.options, options) - route._lazyLoaded = true - route._lazyPromise = undefined // gc promise, we won't need it anymore - }) - } else { - route._lazyLoaded = true - } - } - - const runAfterLazy = () => - route._componentsLoaded - ? undefined - : componentTypesToLoad === componentTypes - ? (() => { - if (route._componentsPromise === undefined) { - const componentsPromise = preloadRouteComponents( - route, - componentTypes, - ) - - if (componentsPromise) { - route._componentsPromise = componentsPromise.then(() => { - route._componentsLoaded = true - route._componentsPromise = undefined // gc promise, we won't need it anymore - }) - } else { - route._componentsLoaded = true - } - } - - return route._componentsPromise - })() - : preloadRouteComponents(route, componentTypesToLoad) - - return route._lazyPromise - ? route._lazyPromise.then(runAfterLazy) - : runAfterLazy() -} - -function makeMaybe( - value: TValue, - error: TError, -): { status: 'success'; value: TValue } | { status: 'error'; error: TError } { - if (error) { - return { status: 'error' as const, error } - } - return { status: 'success' as const, value } -} - -export function routeNeedsPreload(route: AnyRoute) { - for (const componentType of componentTypes) { - if ((route.options[componentType] as any)?.preload) { - return true - } - } - return false -} - -export const componentTypes: Array = [ - 'component', - 'errorComponent', - 'pendingComponent', - 'notFoundComponent', -] as const diff --git a/packages/router-core/src/location-change.ts b/packages/router-core/src/location-change.ts new file mode 100644 index 0000000000..57c272113e --- /dev/null +++ b/packages/router-core/src/location-change.ts @@ -0,0 +1,19 @@ +import type { HistoryAction } from '@tanstack/history' +import type { ParsedLocation } from './location' + +export function getLocationChangeInfo( + location: ParsedLocation, + resolvedLocation?: ParsedLocation, +) { + const fromLocation = resolvedLocation + const toLocation = location + const pathChanged = fromLocation?.pathname !== toLocation.pathname + const hrefChanged = fromLocation?.href !== toLocation.href + const hashChanged = fromLocation?.hash !== toLocation.hash + return { fromLocation, toLocation, pathChanged, hrefChanged, hashChanged } +} + +export const locationHistoryActions = new WeakMap< + ParsedLocation, + HistoryAction +>() diff --git a/packages/router-core/src/redirect.ts b/packages/router-core/src/redirect.ts index b10fac6d7a..312343b7a1 100644 --- a/packages/router-core/src/redirect.ts +++ b/packages/router-core/src/redirect.ts @@ -1,3 +1,4 @@ +import { isServer } from '@tanstack/router-core/isServer' import type { NavigateOptions } from './link' import type { AnyRouter, RegisteredRouter } from './router' import type { ParsedLocation } from './location' @@ -121,7 +122,9 @@ export function redirect< >( opts: RedirectOptions, ): Redirect { - opts.statusCode = opts.statusCode || opts.code || 307 + if (isServer ?? typeof document === 'undefined') { + opts.statusCode = opts.statusCode || opts.code || 307 + } if ( !opts._builtLocation && @@ -134,14 +137,14 @@ export function redirect< } catch {} } - const headers = new Headers(opts.headers) - if (opts.href && headers.get('Location') === null) { - headers.set('Location', opts.href) - } - const response = new Response(null, { - status: opts.statusCode, - headers, + ...((isServer ?? typeof document === 'undefined') + ? { status: opts.statusCode } + : undefined), + headers: + (isServer ?? typeof document === 'undefined') && opts.href + ? getRedirectHeaders(opts) + : opts.headers, }) ;(response as Redirect).options = @@ -154,6 +157,14 @@ export function redirect< return response as Redirect } +function getRedirectHeaders(opts: { href?: string; headers?: HeadersInit }) { + const headers = new Headers(opts.headers) + if (headers.get('Location') === null) { + headers.set('Location', opts.href!) + } + return headers +} + /** Check whether a value is a TanStack Router redirect Response. */ /** Check whether a value is a TanStack Router redirect Response. */ export function isRedirect(obj: any): obj is AnyRedirect { diff --git a/packages/router-core/src/route-assets.client.ts b/packages/router-core/src/route-assets.client.ts new file mode 100644 index 0000000000..6b52f70f20 --- /dev/null +++ b/packages/router-core/src/route-assets.client.ts @@ -0,0 +1,122 @@ +import { isPromise } from './utils' +import type { AnyRouteMatch } from './Matches' +import type { AnyRouter } from './router' + +function commitClientAssets( + matches: Array, + index: number, + head: any, + scripts: any, +): void { + matches[index] = { + ...matches[index]!, + meta: head?.meta, + links: head?.links, + headScripts: head?.scripts, + scripts, + styles: head?.styles, + } +} + +export function projectClientRouteAssets( + router: AnyRouter, + matches: Array, + preload?: boolean, + isCurrent?: () => boolean, + startIndex = 0, +): void | Promise { + for (let i = startIndex; i < matches.length; i++) { + if (isCurrent && !isCurrent()) { + return + } + + const match = matches[i]! + if (preload && !match.preload) { + continue + } + + const routeOptions = router.routesById[match.routeId]!.options + if (!(routeOptions.head || routeOptions.scripts)) { + continue + } + + try { + const assetContext = { + ssr: router.options.ssr, + matches, + match, + params: match.params, + loaderData: match.loaderData, + } + + const head = routeOptions.head?.(assetContext) + if (isCurrent && !isCurrent()) { + // This pass lost ownership before the normal Promise.all path could + // observe `head`; allSettled owns any later rejection. + void Promise.allSettled([head]) + return + } + + let scripts: any + try { + scripts = routeOptions.scripts?.(assetContext) + } catch (error) { + // `head` may be async and abandoned because `scripts` threw + // synchronously. Own its rejection so it cannot become unhandled. + void Promise.allSettled([head]) + throw error + } + if (isCurrent && !isCurrent()) { + // This pass lost ownership before the normal Promise.all path could + // observe the asset promises; allSettled owns any later rejection. + void Promise.allSettled([head, scripts]) + return + } + + if (isPromise(head) || isPromise(scripts)) { + return Promise.all([head, scripts]).then( + ([headResult, scriptResult]) => { + if (!isCurrent || isCurrent()) { + commitClientAssets(matches, i, headResult, scriptResult) + return projectClientRouteAssets( + router, + matches, + preload, + isCurrent, + i + 1, + ) + } + }, + (error) => { + if (!isCurrent || isCurrent()) { + if (process.env.NODE_ENV !== 'production') { + console.error( + `Error executing head for route ${match.routeId}:`, + error, + ) + } + + return projectClientRouteAssets( + router, + matches, + preload, + isCurrent, + i + 1, + ) + } + }, + ) + } + + commitClientAssets(matches, i, head, scripts) + } catch (error) { + if (isCurrent && !isCurrent()) { + return + } + + if (process.env.NODE_ENV !== 'production') { + console.error(`Error executing head for route ${match.routeId}:`, error) + } + } + } +} diff --git a/packages/router-core/src/route-assets.server.ts b/packages/router-core/src/route-assets.server.ts new file mode 100644 index 0000000000..2592e9640b --- /dev/null +++ b/packages/router-core/src/route-assets.server.ts @@ -0,0 +1,183 @@ +import { isPromise } from './utils' +import type { AnyRouteMatch } from './Matches' +import type { AnyRouter } from './router' + +const withServerAssets = ( + match: AnyRouteMatch, + head: any, + scripts: any, + headers: any, +): AnyRouteMatch => ({ + ...match, + meta: head?.meta, + links: head?.links, + headScripts: head?.scripts, + scripts, + styles: head?.styles, + headers, +}) + +export const projectServerRouteAssets = ( + router: AnyRouter, + matches: Array, + startIndex = 0, +): void | Promise => { + for (let i = startIndex; i < matches.length; i++) { + const match = matches[i]! + const routeOptions = router.routesById[match.routeId]!.options + if (!(routeOptions.head || routeOptions.scripts || routeOptions.headers)) { + continue + } + + try { + const assetContext = { + ssr: router.options.ssr, + matches, + match, + params: match.params, + loaderData: match.loaderData, + } + + const head = routeOptions.head?.(assetContext) + let scripts: any + try { + scripts = routeOptions.scripts?.(assetContext) + } catch (error) { + // `head` may be async and abandoned because `scripts` threw + // synchronously. Own its rejection so it cannot become unhandled. + void Promise.allSettled([head]) + throw error + } + let headers: any + try { + headers = routeOptions.headers?.(assetContext) + } catch (error) { + // `head`/`scripts` may be async and abandoned because `headers` threw + // synchronously. Own rejections so they cannot become unhandled. + void Promise.allSettled([head, scripts]) + throw error + } + + if (isPromise(head) || isPromise(scripts) || isPromise(headers)) { + return continueServerRouteAssets( + router, + matches, + i, + match, + head, + scripts, + headers, + ) + } + + matches[i] = withServerAssets(match, head, scripts, headers) + } catch (error) { + if (process.env.NODE_ENV !== 'production') { + console.error(`Error executing head for route ${match.routeId}:`, error) + } + } + } +} + +const continueServerRouteAssets = async ( + router: AnyRouter, + matches: Array, + startIndex: number, + firstMatch: AnyRouteMatch, + firstHead: any, + firstScripts: any, + firstHeaders: any, +): Promise => { + let i = startIndex + let match = firstMatch + let head = firstHead + let scripts = firstScripts + let headers = firstHeaders + + while (true) { + const results = await Promise.allSettled([head, scripts, headers]) + + const headResult = results[0] + const scriptResult = results[1] + const headerResult = results[2] + + if ( + headResult.status === 'fulfilled' && + scriptResult.status === 'fulfilled' && + headerResult.status === 'fulfilled' + ) { + matches[i] = withServerAssets( + match, + headResult.value, + scriptResult.value, + headerResult.value, + ) + } else if (process.env.NODE_ENV !== 'production') { + const failed = + headResult.status === 'rejected' + ? headResult + : scriptResult.status === 'rejected' + ? scriptResult + : headerResult + console.error( + `Error executing head for route ${match.routeId}:`, + (failed as PromiseRejectedResult).reason, + ) + } + + for (i++; i < matches.length; i++) { + match = matches[i]! + const routeOptions = router.routesById[match.routeId]!.options + if ( + !(routeOptions.head || routeOptions.scripts || routeOptions.headers) + ) { + continue + } + + try { + const assetContext = { + ssr: router.options.ssr, + matches, + match, + params: match.params, + loaderData: match.loaderData, + } + + head = routeOptions.head?.(assetContext) + try { + scripts = routeOptions.scripts?.(assetContext) + } catch (error) { + // `head` may be async and abandoned because `scripts` threw + // synchronously. Own its rejection so it cannot become unhandled. + void Promise.allSettled([head]) + throw error + } + try { + headers = routeOptions.headers?.(assetContext) + } catch (error) { + // `head`/`scripts` may be async and abandoned because `headers` threw + // synchronously. Own rejections so they cannot become unhandled. + void Promise.allSettled([head, scripts]) + throw error + } + + if (isPromise(head) || isPromise(scripts) || isPromise(headers)) { + break + } + + matches[i] = withServerAssets(match, head, scripts, headers) + } catch (error) { + if (process.env.NODE_ENV !== 'production') { + console.error( + `Error executing head for route ${match.routeId}:`, + error, + ) + } + } + } + + if (i >= matches.length) { + return + } + } +} diff --git a/packages/router-core/src/route-chunks.ts b/packages/router-core/src/route-chunks.ts new file mode 100644 index 0000000000..5b06543ee2 --- /dev/null +++ b/packages/router-core/src/route-chunks.ts @@ -0,0 +1,97 @@ +import type { AnyRoute } from './route' + +type RouteComponentType = + | 'component' + | 'errorComponent' + | 'pendingComponent' + | 'notFoundComponent' + +function preloadComponent(component: any): Promise | undefined { + try { + return component?.preload?.() + } catch (error) { + return Promise.reject(error) + } +} + +function preloadRouteComponents( + route: AnyRoute, +): Promise> | undefined { + let preloads: Array> | undefined + for (const componentType of componentTypes) { + const preload = preloadComponent(route.options[componentType]) + if (preload) { + ;(preloads ||= []).push(preload) + } + } + + return preloads && Promise.all(preloads) +} + +export function loadRouteChunk( + route: AnyRoute, + componentType?: RouteComponentType, +) { + if (!route._lazyLoaded && !route._lazyPromise) { + if (route.lazyFn) { + try { + route._lazyPromise = route.lazyFn().then((lazyRoute) => { + // explicitly don't copy over the lazy route's id + const { id: _id, ...options } = lazyRoute.options + Object.assign(route.options, options) + route._lazyLoaded = true + route._lazyPromise = undefined // gc promise, we won't need it anymore + }) + } catch (error) { + route._lazyPromise = Promise.reject(error) + } + } else { + route._lazyLoaded = true + } + } + + const runAfterLazy = () => { + if (route._componentsLoaded) { + return + } + if (componentType) { + return ( + route._componentsPromise || + preloadComponent(route.options[componentType]) + ) + } + if (!route._componentsPromise) { + const componentsPromise = preloadRouteComponents(route) + + if (componentsPromise) { + route._componentsPromise = componentsPromise.then(() => { + route._componentsLoaded = true + route._componentsPromise = undefined // gc promise, we won't need it anymore + }) + } else { + route._componentsLoaded = true + } + } + return route._componentsPromise + } + + return route._lazyPromise + ? route._lazyPromise.then(runAfterLazy) + : runAfterLazy() +} + +export function routeNeedsPreload(route: AnyRoute) { + for (const componentType of componentTypes) { + if ((route.options[componentType] as any)?.preload) { + return true + } + } + return false +} + +const componentTypes = [ + 'component', + 'errorComponent', + 'pendingComponent', + 'notFoundComponent', +] as const satisfies ReadonlyArray diff --git a/packages/router-core/src/router-load.client.ts b/packages/router-core/src/router-load.client.ts new file mode 100644 index 0000000000..6ec881acdf --- /dev/null +++ b/packages/router-core/src/router-load.client.ts @@ -0,0 +1,258 @@ +import { createControlledPromise, isPromise } from './utils' +import { isRedirect } from './redirect' +import { + getLocationChangeInfo, + locationHistoryActions, +} from './location-change' +import { settleMatchLoad } from './load-matches' +import { + clearBackgroundFetching, + loadClientMatches, + startBackgroundLoad, +} from './load-matches.client' +import { projectClientRouteAssets } from './route-assets.client' +import type { AnyRouteMatch } from './Matches' +import type { AnyRouter, LoadFn } from './router' +import type { InnerLoadContext } from './load-matches' + +const commitFinalMatches = ( + router: AnyRouter, + baseMatches: Array, + nextMatches: Array, +): void => { + const { stores } = router + router.batch(() => { + const now = Date.now() + const cached = stores.cachedMatches.get().slice() + + for (let i = 0; i < baseMatches.length; i++) { + const match = baseMatches[i]! + if (nextMatches[i]?.id !== match.id) { + cached.push({ + ...match, + isFetching: false, + }) + } + } + + let write = 0 + for (const match of cached) { + const routeOptions = router.routesById[match.routeId]!.options + const gcTime = + (match.preload + ? (routeOptions.preloadGcTime ?? router.options.defaultPreloadGcTime) + : (routeOptions.gcTime ?? router.options.defaultGcTime)) ?? 300_000 + + if ( + routeOptions.loader && + match.status === 'success' && + now - match.updatedAt < gcTime + ) { + cached[write++] = match + } else { + settleMatchLoad(match) + } + } + + cached.length = write + stores.isLoading.set(false) + stores.setMatches(nextMatches) + if (stores.pendingIds.get().length) { + stores.setPending([]) + } + stores.loadedAt.set(now) + stores.setCached(cached) + }) + + const matchCount = Math.max(baseMatches.length, nextMatches.length) + for (let i = 0; i < matchCount; i++) { + const current = baseMatches[i] + const nextMatch = nextMatches[i] + + if (current && current.routeId !== nextMatch?.routeId) { + router.routesById[current.routeId]!.options.onLeave?.(current) + } + + if (nextMatch) { + router.routesById[nextMatch.routeId]!.options[ + current?.routeId === nextMatch.routeId ? 'onStay' : 'onEnter' + ]?.(nextMatch) + } + } +} + +export const loadClientRouter = async ( + router: AnyRouter, + opts?: Parameters[0], +): Promise => { + const historyAction = opts?.action?.type + const loadPromise = createControlledPromise() + const { stores } = router + + router.latestLoadPromise = loadPromise + + const isCurrentLoad = () => router.latestLoadPromise === loadPromise + let startedBackgroundLoad = false + + try { + const backgroundLoad = router._backgroundLoad + if (backgroundLoad) { + // A foreground navigation supersedes stale same-href background work. + // Abort its private token and clear active fetching markers now, + // because the background finalizer no longer owns the token. + backgroundLoad.controller.abort() + router._backgroundLoad = undefined + clearBackgroundFetching(router) + } + router.cancelMatches() + router.updateLatestLocation() + + const next = router.latestLocation + const pendingMatches = router.matchRoutes(next) + const sameHref = + (stores.resolvedLocation.get() ?? stores.location.get()).href === + next.href + + router.batch(() => { + stores.status.set('pending') + stores.isLoading.set(true) + stores.location.set(next) + stores.setPending(pendingMatches) + stores.setCached( + stores.cachedMatches + .get() + .filter((match) => pendingMatches[match.index]?.id !== match.id), + ) + }) + + const baseMatches = stores.matches.get() + if (historyAction) { + locationHistoryActions.set(next, historyAction) + } else { + locationHistoryActions.delete(next) + } + + if (router.subscribers.size) { + const locationChangeInfo = getLocationChangeInfo( + next, + stores.resolvedLocation.get(), + ) + + router.emit({ + type: 'onBeforeNavigate', + ...locationChangeInfo, + }) + + router.emit({ + type: 'onBeforeLoad', + ...locationChangeInfo, + }) + } + + let loadedMatches: Array = pendingMatches + const background = opts?.sync ? undefined : ([] as Array) + const commitReady = (matches: Array) => { + if (!isCurrentLoad()) { + return + } + + router.batch(() => { + stores.setMatches(matches) + if (stores.pendingIds.get().length) { + stores.setPending([]) + } + }) + } + const loadContext: InnerLoadContext = { + router, + forceStaleReload: sameHref, + matches: pendingMatches, + location: next, + background, + onReady: commitReady, + } + try { + loadedMatches = (await loadClientMatches( + loadContext, + )) as Array + } catch (err) { + if (err === loadContext) { + // This foreground lane was superseded before reaching a route outcome. + // Let the outer load cleanup settle it as cancellation, not route error. + throw err + } + if (isRedirect(err)) { + throw err + } + loadContext.requiresCommit = true + } + + const backgroundIndices = background?.filter((index) => { + const match = loadedMatches[index] + return match && match.status === 'success' && !match.globalNotFound + }) + const backgroundLength = backgroundIndices?.length + const backgroundOnly = + sameHref && + backgroundLength && + !loadContext.requiresCommit && + !loadContext.pendingPublished + + if (isCurrentLoad()) { + if (backgroundOnly) { + router.batch(() => { + stores.isLoading.set(false) + if (stores.pendingIds.get().length) { + stores.setPending([]) + } + }) + } else { + const assets = projectClientRouteAssets( + router, + loadedMatches, + undefined, + isCurrentLoad, + ) + if (isPromise(assets)) { + await assets + } + if (isCurrentLoad()) { + await router.startViewTransition(async () => { + if (isCurrentLoad()) { + router.startTransition(() => { + commitFinalMatches(router, baseMatches, loadedMatches) + }) + } + }) + } + } + } + if (isCurrentLoad() && backgroundLength) { + startedBackgroundLoad = true + startBackgroundLoad(router, next, loadedMatches, backgroundIndices) + } + } catch (err) { + if (isCurrentLoad() && isRedirect(err)) { + stores.setPending([]) + router.navigate({ + ...err.options, + replace: true, + ignoreBlocker: true, + }) + } + } + + if (isCurrentLoad()) { + const commitLocationPromise = router.commitLocationPromise + router.latestLoadPromise = router.commitLocationPromise = undefined + commitLocationPromise?.resolve() + } + + loadPromise.resolve() + if (startedBackgroundLoad) { + // Background stale reloads run after the foreground lane is done. If that + // background work is sync, its commit is queued in the next microtask; yield + // once so the caller does not observe the temporary fetching marker. + await Promise.resolve() + } +} diff --git a/packages/router-core/src/router-load.server.ts b/packages/router-core/src/router-load.server.ts new file mode 100644 index 0000000000..b768e3d958 --- /dev/null +++ b/packages/router-core/src/router-load.server.ts @@ -0,0 +1,96 @@ +import { isNotFound } from './not-found' +import { isRedirect, redirect } from './redirect' +import { loadServerMatches } from './load-matches.server' +import type { AnyRouteMatch } from './Matches' +import type { AnyRouter, LoadFn } from './router' + +export const loadServerRouter = async ( + router: AnyRouter, + opts?: Parameters[0], +): Promise => { + let matchedMatches: Array | undefined + try { + const next = router.pendingBuiltLocation ?? router.latestLocation + router.latestLocation = next + + const nextLocation = router.buildLocation({ + to: next.pathname, + search: true, + params: true, + hash: true, + state: true, + _includeValidateSearch: true, + }) + + if (next.publicHref !== nextLocation.publicHref) { + const href = nextLocation.publicHref || '/' + throw nextLocation.external + ? redirect({ href }) + : redirect({ href, _builtLocation: nextLocation }) + } + + matchedMatches = router.matchRoutes(next) + + router.statusCode = 200 + router.stores.location.set(next) + + const loadedMatches = (await loadServerMatches({ + router, + matches: matchedMatches, + location: next, + })) as Array + + router.stores.loadedAt.set(Date.now()) + router.stores.setMatches(loadedMatches) + } catch (err) { + let resolvedRedirect = isRedirect(err) + ? router.resolveRedirect(err) + : undefined + if (resolvedRedirect) { + const options = resolvedRedirect.options as any + const statusCode = + options.statusCode ?? + options.code ?? + (resolvedRedirect.status === 200 ? 307 : resolvedRedirect.status) + options.statusCode = statusCode + + if (resolvedRedirect.status !== statusCode) { + const redirectResponse = new Response(null, { + status: statusCode, + headers: resolvedRedirect.headers, + }) as typeof resolvedRedirect + redirectResponse.options = resolvedRedirect.options + redirectResponse.redirectHandled = resolvedRedirect.redirectHandled + resolvedRedirect = redirectResponse + } + } else if (matchedMatches?.length) { + router.stores.loadedAt.set(Date.now()) + router.stores.setMatches(matchedMatches) + } + + router.statusCode = resolvedRedirect + ? (resolvedRedirect.options as any).statusCode + : isNotFound(err) + ? 404 + : router.stores.matches.get().some((d) => d.status === 'error') + ? 500 + : 200 + router.redirect = resolvedRedirect + } finally { + const commitLocationPromise = router.commitLocationPromise + router.latestLoadPromise = undefined + router.commitLocationPromise = undefined + commitLocationPromise?.resolve() + } + + const newStatusCode = router.stores.matches + .get() + .some((d) => d.status === 'notFound' || d.globalNotFound) + ? 404 + : router.stores.matches.get().some((d) => d.status === 'error') + ? 500 + : undefined + if (newStatusCode) { + router.statusCode = newStatusCode + } +} diff --git a/packages/router-core/src/router-preload.client.ts b/packages/router-core/src/router-preload.client.ts new file mode 100644 index 0000000000..1845e94729 --- /dev/null +++ b/packages/router-core/src/router-preload.client.ts @@ -0,0 +1,88 @@ +import { isNotFound } from './not-found' +import { isRedirect } from './redirect' +import { loadClientMatches } from './load-matches.client' +import { projectClientRouteAssets } from './route-assets.client' +import { settleMatchLoad } from './load-matches' +import { isPromise } from './utils' +import type { AnyRouteMatch } from './Matches' +import type { AnyRouter } from './router' +import type { InnerLoadContext } from './load-matches' + +export const preloadClientRoute = async ( + router: AnyRouter, + opts: any, +): Promise | undefined> => { + const next = opts._builtLocation ?? router.buildLocation(opts) + + let matches = router.matchRoutes(next, { + throwOnError: true, + preload: true, + }) + + const loadContext: InnerLoadContext = { + router, + matches, + location: next, + preload: router.stores.matchesId + .get() + .concat(router.stores.pendingIds.get()), + } + + try { + matches = await loadClientMatches(loadContext) + + if (matches.every((match) => match.status === 'success')) { + const assets = projectClientRouteAssets(router, matches, true) + if (isPromise(assets)) { + await assets + } + + let ownedMatches: Array | undefined + for (const match of matches) { + if (match.preload && !router.getMatch(match.id, false)) { + ;(ownedMatches ||= []).push(match) + } + } + if (ownedMatches) { + router.stores.setCached([ + ...router.stores.cachedMatches + .get() + .filter( + (cachedMatch) => + !ownedMatches.some((match) => match.id === cachedMatch.id), + ), + ...ownedMatches, + ]) + } + } + + return matches + } catch (err) { + if (err === loadContext) { + // The preload lane lost ownership while borrowing active/pending matches. + // Do not project assets or cache speculative descendants for this pass. + return + } + if (isRedirect(err)) { + if (err.options.reloadDocument) { + return + } + + return preloadClientRoute(router, { + ...err.options, + _fromLocation: next, + }) + } + if (process.env.NODE_ENV !== 'production' && !isNotFound(err)) { + // Preload errors are not fatal, but we should still log them + console.error(err) + } + return + } finally { + for (const match of matches) { + if (match.preload) { + settleMatchLoad(match) + } + } + } +} diff --git a/packages/router-core/src/router.ts b/packages/router-core/src/router.ts index 2197dab737..24cc25ce3e 100644 --- a/packages/router-core/src/router.ts +++ b/packages/router-core/src/router.ts @@ -35,8 +35,13 @@ import { isNotFound } from './not-found' import { setupScrollRestoration } from './scroll-restoration' import { defaultParseSearch, defaultStringifySearch } from './searchParams' import { rootRouteId } from './root' -import { isRedirect, redirect } from './redirect' -import { loadMatches, loadRouteChunk, routeNeedsPreload } from './load-matches' +import { isRedirect } from './redirect' +import { getLocationChangeInfo } from './location-change' +import { settleMatchLoad } from './load-matches' +import { preloadClientRoute } from './router-preload.client' +import { loadClientRouter } from './router-load.client' +import { loadServerRouter } from './router-load.server' +import { loadRouteChunk, routeNeedsPreload } from './route-chunks' import { composeRewrites, executeRewriteInput, @@ -51,6 +56,7 @@ import type { } from './new-process-route-tree' import type { SearchParser, SearchSerializer } from './searchParams' import type { AnyRedirect, ResolvedRedirect } from './redirect' +import type { BackgroundLoad } from './load-matches' import type { HistoryAction, HistoryLocation, @@ -81,6 +87,7 @@ import type { SearchMiddleware, SearchMiddlewareMeta, } from './route' + import type { FullSearchSchema, RouteById, @@ -106,7 +113,6 @@ import type { } from './manifest' import type { AnySchema, AnyValidator } from './validators' import type { NavigateOptions, ResolveRelativePath, ToOptions } from './link' -import type { NotFoundError } from './not-found' import type { AnySerializationAdapter, ValidateSerializableInput, @@ -544,14 +550,10 @@ export interface RouterState< in out TRouteMatch = MakeRouteMatchUnion, > { status: 'pending' | 'idle' - loadedAt: number isLoading: boolean - isTransitioning: boolean matches: Array location: ParsedLocation> resolvedLocation?: ParsedLocation> - statusCode: number - redirect?: AnyRedirect } export interface BuildNextOptions { @@ -775,7 +777,14 @@ export interface MatchRoutesFn { ): Array } -export type GetMatchFn = (matchId: string) => AnyRouteMatch | undefined +/** + * Internal match lookup. By default this includes cached matches; pass + * `false` when checking whether a match still has an active/pending owner. + */ +export type GetMatchFn = ( + matchId: string, + includeCached?: boolean, +) => AnyRouteMatch | undefined export type UpdateMatchFn = ( id: string, @@ -842,6 +851,24 @@ export type AnyRouterWithContext = RouterCore< export type AnyRouter = RouterCore +const loadRouter = + isServer === true + ? loadServerRouter + : isServer === false + ? loadClientRouter + : (router: AnyRouter, opts?: Parameters[0]) => + router.isServer + ? loadServerRouter(router, opts) + : loadClientRouter(router, opts) + +const preloadRouterRoute = + isServer === true + ? async () => undefined + : isServer === false + ? preloadClientRoute + : (router: AnyRouter, opts: any) => + router.isServer ? undefined : preloadClientRoute(router, opts) + export interface ViewTransitionOptions { types: | Array @@ -888,27 +915,6 @@ export const trailingSlashOptions = { export type TrailingSlashOption = (typeof trailingSlashOptions)[keyof typeof trailingSlashOptions] -/** - * Compute whether path, href or hash changed between previous and current - * resolved locations. - */ -export function getLocationChangeInfo( - location: ParsedLocation, - resolvedLocation?: ParsedLocation, -) { - const fromLocation = resolvedLocation - const toLocation = location - const pathChanged = fromLocation?.pathname !== toLocation.pathname - const hrefChanged = fromLocation?.href !== toLocation.href - const hashChanged = fromLocation?.hash !== toLocation.hash - return { fromLocation, toLocation, pathChanged, hrefChanged, hashChanged } -} - -export const locationHistoryActions = new WeakMap< - ParsedLocation, - HistoryAction ->() - type LightweightRouteMatchResult = { matchedRoutes: ReadonlyArray fullPath: string @@ -982,10 +988,9 @@ export class RouterCore< restoration?: boolean reset?: boolean } = { next: true } - shouldViewTransition?: boolean | ViewTransitionOptions = undefined - isViewTransitionTypesSupported?: boolean = undefined + shouldViewTransition?: boolean | ViewTransitionOptions + isViewTransitionTypesSupported?: boolean subscribers = new Set>() - viewTransitionPromise?: ControlledPromise // Must build in constructor stores!: RouterStores @@ -1007,6 +1012,8 @@ export class RouterCore< origin?: string latestLocation!: ParsedLocation> pendingBuiltLocation?: ParsedLocation> + declare redirect: AnyRedirect | undefined + declare statusCode: number basepath!: string routeTree!: TRouteTree routesById!: RoutesById @@ -1054,6 +1061,14 @@ export class RouterCore< if (typeof document !== 'undefined') { self.__TSR_ROUTER__ = this } + + if (isServer ?? this.isServer) { + this.statusCode = 200 + // Server instances read these from per-request options. Client instances + // keep the prototype fallbacks below, which always return false. + this.isShell = () => !!this.options.isShell + this.isPrerendering = () => !!this.options.isPrerendering + } } // This is a default implementation that can optionally be overridden @@ -1061,12 +1076,13 @@ export class RouterCore< // router can be used in a non-react environment if necessary startTransition: StartTransitionFn = (fn) => fn() + // Client fallbacks. Server routers shadow these methods in the constructor. isShell() { - return !!this.options.isShell + return false } isPrerendering() { - return !!this.options.isPrerendering + return false } update: UpdateFn< @@ -1169,7 +1185,14 @@ export class RouterCore< const config = this.getStoreConfig(this) this.batch = config.batch this.stores = createRouterStores( - getInitialRouterState(this.latestLocation), + { + loadedAt: 0, + isLoading: false, + status: 'idle', + resolvedLocation: undefined, + location: this.latestLocation, + matches: [], + }, config, ) @@ -1178,7 +1201,6 @@ export class RouterCore< } } - let needsLocationUpdate = false const nextBasepath = this.options.basepath ?? '/' const nextRewriteOption = this.options.rewrite const basepathChanged = basepathWasUnset || prevBasepath !== nextBasepath @@ -1201,31 +1223,15 @@ export class RouterCore< } this.rewrite = - rewrites.length === 0 - ? undefined - : rewrites.length === 1 - ? rewrites[0] - : composeRewrites(rewrites) + rewrites.length > 1 ? composeRewrites(rewrites) : rewrites[0] if (this.history) { this.updateLatestLocation() } - needsLocationUpdate = true - } - - if (needsLocationUpdate && this.stores) { - this.stores.location.set(this.latestLocation) - } - - if ( - typeof window !== 'undefined' && - 'CSS' in window && - typeof window.CSS?.supports === 'function' - ) { - this.isViewTransitionTypesSupported = window.CSS.supports( - 'selector(:active-view-transition-type(a))', - ) + if (this.stores) { + this.stores.location.set(this.latestLocation) + } } } @@ -1250,6 +1256,7 @@ export class RouterCore< }) }, ) + if (this.options.routeMasks) { processRouteMasks(this.options.routeMasks, result.processedTree) } @@ -1408,10 +1415,6 @@ export class RouterCore< return branch } - get looseRoutesById() { - return this.routesById as Record - } - matchRoutes: MatchRoutesFn = ( pathnameOrNext: string | ParsedLocation, locationSearchOrOpts?: AnySchema | MatchRoutesOpts, @@ -1430,24 +1433,16 @@ export class RouterCore< return this.matchRoutesInternal(pathnameOrNext, locationSearchOrOpts) } - private getParentContext(parentMatch?: AnyRouteMatch) { - const parentMatchId = parentMatch?.id - - const parentContext = !parentMatchId - ? ((this.options.context as any) ?? undefined) - : (parentMatch.context ?? this.options.context ?? undefined) - - return parentContext - } - private matchRoutesInternal( next: ParsedLocation, opts?: MatchRoutesOpts, ): Array { + const throwOnError = opts?.throwOnError + const preload = opts?.preload === true const matchedRoutesResult = this.getMatchedRoutes(next.pathname) const { foundRoute, routeParams } = matchedRoutesResult let { matchedRoutes } = matchedRoutesResult - let isGlobalNotFound = false + let globalNotFoundRouteId: string | undefined // Check to see if the route needs a 404 entry if ( @@ -1462,26 +1457,26 @@ export class RouterCore< matchedRoutes = [...matchedRoutes, this.options.notFoundRoute] } else { // If there is no routes found during path matching - isGlobalNotFound = true + globalNotFoundRouteId = rootRouteId + if (this.options.notFoundMode !== 'root') { + for (let i = matchedRoutes.length - 1; i >= 0; i--) { + const route = matchedRoutes[i]! + if (route.children) { + globalNotFoundRouteId = route.id + break + } + } + } } } - const globalNotFoundRouteId = isGlobalNotFound - ? findGlobalNotFoundRouteId(this.options.notFoundMode, matchedRoutes) - : undefined - - const matches = new Array(matchedRoutes.length) - // Snapshot of active match state keyed by routeId, used to stabilise - // params/search across navigations. - const previousActiveMatchesByRouteId = new Map() - for (const store of this.stores.matchStores.values()) { - if (store.routeId) { - previousActiveMatchesByRouteId.set(store.routeId, store.get()) - } - } + const matches: Array = [] + const previousActiveMatches = this.stores.matches.get() + const rootContext = this.options.context ?? {} for (let index = 0; index < matchedRoutes.length; index++) { const route = matchedRoutes[index]! + const routeOptions = route.options // Take each matched route and resolve + validate its search params // This has to happen serially because each route's search params // can depend on the parent route's search params @@ -1494,14 +1489,15 @@ export class RouterCore< let preMatchSearch: Record let strictMatchSearch: Record let searchError: any + { // Validate the search params and stabilize them const parentSearch = parentMatch?.search ?? next.search - const parentStrictSearch = parentMatch?._strictSearch ?? undefined + const parentStrictSearch = parentMatch?._strictSearch try { const strictSearch = - validateSearch(route.options.validateSearch, { ...parentSearch }) ?? + validateSearch(routeOptions.validateSearch, { ...parentSearch }) ?? undefined preMatchSearch = { @@ -1509,16 +1505,18 @@ export class RouterCore< ...strictSearch, } strictMatchSearch = { ...parentStrictSearch, ...strictSearch } - searchError = undefined } catch (err: any) { let searchParamError = err if (!(err instanceof SearchParamError)) { - searchParamError = new SearchParamError(err.message, { - cause: err, - }) + searchParamError = new SearchParamError( + err?.message ?? String(err), + { + cause: err, + }, + ) } - if (opts?.throwOnError) { + if (throwOnError) { throw searchParamError } @@ -1534,7 +1532,7 @@ export class RouterCore< // potential key function which is used to uniquely identify the route match in state const loaderDeps = - route.options.loaderDeps?.({ + routeOptions.loaderDeps?.({ search: preMatchSearch, }) ?? '' @@ -1544,7 +1542,7 @@ export class RouterCore< path: route.fullPath, params: routeParams, decoder: this.pathParamsDecoder, - server: this.isServer, + ...(isServer === undefined ? { server: this.isServer } : undefined), }) // Waste not, want not. If we already have a match for this route, @@ -1562,12 +1560,14 @@ export class RouterCore< loaderDepsHash const existingMatch = this.getMatch(matchId) - - const previousMatch = previousActiveMatchesByRouteId.get(route.id) + const previousMatch = + previousActiveMatches[index]?.routeId === route.id + ? previousActiveMatches[index] + : undefined const strictParams = existingMatch?._strictParams ?? usedParams - let paramsError: unknown = undefined + let paramsError: unknown if (!existingMatch) { try { @@ -1576,12 +1576,12 @@ export class RouterCore< if (isNotFound(err) || isRedirect(err)) { paramsError = err } else { - paramsError = new PathParamError(err.message, { + paramsError = new PathParamError(err?.message ?? String(err), { cause: err, }) } - if (opts?.throwOnError) { + if (throwOnError) { throw paramsError } } @@ -1589,133 +1589,117 @@ export class RouterCore< Object.assign(routeParams, strictParams) - const cause = previousMatch ? 'stay' : 'enter' + const cause = preload ? 'preload' : previousMatch ? 'stay' : 'enter' + const parentContext = parentMatch?.context ?? rootContext + const search = previousMatch + ? nullReplaceEqualDeep(previousMatch.search, preMatchSearch) + : existingMatch + ? nullReplaceEqualDeep(existingMatch.search, preMatchSearch) + : preMatchSearch + const abortController = new AbortController() let match: AnyRouteMatch if (existingMatch) { + const loadPromise = existingMatch._.loadPromise match = { ...existingMatch, cause, - params: previousMatch?.params ?? routeParams, + params: routeParams, _strictParams: strictParams, - search: previousMatch - ? nullReplaceEqualDeep(previousMatch.search, preMatchSearch) - : nullReplaceEqualDeep(existingMatch.search, preMatchSearch), + abortController, + _: loadPromise + ? { + loadPromise, + } + : existingMatch._.dehydrated + ? { + dehydrated: true, + } + : {}, + search, _strictSearch: strictMatchSearch, + searchError, + preload, } } else { - const status = - route.options.loader || - route.options.beforeLoad || - route.lazyFn || - routeNeedsPreload(route) - ? 'pending' - : 'success' + const pending = + !(isServer ?? this.isServer) && + (routeOptions.loader || + routeOptions.beforeLoad || + route.lazyFn || + routeNeedsPreload(route)) match = { id: matchId, - ssr: (isServer ?? this.isServer) ? undefined : route.options.ssr, + ssr: routeOptions.ssr, index, routeId: route.id, - params: previousMatch?.params ?? routeParams, + params: routeParams, _strictParams: strictParams, pathname: interpolatedPath, updatedAt: Date.now(), - search: previousMatch - ? nullReplaceEqualDeep(previousMatch.search, preMatchSearch) - : preMatchSearch, + search, _strictSearch: strictMatchSearch, - searchError: undefined, - status, + searchError, + status: pending ? 'pending' : 'success', isFetching: false, - error: undefined, paramsError, - __routeContext: undefined, - _nonReactive: { - loadPromise: createControlledPromise(), - }, - __beforeLoadContext: undefined, - context: {}, - abortController: new AbortController(), - fetchCount: 0, + _: pending + ? { + loadPromise: createControlledPromise(), + } + : {}, + abortController, cause, - loaderDeps: previousMatch - ? replaceEqualDeep(previousMatch.loaderDeps, loaderDeps) - : loaderDeps, + loaderDeps, invalid: false, - preload: false, - links: undefined, - scripts: undefined, - headScripts: undefined, - meta: undefined, - staticData: route.options.staticData || {}, + preload, + staticData: routeOptions.staticData || {}, fullPath: route.fullPath, - } + } as AnyRouteMatch } - if (!opts?.preload) { + if (!preload) { // If we have a global not found, mark the right match as global not found match.globalNotFound = globalNotFoundRouteId === route.id } - // update the searchError if there is one - match.searchError = searchError + matches[index] = match - const parentContext = this.getParentContext(parentMatch) - - match.context = { - ...parentContext, - ...match.__routeContext, - ...match.__beforeLoadContext, + if (!existingMatch && routeOptions.context) { + match.__routeContext = routeOptions.context({ + deps: match.loaderDeps, + params: match.params, + context: parentContext, + location: next, + navigate: (opts: any) => + this.navigate({ ...opts, _fromLocation: next }), + buildLocation: this.buildLocation, + cause: match.cause, + abortController: match.abortController, + preload, + matches, + routeId: route.id, + } as RouteContextOptions) } - matches[index] = match - } - - for (let index = 0; index < matches.length; index++) { - const match = matches[index]! - const route = this.looseRoutesById[match.routeId]! - const existingMatch = this.getMatch(match.id) - - // Update the match's params - const previousMatch = previousActiveMatchesByRouteId.get(match.routeId) - match.params = previousMatch - ? nullReplaceEqualDeep(previousMatch.params, routeParams) - : routeParams - - if (!existingMatch) { - const parentMatch = matches[index - 1] - const parentContext = this.getParentContext(parentMatch) - - // Update the match's context - - if (route.options.context) { - const contextFnContext: RouteContextOptions = - { - deps: match.loaderDeps, - params: match.params, - context: parentContext ?? {}, - location: next, - navigate: (opts: any) => - this.navigate({ ...opts, _fromLocation: next }), - buildLocation: this.buildLocation, - cause: match.cause, - abortController: match.abortController, - preload: !!match.preload, - matches, - routeId: route.id, - } - // Get the route context - match.__routeContext = - route.options.context(contextFnContext) ?? undefined - } - + if (match.__routeContext || match.__beforeLoadContext) { match.context = { ...parentContext, ...match.__routeContext, ...match.__beforeLoadContext, } + } else { + match.context = parentContext + } + } + + for (let i = 0; i < matches.length; i++) { + const previousMatch = previousActiveMatches[i] + const match = matches[i]! + if (previousMatch && previousMatch.routeId === match.routeId) { + match.params = nullReplaceEqualDeep(previousMatch.params, routeParams) } } @@ -1808,35 +1792,26 @@ export class RouterCore< return result } - cancelMatch = (id: string) => { - const match = this.getMatch(id) + cancelMatches() { + const cancelMatch = (matchId: string) => { + const match = this.getMatch(matchId) + if (match) { + match.abortController.abort() + settleMatchLoad(match) + } + } - if (!match) return + for (const matchId of this.stores.pendingIds.get()) { + cancelMatch(matchId) + } - match.abortController.abort() - clearTimeout(match._nonReactive.pendingTimeout) - match._nonReactive.pendingTimeout = undefined - } - - cancelMatches = () => { - this.stores.pendingIds.get().forEach((matchId) => { - this.cancelMatch(matchId) - }) - - this.stores.matchesId.get().forEach((matchId) => { + for (const matchId of this.stores.matchesId.get()) { if (this.stores.pendingMatchStores.has(matchId)) { - return + continue } - const match = this.stores.matchStores.get(matchId)?.get() - if (!match) { - return - } - - if (match.status === 'pending' || match.isFetching === 'loader') { - this.cancelMatch(matchId) - } - }) + cancelMatch(matchId) + } } /** @@ -1898,10 +1873,10 @@ export class RouterCore< lightweightResult.params, ) - const isAbsoluteTo = destTo?.charCodeAt(0) === 47 - const sourcePath = isAbsoluteTo - ? '/' - : this.resolvePathWithBase(defaultedFromPath, '.') + const sourcePath = + destTo && destTo.charCodeAt(0) === 47 + ? '/' + : this.resolvePathWithBase(defaultedFromPath, '.') // Resolve the destination. Absolute destinations don't need the source path. const nextTo = destTo @@ -1971,7 +1946,9 @@ export class RouterCore< path: nextTo, params: nextParams, decoder: this.pathParamsDecoder, - server: this.isServer, + ...(isServer === undefined + ? { server: this.isServer } + : undefined), }).interpolatedPath, ).path @@ -2227,11 +2204,7 @@ export class RouterCore< }, } - if ( - nextHistory.unmaskOnReload ?? - this.options.unmaskOnReload ?? - false - ) { + if (nextHistory.unmaskOnReload ?? this.options.unmaskOnReload) { nextHistory.state.__tempKey = this.tempLocationKey } } @@ -2341,7 +2314,7 @@ export class RouterCore< if (href) { try { - new URL(`${href}`) + new URL(href) hrefIsUrl = true } catch {} } @@ -2412,346 +2385,72 @@ export class RouterCore< }) } - latestLoadPromise: undefined | Promise + declare latestLoadPromise: undefined | ControlledPromise + declare _backgroundLoad: BackgroundLoad | undefined - beforeLoad = () => { - // Cancel any pending matches - this.cancelMatches() - this.updateLatestLocation() - - if (isServer ?? this.isServer) { - // for SPAs on the initial load, this is handled by the Transitioner - const nextLocation = this.buildLocation({ - to: this.latestLocation.pathname, - search: true, - params: true, - hash: true, - state: true, - _includeValidateSearch: true, - }) - - // Check if location changed - origin check is unnecessary since buildLocation - // always uses this.origin when constructing URLs - if (this.latestLocation.publicHref !== nextLocation.publicHref) { - const href = this.getParsedLocationHref(nextLocation) - if (nextLocation.external) { - throw redirect({ href }) - } else { - throw redirect({ href, _builtLocation: nextLocation }) - } - } - } - - // Match the routes - const pendingMatches = this.matchRoutes(this.latestLocation) - - const nextCachedMatches = this.stores.cachedMatches - .get() - .filter((d) => !pendingMatches.some((e) => e.id === d.id)) - - // Ingest the new matches - this.batch(() => { - this.stores.status.set('pending') - this.stores.statusCode.set(200) - this.stores.isLoading.set(true) - this.stores.location.set(this.latestLocation) - this.stores.setPending(pendingMatches) - // If a cached match moved to pending matches, remove it from cached matches - this.stores.setCached(nextCachedMatches) - }) + load: LoadFn = async (opts) => { + await loadRouter(this, opts) } - load: LoadFn = async (opts): Promise => { - const historyAction = opts?.action?.type - let redirect: AnyRedirect | undefined - let notFound: NotFoundError | undefined - let loadPromise: Promise - const previousLocation = - this.stores.resolvedLocation.get() ?? this.stores.location.get() - - // eslint-disable-next-line prefer-const - loadPromise = new Promise((resolve) => { - this.startTransition(async () => { - try { - this.beforeLoad() - if (historyAction) { - locationHistoryActions.set(this.latestLocation, historyAction) - } else { - locationHistoryActions.delete(this.latestLocation) - } - const next = this.latestLocation - const prevLocation = this.stores.resolvedLocation.get() - const locationChangeInfo = getLocationChangeInfo(next, prevLocation) - - if (!this.stores.redirect.get()) { - this.emit({ - type: 'onBeforeNavigate', - ...locationChangeInfo, - }) - } - - this.emit({ - type: 'onBeforeLoad', - ...locationChangeInfo, - }) - - await loadMatches({ - router: this, - sync: opts?.sync, - forceStaleReload: previousLocation.href === next.href, - matches: this.stores.pendingMatches.get(), - location: next, - updateMatch: this.updateMatch, - // eslint-disable-next-line @typescript-eslint/require-await - onReady: async () => { - // Wrap batch in framework-specific transition wrapper (e.g., Solid's startTransition) - this.startTransition(() => { - this.startViewTransition(async () => { - // this.viewTransitionPromise = createControlledPromise() - - // Commit the pending matches. If a previous match was - // removed, place it in the cachedMatches - // - // exitingMatches uses match.id (routeId + params + loaderDeps) so - // navigating /foo?page=1 → /foo?page=2 correctly caches the page=1 entry. - let exitingMatches: Array | null = null - - // Lifecycle-hook identity uses routeId only so that navigating between - // different params/deps of the same route fires onStay (not onLeave+onEnter). - let hookExitingMatches: Array | null = null - let hookEnteringMatches: Array | null = null - let hookStayingMatches: Array | null = null - - this.batch(() => { - const pendingMatches = this.stores.pendingMatches.get() - const mountPending = pendingMatches.length - const currentMatches = this.stores.matches.get() - - exitingMatches = mountPending - ? currentMatches.filter( - (match) => - !this.stores.pendingMatchStores.has(match.id), - ) - : null - - // Lifecycle-hook identity: routeId only (route presence in tree) - // Build routeId sets from pools to avoid derived stores. - const pendingRouteIds = new Set() - for (const s of this.stores.pendingMatchStores.values()) { - if (s.routeId) pendingRouteIds.add(s.routeId) - } - const activeRouteIds = new Set() - for (const s of this.stores.matchStores.values()) { - if (s.routeId) activeRouteIds.add(s.routeId) - } - - hookExitingMatches = mountPending - ? currentMatches.filter( - (match) => !pendingRouteIds.has(match.routeId), - ) - : null - hookEnteringMatches = mountPending - ? pendingMatches.filter( - (match) => !activeRouteIds.has(match.routeId), - ) - : null - hookStayingMatches = mountPending - ? pendingMatches.filter((match) => - activeRouteIds.has(match.routeId), - ) - : currentMatches - - this.stores.isLoading.set(false) - this.stores.loadedAt.set(Date.now()) - /** - * When committing new matches, cache any exiting matches that are still usable. - * Routes that resolved with `status: 'error'` or `status: 'notFound'` are - * deliberately excluded from `cachedMatches` so that subsequent invalidations - * or reloads re-run their loaders instead of reusing the failed/not-found data. - */ - if (mountPending) { - this.stores.setMatches(pendingMatches) - this.stores.setPending([]) - this.stores.setCached([ - ...this.stores.cachedMatches.get(), - ...exitingMatches!.filter( - (d) => - d.status !== 'error' && - d.status !== 'notFound' && - d.status !== 'redirected', - ), - ]) - this.clearExpiredCache() - } - }) - - // - for (const [matches, hook] of [ - [hookExitingMatches, 'onLeave'], - [hookEnteringMatches, 'onEnter'], - [hookStayingMatches, 'onStay'], - ] as const) { - if (!matches) continue - for (const match of matches as Array) { - this.looseRoutesById[match.routeId]!.options[hook]?.( - match, - ) - } - } - }) - }) - }, - }) - } catch (err) { - if (isRedirect(err)) { - redirect = err - if (!(isServer ?? this.isServer)) { - this.navigate({ - ...redirect.options, - replace: true, - ignoreBlocker: true, - }) - } - } else if (isNotFound(err)) { - notFound = err - } - - const nextStatusCode = redirect - ? redirect.status - : notFound - ? 404 - : this.stores.matches.get().some((d) => d.status === 'error') - ? 500 - : 200 - - this.batch(() => { - this.stores.statusCode.set(nextStatusCode) - this.stores.redirect.set(redirect) - }) - } - - if (this.latestLoadPromise === loadPromise) { - this.commitLocationPromise?.resolve() - this.latestLoadPromise = undefined - this.commitLocationPromise = undefined - } - - resolve() - }) - }) - - this.latestLoadPromise = loadPromise - - await loadPromise - - while ( - (this.latestLoadPromise as any) && - loadPromise !== this.latestLoadPromise - ) { - await this.latestLoadPromise - } - - let newStatusCode: number | undefined = undefined - if (this.hasNotFoundMatch()) { - newStatusCode = 404 - } else if (this.stores.matches.get().some((d) => d.status === 'error')) { - newStatusCode = 500 - } - if (newStatusCode !== undefined) { - this.stores.statusCode.set(newStatusCode) - } - } - - startViewTransition = (fn: () => Promise) => { - // Determine if we should start a view transition from the navigation - // or from the router default + startViewTransition = (fn: () => Promise): Promise => { const shouldViewTransition = this.shouldViewTransition ?? this.options.defaultViewTransition - // Reset the view transition flag this.shouldViewTransition = undefined - // Attempt to start a view transition (or just apply the changes if we can't) if ( - shouldViewTransition && - typeof document !== 'undefined' && - 'startViewTransition' in document && - typeof document.startViewTransition === 'function' + !shouldViewTransition || + typeof document === 'undefined' || + typeof (document as any).startViewTransition !== 'function' ) { - // lib.dom.ts doesn't support viewTransition types variant yet. - // TODO: Fix this when dom types are updated - let startViewTransitionParams: any + return fn() + } + if (typeof shouldViewTransition === 'object') { if ( - typeof shouldViewTransition === 'object' && - this.isViewTransitionTypesSupported + !(this.isViewTransitionTypesSupported ??= + typeof CSS !== 'undefined' && + CSS.supports?.('selector(:active-view-transition-type(a))')) ) { - const next = this.latestLocation - const prevLocation = this.stores.resolvedLocation.get() - - const resolvedViewTransitionTypes = - typeof shouldViewTransition.types === 'function' - ? shouldViewTransition.types( - getLocationChangeInfo(next, prevLocation), - ) - : shouldViewTransition.types - - if (resolvedViewTransitionTypes === false) { - fn() - return - } - - startViewTransitionParams = { - update: fn, - types: resolvedViewTransitionTypes, - } - } else { - startViewTransitionParams = fn + return fn() } - document.startViewTransition(startViewTransitionParams) - } else { - fn() + const types = + typeof shouldViewTransition.types === 'function' + ? shouldViewTransition.types( + getLocationChangeInfo( + this.latestLocation, + this.stores.resolvedLocation.get(), + ), + ) + : shouldViewTransition.types + + if (types === false) { + return fn() + } + + return (document as any).startViewTransition({ update: fn, types }) + .updateCallbackDone } + + return (document as any).startViewTransition(fn).updateCallbackDone } updateMatch: UpdateMatchFn = (id, updater) => { - this.startTransition(() => { - const pendingMatch = this.stores.pendingMatchStores.get(id) - if (pendingMatch) { - pendingMatch.set(updater) - return - } - - const activeMatch = this.stores.matchStores.get(id) - if (activeMatch) { - activeMatch.set(updater) - return - } - - const cachedMatch = this.stores.cachedMatchStores.get(id) - if (cachedMatch) { - const next = updater(cachedMatch.get()) - if (next.status === 'redirected') { - const deleted = this.stores.cachedMatchStores.delete(id) - if (deleted) { - this.stores.cachedIds.set((prev) => - prev.filter((matchId) => matchId !== id), - ) - } - } else { - cachedMatch.set(next) - } - } - }) + const matchStore = + this.stores.pendingMatchStores.get(id) ?? this.stores.matchStores.get(id) + matchStore?.set(updater) } - getMatch: GetMatchFn = (matchId: string): AnyRouteMatch | undefined => { + getMatch: GetMatchFn = (matchId, includeCached) => { + const matchStore = + this.stores.pendingMatchStores.get(matchId) ?? + this.stores.matchStores.get(matchId) return ( - this.stores.cachedMatchStores.get(matchId)?.get() ?? - this.stores.pendingMatchStores.get(matchId)?.get() ?? - this.stores.matchStores.get(matchId)?.get() - ) + includeCached === false + ? matchStore + : (matchStore ?? this.stores.cachedMatchStores.get(matchId)) + )?.get() } /** @@ -2771,7 +2470,7 @@ export class RouterCore< TDehydrated > > = (opts) => { - const invalidate = (d: MakeRouteMatch) => { + const invalidateLive = (d: MakeRouteMatch) => { if (opts?.filter?.(d as MakeRouteMatchUnion) ?? true) { return { ...d, @@ -2785,39 +2484,50 @@ export class RouterCore< } return d } + const invalidateCached = (d: MakeRouteMatch) => { + if (opts?.filter?.(d as MakeRouteMatchUnion) ?? true) { + return { + ...d, + invalid: true, + } + } + return d + } this.batch(() => { - this.stores.setMatches(this.stores.matches.get().map(invalidate)) - this.stores.setCached(this.stores.cachedMatches.get().map(invalidate)) - this.stores.setPending(this.stores.pendingMatches.get().map(invalidate)) + this.stores.setMatches(this.stores.matches.get().map(invalidateLive)) + this.stores.setCached( + this.stores.cachedMatches.get().map(invalidateCached), + ) + this.stores.setPending( + this.stores.pendingMatches.get().map(invalidateLive), + ) }) this.shouldViewTransition = false return this.load({ sync: opts?.sync }) } - getParsedLocationHref = (location: ParsedLocation) => { - // For redirects and external use, we need publicHref (with rewrite output applied) - // href is the internal path after rewrite input, publicHref is user-facing - return location.publicHref || '/' - } - resolveRedirect = (redirect: AnyRedirect): AnyRedirect => { - const locationHeader = redirect.headers.get('Location') + const options = redirect.options - if (!redirect.options.href || redirect.options._builtLocation) { - const location = - redirect.options._builtLocation ?? this.buildLocation(redirect.options) - const href = this.getParsedLocationHref(location) - redirect.options.href = href - redirect.headers.set('Location', href) - } else if (locationHeader) { + if (!options.href || options._builtLocation) { + const location = options._builtLocation ?? this.buildLocation(options) + const href = location.publicHref || '/' + options.href = href + if (isServer === true || (isServer === undefined && this.isServer)) { + redirect.headers.set('Location', href) + } + } else if (isServer === true || (isServer === undefined && this.isServer)) { + const locationHeader = redirect.headers.get('Location') try { - const url = new URL(locationHeader) - if (this.origin && url.origin === this.origin) { - const href = url.pathname + url.search + url.hash - redirect.options.href = href - redirect.headers.set('Location', href) + if (locationHeader) { + const url = new URL(locationHeader) + if (url.origin === this.origin) { + const href = url.pathname + url.search + url.hash + options.href = href + redirect.headers.set('Location', href) + } } } catch { // ignore invalid URLs @@ -2825,20 +2535,22 @@ export class RouterCore< } if ( - redirect.options.href && - !redirect.options._builtLocation && + !options._builtLocation && // Check for dangerous protocols before processing the redirect - isDangerousProtocol(redirect.options.href, this.protocolAllowlist) + isDangerousProtocol(options.href, this.protocolAllowlist) ) { throw new Error( process.env.NODE_ENV !== 'production' - ? `Redirect blocked: unsafe protocol in href "${redirect.options.href}". Allowed protocols: ${Array.from(this.protocolAllowlist).join(', ')}.` + ? `Redirect blocked: unsafe protocol in href "${options.href}". Allowed protocols: ${Array.from(this.protocolAllowlist).join(', ')}.` : 'Redirect blocked: unsafe protocol', ) } - if (!redirect.headers.get('Location')) { - redirect.headers.set('Location', redirect.options.href) + if ( + (isServer === true || (isServer === undefined && this.isServer)) && + !redirect.headers.get('Location') + ) { + redirect.headers.set('Location', options.href) } return redirect @@ -2846,42 +2558,16 @@ export class RouterCore< clearCache: ClearCacheFn = (opts) => { const filter = opts?.filter - if (filter !== undefined) { - this.stores.setCached( - this.stores.cachedMatches - .get() - .filter((m) => !filter(m as MakeRouteMatchUnion)), - ) - } else { - this.stores.setCached([]) - } - } + const cachedMatches = this.stores.cachedMatches.get() + const nextCachedMatches: Array = [] - clearExpiredCache = () => { - const now = Date.now() - // This is where all of the garbage collection magic happens - const filter = (d: MakeRouteMatch) => { - const route = this.looseRoutesById[d.routeId]! - - if (!route.options.loader) { - return true + for (const match of cachedMatches) { + if (filter && !filter(match as MakeRouteMatchUnion)) { + nextCachedMatches.push(match) } - - // If the route was preloaded, use the preloadGcTime - // otherwise, use the gcTime - const gcTime = - (d.preload - ? (route.options.preloadGcTime ?? this.options.defaultPreloadGcTime) - : (route.options.gcTime ?? this.options.defaultGcTime)) ?? - 5 * 60 * 1000 - - const isError = d.status === 'error' - if (isError) return true - - const gcEligible = now - d.updatedAt >= gcTime - return gcEligible } - this.clearCache({ filter }) + + this.stores.setCached(nextCachedMatches) } loadRouteChunk = loadRouteChunk @@ -2892,67 +2578,7 @@ export class RouterCore< TDefaultStructuralSharingOption, TRouterHistory > = async (opts) => { - const next = opts._builtLocation ?? this.buildLocation(opts as any) - - let matches = this.matchRoutes(next, { - throwOnError: true, - preload: true, - dest: opts, - }) - - const activeMatchIds = new Set([ - ...this.stores.matchesId.get(), - ...this.stores.pendingIds.get(), - ]) - - const loadedMatchIds = new Set([ - ...activeMatchIds, - ...this.stores.cachedIds.get(), - ]) - - // If the matches are already loaded, we need to add them to the cached matches. - const matchesToCache = matches.filter( - (match) => !loadedMatchIds.has(match.id), - ) - if (matchesToCache.length) { - const cachedMatches = this.stores.cachedMatches.get() - this.stores.setCached([...cachedMatches, ...matchesToCache]) - } - - try { - matches = await loadMatches({ - router: this, - matches, - location: next, - preload: true, - updateMatch: (id, updater) => { - // Don't update the match if it's currently loaded - if (activeMatchIds.has(id)) { - matches = matches.map((d) => (d.id === id ? updater(d) : d)) - } else { - this.updateMatch(id, updater) - } - }, - }) - - return matches - } catch (err) { - if (isRedirect(err)) { - if (err.options.reloadDocument) { - return undefined - } - - return await this.preloadRoute({ - ...err.options, - _fromLocation: next, - }) - } - if (!isNotFound(err)) { - // Preload errors are not fatal, but we should still log them - console.error(err) - } - return undefined - } + return preloadRouterRoute(this, opts) } matchRoute: MatchRouteFn< @@ -3016,12 +2642,6 @@ export class RouterCore< serverSsr?: ServerSsr serverSsrLifecycle?: RouterSsrLifecycle - - hasNotFoundMatch = () => { - return this.stores.matches - .get() - .some((d) => d.status === 'notFound' || d.globalNotFound) - } } /** Error thrown when search parameter validation fails. */ @@ -3052,22 +2672,6 @@ export function lazyFn< } } -/** Create an initial RouterState from a parsed location. */ -export function getInitialRouterState( - location: ParsedLocation, -): RouterState { - return { - loadedAt: 0, - isLoading: false, - isTransitioning: false, - status: 'idle', - resolvedLocation: undefined, - location, - matches: [], - statusCode: 200, - } -} - function validateSearch(validateSearch: AnyValidator, input: unknown): unknown { if (validateSearch == null) return {} @@ -3249,21 +2853,6 @@ function buildMiddlewareChain(destRoutes: ReadonlyArray) { } } -function findGlobalNotFoundRouteId( - notFoundMode: 'root' | 'fuzzy' | undefined, - routes: ReadonlyArray, -) { - if (notFoundMode !== 'root') { - for (let i = routes.length - 1; i >= 0; i--) { - const route = routes[i]! - if (route.children) { - return route.id - } - } - } - return rootRouteId -} - function extractStrictParams( route: AnyRoute, accumulatedParams: Record, diff --git a/packages/router-core/src/scroll-restoration.ts b/packages/router-core/src/scroll-restoration.ts index 6287a6fce0..ab71bc07bc 100644 --- a/packages/router-core/src/scroll-restoration.ts +++ b/packages/router-core/src/scroll-restoration.ts @@ -1,5 +1,5 @@ import { isServer } from '@tanstack/router-core/isServer' -import { locationHistoryActions } from './router' +import { locationHistoryActions } from './location-change' import type { AnyRouter } from './router' import type { ParsedLocation } from './location' diff --git a/packages/router-core/src/ssr/createRequestHandler.ts b/packages/router-core/src/ssr/createRequestHandler.ts index 32377b2bea..091269aa46 100644 --- a/packages/router-core/src/ssr/createRequestHandler.ts +++ b/packages/router-core/src/ssr/createRequestHandler.ts @@ -84,7 +84,7 @@ function getRequestHeaders(opts: { router: AnyRouter }): Headers { } // Handle Redirects - const redirect = opts.router.stores.redirect.get() + const redirect = opts.router.redirect if (redirect) { matchHeaders.push(redirect.headers) } diff --git a/packages/router-core/src/ssr/ssr-client.ts b/packages/router-core/src/ssr/ssr-client.ts index 2aa5358ac0..299e31172b 100644 --- a/packages/router-core/src/ssr/ssr-client.ts +++ b/packages/router-core/src/ssr/ssr-client.ts @@ -1,9 +1,9 @@ import { invariant } from '../invariant' +import { getMatchContext, settleMatchLoad } from '../load-matches' import { isNotFound } from '../not-found' -import { createControlledPromise } from '../utils' import { hydrateSsrMatchId } from './ssr-match-id' import type { GLOBAL_SEROVAL, GLOBAL_TSR } from './constants' -import type { DehydratedMatch, TsrSsrGlobal } from './types' +import type { TsrSsrGlobal } from './types' import type { AnyRouteMatch } from '../Matches' import type { AnyRouter } from '../router' import type { RouteContextOptions } from '../route' @@ -16,29 +16,9 @@ declare global { } } -function hydrateMatch( - match: AnyRouteMatch, - deyhydratedMatch: DehydratedMatch, -): void { - match.id = deyhydratedMatch.i - match.__beforeLoadContext = deyhydratedMatch.b - match.loaderData = deyhydratedMatch.l - match.status = deyhydratedMatch.s - match.ssr = deyhydratedMatch.ssr - match.updatedAt = deyhydratedMatch.u - match.error = deyhydratedMatch.e - // Only hydrate global-not-found when a defined value is present in the - // dehydrated payload. If omitted, preserve the value computed from the - // current client location (important for SPA fallback HTML served at unknown - // URLs, where dehydrated matches may come from `/` but client matching marks - // root as globalNotFound). - if (deyhydratedMatch.g !== undefined) { - match.globalNotFound = deyhydratedMatch.g - } -} - export async function hydrate(router: AnyRouter): Promise { - if (!window.$_TSR) { + const tsr = window.$_TSR + if (!tsr) { if (process.env.NODE_ENV !== 'production') { throw new Error( 'Invariant failed: Expected to find bootstrap data on window.$_TSR, but we did not. Please file an issue!', @@ -54,15 +34,18 @@ export async function hydrate(router: AnyRouter): Promise { if (serializationAdapters?.length) { const fromSerializableMap = new Map() - serializationAdapters.forEach((adapter) => { + for (const adapter of serializationAdapters) { fromSerializableMap.set(adapter.key, adapter.fromSerializable) - }) - window.$_TSR.t = fromSerializableMap - window.$_TSR.buffer.forEach((script) => script()) + } + tsr.t = fromSerializableMap + for (const script of tsr.buffer) { + script() + } } - window.$_TSR.initialized = true + tsr.initialized = true - if (!window.$_TSR.router) { + const dehydratedRouter = tsr.router + if (!dehydratedRouter) { if (process.env.NODE_ENV !== 'production') { throw new Error( 'Invariant failed: Expected to find a dehydrated data on window.$_TSR.router, but we did not. Please file an issue!', @@ -72,17 +55,10 @@ export async function hydrate(router: AnyRouter): Promise { invariant() } - const dehydratedRouter = window.$_TSR.router - dehydratedRouter.matches.forEach((dehydratedMatch) => { - dehydratedMatch.i = hydrateSsrMatchId(dehydratedMatch.i) - }) - if (dehydratedRouter.lastMatchId) { - dehydratedRouter.lastMatchId = hydrateSsrMatchId( - dehydratedRouter.lastMatchId, - ) - } - const { manifest, dehydratedData, lastMatchId } = dehydratedRouter - + const lastMatchId = dehydratedRouter.lastMatchId + ? hydrateSsrMatchId(dehydratedRouter.lastMatchId) + : undefined + const { manifest, dehydratedData } = dehydratedRouter router.ssr = { manifest, } @@ -96,99 +72,177 @@ export async function hydrate(router: AnyRouter): Promise { // Allow the user to handle custom hydration data before matching routes. // This lets hydration install router config that affects matching, e.g. rewrites. + // Do not alias `router.options` across this hook: it may call `router.update`, + // and the rest of hydration must observe the updated options. await router.options.hydrate?.(dehydratedData) // Hydrate the router state - const matches = router.matchRoutes(router.stores.location.get()) + const location = router.stores.location.get() + const matches = router.matchRoutes(location) + const routesById = router.routesById - // kick off loading the route chunks - const routeChunkPromise = Promise.all( - matches.map((match) => - router.loadRouteChunk(router.looseRoutesById[match.routeId]!), - ), - ) - - function setMatchForcePending(match: AnyRouteMatch) { - // usually the minPendingPromise is created in the Match component if a pending match is rendered - // however, this might be too late if the match synchronously resolves - const route = router.looseRoutesById[match.routeId]! - const pendingMinMs = - route.options.pendingMinMs ?? router.options.defaultPendingMinMs - if (pendingMinMs) { - const minPendingPromise = createControlledPromise() - match._nonReactive.minPendingPromise = minPendingPromise - match._forcePending = true - - setTimeout(() => { - minPendingPromise.resolve() - // We've handled the minPendingPromise, so we can delete it - router.updateMatch(match.id, (prev) => { - prev._nonReactive.minPendingPromise = undefined - return { - ...prev, - _forcePending: undefined, - } - }) - }, pendingMinMs) - } - } - - function setRouteSsr(match: AnyRouteMatch) { - const route = router.looseRoutesById[match.routeId] - if (route) { - route.options.ssr = match.ssr - } - } // Right after hydration and before the first render, we need to rehydrate each match - // First step is to reyhdrate loaderData and __beforeLoadContext - let firstNonSsrMatchIndex: number | undefined = undefined - matches.forEach((match) => { - const dehydratedMatch = dehydratedRouter.matches.find( - (d) => d.i === match.id, - ) - if (!dehydratedMatch) { - match._nonReactive.dehydrated = false - match.ssr = false - setRouteSsr(match) - return - } + // First step is to rehydrate loaderData and beforeLoad context. + let firstNonSsrMatch: AnyRouteMatch | undefined = undefined + let hasSsrFalseMatches = false + const routeChunkPromise = Promise.all( + matches.map((match) => { + const route = routesById[match.routeId]! - hydrateMatch(match, dehydratedMatch) - setRouteSsr(match) + const dehydratedMatch = dehydratedRouter.matches.find( + (dehydrated) => hydrateSsrMatchId(dehydrated.i) === match.id, + ) + if (!dehydratedMatch) { + match.ssr = false + } else { + match.__beforeLoadContext = dehydratedMatch.b + match.loaderData = dehydratedMatch.l + match.status = dehydratedMatch.s + match.ssr = dehydratedMatch.ssr + match.updatedAt = dehydratedMatch.u + match.error = dehydratedMatch.e - match._nonReactive.dehydrated = match.ssr !== false - - if (match.ssr === 'data-only' || match.ssr === false) { - if (firstNonSsrMatchIndex === undefined) { - firstNonSsrMatchIndex = match.index - setMatchForcePending(match) + // Only hydrate global-not-found when a defined value is present in the + // dehydrated payload. If omitted, preserve the value computed from the + // current client location. + if (dehydratedMatch.g !== undefined) { + match.globalNotFound = dehydratedMatch.g + } } + + route.options.ssr = match.ssr + + match._.dehydrated = match.ssr !== false + + if (match.ssr === false) { + match.status = 'pending' + match.error = undefined + hasSsrFalseMatches = true + if (!firstNonSsrMatch) { + firstNonSsrMatch = match + } + } else if (!firstNonSsrMatch && match.ssr === 'data-only') { + firstNonSsrMatch = match + } + + return router.loadRouteChunk(route) + }), + ) + const loadContext = { router, matches } + + const isSpaMode = matches[matches.length - 1]!.id !== lastMatchId + + let displayMatch = isSpaMode ? matches[1] : firstNonSsrMatch + let displayUntil = 0 + + if (isSpaMode && !displayMatch) { + if (process.env.NODE_ENV !== 'production') { + throw new Error( + 'Invariant failed: Expected to find a match below the root match in SPA mode.', + ) } - }) + + invariant() + } + + if (displayMatch) { + const route = routesById[displayMatch.routeId]! + const pendingComponent = + route.options.pendingComponent ?? + (router.options as any).defaultPendingComponent + + const displayMinMs = pendingComponent + ? (route.options.pendingMinMs ?? router.options.defaultPendingMinMs) + : undefined + + if (isSpaMode || hasSsrFalseMatches || displayMinMs) { + displayMatch._displayPending = true + settleMatchLoad(displayMatch) + + if (displayMinMs) { + displayUntil = Date.now() + displayMinMs + } + } else { + displayMatch = undefined + } + } router.stores.setMatches(matches) + const clearDisplayPending = () => { + let isStillLoadingDisplayMatch = false + if (displayMatch) { + router.updateMatch(displayMatch.id, (match) => { + if ( + !match._displayPending || + (match.status === 'pending' && router.stores.isLoading.get()) + ) { + // A SPA/ssr:false hydration pass can start a follow-up client load + // for this match. Keep the server-visible fallback until that load + // leaves the match's pending state. + isStillLoadingDisplayMatch = !!match._displayPending + return match + } + + settleMatchLoad(match) + return { + ...match, + _displayPending: undefined, + } + }) + } + return isStillLoadingDisplayMatch + } + + const finishDisplayPending = (): void | Promise => { + const remaining = displayUntil - Date.now() + if (remaining > 0) { + return new Promise((resolve) => + setTimeout(resolve, remaining), + ).then(finishDisplayPending) + } + + if (clearDisplayPending()) { + return router.latestLoadPromise?.then(finishDisplayPending) + } + return undefined + } + + const clearAndFailHydration = (err: unknown): never => { + matches.forEach(settleMatchLoad) + clearDisplayPending() + throw err + } + + try { + // Lazy route chunks can install context/head/scripts options. Display + // pending is already published above, so wait here before reconstructing + // hydration state from those route options. + await routeChunkPromise + } catch (err) { + return clearAndFailHydration(err) + } + // now that all necessary data is hydrated: // 1) fully reconstruct the route context // 2) execute `head()` and `scripts()` for each match - const activeMatches = router.stores.matches.get() - const location = router.stores.location.get() - await Promise.all( - activeMatches.map(async (match) => { - try { - const route = router.looseRoutesById[match.routeId]! + try { + await Promise.all( + matches.map(async (match) => { + try { + const route = routesById[match.routeId]! + route.options.ssr = match.ssr - const parentMatch = activeMatches[match.index - 1] - const parentContext = parentMatch?.context ?? router.options.context - - // `context()` was already executed by `matchRoutes`, however route context was not yet fully reconstructed - // so run it again and merge route context - if (route.options.context) { - const contextFnContext: RouteContextOptions = - { + // `context()` was already executed by `matchRoutes`, however route context was not yet fully reconstructed + // so run it again and merge route context + if (route.options.context) { + match.__routeContext = route.options.context({ deps: match.loaderDeps, params: match.params, - context: parentContext ?? {}, + context: + matches[match.index - 1]?.context ?? + router.options.context ?? + {}, location, navigate: (opts: any) => router.navigate({ @@ -201,94 +255,83 @@ export async function hydrate(router: AnyRouter): Promise { preload: false, matches, routeId: route.id, + } as RouteContextOptions) + } + + match.context = getMatchContext( + loadContext, + match.index, + match.__beforeLoadContext, + ) + + const assetContext = { + ssr: router.options.ssr, + matches, + match, + params: match.params, + loaderData: match.loaderData, + } + const headFnContent = await route.options.head?.(assetContext) + + const scripts = await route.options.scripts?.(assetContext) + + match.meta = headFnContent?.meta + match.links = headFnContent?.links + match.headScripts = headFnContent?.scripts + match.styles = headFnContent?.styles + match.scripts = scripts + } catch (err) { + if (isNotFound(err)) { + match.error = { isNotFound: true } + if (process.env.NODE_ENV !== 'production') { + console.error( + `NotFound error during hydration for routeId: ${match.routeId}`, + err, + ) } - match.__routeContext = - route.options.context(contextFnContext) ?? undefined + } else { + match.error = err as any + if (process.env.NODE_ENV !== 'production') { + console.error( + `Error during hydration for route ${match.routeId}:`, + err, + ) + } + throw err + } } + }), + ) + } catch (err) { + return clearAndFailHydration(err) + } - match.context = { - ...parentContext, - ...match.__routeContext, - ...match.__beforeLoadContext, - } - - const assetContext = { - ssr: router.options.ssr, - matches: activeMatches, - match, - params: match.params, - loaderData: match.loaderData, - } - const headFnContent = await route.options.head?.(assetContext) - - const scripts = await route.options.scripts?.(assetContext) - - match.meta = headFnContent?.meta - match.links = headFnContent?.links - match.headScripts = headFnContent?.scripts - match.styles = headFnContent?.styles - match.scripts = scripts - } catch (err) { - if (isNotFound(err)) { - match.error = { isNotFound: true } - console.error( - `NotFound error during hydration for routeId: ${match.routeId}`, - err, - ) - } else { - match.error = err as any - console.error( - `Error during hydration for route ${match.routeId}:`, - err, - ) - throw err - } - } - }), - ) - - const isSpaMode = matches[matches.length - 1]!.id !== lastMatchId - const hasSsrFalseMatches = matches.some((m) => m.ssr === false) // all matches have data from the server and we are not in SPA mode so we don't need to kick of router.load() if (!hasSsrFalseMatches && !isSpaMode) { matches.forEach((match) => { // remove the dehydrated flag since we won't run router.load() which would remove it - match._nonReactive.dehydrated = undefined + match._.dehydrated = undefined }) // Mark the current location as resolved so that later load cycles // (e.g. preloads, invalidations) don't mistakenly detect a href change // (resolvedLocation defaults to undefined and router.load() is skipped // in the normal SSR hydration path). - router.stores.resolvedLocation.set(router.stores.location.get()) - return routeChunkPromise + router.stores.resolvedLocation.set(location) + + matches.forEach(settleMatchLoad) + + void finishDisplayPending() + return } - // schedule router.load() to run after the next tick so we can store the promise in the match before loading starts - const loadPromise = Promise.resolve() + void Promise.resolve() .then(() => router.load()) .catch((err) => { - console.error('Error during router hydration:', err) - }) - - // in SPA mode we need to keep the first match below the root route pending until router.load() is finished - // this will prevent that other pending components are rendered but hydration is not blocked - if (isSpaMode) { - const match = matches[1] - if (!match) { if (process.env.NODE_ENV !== 'production') { - throw new Error( - 'Invariant failed: Expected to find a match below the root match in SPA mode.', - ) + console.error('Error during router hydration:', err) } - - invariant() - } - setMatchForcePending(match) - - match._displayPending = true - match._nonReactive.displayPendingPromise = loadPromise - - loadPromise.then(() => { + }) + .then(() => { router.batch(() => { // ensure router is not in status 'pending' anymore // this usually happens in Transitioner but if loading synchronously resolves, @@ -297,14 +340,8 @@ export async function hydrate(router: AnyRouter): Promise { router.stores.status.set('idle') router.stores.resolvedLocation.set(router.stores.location.get()) } - // hide the pending component once the load is finished - router.updateMatch(match.id, (prev) => ({ - ...prev, - _displayPending: undefined, - displayPendingPromise: undefined, - })) }) + + return finishDisplayPending() }) - } - return routeChunkPromise } diff --git a/packages/router-core/src/stores.ts b/packages/router-core/src/stores.ts index c2ab8311c3..910d681e97 100644 --- a/packages/router-core/src/stores.ts +++ b/packages/router-core/src/stores.ts @@ -1,11 +1,9 @@ import { createLRUCache } from './lru-cache' import { arraysEqual, functionalUpdate } from './utils' - import type { AnyRoute } from './route' import type { RouterState } from './router' import type { FullSearchSchema } from './routeInfo' import type { ParsedLocation } from './location' -import type { AnyRedirect } from './redirect' import type { AnyRouteMatch } from './Matches' export interface RouterReadableStore { @@ -73,13 +71,10 @@ export interface RouterStores { status: RouterWritableStore['status']> loadedAt: RouterWritableStore isLoading: RouterWritableStore - isTransitioning: RouterWritableStore location: RouterWritableStore>> resolvedLocation: RouterWritableStore< ParsedLocation> | undefined > - statusCode: RouterWritableStore - redirect: RouterWritableStore matchesId: RouterWritableStore> pendingIds: RouterWritableStore> /** @internal */ @@ -116,7 +111,7 @@ export interface RouterStores { } export function createRouterStores( - initialState: RouterState, + initialState: RouterState & { loadedAt: number }, config: StoreConfig, ): RouterStores { const { createMutableStore, createReadonlyStore, batch, init } = config @@ -130,11 +125,8 @@ export function createRouterStores( const status = createMutableStore(initialState.status) const loadedAt = createMutableStore(initialState.loadedAt) const isLoading = createMutableStore(initialState.isLoading) - const isTransitioning = createMutableStore(initialState.isTransitioning) const location = createMutableStore(initialState.location) const resolvedLocation = createMutableStore(initialState.resolvedLocation) - const statusCode = createMutableStore(initialState.statusCode) - const redirect = createMutableStore(initialState.redirect) const matchesId = createMutableStore>([]) const pendingIds = createMutableStore>([]) const cachedIds = createMutableStore>([]) @@ -165,14 +157,10 @@ export function createRouterStores( // compatibility "big" state store const __store = createReadonlyStore(() => ({ status: status.get(), - loadedAt: loadedAt.get(), isLoading: isLoading.get(), - isTransitioning: isTransitioning.get(), matches: matches.get(), location: location.get(), resolvedLocation: resolvedLocation.get(), - statusCode: statusCode.get(), - redirect: redirect.get(), })) // Per-routeId computed store cache. @@ -217,11 +205,8 @@ export function createRouterStores( status, loadedAt, isLoading, - isTransitioning, location, resolvedLocation, - statusCode, - redirect, matchesId, pendingIds, cachedIds, @@ -249,11 +234,11 @@ export function createRouterStores( setMatches, setPending, setCached, - } + } as RouterStores // initialize the active matches setMatches(initialState.matches as Array) - init?.(store) + init?.(store as unknown as RouterStores) // setters to update non-reactive utilities in sync with the reactive stores function setMatches(nextMatches: Array) { diff --git a/packages/router-core/src/utils.ts b/packages/router-core/src/utils.ts index f017215b5c..0e48cbe2b4 100644 --- a/packages/router-core/src/utils.ts +++ b/packages/router-core/src/utils.ts @@ -471,15 +471,19 @@ export function createControlledPromise(onResolve?: (value: T) => void) { controlledPromise.status = 'pending' controlledPromise.resolve = (value: T) => { - controlledPromise.status = 'resolved' - controlledPromise.value = value - resolveLoadPromise(value) - onResolve?.(value) + if (controlledPromise.status === 'pending') { + controlledPromise.status = 'resolved' + controlledPromise.value = value + resolveLoadPromise(value) + onResolve?.(value) + } } controlledPromise.reject = (e) => { - controlledPromise.status = 'rejected' - rejectLoadPromise(e) + if (controlledPromise.status === 'pending') { + controlledPromise.status = 'rejected' + rejectLoadPromise(e) + } } return controlledPromise diff --git a/packages/router-core/tests/granular-stores.test.ts b/packages/router-core/tests/granular-stores.test.ts index 54d2a4efab..18db398dca 100644 --- a/packages/router-core/tests/granular-stores.test.ts +++ b/packages/router-core/tests/granular-stores.test.ts @@ -349,6 +349,6 @@ describe('granular stores', () => { ).toBe('pending') expect(router.stores.pendingMatches.get()[0]?.status).toBe('pending') expect(router.stores.cachedMatches.get()[0]?.status).toBe('success') - expect(router.getMatch(duplicatedId)?.status).toBe('success') + expect(router.getMatch(duplicatedId)?.status).toBe('pending') }) }) diff --git a/packages/router-core/tests/hydrate.test.ts b/packages/router-core/tests/hydrate.test.ts index efac230e49..ea39945ce6 100644 --- a/packages/router-core/tests/hydrate.test.ts +++ b/packages/router-core/tests/hydrate.test.ts @@ -1,6 +1,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { createMemoryHistory } from '@tanstack/history' -import { BaseRootRoute, BaseRoute, notFound } from '../src' +import { + BaseRootRoute, + BaseRoute, + createControlledPromise, + notFound, +} from '../src' import { hydrate } from '../src/ssr/client' import { createTestRouter } from './routerTestUtils' import { dehydrateSsrMatchId } from '../src/ssr/ssr-match-id' @@ -91,7 +96,7 @@ describe('hydrate', () => { mockRouter.options.serializationAdapters = [mockSerializer] - const mockMatches = [{ id: '/', routeId: '/', index: 0, _nonReactive: {} }] + const mockMatches = [{ id: '/', routeId: '/', index: 0, _: {} }] mockRouter.matchRoutes = vi.fn().mockReturnValue(mockMatches) mockRouter.state.matches = mockMatches @@ -176,14 +181,14 @@ describe('hydrate', () => { routeId: '/', index: 0, ssr: undefined, - _nonReactive: {}, + _: {}, }, { id: '/other', routeId: '/other', index: 1, ssr: undefined, - _nonReactive: {}, + _: { loadPromise: createControlledPromise() }, }, ] @@ -224,6 +229,796 @@ describe('hydrate', () => { expect(ssr).toBe(true) }) + it('clears loadPromise references after fully SSR hydration', async () => { + const matches = mockRouter.matchRoutes( + mockRouter.stores.location.get(), + ) as Array + mockRouter.matchRoutes = vi.fn().mockReturnValue(matches) + + mockWindow.$_TSR = { + router: { + manifest: testManifest, + dehydratedData: {}, + lastMatchId: matches[matches.length - 1]!.id, + matches: matches.map((match) => ({ + i: match.id, + s: 'success' as const, + ssr: true, + u: Date.now(), + })), + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + initialized: false, + } + + await hydrate(mockRouter) + + expect( + mockRouter.state.matches.every( + (match: AnyRouteMatch) => match._.loadPromise === undefined, + ), + ).toBe(true) + }) + + it('fully SSR hydration runs no client loader and executes head and scripts once', async () => { + const matches = mockRouter.matchRoutes( + mockRouter.stores.location.get(), + ) as Array + const targetMatch = matches[matches.length - 1]! + const targetRoute = mockRouter.routesById[targetMatch.routeId] + const loader = vi.fn(() => 'client-loader') + const scripts = vi.fn(() => [{ children: 'hydrated-script' }]) + const loadSpy = vi.spyOn(mockRouter, 'load') + + targetRoute.options.loader = loader + targetRoute.options.scripts = scripts + mockRouter.matchRoutes = vi.fn().mockReturnValue(matches) + + mockWindow.$_TSR = { + router: { + manifest: testManifest, + dehydratedData: {}, + lastMatchId: matches[matches.length - 1]!.id, + matches: matches.map((match) => ({ + i: match.id, + l: match.id === targetMatch.id ? 'server-loader' : undefined, + s: 'success' as const, + ssr: true, + u: Date.now(), + })), + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + initialized: false, + } + + await hydrate(mockRouter) + + expect(loadSpy).not.toHaveBeenCalled() + expect(loader).not.toHaveBeenCalled() + expect(mockHead).toHaveBeenCalledTimes(1) + expect(scripts).toHaveBeenCalledTimes(1) + expect(targetMatch.loaderData).toBe('server-loader') + expect(targetMatch.scripts).toEqual([{ children: 'hydrated-script' }]) + }) + + it('selective SSR hydration client-loads ssr false shell matches', async () => { + const rootBeforeLoad = vi.fn(() => ({ root: 'client' })) + const childBeforeLoad = vi.fn(() => ({ child: 'client' })) + const rootLoader = vi.fn(({ context }) => ({ + root: context.root, + })) + const childLoader = vi.fn(({ context }) => ({ + child: context.child, + })) + const history = createMemoryHistory({ initialEntries: ['/child'] }) + const rootRoute = new BaseRootRoute({ + beforeLoad: rootBeforeLoad, + loader: rootLoader, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/child', + }).lazy(() => + Promise.resolve({ + options: { + ssr: () => { + throw new Error('ssr should not run on the client') + }, + beforeLoad: childBeforeLoad, + loader: childLoader, + }, + } as any), + ) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([childRoute]), + history, + isServer: false, + }) + const matches = router.matchRoutes(router.stores.location.get()) + + mockWindow.$_TSR = { + router: { + manifest: testManifest, + dehydratedData: {}, + lastMatchId: matches[matches.length - 1]!.id, + matches: matches.map((match) => ({ + i: match.id, + s: 'pending' as const, + ssr: false, + u: Date.now(), + })), + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + initialized: false, + } + + await hydrate(router) + await Promise.resolve() + + expect(rootBeforeLoad).toHaveBeenCalledTimes(1) + expect(childBeforeLoad).toHaveBeenCalledTimes(1) + expect(rootLoader).toHaveBeenCalledTimes(1) + expect(childLoader).toHaveBeenCalledTimes(1) + expect(childRoute.options.ssr).toBe(false) + await vi.waitFor(() => { + const loadedMatches = router.state.matches + const rootMatch = loadedMatches.find( + (match) => match.routeId === rootRoute.id, + ) + const childMatch = loadedMatches.find( + (match) => match.routeId === childRoute.id, + ) + + expect(rootMatch?.loaderData).toEqual({ root: 'client' }) + expect(childMatch?.loaderData).toEqual({ child: 'client' }) + }) + }) + + it('keeps SPA display pending when the initial client load does not commit final matches', async () => { + vi.useFakeTimers() + try { + const history = createMemoryHistory({ initialEntries: ['/other'] }) + const rootRoute = new BaseRootRoute({}) + const otherRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/other', + loader: () => 'other', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([otherRoute]), + history, + isServer: false, + }) + const matches = router.matchRoutes(router.stores.location.get()) + const displayMatch = matches[1]! + + router.load = vi.fn(async () => { + router.cancelMatches() + router.stores.isLoading.set(true) + }) + + mockWindow.$_TSR = { + router: { + manifest: testManifest, + dehydratedData: {}, + lastMatchId: matches[0]!.id, + matches: [ + { + i: matches[0]!.id, + s: 'success' as const, + ssr: true, + u: Date.now(), + }, + ], + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + initialized: false, + } + + await hydrate(router) + await vi.runOnlyPendingTimersAsync() + + expect(router.load).toHaveBeenCalledTimes(1) + + const currentDisplayMatch = router.getMatch(displayMatch.id) + if (!currentDisplayMatch) { + throw new Error('expected display match to remain mounted') + } + + expect(currentDisplayMatch.status).toBe('pending') + expect(currentDisplayMatch._displayPending).toBe(true) + expect(currentDisplayMatch._.loadPromise).toBeUndefined() + } finally { + vi.useRealTimers() + } + }) + + it('clears SPA display pending after a follow-up client load commits final matches', async () => { + vi.useFakeTimers() + try { + const followUpLoad = createControlledPromise() + const history = createMemoryHistory({ initialEntries: ['/other'] }) + const rootRoute = new BaseRootRoute({}) + const otherRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/other', + loader: () => 'other', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([otherRoute]), + history, + isServer: false, + }) + const matches = router.matchRoutes(router.stores.location.get()) + const displayMatch = matches[1]! + + router.load = vi.fn(async () => { + router.cancelMatches() + router.stores.isLoading.set(true) + router.latestLoadPromise = followUpLoad + }) + + mockWindow.$_TSR = { + router: { + manifest: testManifest, + dehydratedData: {}, + lastMatchId: matches[0]!.id, + matches: [ + { + i: matches[0]!.id, + s: 'success' as const, + ssr: true, + u: Date.now(), + }, + ], + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + initialized: false, + } + + await hydrate(router) + await vi.runOnlyPendingTimersAsync() + + const waitingDisplayMatch = router.getMatch(displayMatch.id) + if (!waitingDisplayMatch) { + throw new Error('expected display match to wait for follow-up load') + } + + expect(waitingDisplayMatch._displayPending).toBe(true) + + router.updateMatch(displayMatch.id, (match) => ({ + ...match, + status: 'success' as const, + })) + router.stores.isLoading.set(false) + followUpLoad.resolve() + await Promise.resolve() + + const currentDisplayMatch = router.getMatch(displayMatch.id) + if (!currentDisplayMatch) { + throw new Error('expected display match to remain mounted') + } + + expect(currentDisplayMatch._displayPending).toBeUndefined() + expect(currentDisplayMatch._.loadPromise).toBeUndefined() + } finally { + vi.useRealTimers() + } + }) + + it('clears data-only display pending after route chunks and pendingMinMs', async () => { + vi.useFakeTimers() + try { + mockRouter.options.defaultPendingComponent = () => null + mockRouter.options.defaultPendingMinMs = 500 + const matches = mockRouter.matchRoutes( + mockRouter.stores.location.get(), + ) as Array + const dataOnlyMatch = matches[matches.length - 1]! + mockRouter.matchRoutes = vi.fn().mockReturnValue(matches) + + mockWindow.$_TSR = { + router: { + manifest: testManifest, + dehydratedData: {}, + lastMatchId: dataOnlyMatch.id, + matches: matches.map((match) => ({ + i: match.id, + s: 'success' as const, + ssr: match === dataOnlyMatch ? ('data-only' as const) : true, + u: Date.now(), + })), + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + initialized: false, + } + + await hydrate(mockRouter) + + const displayMatch = mockRouter.getMatch( + dataOnlyMatch.id, + ) as AnyRouteMatch + expect(displayMatch._displayPending).toBe(true) + expect(displayMatch._.loadPromise).toBeUndefined() + + await vi.advanceTimersByTimeAsync(500) + + const updatedMatch = mockRouter.getMatch( + dataOnlyMatch.id, + ) as AnyRouteMatch + expect(updatedMatch._displayPending).toBeUndefined() + expect(updatedMatch._.loadPromise).toBeUndefined() + } finally { + vi.useRealTimers() + } + }) + + it('uses elapsed SSR-visible time for fast data-only hydration pending minimum', async () => { + vi.useFakeTimers() + try { + const headGate = createControlledPromise() + mockHead.mockReturnValue(headGate) + mockRouter.options.defaultPendingComponent = () => null + mockRouter.options.defaultPendingMinMs = 100 + + const matches = mockRouter.matchRoutes( + mockRouter.stores.location.get(), + ) as Array + const dataOnlyMatch = matches[matches.length - 1]! + mockRouter.matchRoutes = vi.fn().mockReturnValue(matches) + + mockWindow.$_TSR = { + router: { + manifest: testManifest, + dehydratedData: {}, + lastMatchId: dataOnlyMatch.id, + matches: matches.map((match) => ({ + i: match.id, + s: 'success' as const, + ssr: match === dataOnlyMatch ? ('data-only' as const) : true, + u: Date.now(), + })), + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + initialized: false, + } + + const hydration = hydrate(mockRouter) + await Promise.resolve() + + const displayMatch = mockRouter.getMatch( + dataOnlyMatch.id, + ) as AnyRouteMatch + + expect(displayMatch._displayPending).toBe(true) + + await vi.advanceTimersByTimeAsync(20) + headGate.resolve() + await hydration + + await vi.advanceTimersByTimeAsync(79) + expect(mockRouter.getMatch(dataOnlyMatch.id)._displayPending).toBe(true) + expect( + mockRouter.getMatch(dataOnlyMatch.id)._.loadPromise, + ).toBeUndefined() + + await vi.advanceTimersByTimeAsync(1) + + const updatedMatch = mockRouter.getMatch( + dataOnlyMatch.id, + ) as AnyRouteMatch + expect(updatedMatch._displayPending).toBeUndefined() + expect(updatedMatch._.loadPromise).toBeUndefined() + } finally { + vi.useRealTimers() + } + }) + + it('does not add a fresh minimum after slow data-only hydration work', async () => { + vi.useFakeTimers() + try { + const headGate = createControlledPromise() + mockHead.mockReturnValue(headGate) + mockRouter.options.defaultPendingComponent = () => null + mockRouter.options.defaultPendingMinMs = 100 + + const matches = mockRouter.matchRoutes( + mockRouter.stores.location.get(), + ) as Array + const dataOnlyMatch = matches[matches.length - 1]! + mockRouter.matchRoutes = vi.fn().mockReturnValue(matches) + + mockWindow.$_TSR = { + router: { + manifest: testManifest, + dehydratedData: {}, + lastMatchId: dataOnlyMatch.id, + matches: matches.map((match) => ({ + i: match.id, + s: 'success' as const, + ssr: match === dataOnlyMatch ? ('data-only' as const) : true, + u: Date.now(), + })), + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + initialized: false, + } + + const hydration = hydrate(mockRouter) + await Promise.resolve() + + const displayMatch = mockRouter.getMatch( + dataOnlyMatch.id, + ) as AnyRouteMatch + + expect(displayMatch._displayPending).toBe(true) + + await vi.advanceTimersByTimeAsync(150) + headGate.resolve() + await hydration + + const updatedMatch = mockRouter.getMatch( + dataOnlyMatch.id, + ) as AnyRouteMatch + expect(updatedMatch._displayPending).toBeUndefined() + expect(updatedMatch._.loadPromise).toBeUndefined() + } finally { + vi.useRealTimers() + } + }) + + it('cleans up data-only display pending when head hydration throws', async () => { + const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + const headError = new Error('head failed') + mockHead.mockImplementation(() => { + throw headError + }) + mockRouter.options.defaultPendingComponent = () => null + mockRouter.options.defaultPendingMinMs = 500 + const updateMatchSpy = vi.spyOn(mockRouter, 'updateMatch') + + const matches = mockRouter.matchRoutes( + mockRouter.stores.location.get(), + ) as Array + const dataOnlyMatch = matches[matches.length - 1]! + mockRouter.matchRoutes = vi.fn().mockReturnValue(matches) + + mockWindow.$_TSR = { + router: { + manifest: testManifest, + dehydratedData: {}, + lastMatchId: dataOnlyMatch.id, + matches: matches.map((match) => ({ + i: match.id, + s: 'success' as const, + ssr: match === dataOnlyMatch ? ('data-only' as const) : true, + u: Date.now(), + })), + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + initialized: false, + } + + await expect(hydrate(mockRouter)).rejects.toThrow(headError) + + const updatedMatch = mockRouter.getMatch(dataOnlyMatch.id) as AnyRouteMatch + expect(updatedMatch._displayPending).toBeUndefined() + expect(updatedMatch._.loadPromise).toBeUndefined() + expect(updateMatchSpy).toHaveBeenCalledWith( + dataOnlyMatch.id, + expect.any(Function), + ) + + consoleSpy.mockRestore() + }) + + it('runs hydration head work after route chunks resolve', async () => { + const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + const headError = new Error('head failed') + const headGate = createControlledPromise() + const routeChunkGate = createControlledPromise() + mockHead.mockReturnValue(headGate) + vi.spyOn(mockRouter, 'loadRouteChunk').mockReturnValue(routeChunkGate) + + const matches = mockRouter.matchRoutes( + mockRouter.stores.location.get(), + ) as Array + mockRouter.matchRoutes = vi.fn().mockReturnValue(matches) + + mockWindow.$_TSR = { + router: { + manifest: testManifest, + dehydratedData: {}, + lastMatchId: matches[matches.length - 1]!.id, + matches: matches.map((match) => ({ + i: match.id, + s: 'success' as const, + ssr: true, + u: Date.now(), + })), + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + initialized: false, + } + + try { + const hydration = hydrate(mockRouter) + await Promise.resolve() + + expect(mockHead).not.toHaveBeenCalled() + + routeChunkGate.resolve() + await vi.waitFor(() => expect(mockHead).toHaveBeenCalled()) + + headGate.reject(headError) + await expect(hydration).rejects.toThrow(headError) + } finally { + consoleSpy.mockRestore() + } + }) + + it('lazy route head rejection after chunk resolution cleans up display pending', async () => { + const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + const headError = new Error('head failed') + const routeChunkGate = createControlledPromise() + const head = vi.fn(() => { + throw headError + }) + const scripts = vi.fn(() => [{ children: 'hydrated-script' }]) + mockRouter.options.defaultPendingComponent = () => null + mockRouter.options.defaultPendingMinMs = 500 + + const matches = mockRouter.matchRoutes( + mockRouter.stores.location.get(), + ) as Array + const dataOnlyMatch = matches[matches.length - 1]! + const dataOnlyRoute = mockRouter.routesById[dataOnlyMatch.routeId] + dataOnlyRoute.options.head = undefined + dataOnlyRoute.options.scripts = undefined + vi.spyOn(mockRouter, 'loadRouteChunk').mockReturnValue( + routeChunkGate.then(() => { + dataOnlyRoute.options.head = head + dataOnlyRoute.options.scripts = scripts + }), + ) + mockRouter.matchRoutes = vi.fn().mockReturnValue(matches) + + mockWindow.$_TSR = { + router: { + manifest: testManifest, + dehydratedData: {}, + lastMatchId: dataOnlyMatch.id, + matches: matches.map((match) => ({ + i: match.id, + s: 'success' as const, + ssr: match === dataOnlyMatch ? ('data-only' as const) : true, + u: Date.now(), + })), + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + initialized: false, + } + + try { + const hydration = hydrate(mockRouter) + await Promise.resolve() + + const displayMatch = mockRouter.getMatch( + dataOnlyMatch.id, + ) as AnyRouteMatch + expect(displayMatch._displayPending).toBe(true) + + routeChunkGate.resolve() + await expect(hydration).rejects.toThrow(headError) + + const updatedMatch = mockRouter.getMatch( + dataOnlyMatch.id, + ) as AnyRouteMatch + expect(head).toHaveBeenCalledTimes(1) + expect(scripts).not.toHaveBeenCalled() + expect(updatedMatch._displayPending).toBeUndefined() + expect(updatedMatch._.loadPromise).toBeUndefined() + expect(consoleSpy).not.toHaveBeenCalledWith( + 'Error during router hydration:', + expect.anything(), + ) + } finally { + consoleSpy.mockRestore() + } + }) + + it('route-chunk rejection rejects before hydration head work starts', async () => { + const chunkError = new Error('chunk failed') + const unhandledRejection = vi.fn() + let rejectedChunk = false + mockRouter.options.defaultPendingComponent = () => null + mockRouter.options.defaultPendingMinMs = 500 + vi.spyOn(mockRouter, 'loadRouteChunk').mockImplementation(() => { + if (rejectedChunk) { + return Promise.resolve() + } + rejectedChunk = true + return Promise.reject(chunkError) + }) + + const matches = mockRouter.matchRoutes( + mockRouter.stores.location.get(), + ) as Array + const dataOnlyMatch = matches[matches.length - 1]! + mockRouter.matchRoutes = vi.fn().mockReturnValue(matches) + + mockWindow.$_TSR = { + router: { + manifest: testManifest, + dehydratedData: {}, + lastMatchId: dataOnlyMatch.id, + matches: matches.map((match) => ({ + i: match.id, + s: 'success' as const, + ssr: match === dataOnlyMatch ? ('data-only' as const) : true, + u: Date.now(), + })), + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + initialized: false, + } + + process.on('unhandledRejection', unhandledRejection) + + try { + const hydrationError = hydrate(mockRouter).catch((err) => err) + await new Promise((resolve) => setTimeout(resolve, 0)) + + expect(unhandledRejection).not.toHaveBeenCalled() + expect(mockHead).not.toHaveBeenCalled() + + await expect(hydrationError).resolves.toBe(chunkError) + + const updatedMatch = mockRouter.getMatch( + dataOnlyMatch.id, + ) as AnyRouteMatch + expect(updatedMatch._displayPending).toBeUndefined() + expect(updatedMatch._.loadPromise).toBeUndefined() + } finally { + process.off('unhandledRejection', unhandledRejection) + } + }) + + it('settles hydration load promises when route chunk loading rejects', async () => { + const chunkError = new Error('chunk failed') + const routeChunkGate = createControlledPromise() + mockRouter.options.defaultPendingComponent = () => null + mockRouter.options.defaultPendingMinMs = 500 + vi.spyOn(mockRouter, 'loadRouteChunk').mockReturnValue(routeChunkGate) + const updateMatchSpy = vi.spyOn(mockRouter, 'updateMatch') + const matches = mockRouter.matchRoutes( + mockRouter.stores.location.get(), + ) as Array + const dataOnlyMatch = matches[matches.length - 1]! + mockRouter.matchRoutes = vi.fn().mockReturnValue(matches) + + mockWindow.$_TSR = { + router: { + manifest: testManifest, + dehydratedData: {}, + lastMatchId: dataOnlyMatch.id, + matches: matches.map((match) => ({ + i: match.id, + s: 'success' as const, + ssr: match === dataOnlyMatch ? ('data-only' as const) : true, + u: Date.now(), + })), + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + initialized: false, + } + + const hydration = hydrate(mockRouter) + setTimeout(() => routeChunkGate.reject(chunkError), 0) + + await expect(hydration).rejects.toThrow(chunkError) + expect( + matches.every( + (match: AnyRouteMatch) => match._.loadPromise === undefined, + ), + ).toBe(true) + expect( + mockRouter.getMatch(dataOnlyMatch.id)._displayPending, + ).toBeUndefined() + expect(updateMatchSpy).toHaveBeenCalledWith( + dataOnlyMatch.id, + expect.any(Function), + ) + }) + + it('fully SSR route-chunk rejection does not mark location resolved', async () => { + const chunkError = new Error('chunk failed') + const routeChunkGate = createControlledPromise() + vi.spyOn(mockRouter, 'loadRouteChunk').mockReturnValue(routeChunkGate) + const matches = mockRouter.matchRoutes( + mockRouter.stores.location.get(), + ) as Array + mockRouter.matchRoutes = vi.fn().mockReturnValue(matches) + + mockWindow.$_TSR = { + router: { + manifest: testManifest, + dehydratedData: {}, + lastMatchId: matches[matches.length - 1]!.id, + matches: matches.map((match) => ({ + i: match.id, + s: 'success' as const, + ssr: true, + u: Date.now(), + })), + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + initialized: false, + } + + const hydration = hydrate(mockRouter) + routeChunkGate.reject(chunkError) + + await expect(hydration).rejects.toThrow(chunkError) + expect(mockRouter.stores.resolvedLocation.get()).toBeUndefined() + }) + it('should hydrate globalNotFound when dehydrated flag is present', async () => { const mockMatches = [ { @@ -231,7 +1026,7 @@ describe('hydrate', () => { routeId: '/', index: 0, ssr: undefined, - _nonReactive: {}, + _: {}, }, ] @@ -275,7 +1070,7 @@ describe('hydrate', () => { routeId: '/', index: 0, ssr: undefined, - _nonReactive: {}, + _: {}, }, ] @@ -318,7 +1113,7 @@ describe('hydrate', () => { routeId: '/', index: 0, ssr: undefined, - _nonReactive: {}, + _: {}, globalNotFound: true, }, ] @@ -364,7 +1159,7 @@ describe('hydrate', () => { routeId: '/', index: 0, ssr: undefined, - _nonReactive: {}, + _: {}, }, ] @@ -467,15 +1262,70 @@ describe('hydrate', () => { ).toEqual(['__root__', '/internal']) }) + it('uses router options updated by custom hydration after the hook', async () => { + vi.useFakeTimers() + try { + mockRouter.options.hydrate = () => { + mockRouter.update({ + defaultPendingComponent: () => null, + defaultPendingMinMs: 500, + }) + } + + const matches = mockRouter.matchRoutes( + mockRouter.stores.location.get(), + ) as Array + const dataOnlyMatch = matches[matches.length - 1]! + mockRouter.matchRoutes = vi.fn().mockReturnValue(matches) + + mockWindow.$_TSR = { + router: { + manifest: testManifest, + dehydratedData: {}, + lastMatchId: dataOnlyMatch.id, + matches: matches.map((match) => ({ + i: match.id, + s: 'success' as const, + ssr: match === dataOnlyMatch ? ('data-only' as const) : true, + u: Date.now(), + })), + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + initialized: false, + } + + await hydrate(mockRouter) + + const displayMatch = mockRouter.getMatch( + dataOnlyMatch.id, + ) as AnyRouteMatch + + expect(displayMatch._displayPending).toBe(true) + expect(displayMatch._.loadPromise).toBeUndefined() + + await vi.advanceTimersByTimeAsync(500) + + const updatedMatch = mockRouter.getMatch( + dataOnlyMatch.id, + ) as AnyRouteMatch + expect(updatedMatch._displayPending).toBeUndefined() + expect(updatedMatch._.loadPromise).toBeUndefined() + } finally { + vi.useRealTimers() + } + }) + it('should handle errors during route context hydration', async () => { const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) mockHead.mockImplementation(() => { throw notFound() }) - const mockMatches = [ - { id: '/', routeId: '/', index: 0, ssr: true, _nonReactive: {} }, - ] + const mockMatches = [{ id: '/', routeId: '/', index: 0, ssr: true, _: {} }] mockRouter.matchRoutes = vi.fn().mockReturnValue(mockMatches) mockRouter.state.matches = mockMatches @@ -517,4 +1367,265 @@ describe('hydrate', () => { consoleSpy.mockRestore() }) + + it('SPA display fallback outlives its own match loadPromise', async () => { + const childGate = createControlledPromise() + const history = createMemoryHistory({ initialEntries: ['/parent/child'] }) + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: () => 'parent', + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: async () => { + await childGate + return 'child' + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history, + isServer: false, + defaultPendingMs: 0, + defaultPendingMinMs: 0, + }) + ;(router.options as any).defaultPendingComponent = () => null + const matches = router.matchRoutes(router.stores.location.get()) + + mockWindow.$_TSR = { + router: { + manifest: testManifest, + dehydratedData: {}, + lastMatchId: '/not-the-current-leaf', + matches: [ + { + i: matches[0]!.id, + s: 'success', + ssr: true, + u: Date.now(), + }, + ], + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + initialized: false, + } + + await hydrate(router) + await Promise.resolve() + + await vi.waitFor(() => { + const parent = router.state.matches.find( + (match) => match.routeId === parentRoute.id, + ) as AnyRouteMatch + expect(parent.status).toBe('success') + expect(parent._displayPending).toBe(true) + expect(parent._.loadPromise).toBeUndefined() + }) + + expect(router.stores.status.get()).toBe('pending') + expect(router.stores.resolvedLocation.get()).toBeUndefined() + + childGate.resolve() + + await vi.waitFor(() => expect(router.stores.status.get()).toBe('idle')) + + const currentParent = router.state.matches.find( + (match) => match.routeId === parentRoute.id, + ) as AnyRouteMatch + expect(currentParent._displayPending).toBeUndefined() + expect(currentParent._.loadPromise).toBeUndefined() + expect(router.stores.resolvedLocation.get()).toEqual( + router.stores.location.get(), + ) + }) + + it('keeps SPA hydration fallback through pendingMinMs after load completes', async () => { + vi.useFakeTimers() + try { + let resolveRouterLoad!: () => void + const routerLoadPromise = new Promise((resolve) => { + resolveRouterLoad = resolve + }) + vi.spyOn(mockRouter, 'load').mockReturnValue(routerLoadPromise) + mockRouter.options.defaultPendingComponent = () => null + mockRouter.options.defaultPendingMinMs = 500 + + const matches = mockRouter.matchRoutes(mockRouter.stores.location.get()) + mockRouter.matchRoutes = vi.fn().mockReturnValue(matches) + + mockWindow.$_TSR = { + router: { + manifest: testManifest, + dehydratedData: {}, + lastMatchId: '/not-the-current-leaf', + matches: [ + { + i: matches[0].id, + s: 'success', + ssr: true, + u: Date.now(), + }, + ], + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + initialized: false, + } + + await hydrate(mockRouter) + await Promise.resolve() + + const match = mockRouter.stores.matches.get()[1] as AnyRouteMatch + + expect(match._displayPending).toBe(true) + + resolveRouterLoad() + await Promise.resolve() + await vi.advanceTimersByTimeAsync(499) + + expect(mockRouter.getMatch(match.id)._displayPending).toBe(true) + + await vi.advanceTimersByTimeAsync(1) + + const updatedMatch = mockRouter.getMatch(match.id) as AnyRouteMatch + expect(updatedMatch._displayPending).toBeUndefined() + } finally { + vi.useRealTimers() + } + }) + + it('cleans up SPA display pending when router.load rejects', async () => { + const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + const loadError = new Error('router load failed') + vi.spyOn(mockRouter, 'load').mockRejectedValue(loadError) + mockRouter.options.defaultPendingComponent = () => null + mockRouter.options.defaultPendingMinMs = 0 + + const matches = mockRouter.matchRoutes(mockRouter.stores.location.get()) + mockRouter.matchRoutes = vi.fn().mockReturnValue(matches) + + mockWindow.$_TSR = { + router: { + manifest: testManifest, + dehydratedData: {}, + lastMatchId: '/not-the-current-leaf', + matches: [ + { + i: matches[0].id, + s: 'success', + ssr: true, + u: Date.now(), + }, + ], + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + initialized: false, + } + + await hydrate(mockRouter) + + const match = mockRouter.stores.matches.get()[1] as AnyRouteMatch + + expect(match._displayPending).toBe(true) + + await vi.waitFor(() => { + const updatedMatch = mockRouter.getMatch(match.id) as AnyRouteMatch + expect(updatedMatch._displayPending).toBeUndefined() + }) + expect(consoleSpy).toHaveBeenCalledWith( + 'Error during router hydration:', + loadError, + ) + + consoleSpy.mockRestore() + }) + + it('SPA route-chunk failure rejects before starting router.load', async () => { + const chunkError = new Error('chunk failed') + const routeChunkGate = createControlledPromise() + const childLoader = vi.fn() + const history = createMemoryHistory({ initialEntries: ['/parent/child'] }) + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: () => 'parent', + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: childLoader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history, + isServer: false, + defaultPendingMs: 0, + defaultPendingMinMs: 0, + }) + ;(router.options as any).defaultPendingComponent = () => null + const matches = router.matchRoutes(router.stores.location.get()) + const childMatch = matches.find( + (match) => match.routeId === childRoute.id, + ) as AnyRouteMatch + router.matchRoutes = vi.fn().mockReturnValue(matches) + + let routeChunkCalls = 0 + vi.spyOn(router, 'loadRouteChunk').mockImplementation(() => { + routeChunkCalls++ + return routeChunkCalls <= matches.length ? routeChunkGate : undefined + }) + const load = router.load.bind(router) + vi.spyOn(router, 'load').mockImplementation((opts) => { + return load(opts) + }) + + mockWindow.$_TSR = { + router: { + manifest: testManifest, + dehydratedData: {}, + lastMatchId: '/not-the-current-leaf', + matches: [ + { + i: matches[0]!.id, + s: 'success' as const, + ssr: true, + u: Date.now(), + }, + ], + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + initialized: false, + } + + const hydration = hydrate(router) + await Promise.resolve() + + routeChunkGate.reject(chunkError) + + await expect(hydration).rejects.toThrow(chunkError) + + const currentChild = router.getMatch(childMatch.id) as AnyRouteMatch + expect(currentChild).toBe(childMatch) + expect(router.load).not.toHaveBeenCalled() + expect(childLoader).not.toHaveBeenCalled() + }) }) diff --git a/packages/router-core/tests/load.test.ts b/packages/router-core/tests/load.test.ts index 1ea6fca30e..779f477a03 100644 --- a/packages/router-core/tests/load.test.ts +++ b/packages/router-core/tests/load.test.ts @@ -3,26 +3,166 @@ import { createMemoryHistory } from '@tanstack/history' import { BaseRootRoute, BaseRoute, + PathParamError, + SearchParamError, + createControlledPromise, notFound, redirect, rootRouteId, } from '../src' import { createTestRouter } from './routerTestUtils' -import { loadMatches } from '../src/load-matches' +import { + loadClientMatches, + startBackgroundLoad, +} from '../src/load-matches.client' +import { projectClientRouteAssets } from '../src/route-assets.client' +import { projectServerRouteAssets } from '../src/route-assets.server' +import { loadServerMatches } from '../src/load-matches.server' +import { settleMatchLoad } from '../src/load-matches' +import { loadRouteChunk } from '../src/route-chunks' +import { isRedirect } from '../src/redirect' +import type { LoadMatchesArg } from '../src/load-matches' import type { + AnyRouteMatch, AnyRouter, + ControlledPromise, LoaderStaleReloadMode, RootRouteOptions, RouterCore, + LocationRewrite, } from '../src' type AnyRouteOptions = RootRouteOptions type BeforeLoad = NonNullable type Loader = NonNullable type LoaderEntry = Exclude +type LoaderFn = Exclude + +const settleClientLane = (matches: Array) => { + for (const match of matches) { + settleMatchLoad(match) + } +} + +const loadClientMatchesArg = (arg: LoadMatchesArg) => { + const loadContext = { + router: arg.router, + location: arg.location, + matches: arg.matches, + preload: arg.preload, + forceStaleReload: arg.forceReload, + background: arg.background, + onReady: arg.onReady, + } + + return loadClientMatches(loadContext).catch((error) => { + if (error === loadContext) { + return arg.matches + } + throw error + }) +} + +const loadMatches = async (arg: LoadMatchesArg) => { + if (arg.router.isServer) { + return loadServerMatches(arg) + } + + try { + const matches = await loadClientMatchesArg(arg) + settleClientLane(matches) + return matches + } catch (error) { + if (!isRedirect(error)) { + settleClientLane(arg.matches) + } + throw error + } +} + +const projectAssets = async ({ + router, + matches, + preload, + isCurrent = () => true, +}: { + router: AnyRouter + matches: Array + preload?: boolean + isCurrent?: () => boolean +}) => { + const assets = projectClientRouteAssets(router, matches, preload, isCurrent) + if (assets) { + await assets + } +} + +const gateFinalCommit = (router: AnyRouter) => { + const gate = createControlledPromise() + const started = vi.fn() + const original = router.startViewTransition + + router.startViewTransition = ((fn: any) => { + started() + return gate.then(() => fn()) + }) as AnyRouter['startViewTransition'] + + return { + gate, + started, + restore: () => { + router.startViewTransition = original + }, + } +} + +function expectNoCachedActiveOverlap(router: AnyRouter) { + const ownedIds = new Set([ + ...router.state.matches.map((match) => match.id), + ...router.stores.pendingMatches.get().map((match) => match.id), + ]) + const overlappingCachedIds = router.stores.cachedMatches + .get() + .flatMap((match) => (ownedIds.has(match.id) ? [match.id] : [])) + + expect(overlappingCachedIds).toEqual([]) +} + +const getLaneMatch = (matches: Array, id: string) => + matches.find((match) => match.id === id) + +describe('router server flags', () => { + test('uses false fallbacks on client routers', () => { + const rootRoute = new BaseRootRoute({}) + const router = createTestRouter({ + routeTree: rootRoute, + history: createMemoryHistory({ initialEntries: ['/'] }), + isServer: false, + isShell: true, + isPrerendering: true, + }) + + expect(router.isShell()).toBe(false) + expect(router.isPrerendering()).toBe(false) + }) + + test('reads shell and prerendering options on server routers', () => { + const rootRoute = new BaseRootRoute({}) + const router = createTestRouter({ + routeTree: rootRoute, + history: createMemoryHistory({ initialEntries: ['/'] }), + isServer: true, + isShell: true, + isPrerendering: true, + }) + + expect(router.isShell()).toBe(true) + expect(router.isPrerendering()).toBe(true) + }) +}) describe('redirect resolution', () => { - test('resolveRedirect normalizes same-origin Location to path-only', async () => { + test('resolveRedirect normalizes same-origin Location to path-only on the server', async () => { const rootRoute = new BaseRootRoute({}) const fooRoute = new BaseRoute({ getParentRoute: () => rootRoute, @@ -37,6 +177,7 @@ describe('redirect resolution', () => { initialEntries: ['https://example.com/foo'], }), origin: 'https://example.com', + isServer: true, }) // This redirect already includes an absolute Location header (external-ish), @@ -53,6 +194,57 @@ describe('redirect resolution', () => { expect(resolved.options.href).toBe('/foo') }) + test('resolveRedirect does not rewrite Location on the client', async () => { + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + }) + + const routeTree = rootRoute.addChildren([fooRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ + initialEntries: ['https://example.com/foo'], + }), + origin: 'https://example.com', + isServer: false, + }) + + const unresolved = redirect({ + to: '/foo', + headers: { Location: 'https://example.com/foo' }, + }) + + const resolved = router.resolveRedirect(unresolved) + + expect(resolved.headers.get('Location')).toBe('https://example.com/foo') + expect(resolved.options.href).toBe('/foo') + }) + + test('resolveRedirect does not add Location on the client', async () => { + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + }) + + const routeTree = rootRoute.addChildren([fooRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/foo'] }), + isServer: false, + }) + + const unresolved = redirect({ to: '/foo' }) + const resolved = router.resolveRedirect(unresolved) + + expect(resolved.headers.get('Location')).toBe(null) + expect(resolved.options.href).toBe('/foo') + }) + test.each(['/$a', '/$toString', '/$__proto__'])( 'server startup redirects initial path %s to /undefined', async (initialPath) => { @@ -72,12 +264,432 @@ describe('redirect resolution', () => { await router.load() - expect(router.state.redirect).toEqual( + expect(router.redirect).toEqual( expect.objectContaining({ options: expect.objectContaining({ href: '/undefined' }), }), ) - expect(router.state.redirect?.headers.get('Location')).toBe('/undefined') + expect(router.redirect?.headers.get('Location')).toBe('/undefined') + }, + ) +}) + +describe('server router.load status codes', () => { + test('keeps successful server loads at status 200', async () => { + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + loader: () => 'home', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + isServer: true, + }) + + await router.load() + + expect(router.statusCode).toBe(200) + expect(router.redirect).toBeUndefined() + expect(router.state.matches.at(-1)?.loaderData).toBe('home') + }) + + test('uses redirect status and instance redirect for server redirects', async () => { + const rootRoute = new BaseRootRoute({}) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const fromRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/from', + beforeLoad: () => { + throw redirect({ to: '/target', statusCode: 307 }) + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fromRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/from'] }), + isServer: true, + }) + + await router.load() + + expect(router.statusCode).toBe(307) + expect(router.redirect?.status).toBe(307) + expect(router.redirect?.options.href).toBe('/target') + expect(router.redirect?.headers.get('Location')).toBe('/target') + }) + + test.each([ + [ + 'loader returns notFound', + '/loader-return-not-found', + () => ({ + loader: () => notFound(), + }), + ], + [ + 'loader throws notFound', + '/loader-throw-not-found', + () => ({ + loader: () => { + throw notFound() + }, + }), + ], + [ + 'beforeLoad returns notFound', + '/before-return-not-found', + () => ({ + beforeLoad: () => notFound(), + }), + ], + [ + 'beforeLoad throws notFound', + '/before-throw-not-found', + () => ({ + beforeLoad: () => { + throw notFound() + }, + }), + ], + ] as const)('sets 404 when a server %s', async (_name, path, getOptions) => { + const rootRoute = new BaseRootRoute({}) + const missingRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path, + ...getOptions(), + notFoundComponent: () => null, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([missingRoute]), + history: createMemoryHistory({ initialEntries: [path] }), + isServer: true, + }) + + await router.load() + + const match = router.state.matches.find( + (item) => item.routeId === missingRoute.id, + ) + expect(router.statusCode).toBe(404) + expect(router.redirect).toBeUndefined() + expect(match?.status).toBe('notFound') + expect(match?.error).toEqual(expect.objectContaining({ isNotFound: true })) + }) + + test('sets 404 for unmatched server routes with a root notFound boundary', async () => { + const rootRoute = new BaseRootRoute({ + notFoundComponent: () => null, + }) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history: createMemoryHistory({ initialEntries: ['/missing'] }), + isServer: true, + }) + + await router.load() + + const rootMatch = router.state.matches.find( + (item) => item.routeId === rootRoute.id, + ) + expect(router.statusCode).toBe(404) + expect(router.redirect).toBeUndefined() + expect(rootMatch?.globalNotFound).toBe(true) + }) + + test('sets 500 when a server loader throws', async () => { + const loaderError = new Error('loader failed') + const rootRoute = new BaseRootRoute({}) + const errorRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/error', + loader: () => { + throw loaderError + }, + errorComponent: () => null, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([errorRoute]), + history: createMemoryHistory({ initialEntries: ['/error'] }), + isServer: true, + }) + + await router.load() + + const match = router.state.matches.find( + (item) => item.routeId === errorRoute.id, + ) + expect(router.statusCode).toBe(500) + expect(router.redirect).toBeUndefined() + expect(match?.status).toBe('error') + expect(match?.error).toBe(loaderError) + }) + + test('sets 500 when a server beforeLoad throws', async () => { + const beforeLoadError = new Error('beforeLoad failed') + const rootRoute = new BaseRootRoute({}) + const errorRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/before-error', + beforeLoad: () => { + throw beforeLoadError + }, + errorComponent: () => null, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([errorRoute]), + history: createMemoryHistory({ initialEntries: ['/before-error'] }), + isServer: true, + }) + + await router.load() + + const match = router.state.matches.find( + (item) => item.routeId === errorRoute.id, + ) + expect(router.statusCode).toBe(500) + expect(router.redirect).toBeUndefined() + expect(match?.status).toBe('error') + expect(match?.error).toBe(beforeLoadError) + }) +}) + +describe('direct client/server match loading', () => { + const setupDirectLoad = ({ + isServer, + routeTree, + path, + }: { + isServer: boolean + routeTree: any + path: string + }) => { + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: [path] }), + isServer, + }) + const location = router.latestLocation + const matches = router.matchRoutes(location) + router.stores.setPending(matches) + return { router, location, matches } + } + + test.each([ + ['client', false, loadClientMatchesArg], + ['server', true, loadServerMatches], + ] as const)( + 'loads beforeLoad context into loaders on the %s path', + async (label, isServer, loadImpl) => { + const token = `${label}-token` + const parentBeforeLoad = vi.fn(() => ({ token })) + const childLoader = vi.fn(({ context, preload }) => ({ + token: (context as { token: string }).token, + preload, + })) + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + beforeLoad: parentBeforeLoad, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: childLoader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + isServer, + }) + const location = router.latestLocation + const matches = router.matchRoutes(location) + router.stores.setPending(matches) + + const loadedMatches = await loadImpl({ router, location, matches }) + + const parentMatch = loadedMatches.find( + (item) => item.routeId === parentRoute.id, + ) + const childMatch = loadedMatches.find( + (item) => item.routeId === childRoute.id, + ) + expect(parentBeforeLoad).toHaveBeenCalledTimes(1) + expect(childLoader).toHaveBeenCalledTimes(1) + expect(parentMatch?.context).toMatchObject({ token }) + expect(childMatch?.status).toBe('success') + expect(childMatch?.loaderData).toEqual({ token, preload: false }) + }, + ) + + test('server beforeLoad and loader reuse the route-matched abortController', async () => { + let beforeLoadController: AbortController | undefined + let loaderController: AbortController | undefined + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + beforeLoad: ({ abortController }) => { + beforeLoadController = abortController + }, + loader: ({ abortController }) => { + loaderController = abortController + }, + }) + const { router, location, matches } = setupDirectLoad({ + isServer: true, + routeTree: rootRoute.addChildren([fooRoute]), + path: '/foo', + }) + const matchedController = matches[1]!.abortController + + await loadServerMatches({ router, location, matches }) + + expect(beforeLoadController).toBe(matchedController) + expect(loaderController).toBe(matchedController) + expect(matches[1]!.abortController).toBe(matchedController) + }) + + test.each([ + ['client', false, loadClientMatchesArg], + ['server', true, loadServerMatches], + ] as const)( + 'commits an ancestor notFound boundary and trims descendants on the %s path', + async (_label, isServer, loadImpl) => { + const rootRoute = new BaseRootRoute({ + notFoundComponent: () => null, + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + notFoundComponent: () => null, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + beforeLoad: () => { + throw notFound({ routeId: parentRoute.id }) + }, + }) + const { router, location, matches } = setupDirectLoad({ + isServer, + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([childRoute]), + ]), + path: '/parent/child', + }) + const childMatch = matches[2]! + + await expect(loadImpl({ router, location, matches })).rejects.toEqual( + expect.objectContaining({ isNotFound: true }), + ) + + expect(matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + parentRoute.id, + ]) + expect(matches[1]).toEqual( + expect.objectContaining({ + routeId: parentRoute.id, + status: 'notFound', + error: expect.objectContaining({ isNotFound: true }), + }), + ) + expect(childMatch._.loadPromise?.status).not.toBe('pending') + }, + ) + + test.each([ + ['client', false, loadClientMatchesArg], + ['server', true, loadServerMatches], + ] as const)( + 'throws redirects from beforeLoad on the %s path without running descendant loaders', + async (_label, isServer, loadImpl) => { + const childLoader = vi.fn() + const rootRoute = new BaseRootRoute({}) + const protectedRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/protected', + beforeLoad: () => { + throw redirect({ to: '/login', statusCode: 302 }) + }, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => protectedRoute, + path: '/child', + loader: childLoader, + }) + const loginRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/login', + }) + const { router, location, matches } = setupDirectLoad({ + isServer, + routeTree: rootRoute.addChildren([ + protectedRoute.addChildren([childRoute]), + loginRoute, + ]), + path: '/protected/child', + }) + + await expect(loadImpl({ router, location, matches })).rejects.toEqual( + expect.objectContaining({ + options: expect.objectContaining({ href: '/login' }), + }), + ) + expect(childLoader).not.toHaveBeenCalled() + }, + ) + + test.each([ + ['client', false, loadClientMatchesArg], + ['server', true, loadServerMatches], + ] as const)( + 'commits loader errors to the matching route on the %s path', + async (_label, isServer, loadImpl) => { + const thrown = new Error('direct loader failed') + const rootRoute = new BaseRootRoute({}) + const errorRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/error', + loader: () => { + throw thrown + }, + errorComponent: () => null, + }) + const { router, location, matches } = setupDirectLoad({ + isServer, + routeTree: rootRoute.addChildren([errorRoute]), + path: '/error', + }) + + if (isServer) { + await expect(loadImpl({ router, location, matches })).rejects.toBe( + thrown, + ) + } else { + await expect(loadImpl({ router, location, matches })).resolves.toBe( + matches, + ) + } + + expect(matches.at(-1)).toEqual( + expect.objectContaining({ + routeId: errorRoute.id, + status: 'error', + error: thrown, + }), + ) }, ) }) @@ -173,6 +785,85 @@ describe('beforeLoad skip or exec', () => { expect(beforeLoad).toHaveBeenCalledTimes(1) }) + test('sync beforeLoad starts descendant loaders in the same turn', async () => { + const parentBeforeLoad = vi.fn(() => ({ token: 'sync' })) + const childLoader = vi.fn(({ context }) => context) + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + beforeLoad: parentBeforeLoad, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: childLoader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + }) + const location = router.latestLocation + const matches = router.matchRoutes(location) + router.stores.setPending(matches) + + const loadPromise = loadMatches({ router, location, matches }) + + expect(parentBeforeLoad).toHaveBeenCalledTimes(1) + expect(childLoader).toHaveBeenCalledTimes(1) + expect(childLoader).toHaveReturnedWith( + expect.objectContaining({ + token: 'sync', + }), + ) + + await loadPromise + }) + + test('async beforeLoad delays descendant loaders until it settles', async () => { + const beforeLoadGate = createControlledPromise<{ token: string }>() + const parentBeforeLoad = vi.fn(() => beforeLoadGate) + const childLoader = vi.fn(({ context }) => context) + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + beforeLoad: parentBeforeLoad, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: childLoader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + }) + const location = router.latestLocation + const matches = router.matchRoutes(location) + router.stores.setPending(matches) + + const loadPromise = loadMatches({ router, location, matches }) + + expect(parentBeforeLoad).toHaveBeenCalledTimes(1) + expect(childLoader).not.toHaveBeenCalled() + + beforeLoadGate.resolve({ token: 'async' }) + await Promise.resolve() + await Promise.resolve() + + expect(childLoader).toHaveBeenCalledTimes(1) + expect(childLoader).toHaveReturnedWith( + expect.objectContaining({ + token: 'async', + }), + ) + + await loadPromise + }) + test('preserves primitive errors thrown from beforeLoad', async () => { const beforeLoad = vi.fn(() => { throw 'primitive error' @@ -181,7 +872,6 @@ describe('beforeLoad skip or exec', () => { await router.navigate({ to: '/foo' }) - expect(router.state.statusCode).toBe(500) expect(router.state.matches).toEqual( expect.arrayContaining([ expect.objectContaining({ @@ -202,13 +892,177 @@ describe('beforeLoad skip or exec', () => { await router.navigate({ to: '/foo' }) - expect(router.state.statusCode).toBe(500) expect(router.state.matches.find((d) => d.id === '/foo/foo')?.error).toBe( thrown, ) expect(thrown).toEqual({ type: 'domain-error' }) }) + test.each([false, true])( + 'handles %s async returned redirects from beforeLoad', + async (asyncReturn) => { + const beforeLoad = vi.fn(() => { + const result = redirect({ to: '/bar' }) + return asyncReturn ? Promise.resolve(result) : result + }) + const router = setup({ beforeLoad }) + + await router.navigate({ to: '/foo' }) + + expect(router.state.location.pathname).toBe('/bar') + expect(beforeLoad).toHaveBeenCalledTimes(1) + }, + ) + + test('client beforeLoad redirect stays current during basepath navigation', async () => { + const beforeLoad = vi.fn(() => { + throw redirect({ to: '/about' }) + }) + const rootRoute = new BaseRootRoute({}) + const redirectRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/redirect', + beforeLoad, + }) + const aboutRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/about', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([redirectRoute, aboutRoute]), + history: createMemoryHistory({ initialEntries: ['/app/'] }), + basepath: '/app', + isServer: false, + }) + + await router.load() + await router.navigate({ to: '/redirect' }) + + await vi.waitFor(() => + expect(router.state.location.publicHref).toBe('/app/about'), + ) + expect(beforeLoad).toHaveBeenCalledTimes(1) + }) + + test('client beforeLoad redirect stays current during rewritten navigation', async () => { + const rewrite = { + input: ({ url }) => { + if (url.pathname.startsWith('/en/')) { + url.pathname = url.pathname.slice(3) + } + return url + }, + output: ({ url }) => { + url.pathname = `/en${url.pathname}` + return url + }, + } satisfies LocationRewrite + const beforeLoad = vi.fn(() => { + throw redirect({ to: '/about' }) + }) + const rootRoute = new BaseRootRoute({}) + const redirectRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/redirect', + beforeLoad, + }) + const aboutRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/about', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([redirectRoute, aboutRoute]), + history: createMemoryHistory({ initialEntries: ['/en/'] }), + rewrite, + isServer: false, + }) + + await router.load() + await router.navigate({ to: '/redirect' }) + + await vi.waitFor(() => + expect(router.state.location.publicHref).toBe('/en/about'), + ) + expect(beforeLoad).toHaveBeenCalledTimes(1) + }) + + test.each([false, true])( + 'handles %s async returned notFounds from beforeLoad', + async (asyncReturn) => { + const loader = vi.fn() + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + beforeLoad: () => { + const result = notFound() + return asyncReturn ? Promise.resolve(result) : result + }, + loader, + notFoundComponent: () => null, + }) + + const routeTree = rootRoute.addChildren([fooRoute]) + const router = createTestRouter({ + routeTree, + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/foo' }) + + const match = router.state.matches.find((m) => m.routeId === fooRoute.id) + expect(match?.status).toBe('notFound') + expect(loader).not.toHaveBeenCalled() + }, + ) + + test.each([false, true])( + 'exec if %s async returned preload redirect from beforeLoad', + async (asyncReturn) => { + const beforeLoad = vi.fn(({ preload }) => { + if (preload) { + const result = redirect({ to: '/bar' }) + return asyncReturn ? Promise.resolve(result) : result + } + return undefined + }) + const router = setup({ beforeLoad }) + + await router.preloadRoute({ to: '/foo' }) + expect( + router.stores.cachedMatches.get().some((d) => d.id === '/foo/foo'), + ).toBe(false) + + await router.navigate({ to: '/foo' }) + + expect(router.state.location.pathname).toBe('/foo') + expect(beforeLoad).toHaveBeenCalledTimes(2) + }, + ) + + test.each([false, true])( + 'exec if %s async returned preload notFound from beforeLoad', + async (asyncReturn) => { + const beforeLoad = vi.fn(({ preload }) => { + if (preload) { + const result = notFound() + return asyncReturn ? Promise.resolve(result) : result + } + return undefined + }) + const router = setup({ beforeLoad }) + + await router.preloadRoute({ to: '/foo' }) + expect( + router.stores.cachedMatches.get().some((d) => d.id === '/foo/foo'), + ).toBe(false) + await router.navigate({ to: '/foo' }) + + expect(router.state.location.pathname).toBe('/foo') + expect(beforeLoad).toHaveBeenCalledTimes(2) + }, + ) + test('exec if resolved preload (success)', async () => { const beforeLoad = vi.fn() const router = setup({ beforeLoad }) @@ -227,9 +1081,7 @@ describe('beforeLoad skip or exec', () => { const router = setup({ beforeLoad }) router.preloadRoute({ to: '/foo' }) await Promise.resolve() - expect(router.stores.cachedMatches.get()).toEqual( - expect.arrayContaining([expect.objectContaining({ id: '/foo/foo' })]), - ) + expect(router.stores.cachedMatches.get()).toEqual([]) await router.navigate({ to: '/foo' }) expect(beforeLoad).toHaveBeenCalledTimes(2) @@ -275,14 +1127,14 @@ describe('beforeLoad skip or exec', () => { }) await router.preloadRoute({ to: '/foo' }) expect( - router.stores.cachedMatches.get().some((d) => d.status === 'redirected'), + router.stores.cachedMatches.get().some((d) => d.id === '/foo/foo'), ).toBe(false) await sleep(10) await router.navigate({ to: '/foo' }) expect(router.state.location.pathname).toBe('/foo') expect( - router.stores.cachedMatches.get().some((d) => d.status === 'redirected'), + router.stores.cachedMatches.get().some((d) => d.id === '/foo/foo'), ).toBe(false) expect(beforeLoad).toHaveBeenCalledTimes(2) }) @@ -297,14 +1149,11 @@ describe('beforeLoad skip or exec', () => { }) router.preloadRoute({ to: '/foo' }) await Promise.resolve() - expect( - router.stores.cachedMatches.get().some((d) => d.status === 'redirected'), - ).toBe(false) await router.navigate({ to: '/foo' }) expect(router.state.location.pathname).toBe('/foo') expect( - router.stores.cachedMatches.get().some((d) => d.status === 'redirected'), + router.stores.cachedMatches.get().some((d) => d.id === '/foo/foo'), ).toBe(false) expect(beforeLoad).toHaveBeenCalledTimes(2) }) @@ -355,10 +1204,1920 @@ describe('beforeLoad skip or exec', () => { expect(parentBeforeLoad).toHaveBeenCalledTimes(1) expect(childBeforeLoad).not.toHaveBeenCalled() + expect(parentHead).not.toHaveBeenCalled() + expect(childHead).not.toHaveBeenCalled() + }) + + test('preload descendant waits for active parent beforeLoad context', async () => { + const parentBeforeLoadPromise = createControlledPromise<{ auth: string }>() + const parentBeforeLoad = vi.fn(() => parentBeforeLoadPromise) + const childLoader = vi.fn(({ context }) => context) + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + beforeLoad: parentBeforeLoad, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: childLoader, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory(), + }) + + const navigation = router.navigate({ to: '/parent' }) + await Promise.resolve() + expect(parentBeforeLoad).toHaveBeenCalledTimes(1) + + const preload = router.preloadRoute({ to: '/parent/child' }) + await Promise.resolve() + expect(childLoader).not.toHaveBeenCalled() + + parentBeforeLoadPromise.resolve({ auth: 'ok' }) + await navigation + await preload + + expect(childLoader).toHaveBeenCalledTimes(1) + expect(childLoader.mock.calls[0]?.[0].context).toMatchObject({ + auth: 'ok', + }) + }) + + test('joined preload waits for borrowed parent success while a sibling is still loading', async () => { + const siblingLoaderPromise = createControlledPromise() + const parentLoader = vi.fn(() => ({ auth: 'ok' })) + const siblingLoader = vi.fn(() => siblingLoaderPromise) + const childLoader = vi.fn(() => ({ child: 'preloaded' })) + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: parentLoader, + }) + const siblingRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/sibling', + loader: siblingLoader, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: childLoader, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([siblingRoute, childRoute]), + ]), + history: createMemoryHistory(), + }) + + await router.load() + + const navigation = router.navigate({ to: '/parent/sibling' }) + await vi.waitFor(() => expect(siblingLoader).toHaveBeenCalledTimes(1)) + + const preloadSettled = vi.fn() + const preload = router.preloadRoute({ to: '/parent/child' }) + preload.then(preloadSettled) + await Promise.resolve() + + expect(childLoader).not.toHaveBeenCalled() + expect(preloadSettled).not.toHaveBeenCalled() + + siblingLoaderPromise.resolve() + await Promise.all([navigation, preload]) + + expect(childLoader).toHaveBeenCalledTimes(1) + expect(preloadSettled).toHaveBeenCalledTimes(1) + }) + + test('joined preload waits for borrowed terminal error to commit', async () => { + const parentError = new Error('parent failed') + const parentLoader = vi.fn(() => { + throw parentError + }) + const childLoader = vi.fn(() => ({ child: 'preloaded' })) + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: parentLoader, + errorComponent: () => null, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: childLoader, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory(), + }) + const finalCommit = gateFinalCommit(router) + + try { + const navigation = router.navigate({ to: '/parent' }) + await vi.waitFor(() => expect(finalCommit.started).toHaveBeenCalled()) + + const preloadSettled = vi.fn() + const preload = router.preloadRoute({ to: '/parent/child' }) + preload.then(preloadSettled) + await Promise.resolve() + + expect(preloadSettled).not.toHaveBeenCalled() + expect(childLoader).not.toHaveBeenCalled() + + finalCommit.gate.resolve() + const [, preloadResult] = await Promise.all([navigation, preload]) + + expect(preloadSettled).toHaveBeenCalledTimes(1) + expect(preloadResult).toBeUndefined() + expect(childLoader).not.toHaveBeenCalled() + } finally { + finalCommit.restore() + } + }) + + test('preload canceled by borrowed redirect projects no assets and caches nothing', async () => { + vi.useFakeTimers() + + try { + let rejectParent!: (error: unknown) => void + const parentLoader = vi.fn( + () => + new Promise((_resolve, reject) => { + rejectParent = reject + }), + ) + const childLoader = vi.fn(() => ({ child: 'preloaded' })) + const childHead = vi.fn(() => ({})) + const targetLoader = vi.fn(() => ({ target: true })) + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: parentLoader, + pendingMs: 1, + pendingComponent: {}, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: childLoader, + head: childHead, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + loader: targetLoader, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + targetRoute, + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + + const navigation = router.navigate({ to: '/parent' }) + await vi.waitFor(() => expect(parentLoader).toHaveBeenCalledTimes(1)) + + await vi.advanceTimersByTimeAsync(1) + await vi.waitFor(() => + expect( + router.state.matches.some( + (match) => + match.routeId === parentRoute.id && match.status === 'pending', + ), + ).toBe(true), + ) + + const preload = router.preloadRoute({ to: '/parent/child' }) + await Promise.resolve() + + expect(childLoader).not.toHaveBeenCalled() + expect(childHead).not.toHaveBeenCalled() + + rejectParent(redirect({ to: '/target' })) + const [, preloadResult] = await Promise.all([navigation, preload]) + + expect(router.state.location.pathname).toBe('/target') + expect(preloadResult).toBeUndefined() + expect(childLoader).not.toHaveBeenCalled() + expect(childHead).not.toHaveBeenCalled() + expect(targetLoader).toHaveBeenCalledTimes(1) + expect( + router.stores.cachedMatches + .get() + .some((match) => match.routeId === childRoute.id), + ).toBe(false) + } finally { + vi.useRealTimers() + } + }) + + test('joined preload waits for borrowed notFound to commit', async () => { + const parentLoader = vi.fn(() => notFound()) + const childLoader = vi.fn(() => ({ child: 'preloaded' })) + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: parentLoader, + notFoundComponent: () => null, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: childLoader, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory(), + }) + const finalCommit = gateFinalCommit(router) + + try { + const navigation = router.navigate({ to: '/parent' }) + await vi.waitFor(() => expect(finalCommit.started).toHaveBeenCalled()) + + const preloadSettled = vi.fn() + const preload = router.preloadRoute({ to: '/parent/child' }) + preload.then(preloadSettled) + await Promise.resolve() + + expect(preloadSettled).not.toHaveBeenCalled() + expect(childLoader).not.toHaveBeenCalled() + + finalCommit.gate.resolve() + const [, preloadResult] = await Promise.all([navigation, preload]) + + expect(preloadSettled).toHaveBeenCalledTimes(1) + expect(preloadResult).toBeUndefined() + expect(childLoader).not.toHaveBeenCalled() + } finally { + finalCommit.restore() + } + }) + + test('preload canceled by borrowed notFound does not load the borrowed boundary component', async () => { + const notFoundPreload = vi.fn() + const parentLoader = vi.fn(() => notFound()) + const childLoader = vi.fn(() => ({ child: 'preloaded' })) + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: parentLoader, + notFoundComponent: { preload: notFoundPreload } as any, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: childLoader, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory(), + }) + const finalCommit = gateFinalCommit(router) + + try { + const navigation = router.navigate({ to: '/parent' }) + await vi.waitFor(() => expect(finalCommit.started).toHaveBeenCalled()) + expect(notFoundPreload).toHaveBeenCalledTimes(1) + + const preload = router.preloadRoute({ to: '/parent/child' }) + await Promise.resolve() + + expect(childLoader).not.toHaveBeenCalled() + expect(notFoundPreload).toHaveBeenCalledTimes(1) + + finalCommit.gate.resolve() + const [, preloadResult] = await Promise.all([navigation, preload]) + + expect(preloadResult).toBeUndefined() + expect(childLoader).not.toHaveBeenCalled() + expect(notFoundPreload).toHaveBeenCalledTimes(1) + expect( + router.stores.cachedMatches + .get() + .some((match) => match.routeId === childRoute.id), + ).toBe(false) + } finally { + finalCommit.restore() + } + }) + + test('preload canceled by borrowed owner disappearance projects no assets and caches nothing', async () => { + const parentLoader = vi.fn(() => ({ auth: 'ok' })) + const childLoader = vi.fn(() => ({ child: 'preloaded' })) + const childHead = vi.fn(() => ({})) + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: parentLoader, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: childLoader, + head: childHead, + }) + const otherRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/other', + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + otherRoute, + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + + const finalCommit = gateFinalCommit(router) + try { + const parentNavigation = router.navigate({ to: '/parent' }) + await vi.waitFor(() => expect(finalCommit.started).toHaveBeenCalled()) + + const preload = router.preloadRoute({ to: '/parent/child' }) + await Promise.resolve() + expect(childLoader).not.toHaveBeenCalled() + + const otherNavigation = router.navigate({ to: '/other' }) + finalCommit.gate.resolve() + const [, , preloadResult] = await Promise.all([ + parentNavigation, + otherNavigation, + preload, + ]) + + expect(router.state.location.pathname).toBe('/other') + expect(preloadResult).toBeUndefined() + expect(childLoader).not.toHaveBeenCalled() + expect(childHead).not.toHaveBeenCalled() + expect( + router.stores.cachedMatches + .get() + .some((match) => match.routeId === childRoute.id), + ).toBe(false) + } finally { + finalCommit.restore() + } + }) + + test('preload does not continue loader-owned descendants when joined active beforeLoad owner exits before settling', async () => { + vi.useFakeTimers() + const consoleError = vi + .spyOn(console, 'error') + .mockImplementation(() => undefined) + + try { + const parentBeforeLoadPromise = createControlledPromise<{ + auth: string + }>() + const parentBeforeLoad = vi.fn(() => parentBeforeLoadPromise) + const childBeforeLoad = vi.fn() + const childLoader = vi.fn(() => undefined) + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + beforeLoad: parentBeforeLoad, + pendingMs: 1, + pendingComponent: {}, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + beforeLoad: childBeforeLoad, + loader: childLoader, + }) + const otherRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/other', + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + otherRoute, + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + + const parentNavigation = router.navigate({ to: '/parent' }) + await vi.waitFor(() => expect(parentBeforeLoad).toHaveBeenCalledTimes(1)) + + await vi.advanceTimersByTimeAsync(1) + await vi.waitFor(() => + expect( + router.state.matches.some( + (match) => + match.routeId === parentRoute.id && match.status === 'pending', + ), + ).toBe(true), + ) + + const preload = router.preloadRoute({ to: '/parent/child' }) + await Promise.resolve() + expect(childBeforeLoad).not.toHaveBeenCalled() + + expect( + router.stores.cachedMatches + .get() + .some((match) => match.routeId === childRoute.id), + ).toBe(false) + + await router.navigate({ to: '/other' }) + + parentBeforeLoadPromise.resolve({ auth: 'late' }) + await Promise.all([parentNavigation, preload]) + + expect(router.state.location.pathname).toBe('/other') + expect(childBeforeLoad).not.toHaveBeenCalled() + expect(childLoader).not.toHaveBeenCalled() + expect( + router.stores.cachedMatches + .get() + .some((match) => match.routeId === childRoute.id), + ).toBe(false) + } finally { + consoleError.mockRestore() + vi.useRealTimers() + } + }) + + test('beforeLoad error commits only the renderable match prefix', async () => { + const parentHead = vi.fn(({ match }) => ({ + meta: [{ title: match.error ? 'Parent error' : 'Parent success' }], + })) + const childHead = vi.fn(() => ({ + meta: [{ title: 'Child success' }], + })) + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + validateSearch: (search: Record) => ({ + fail: search.fail === true || search.fail === 'true', + }), + beforeLoad: ({ search }) => { + if (search.fail) { + throw new Error('Parent beforeLoad failed') + } + }, + head: parentHead, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + head: childHead, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ + initialEntries: ['/parent/child?fail=false'], + }), + }) + + await router.load() + + expect(router.state.matches.map((match) => match.routeId)).toContain( + childRoute.id, + ) + expect(childHead).toHaveBeenCalledTimes(1) + + await router.navigate({ + to: '/parent/child', + search: { fail: true }, + } as never) + + expect(router.state.matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + parentRoute.id, + ]) + expect( + router.state.matches.find((match) => match.routeId === parentRoute.id) + ?.status, + ).toBe('error') + expect(parentHead).toHaveBeenCalledTimes(2) + expect(childHead).toHaveBeenCalledTimes(1) + }) + + test('loader error commits only the renderable match prefix', async () => { + const parentHead = vi.fn(({ match }) => ({ + meta: [{ title: match.error ? 'Parent error' : 'Parent success' }], + })) + const childHead = vi.fn(() => ({ + meta: [{ title: 'Child success' }], + })) + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + validateSearch: (search: Record) => ({ + fail: search.fail === true || search.fail === 'true', + }), + loaderDeps: ({ search }) => ({ fail: search.fail }), + loader: (({ deps }) => { + if ((deps as { fail?: boolean }).fail) { + throw new Error('Parent loader failed') + } + }) as LoaderFn, + head: parentHead, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + head: childHead, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ + initialEntries: ['/parent/child?fail=false'], + }), + }) + + await router.load() + + expect(router.state.matches.map((match) => match.routeId)).toContain( + childRoute.id, + ) + expect(childHead).toHaveBeenCalledTimes(1) + + await router.navigate({ + to: '/parent/child', + search: { fail: true }, + } as never) + + expect(router.state.matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + parentRoute.id, + ]) + expect( + router.state.matches.find((match) => match.routeId === parentRoute.id) + ?.status, + ).toBe('error') + expect(parentHead).toHaveBeenCalledTimes(2) + expect(childHead).toHaveBeenCalledTimes(1) + }) + + test('loader errors trim to the shallowest failed match when child fails first', async () => { + const parentGate = createControlledPromise() + const parentHead = vi.fn(({ match }) => ({ + meta: [{ title: match.error ? 'Parent error' : 'Parent success' }], + })) + const childHead = vi.fn(() => ({ + meta: [{ title: 'Child error' }], + })) + const parentLoader = vi.fn(async () => { + await parentGate + throw new Error('Parent loader failed') + }) + const childLoader = vi.fn(() => { + throw new Error('Child loader failed') + }) + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: parentLoader, + head: parentHead, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: childLoader, + head: childHead, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory(), + }) + + const navigation = router.navigate({ to: '/parent/child' }) + await vi.waitFor(() => expect(childLoader).toHaveBeenCalledTimes(1)) + + parentGate.resolve() + await navigation + + expect(router.state.matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + parentRoute.id, + ]) + expect( + router.state.matches.find((match) => match.routeId === parentRoute.id) + ?.status, + ).toBe('error') expect(parentHead).toHaveBeenCalledTimes(1) expect(childHead).not.toHaveBeenCalled() }) + test('latest load trims when it joins an existing parent loader that later errors', async () => { + const parentGate = createControlledPromise() + const parentLoader = vi.fn(async () => { + await parentGate + throw new Error('Parent loader failed') + }) + const childHead = vi.fn(() => ({ + meta: [{ title: 'Child should not render' }], + })) + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: parentLoader, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + head: childHead, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory(), + }) + + const staleNavigation = router.navigate({ to: '/parent/child' }) + await vi.waitFor(() => expect(parentLoader).toHaveBeenCalledTimes(1)) + + const latestLoad = router.load() + parentGate.resolve() + await Promise.allSettled([staleNavigation, latestLoad]) + + expect(parentLoader).toHaveBeenCalledTimes(2) + expect(router.state.matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + parentRoute.id, + ]) + expect( + router.state.matches.find((match) => match.routeId === parentRoute.id) + ?.status, + ).toBe('error') + expect(childHead).not.toHaveBeenCalled() + }) + ;[ + { name: 'false', value: false }, + { name: '0', value: 0 }, + { name: 'empty string', value: '' }, + { name: 'null', value: null }, + { name: 'undefined', value: undefined }, + ].forEach(({ name, value }) => { + test(`latest load trims when it joins a parent loader that rejects with ${name}`, async () => { + const parentGate = createControlledPromise() + const parentLoader = vi.fn(async () => { + await parentGate + throw value + }) + const childHead = vi.fn(() => ({ + meta: [{ title: 'Child should not render' }], + })) + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: parentLoader, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + head: childHead, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory(), + }) + + const staleNavigation = router.navigate({ to: '/parent/child' }) + await vi.waitFor(() => expect(parentLoader).toHaveBeenCalledTimes(1)) + + const latestLoad = router.load() + parentGate.resolve() + await Promise.allSettled([staleNavigation, latestLoad]) + + const parentMatch = router.state.matches.find( + (match) => match.routeId === parentRoute.id, + ) + const expectedError = + value === undefined + ? expect.objectContaining({ + message: 'Route load failed with undefined', + }) + : value + + expect(parentLoader).toHaveBeenCalledTimes(2) + expect(router.state.matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + parentRoute.id, + ]) + expect(parentMatch?.status).toBe('error') + expect(parentMatch?.error).toEqual(expectedError) + expect(childHead).not.toHaveBeenCalled() + }) + }) + + test('pending publication runs no lifecycle or cache reconciliation before beforeLoad error final commit', async () => { + vi.useFakeTimers() + + try { + const beforeLoadGate = createControlledPromise() + const parentOnEnter = vi.fn() + const parentOnStay = vi.fn() + const childOnEnter = vi.fn() + const childOnLeave = vi.fn() + const parentBeforeLoad = vi.fn(async () => { + await beforeLoadGate + throw new Error('Parent beforeLoad failed') + }) + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + beforeLoad: parentBeforeLoad, + pendingMs: 1, + pendingComponent: {}, + onEnter: parentOnEnter, + onStay: parentOnStay, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + onEnter: childOnEnter, + onLeave: childOnLeave, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory(), + }) + const setPending = vi.spyOn(router.stores, 'setPending') + const setCached = vi.spyOn(router.stores, 'setCached') + const setLoadedAt = vi.spyOn(router.stores.loadedAt, 'set') + const setIsLoading = vi.spyOn(router.stores.isLoading, 'set') + + const navigation = router.navigate({ to: '/parent/child' }) + await vi.waitFor(() => expect(parentBeforeLoad).toHaveBeenCalledTimes(1)) + + const setCachedBeforePending = setCached.mock.calls.length + const setLoadedAtBeforePending = setLoadedAt.mock.calls.length + const setIsLoadingBeforePending = setIsLoading.mock.calls.length + + await vi.advanceTimersByTimeAsync(1) + await vi.waitFor(() => + expect(router.state.matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + parentRoute.id, + childRoute.id, + ]), + ) + const setPendingAfterPending = setPending.mock.calls.length + const setCachedAfterPending = setCached.mock.calls.length + const setLoadedAtAfterPending = setLoadedAt.mock.calls.length + const setIsLoadingAfterPending = setIsLoading.mock.calls.length + + expect(parentOnEnter).not.toHaveBeenCalled() + expect(parentOnStay).not.toHaveBeenCalled() + expect(childOnEnter).not.toHaveBeenCalled() + expect(childOnLeave).not.toHaveBeenCalled() + expect(setCached).toHaveBeenCalledTimes(setCachedBeforePending) + expect(setLoadedAt).toHaveBeenCalledTimes(setLoadedAtBeforePending) + expect(setIsLoading).toHaveBeenCalledTimes(setIsLoadingBeforePending) + + beforeLoadGate.resolve() + await navigation + + expect(router.state.matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + parentRoute.id, + ]) + expect( + router.state.matches.find((match) => match.routeId === parentRoute.id) + ?.status, + ).toBe('error') + expect(parentOnEnter).toHaveBeenCalledTimes(1) + expect(parentOnStay).not.toHaveBeenCalled() + expect(childOnEnter).not.toHaveBeenCalled() + expect(childOnLeave).not.toHaveBeenCalled() + expect(setPending).toHaveBeenCalledTimes(setPendingAfterPending) + expect(setCached).toHaveBeenCalledTimes(setCachedAfterPending + 1) + expect(setLoadedAt).toHaveBeenCalledTimes(setLoadedAtAfterPending + 1) + expect(setIsLoading).toHaveBeenCalledTimes(setIsLoadingAfterPending + 1) + } finally { + vi.restoreAllMocks() + vi.useRealTimers() + } + }) + + test('loader error commits final renderable prefix after pending UI renders', async () => { + vi.useFakeTimers() + + try { + const loaderGate = createControlledPromise() + const parentLoader = vi.fn(async () => { + await loaderGate + throw new Error('Parent loader failed') + }) + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: parentLoader, + pendingMs: 1, + pendingComponent: {}, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory(), + }) + + const navigation = router.navigate({ to: '/parent/child' }) + await vi.waitFor(() => expect(parentLoader).toHaveBeenCalledTimes(1)) + + await vi.advanceTimersByTimeAsync(1) + await vi.waitFor(() => + expect(router.state.matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + parentRoute.id, + childRoute.id, + ]), + ) + + loaderGate.resolve() + await navigation + + expect(router.state.matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + parentRoute.id, + ]) + expect( + router.state.matches.find((match) => match.routeId === parentRoute.id) + ?.status, + ).toBe('error') + } finally { + vi.useRealTimers() + } + }) + + test('loader success after pending UI renders performs final reconciliation once', async () => { + vi.useFakeTimers() + + try { + const loaderGate = createControlledPromise() + const parentLoader = vi.fn(async () => { + await loaderGate + }) + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: parentLoader, + pendingMs: 1, + pendingComponent: {}, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory(), + }) + const setMatches = vi.spyOn(router.stores, 'setMatches') + const setCached = vi.spyOn(router.stores, 'setCached') + + const navigation = router.navigate({ to: '/parent/child' }) + await vi.waitFor(() => expect(parentLoader).toHaveBeenCalledTimes(1)) + + await vi.advanceTimersByTimeAsync(1) + await vi.waitFor(() => + expect(router.state.matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + parentRoute.id, + childRoute.id, + ]), + ) + const setMatchesAfterPending = setMatches.mock.calls.length + const setCachedAfterPending = setCached.mock.calls.length + + loaderGate.resolve() + await navigation + + expect(router.state.matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + parentRoute.id, + childRoute.id, + ]) + expect(setMatches).toHaveBeenCalledTimes(setMatchesAfterPending + 1) + expect(setCached).toHaveBeenCalledTimes(setCachedAfterPending + 1) + } finally { + vi.restoreAllMocks() + vi.useRealTimers() + } + }) + + test('pending publication does not consume the final view transition', async () => { + vi.useFakeTimers() + + try { + const loaderGate = createControlledPromise<{ value: string }>() + const childLoader = vi.fn(() => loaderGate) + + const rootRoute = new BaseRootRoute({}) + const childRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/child', + loader: childLoader, + pendingMs: 1, + pendingComponent: {}, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([childRoute]), + history: createMemoryHistory(), + }) + + const startViewTransition = vi.spyOn(router, 'startViewTransition') + + const navigation = router.navigate({ + to: '/child', + viewTransition: true, + }) + await vi.waitFor(() => expect(childLoader).toHaveBeenCalledTimes(1)) + + await vi.advanceTimersByTimeAsync(1) + await vi.waitFor(() => { + const childMatch = router.state.matches.find( + (match) => match.routeId === childRoute.id, + ) + expect(childMatch?.status).toBe('pending') + }) + expect(startViewTransition).not.toHaveBeenCalled() + expect(router.shouldViewTransition).toBe(true) + + loaderGate.resolve({ value: 'fresh' }) + await navigation + + const childMatch = router.state.matches.find( + (match) => match.routeId === childRoute.id, + ) + expect(childMatch?.status).toBe('success') + expect(childMatch?.loaderData).toEqual({ value: 'fresh' }) + expect(startViewTransition).toHaveBeenCalledTimes(1) + } finally { + vi.restoreAllMocks() + vi.useRealTimers() + } + }) + + test("stale onReady does not consume a newer navigation's view transition", async () => { + vi.useFakeTimers() + + try { + const slowGate = createControlledPromise() + const fastGate = createControlledPromise() + const slowLoader = vi.fn(() => slowGate) + const fastLoader = vi.fn(() => fastGate) + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const slowRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/slow', + loader: slowLoader, + pendingMs: 0, + pendingComponent: {}, + }) + const fastRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/fast', + loader: fastLoader, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, slowRoute, fastRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + await router.load() + + const startViewTransition = vi.spyOn(router, 'startViewTransition') + + const staleNavigation = router.navigate({ to: '/slow' }) + await vi.waitFor(() => expect(slowLoader).toHaveBeenCalledTimes(1)) + + await vi.advanceTimersByTimeAsync(0) + await vi.waitFor(() => + expect(router.state.location.pathname).toBe('/slow'), + ) + expect(startViewTransition).not.toHaveBeenCalled() + + const latestNavigation = router.navigate({ + to: '/fast', + viewTransition: true, + }) + await vi.waitFor(() => expect(fastLoader).toHaveBeenCalledTimes(1)) + + slowGate.resolve() + fastGate.resolve() + await Promise.all([staleNavigation, latestNavigation]) + + expect(startViewTransition).toHaveBeenCalledTimes(1) + } finally { + vi.restoreAllMocks() + vi.useRealTimers() + } + }) + + test('redirect resolving while the render-ready commit is pending does not lose or duplicate that commit', async () => { + vi.useFakeTimers() + + try { + const slowGate = createControlledPromise() + const slowLoader = vi.fn(() => slowGate) + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const slowRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/slow', + loader: slowLoader, + pendingMs: 0, + pendingComponent: {}, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, slowRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + await router.load() + + const startViewTransition = vi.spyOn(router, 'startViewTransition') + + const navigation = router.navigate({ to: '/slow' }) + await vi.waitFor(() => expect(slowLoader).toHaveBeenCalledTimes(1)) + + await vi.advanceTimersByTimeAsync(0) + await vi.waitFor(() => + expect(router.state.location.pathname).toBe('/slow'), + ) + expect(startViewTransition).not.toHaveBeenCalled() + + slowGate.resolve(redirect({ to: '/target' })) + await vi.waitFor(() => + expect(router.state.location.pathname).toBe('/target'), + ) + + await navigation + + expect(router.state.location.pathname).toBe('/target') + expect(router.state.matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + targetRoute.id, + ]) + } finally { + vi.restoreAllMocks() + vi.useRealTimers() + } + }) + + test("stale final trim does not disable a newer navigation's view transition", async () => { + vi.useFakeTimers() + + try { + const parentGate = createControlledPromise() + const fastGate = createControlledPromise() + const parentBeforeLoad = vi.fn(async () => { + await parentGate + throw new Error('Parent beforeLoad failed') + }) + const fastLoader = vi.fn(() => fastGate) + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + beforeLoad: parentBeforeLoad, + pendingMs: 0, + pendingComponent: {}, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + }) + const fastRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/fast', + loader: fastLoader, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + fastRoute, + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + await router.load() + + const startViewTransition = vi.spyOn(router, 'startViewTransition') + + const staleNavigation = router.navigate({ to: '/parent/child' }) + await vi.waitFor(() => expect(parentBeforeLoad).toHaveBeenCalledTimes(1)) + + await vi.advanceTimersByTimeAsync(0) + await vi.waitFor(() => + expect(router.state.location.pathname).toBe('/parent/child'), + ) + expect(startViewTransition).not.toHaveBeenCalled() + + const latestNavigation = router.navigate({ + to: '/fast', + viewTransition: true, + }) + await vi.waitFor(() => expect(fastLoader).toHaveBeenCalledTimes(1)) + + parentGate.resolve() + await Promise.resolve() + await Promise.resolve() + + expect(startViewTransition).not.toHaveBeenCalled() + expect(router.shouldViewTransition).toBe(true) + + fastGate.resolve() + await Promise.all([staleNavigation, latestNavigation]) + + expect(startViewTransition).toHaveBeenCalledTimes(1) + } finally { + vi.restoreAllMocks() + vi.useRealTimers() + } + }) + + test('final parent loader-error trim does not cache a dropped successful child', async () => { + vi.useFakeTimers() + + try { + const parentGate = createControlledPromise() + const parentLoader = vi.fn(async () => { + await parentGate + throw new Error('Parent loader failed') + }) + const childLoader = vi.fn(() => ({ value: 'child' })) + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: parentLoader, + pendingMs: 1, + pendingComponent: {}, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: childLoader, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory(), + }) + + const navigation = router.navigate({ to: '/parent/child' }) + await vi.waitFor(() => expect(parentLoader).toHaveBeenCalledTimes(1)) + + await vi.advanceTimersByTimeAsync(1) + await vi.waitFor(() => { + const childMatch = router.state.matches.find( + (match) => match.routeId === childRoute.id, + ) + expect(childMatch?.status).toBe('success') + }) + + parentGate.resolve() + await navigation + + expect(router.state.matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + parentRoute.id, + ]) + expect( + router.stores.cachedMatches + .get() + .some((match) => match.routeId === childRoute.id), + ).toBe(false) + } finally { + vi.useRealTimers() + } + }) + + test('preload from onBeforeLoad waits for active root beforeLoad context', async () => { + vi.useFakeTimers() + + try { + const rootBeforeLoadPromise = createControlledPromise<{ auth: string }>() + const rootBeforeLoad = vi.fn(() => rootBeforeLoadPromise) + const childLoader = vi.fn(({ context }) => context) + + const rootRoute = new BaseRootRoute({ + beforeLoad: rootBeforeLoad, + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: childLoader, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory(), + }) + + let preload: ReturnType | undefined + const unsubscribe = router.subscribe('onBeforeLoad', (event) => { + if (!preload && event.toLocation.pathname === '/parent') { + preload = router.preloadRoute({ to: '/parent/child' }) + } + }) + + try { + const navigation = router.navigate({ to: '/parent' }) + await vi.advanceTimersByTimeAsync(0) + + expect(rootBeforeLoad).toHaveBeenCalledTimes(1) + expect(childLoader).not.toHaveBeenCalled() + + rootBeforeLoadPromise.resolve({ auth: 'ok' }) + await navigation + await preload + + expect(childLoader).toHaveBeenCalledTimes(1) + expect(childLoader.mock.calls[0]?.[0].context).toMatchObject({ + auth: 'ok', + }) + } finally { + unsubscribe() + } + } finally { + vi.useRealTimers() + } + }) + + test('preload descendant waits for active parent loader data', async () => { + vi.useFakeTimers() + + try { + const parentLoaderPromise = createControlledPromise<{ auth: string }>() + const unexpectedParentPreloadPromise = createControlledPromise<{ + auth: string + }>() + const parentLoader = vi.fn(({ preload }) => { + return preload ? unexpectedParentPreloadPromise : parentLoaderPromise + }) + let childLoaderSettled = false + const childLoader = vi.fn(async ({ parentMatchPromise }) => { + const parentMatch = (await parentMatchPromise) as any + childLoaderSettled = true + return parentMatch.loaderData + }) + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: parentLoader, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: childLoader, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory(), + }) + + const navigation = router.navigate({ to: '/parent' }) + await vi.waitFor(() => expect(parentLoader).toHaveBeenCalledTimes(1)) + + const preload = router.preloadRoute({ to: '/parent/child' }) + await vi.advanceTimersByTimeAsync(5) + expect(parentLoader).toHaveBeenCalledTimes(1) + expect(childLoader).not.toHaveBeenCalled() + expect(childLoaderSettled).toBe(false) + + parentLoaderPromise.resolve({ auth: 'ok' }) + await navigation + await preload + + expect(parentLoader).toHaveBeenCalledTimes(1) + expect(childLoaderSettled).toBe(true) + await expect(childLoader.mock.results[0]!.value).resolves.toEqual({ + auth: 'ok', + }) + } finally { + vi.useRealTimers() + } + }) + + test('preload does not start descendant loader when joined active loader owner exits before settling', async () => { + vi.useFakeTimers() + + try { + const parentLoaderPromise = createControlledPromise<{ auth: string }>() + const parentLoader = vi.fn(() => parentLoaderPromise) + let childLoaderSettled = false + const childLoader = vi.fn(async ({ parentMatchPromise }) => { + await parentMatchPromise + childLoaderSettled = true + }) + const childOnError = vi.fn() + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: parentLoader, + pendingMs: 1, + pendingComponent: {}, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: childLoader, + onError: childOnError, + }) + const otherRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/other', + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + otherRoute, + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + + const parentNavigation = router.navigate({ to: '/parent' }) + await vi.waitFor(() => expect(parentLoader).toHaveBeenCalledTimes(1)) + + const preload = router.preloadRoute({ to: '/parent/child' }) + await vi.advanceTimersByTimeAsync(5) + expect(parentLoader).toHaveBeenCalledTimes(1) + expect(childLoader).not.toHaveBeenCalled() + expect(childLoaderSettled).toBe(false) + + await router.navigate({ to: '/other' }) + + parentLoaderPromise.resolve({ auth: 'late' }) + await Promise.all([parentNavigation, preload]) + + expect(router.state.location.pathname).toBe('/other') + expect(childLoaderSettled).toBe(false) + expect(childOnError).not.toHaveBeenCalled() + expect( + router.stores.cachedMatches + .get() + .some((match) => match.routeId === childRoute.id), + ).toBe(false) + } finally { + vi.useRealTimers() + } + }) + + test('preload leaves no descendant cache when joined active loader owner exits', async () => { + vi.useFakeTimers() + + try { + const parentLoaderPromise = createControlledPromise<{ auth: string }>() + const parentLoader = vi.fn(() => parentLoaderPromise) + const childLoader = vi.fn(() => ({ child: 'preloaded' })) + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: parentLoader, + pendingMs: 1, + pendingComponent: {}, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: childLoader, + }) + const otherRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/other', + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + otherRoute, + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + + const parentNavigation = router.navigate({ to: '/parent' }) + await vi.waitFor(() => expect(parentLoader).toHaveBeenCalledTimes(1)) + + const preload = router.preloadRoute({ to: '/parent/child' }) + await Promise.resolve() + expect(childLoader).not.toHaveBeenCalled() + + await router.navigate({ to: '/other' }) + + parentLoaderPromise.resolve({ auth: 'late' }) + await Promise.all([parentNavigation, preload]) + + expect(router.state.location.pathname).toBe('/other') + expect( + router.stores.cachedMatches + .get() + .some((match) => match.routeId === childRoute.id), + ).toBe(false) + } finally { + vi.useRealTimers() + } + }) + + test('preload resolves when joined active loader owner exits with a never-settling descendant loader', async () => { + vi.useFakeTimers() + + try { + const parentLoaderPromise = createControlledPromise<{ auth: string }>() + const childLoaderPromise = createControlledPromise() + const parentLoader = vi.fn(() => parentLoaderPromise) + const childLoader = vi.fn(() => childLoaderPromise) + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: parentLoader, + pendingMs: 1, + pendingComponent: {}, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: childLoader, + }) + const otherRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/other', + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + otherRoute, + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + + const parentNavigation = router.navigate({ to: '/parent' }) + await vi.waitFor(() => expect(parentLoader).toHaveBeenCalledTimes(1)) + + const preloadSettled = vi.fn() + const preload = router.preloadRoute({ to: '/parent/child' }) + preload.then(preloadSettled) + await Promise.resolve() + expect(childLoader).not.toHaveBeenCalled() + + await router.navigate({ to: '/other' }) + + parentLoaderPromise.resolve({ auth: 'late' }) + await parentNavigation + await preload + + expect(preloadSettled).toHaveBeenCalledTimes(1) + expect(childLoader).not.toHaveBeenCalled() + expect( + router.stores.cachedMatches + .get() + .some((match) => match.routeId === childRoute.id), + ).toBe(false) + } finally { + vi.useRealTimers() + } + }) + + test('preload resolves when joined active loader owner exits with a never-settling descendant beforeLoad', async () => { + vi.useFakeTimers() + + try { + const parentLoaderPromise = createControlledPromise<{ auth: string }>() + const childBeforeLoadPromise = createControlledPromise() + const parentLoader = vi.fn(() => parentLoaderPromise) + const childBeforeLoad = vi.fn(() => childBeforeLoadPromise) + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: parentLoader, + pendingMs: 1, + pendingComponent: {}, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + beforeLoad: childBeforeLoad, + }) + const otherRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/other', + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + otherRoute, + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + + const parentNavigation = router.navigate({ to: '/parent' }) + await vi.waitFor(() => expect(parentLoader).toHaveBeenCalledTimes(1)) + + const preloadSettled = vi.fn() + const preload = router.preloadRoute({ to: '/parent/child' }) + preload.then(preloadSettled) + await Promise.resolve() + expect(childBeforeLoad).not.toHaveBeenCalled() + + await router.navigate({ to: '/other' }) + await vi.waitFor(() => expect(preloadSettled).toHaveBeenCalledTimes(1)) + + expect( + router.stores.cachedMatches + .get() + .some((match) => match.routeId === childRoute.id), + ).toBe(false) + + parentLoaderPromise.resolve({ auth: 'late' }) + childBeforeLoadPromise.resolve() + await Promise.all([parentNavigation, preload]) + } finally { + vi.useRealTimers() + } + }) + + test.each([ + { + name: 'without a never-settling descendant', + withNeverSettlingDescendant: false, + }, + { + name: 'with a never-settling descendant', + withNeverSettlingDescendant: true, + }, + ])( + 'preload cancellation skips descendant redirect after owner exit $name', + async ({ withNeverSettlingDescendant }) => { + vi.useFakeTimers() + const consoleError = vi + .spyOn(console, 'error') + .mockImplementation(() => undefined) + + try { + const parentLoaderPromise = createControlledPromise<{ auth: string }>() + const hangLoaderPromise = createControlledPromise() + const parentLoader = vi.fn(() => parentLoaderPromise) + const childLoader = vi.fn(() => { + throw redirect({ to: '/target' }) + }) + const hangLoader = vi.fn(() => hangLoaderPromise) + const targetLoader = vi.fn(() => undefined) + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: parentLoader, + pendingMs: 1, + pendingComponent: {}, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: childLoader, + }) + const hangRoute = new BaseRoute({ + getParentRoute: () => childRoute, + path: '/hang', + loader: hangLoader, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + loader: targetLoader, + }) + const otherRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/other', + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute.addChildren([hangRoute])]), + targetRoute, + otherRoute, + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + + const parentNavigation = router.navigate({ to: '/parent' }) + await vi.waitFor(() => expect(parentLoader).toHaveBeenCalledTimes(1)) + + const preloadSettled = vi.fn() + const preload = router.preloadRoute({ + to: withNeverSettlingDescendant + ? '/parent/child/hang' + : '/parent/child', + }) + preload.then(preloadSettled) + + await Promise.resolve() + expect(childLoader).not.toHaveBeenCalled() + expect(hangLoader).not.toHaveBeenCalled() + + await router.navigate({ to: '/other' }) + + parentLoaderPromise.resolve({ auth: 'late' }) + await parentNavigation + await vi.waitFor(() => expect(preloadSettled).toHaveBeenCalledTimes(1)) + + expect(router.state.location.pathname).toBe('/other') + expect(childLoader).not.toHaveBeenCalled() + expect(hangLoader).not.toHaveBeenCalled() + expect(targetLoader).not.toHaveBeenCalled() + expect(consoleError).not.toHaveBeenCalled() + } finally { + consoleError.mockRestore() + vi.useRealTimers() + } + }, + ) + + test('preload from onBeforeLoad waits for active parent loader data', async () => { + vi.useFakeTimers() + + try { + const parentLoaderPromise = createControlledPromise<{ auth: string }>() + const unexpectedParentPreloadPromise = createControlledPromise<{ + auth: string + }>() + const parentLoader = vi.fn(({ preload }) => { + return preload ? unexpectedParentPreloadPromise : parentLoaderPromise + }) + let childLoaderSettled = false + const childLoader = vi.fn(async ({ parentMatchPromise }) => { + const parentMatch = (await parentMatchPromise) as any + childLoaderSettled = true + return parentMatch.loaderData + }) + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: parentLoader, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: childLoader, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory(), + }) + + let preload: ReturnType | undefined + const unsubscribe = router.subscribe('onBeforeLoad', (event) => { + if (!preload && event.toLocation.pathname === '/parent') { + preload = router.preloadRoute({ to: '/parent/child' }) + } + }) + + try { + const navigation = router.navigate({ to: '/parent' }) + await vi.advanceTimersByTimeAsync(5) + + expect(parentLoader).toHaveBeenCalledTimes(1) + expect(childLoader).not.toHaveBeenCalled() + expect(childLoaderSettled).toBe(false) + + parentLoaderPromise.resolve({ auth: 'ok' }) + await navigation + await preload + + expect(parentLoader).toHaveBeenCalledTimes(1) + expect(childLoaderSettled).toBe(true) + await expect(childLoader.mock.results[0]!.value).resolves.toEqual({ + auth: 'ok', + }) + } finally { + unsubscribe() + } + } finally { + vi.useRealTimers() + } + }) + + test('does not execute detached head when loader throws notFound during preload', async () => { + const loader = vi.fn(({ preload }) => { + if (preload) { + throw notFound() + } + }) + const head = vi.fn(() => ({ meta: [{ title: 'Foo' }] })) + + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader, + head, + notFoundComponent: () => null, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute]), + history: createMemoryHistory(), + }) + + await router.preloadRoute({ to: '/foo' }) + + expect(loader).toHaveBeenCalledTimes(1) + expect(head).not.toHaveBeenCalled() + }) + + test('does not execute detached head when beforeLoad throws notFound during preload', async () => { + const beforeLoad = vi.fn(({ preload }) => { + if (preload) { + throw notFound() + } + }) + const head = vi.fn(() => ({ meta: [{ title: 'Foo' }] })) + + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + beforeLoad, + head, + notFoundComponent: () => null, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute]), + history: createMemoryHistory(), + }) + + await router.preloadRoute({ to: '/foo' }) + + expect(beforeLoad).toHaveBeenCalledTimes(1) + expect(head).not.toHaveBeenCalled() + }) + test('exec if pending preload (error)', async () => { const beforeLoad = vi.fn(async ({ preload }) => { await sleep(100) @@ -418,6 +3177,332 @@ describe('loader skip or exec', () => { expect(loader).toHaveBeenCalledTimes(0) }) + test('does not call shouldReload on initial pending load', async () => { + const loader = vi.fn() + const shouldReload = vi.fn(() => false) + + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader, + shouldReload, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute]), + history: createMemoryHistory({ initialEntries: ['/foo'] }), + }) + + await router.load() + + expect(loader).toHaveBeenCalledTimes(1) + expect(shouldReload).not.toHaveBeenCalled() + }) + + test('client forceStaleReload reloads stale same-url matches', async () => { + const loader = vi.fn(() => ({ loaded: true })) + const router = setup({ loader, staleTime: 0 }) + + await router.navigate({ to: '/foo' }) + await router.load({ sync: true }) + + expect(loader).toHaveBeenCalledTimes(2) + }) + + test('client blocking reload clears loaderData when loader returns undefined', async () => { + let loaderCalls = 0 + const loader = vi.fn(() => { + loaderCalls += 1 + return loaderCalls === 1 ? 'old' : undefined + }) + const head = vi.fn(({ loaderData }) => ({ + meta: [{ title: String(loaderData) }], + })) + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader, + head, + staleTime: 0, + gcTime: 60_000, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute]), + history: createMemoryHistory(), + defaultStaleReloadMode: 'blocking', + }) + + const getFooMatch = () => + router.state.matches.find((match) => match.routeId === fooRoute.id) + + await router.navigate({ to: '/foo' }) + expect(getFooMatch()?.loaderData).toBe('old') + expect(getFooMatch()?.meta).toEqual([{ title: 'old' }]) + + await router.load({ sync: true }) + + const match = getFooMatch() + expect(loader).toHaveBeenCalledTimes(2) + expect(match?.loaderData).toBeUndefined() + expect(match?.status).toBe('success') + expect(match?.meta).toEqual([{ title: 'undefined' }]) + }) + + test('server load ignores staleTime and shouldReload', async () => { + const loader = vi.fn(() => ({ loaded: true })) + const shouldReload = vi.fn(() => false) + + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader, + staleTime: Infinity, + shouldReload, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute]), + history: createMemoryHistory({ initialEntries: ['/foo'] }), + isServer: true, + }) + + await router.load() + await router.load({ sync: true }) + + expect(loader).toHaveBeenCalledTimes(2) + expect(shouldReload).not.toHaveBeenCalled() + }) + + test('preloading an active route joins the active match', async () => { + const loader = vi.fn(() => ({ source: 'active' })) + const router = setup({ loader }) + + await router.navigate({ to: '/foo' }) + expectNoCachedActiveOverlap(router) + + const activeMatch = router.state.matches.find((match) => + match.id.endsWith('/foo'), + )! + + const matches = await router.preloadRoute({ to: '/foo' }) + const preloadedMatch = matches?.find((match) => match.id === activeMatch.id) + + expect(loader).toHaveBeenCalledTimes(1) + expect(preloadedMatch?.loaderData).toEqual({ source: 'active' }) + expectNoCachedActiveOverlap(router) + }) + + test('active preload does not execute active head hooks', async () => { + const loader = vi.fn(() => ({ source: 'active' })) + const head = vi.fn(() => ({ meta: [{ title: 'Foo' }] })) + + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader, + head, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute]), + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/foo' }) + expect(head).toHaveBeenCalledTimes(1) + + await router.preloadRoute({ to: '/foo' }) + + expect(loader).toHaveBeenCalledTimes(1) + expect(head).toHaveBeenCalledTimes(1) + }) + + test('preload ownership may be non-contiguous when ancestor loaderDeps change', async () => { + const parentLoader = vi.fn(() => ({ source: 'parent' })) + const childLoader = vi.fn(() => ({ source: 'child' })) + const childHead = vi.fn(() => ({ meta: [{ title: 'Child' }] })) + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: parentLoader, + loaderDeps: ({ search }: { search: Record }) => ({ + parentVersion: search['parentVersion'], + }), + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: childLoader, + loaderDeps: () => ({ childVersion: 'stable' }), + head: childHead, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory(), + }) + + await router.navigate({ + to: '/parent/child', + search: { parentVersion: '1' }, + }) + expectNoCachedActiveOverlap(router) + + const activeParent = router.state.matches.find( + (match) => match.routeId === parentRoute.id, + )! + const activeChild = router.state.matches.find( + (match) => match.routeId === childRoute.id, + )! + + const preloadedMatches = await router.preloadRoute({ + to: '/parent/child', + search: { parentVersion: '2' }, + }) + + const preloadedParent = preloadedMatches?.find( + (match) => match.routeId === parentRoute.id, + )! + const preloadedChild = preloadedMatches?.find( + (match) => match.routeId === childRoute.id, + )! + + expect(preloadedParent.id).not.toBe(activeParent.id) + expect(preloadedChild.id).toBe(activeChild.id) + expect(parentLoader).toHaveBeenCalledTimes(2) + expect(childLoader).toHaveBeenCalledTimes(1) + expect(childHead).toHaveBeenCalledTimes(1) + expect( + router.stores.cachedMatches + .get() + .some((match) => match.id === activeChild.id), + ).toBe(false) + expectNoCachedActiveOverlap(router) + }) + + test('preloadRoute returns cache-owned matches with loaderData after load', async () => { + const loader = vi.fn(() => ({ source: 'preload' })) + const router = setup({ loader }) + + const matches = await router.preloadRoute({ to: '/foo' }) + const match = matches?.find((d) => d.id === '/foo/foo') + + expect(loader).toHaveBeenCalledTimes(1) + expect(match?.loaderData).toEqual({ source: 'preload' }) + }) + + test('navigation to a preloaded route commits head assets', async () => { + const loader = vi.fn(() => ({ title: 'Preloaded title' })) + const head = vi.fn(({ loaderData }) => ({ + meta: [{ title: loaderData.title }], + })) + + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader, + head, + staleTime: 60_000, + preloadStaleTime: 60_000, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute]), + history: createMemoryHistory(), + }) + + await router.preloadRoute({ to: '/foo' }) + await router.navigate({ to: '/foo' }) + + const match = router.state.matches.find((item) => item.id === '/foo/foo') + expect(loader).toHaveBeenCalledTimes(1) + expect(head).toHaveBeenCalled() + expect(match?.meta).toEqual([{ title: 'Preloaded title' }]) + }) + + test('head assetContext.matches sees lane-updated loaderData', async () => { + const parentLoader = vi.fn(() => ({ parent: 'data' })) + const seenParentLoaderData: Array = [] + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: parentLoader, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + head: ({ matches }) => { + seenParentLoaderData.push( + matches.find((match) => match.routeId === parentRoute.id)?.loaderData, + ) + return { meta: [{ title: 'Child' }] } + }, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory(), + }) + + await router.preloadRoute({ to: '/parent/child' }) + + expect(parentLoader).toHaveBeenCalledTimes(1) + expect(seenParentLoaderData).toEqual([{ parent: 'data' }]) + }) + + test('active redirect settles source loadPromise without cached ownership', async () => { + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader: () => redirect({ to: '/bar' }), + }) + const barRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/bar', + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute, barRoute]), + history: createMemoryHistory({ initialEntries: ['/foo'] }), + }) + + const location = router.latestLocation + const matches = router.matchRoutes(location) + const fooMatch = matches.find((match) => match.routeId === fooRoute.id)! + const activeLoadPromise = fooMatch._.loadPromise + + router.stores.setPending(matches) + expectNoCachedActiveOverlap(router) + + await expect( + loadMatches({ + router, + location, + matches, + }), + ).rejects.toMatchObject({ + options: expect.objectContaining({ to: '/bar' }), + }) + + expect(activeLoadPromise?.status).toBe('resolved') + expect(fooMatch._.loadPromise).toBeUndefined() + expect( + router.stores.cachedMatches + .get() + .some((match) => match.id === fooMatch.id), + ).toBe(false) + expectNoCachedActiveOverlap(router) + }) + test('exec on regular nav', async () => { const loader = vi.fn(() => Promise.resolve({ hello: 'world' })) const router = setup({ loader }) @@ -441,6 +3526,82 @@ describe('loader skip or exec', () => { expect(loader).toHaveBeenCalledTimes(1) }) + test.each([false, true])( + 'handles %s async returned redirects from loader', + async (asyncReturn) => { + const loader = vi.fn(() => { + const result = redirect({ to: '/bar' }) + return asyncReturn ? Promise.resolve(result) : result + }) + const router = setup({ loader }) + + await router.navigate({ to: '/foo' }) + + expect(router.state.location.pathname).toBe('/bar') + expect(loader).toHaveBeenCalledTimes(1) + }, + ) + + test.each([false, true])( + 'handles %s async returned notFounds from loader', + async (asyncReturn) => { + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader: () => { + const result = notFound() + return asyncReturn ? Promise.resolve(result) : result + }, + notFoundComponent: () => null, + }) + + const routeTree = rootRoute.addChildren([fooRoute]) + const router = createTestRouter({ + routeTree, + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/foo' }) + + const match = router.state.matches.find((m) => m.routeId === fooRoute.id) + expect(match?.status).toBe('notFound') + }, + ) + + test('settles descendant match when notFound renders an ancestor boundary', async () => { + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + notFoundComponent: () => null, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: () => notFound({ routeId: parentRoute.id }), + }) + + const routeTree = rootRoute.addChildren([ + parentRoute.addChildren([childRoute]), + ]) + const router = createTestRouter({ + routeTree, + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/parent/child' }) + + const parentMatch = router.state.matches.find( + (m) => m.routeId === parentRoute.id, + ) + const childMatch = router.state.matches.find( + (m) => m.routeId === childRoute.id, + ) + expect(parentMatch?.status).toBe('notFound') + expect(childMatch).toBeUndefined() + }) + test('exec if resolved preload (success)', async () => { const loader = vi.fn() const router = setup({ loader }) @@ -467,17 +3628,15 @@ describe('loader skip or exec', () => { expect(loader).toHaveBeenCalledTimes(1) }) - test('skip if pending preload (success)', async () => { + test('exec if pending preload (success)', async () => { const loader = vi.fn(() => sleep(100)) const router = setup({ loader }) router.preloadRoute({ to: '/foo' }) await Promise.resolve() - expect(router.stores.cachedMatches.get()).toEqual( - expect.arrayContaining([expect.objectContaining({ id: '/foo/foo' })]), - ) + expect(router.stores.cachedMatches.get()).toEqual([]) await router.navigate({ to: '/foo' }) - expect(loader).toHaveBeenCalledTimes(1) + expect(loader).toHaveBeenCalledTimes(2) }) test('exec if rejected preload (notFound)', async () => { @@ -495,7 +3654,7 @@ describe('loader skip or exec', () => { expect(loader).toHaveBeenCalledTimes(2) }) - test('skip if pending preload (notFound)', async () => { + test('exec if pending preload (notFound)', async () => { const loader: Loader = vi.fn(async ({ preload }) => { await sleep(100) if (preload) throw notFound() @@ -507,7 +3666,7 @@ describe('loader skip or exec', () => { await Promise.resolve() await router.navigate({ to: '/foo' }) - expect(loader).toHaveBeenCalledTimes(1) + expect(loader).toHaveBeenCalledTimes(2) }) test('exec if rejected preload (redirect)', async () => { @@ -520,19 +3679,19 @@ describe('loader skip or exec', () => { }) await router.preloadRoute({ to: '/foo' }) expect( - router.stores.cachedMatches.get().some((d) => d.status === 'redirected'), + router.stores.cachedMatches.get().some((d) => d.id === '/foo/foo'), ).toBe(false) await sleep(10) await router.navigate({ to: '/foo' }) expect(router.state.location.pathname).toBe('/foo') expect( - router.stores.cachedMatches.get().some((d) => d.status === 'redirected'), + router.stores.cachedMatches.get().some((d) => d.id === '/foo/foo'), ).toBe(false) expect(loader).toHaveBeenCalledTimes(2) }) - test('skip if pending preload (redirect)', async () => { + test('exec if pending preload (redirect)', async () => { const loader: Loader = vi.fn(async ({ preload }) => { await sleep(100) if (preload) throw redirect({ to: '/bar' }) @@ -542,40 +3701,217 @@ describe('loader skip or exec', () => { }) router.preloadRoute({ to: '/foo' }) await Promise.resolve() - expect( - router.stores.cachedMatches.get().some((d) => d.status === 'redirected'), - ).toBe(false) await router.navigate({ to: '/foo' }) - expect(router.state.location.pathname).toBe('/bar') - expect( - router.stores.cachedMatches.get().some((d) => d.status === 'redirected'), - ).toBe(false) - expect(loader).toHaveBeenCalledTimes(1) - }) - - test('updateMatch removes redirected matches from cachedMatches', async () => { - const loader = vi.fn() - const router = setup({ loader }) - - await router.preloadRoute({ to: '/foo' }) - expect(router.stores.cachedMatches.get()).toEqual( - expect.arrayContaining([expect.objectContaining({ id: '/foo/foo' })]), - ) - - router.updateMatch('/foo/foo', (prev) => ({ - ...prev, - status: 'redirected', - })) - + expect(router.state.location.pathname).toBe('/foo') expect( router.stores.cachedMatches.get().some((d) => d.id === '/foo/foo'), ).toBe(false) - expect( - router.stores.cachedMatches.get().some((d) => d.status === 'redirected'), - ).toBe(false) + expect(loader).toHaveBeenCalledTimes(2) }) + test('private pending preload redirect does not affect active pending navigation', async () => { + vi.useFakeTimers() + + try { + const rejectFoo: Array<(error: unknown) => void> = [] + const resolveFoo: Array<() => void> = [] + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + pendingMs: 1, + pendingComponent: {}, + loader: () => + new Promise((resolve, reject) => { + resolveFoo.push(resolve) + rejectFoo.push(reject) + }), + }) + const barRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/bar', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, fooRoute, barRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + + const preload = router.preloadRoute({ to: '/foo' }) + await vi.waitFor(() => expect(rejectFoo).toHaveLength(1)) + + const navigation = router.navigate({ to: '/foo' }) + await vi.waitFor(() => expect(rejectFoo).toHaveLength(2)) + await vi.advanceTimersByTimeAsync(1) + await vi.waitFor(() => + expect( + router.state.matches.some( + (match) => match.id === '/foo/foo' && match.status === 'pending', + ), + ).toBe(true), + ) + + rejectFoo[0]!(redirect({ to: '/bar' })) + await preload + + expect( + router.state.matches.find((match) => match.id === '/foo/foo')?.status, + ).toBe('pending') + expect(router.state.location.pathname).toBe('/foo') + + resolveFoo[1]!() + await navigation + + expect(router.state.location.pathname).toBe('/foo') + } finally { + vi.useRealTimers() + } + }) + + test('active-join preload observes active redirect after settling active owner loadPromise', async () => { + vi.useFakeTimers() + + try { + let rejectFoo!: (error: unknown) => void + let resolveBar!: () => void + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + pendingMs: 1, + pendingComponent: {}, + loader: () => + new Promise((_resolve, reject) => { + rejectFoo = reject + }), + }) + const barRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/bar', + loader: () => + new Promise((resolve) => { + resolveBar = resolve + }), + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, fooRoute, barRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + + const navigation = router.navigate({ to: '/foo' }) + await vi.waitFor(() => expect(rejectFoo).toBeTypeOf('function')) + await vi.advanceTimersByTimeAsync(1) + await vi.waitFor(() => + expect( + router.state.matches.some( + (match) => match.id === '/foo/foo' && match.status === 'pending', + ), + ).toBe(true), + ) + + const activeFoo = router.state.matches.find( + (match) => match.id === '/foo/foo', + )! + const activeLoadPromise = activeFoo._.loadPromise + expect(activeLoadPromise?.status).toBe('pending') + + const preload = router.preloadRoute({ to: '/foo' }) + await Promise.resolve() + + rejectFoo(redirect({ to: '/bar' })) + await vi.waitFor(() => + expect( + router.stores.pendingMatches + .get() + .some((match) => match.id === '/bar/bar'), + ).toBe(true), + ) + + expect(activeLoadPromise?.status).toBe('resolved') + expect(activeFoo._.loadPromise).toBeUndefined() + + resolveBar() + await Promise.all([navigation, preload]) + + expect(router.state.location.pathname).toBe('/bar') + } finally { + vi.useRealTimers() + } + }) + + test.each([ + { name: 'false', value: false }, + { name: '0', value: 0 }, + { name: 'empty string', value: '' }, + { name: 'null', value: null }, + { name: 'undefined', value: undefined }, + ])( + 'borrowed active error with $name stops preload descendants', + async ({ value }) => { + const originalNodeEnv = process.env.NODE_ENV + process.env.NODE_ENV = 'production' + try { + const childBeforeLoad = vi.fn() + const childLoader = vi.fn(() => 'child') + const childHead = vi.fn(() => ({})) + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: () => { + throw value + }, + errorComponent: () => null, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + beforeLoad: childBeforeLoad, + loader: childLoader, + head: childHead, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/parent' }) + const activeParent = router.state.matches.find( + (match) => match.routeId === parentRoute.id, + ) + expect(activeParent?.status).toBe('error') + expect(activeParent?.error).toBe(value) + + await router.preloadRoute({ to: '/parent/child' }) + + expect(childBeforeLoad).not.toHaveBeenCalled() + expect(childLoader).not.toHaveBeenCalled() + expect(childHead).not.toHaveBeenCalled() + expect( + router.stores.cachedMatches + .get() + .some((match) => match.routeId === childRoute.id), + ).toBe(false) + } finally { + process.env.NODE_ENV = originalNodeEnv + } + }, + ) + test('exec if rejected preload (error)', async () => { const loader: Loader = vi.fn(async ({ preload }) => { if (preload) throw new Error('error') @@ -591,7 +3927,7 @@ describe('loader skip or exec', () => { expect(loader).toHaveBeenCalledTimes(2) }) - test('skip if pending preload (error)', async () => { + test('exec if pending preload (error)', async () => { const loader: Loader = vi.fn(async ({ preload }) => { await sleep(100) if (preload) throw new Error('error') @@ -603,7 +3939,7 @@ describe('loader skip or exec', () => { await Promise.resolve() await router.navigate({ to: '/foo' }) - expect(loader).toHaveBeenCalledTimes(1) + expect(loader).toHaveBeenCalledTimes(2) }) }) @@ -714,6 +4050,11 @@ describe('stale loader reload triggers', () => { ) => router.stores.pendingMatches.get().some((match) => match.id === id) ?? false + const getTitle = (match?: AnyRouteMatch) => + (match?.meta as Array<{ title?: string }> | undefined)?.find( + (item) => item.title, + )?.title + const setup = ({ loader, staleTime, @@ -738,7 +4079,12 @@ describe('stale loader reload triggers', () => { path: '/bar', }) - const routeTree = rootRoute.addChildren([fooRoute, barRoute]) + const bazRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/baz', + }) + + const routeTree = rootRoute.addChildren([fooRoute, barRoute, bazRoute]) return createTestRouter({ routeTree, @@ -782,6 +4128,7 @@ describe('stale loader reload triggers', () => { await vi.advanceTimersByTimeAsync(1) await router.navigate({ to: '/bar' }) await vi.advanceTimersByTimeAsync(1) + expectNoCachedActiveOverlap(router) const revisit = router.navigate({ to: '/foo' }) await Promise.resolve() @@ -793,6 +4140,7 @@ describe('stale loader reload triggers', () => { expect(getMatchById(router, '/foo/foo')?.loaderData).toEqual({ value: 'first', }) + expectNoCachedActiveOverlap(router) resolveStaleReload() await revisit @@ -804,6 +4152,7 @@ describe('stale loader reload triggers', () => { expect(getMatchById(router, '/foo/foo')?.loaderData).toEqual({ value: 'second', }) + expectNoCachedActiveOverlap(router) } const expectBackgroundStaleReloadBehavior = async ( @@ -817,29 +4166,32 @@ describe('stale loader reload triggers', () => { await vi.advanceTimersByTimeAsync(1) await router.navigate({ to: '/bar' }) await vi.advanceTimersByTimeAsync(1) + expectNoCachedActiveOverlap(router) const revisit = router.navigate({ to: '/foo' }) - expect(loader).toHaveBeenCalledTimes(2) + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(2)) await revisit - const backgroundReloadPromise = getMatchById(router, '/foo/foo') - ?._nonReactive.loaderPromise - expect(backgroundReloadPromise).toBeDefined() expect(hasActiveMatch(router, '/foo/foo')).toBe(true) expect(hasPendingMatch(router, '/foo/foo')).toBe(false) expect(router.state.location.pathname).toBe('/foo') expect(getMatchById(router, '/foo/foo')?.loaderData).toEqual({ value: 'first', }) + expect(getMatchById(router, '/foo/foo')?.isFetching).toBe('loader') + expectNoCachedActiveOverlap(router) resolveStaleReload() - await backgroundReloadPromise - expect(getMatchById(router, '/foo/foo')?.loaderData).toEqual({ - value: 'second', - }) + await vi.waitFor(() => + expect(getMatchById(router, '/foo/foo')?.loaderData).toEqual({ + value: 'second', + }), + ) + expect(getMatchById(router, '/foo/foo')?.isFetching).toBe(false) + expectNoCachedActiveOverlap(router) } test('skips stale loader when only unrelated search params change', async () => { @@ -1071,12 +4423,14 @@ describe('stale loader reload triggers', () => { await router.navigate({ to: '/foo', search: { page: '1', filter: 'a' } }) expect(loader).toHaveBeenCalledTimes(1) + expectNoCachedActiveOverlap(router) await vi.advanceTimersByTimeAsync(1) await router.load() await Promise.resolve() expect(loader).toHaveBeenCalledTimes(2) + expectNoCachedActiveOverlap(router) }) test('supports object-form loader handler', async () => { @@ -1111,6 +4465,2298 @@ describe('stale loader reload triggers', () => { ) }) + test('async background stale reload runs head once with fresh loaderData', async () => { + let resolveStaleReload!: (data: { title: string }) => void + let loaderCalls = 0 + const loader = vi.fn(() => { + loaderCalls += 1 + if (loaderCalls === 1) { + return null + } + + return new Promise<{ title: string }>((resolve) => { + resolveStaleReload = resolve + }) + }) + const seenLoaderData: Array = [] + const head = vi.fn(({ loaderData }) => { + seenLoaderData.push(loaderData) + return { + meta: [ + { + title: loaderData?.title ?? 'Article Not Found', + }, + ], + } + }) + + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader, + head, + staleTime: 0, + gcTime: 60_000, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute]), + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/foo' }) + expect(head).toHaveBeenCalledTimes(1) + expect(seenLoaderData).toEqual([null]) + + head.mockClear() + seenLoaderData.length = 0 + + await vi.advanceTimersByTimeAsync(1) + await router.load() + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(2)) + + expect(getMatchById(router, '/foo/foo')?.isFetching).toBe('loader') + expect(head).not.toHaveBeenCalled() + + resolveStaleReload({ title: 'Article 123 Title' }) + await vi.waitFor(() => expect(head).toHaveBeenCalledTimes(1)) + + expect(head).toHaveBeenCalledTimes(1) + expect(seenLoaderData).toEqual([{ title: 'Article 123 Title' }]) + }) + + test('client background reload clears loaderData when loader returns undefined', async () => { + let resolveStaleReload!: (data: undefined) => void + let loaderCalls = 0 + const loader = vi.fn(() => { + loaderCalls += 1 + if (loaderCalls === 1) { + return 'old' + } + + return new Promise((resolve) => { + resolveStaleReload = resolve + }) + }) + const head = vi.fn(({ loaderData }) => ({ + meta: [{ title: String(loaderData) }], + })) + + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader, + head, + staleTime: 0, + gcTime: 60_000, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute]), + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/foo' }) + const matchId = router.state.matches.find( + (match) => match.routeId === fooRoute.id, + )!.id + expect(getMatchById(router, matchId)?.loaderData).toBe('old') + expect(getMatchById(router, matchId)?.meta).toEqual([{ title: 'old' }]) + + const matchStore = router.stores.matchStores.get(matchId)! as any + const seen: Array<{ loaderData: unknown; title?: string }> = [] + const subscription = matchStore.subscribe(() => { + const match = getMatchById(router, matchId) + seen.push({ + loaderData: match?.loaderData, + title: getTitle(match), + }) + }) + + await vi.advanceTimersByTimeAsync(1) + await router.load() + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(2)) + + expect(getMatchById(router, matchId)?.isFetching).toBe('loader') + + resolveStaleReload(undefined) + await vi.waitFor(() => + expect(getMatchById(router, matchId)?.isFetching).toBe(false), + ) + subscription?.unsubscribe?.() + + const match = getMatchById(router, matchId) + expect(match?.loaderData).toBeUndefined() + expect(match?.status).toBe('success') + expect(match?.meta).toEqual([{ title: 'undefined' }]) + expect(seen).not.toContainEqual({ + loaderData: 'old', + title: 'undefined', + }) + expect(seen).not.toContainEqual({ + loaderData: undefined, + title: 'old', + }) + }) + + test('production background loader throw undefined commits an error match', async () => { + const originalNodeEnv = process.env.NODE_ENV + process.env.NODE_ENV = 'production' + try { + let loaderCalls = 0 + const loader = vi.fn(() => { + loaderCalls += 1 + if (loaderCalls === 1) { + return { title: 'initial' } + } + + throw undefined + }) + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader, + staleTime: 0, + gcTime: 60_000, + errorComponent: () => null, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute]), + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/foo' }) + await vi.advanceTimersByTimeAsync(1) + await router.load() + + await vi.waitFor(() => + expect(getMatchById(router, '/foo/foo')?.status).toBe('error'), + ) + expect(getMatchById(router, '/foo/foo')?.error).toBeUndefined() + expect(loader).toHaveBeenCalledTimes(2) + } finally { + process.env.NODE_ENV = originalNodeEnv + } + }) + + test('same-url background beforeLoad context remains private until the atomic background commit', async () => { + const initialData = { version: 'old' } + const freshData = { version: 'new' } + let contextVersion = 'old' + let resolveParent!: (data: typeof freshData) => void + let parentLoaderCalls = 0 + const parentLoader = vi.fn(() => { + parentLoaderCalls += 1 + if (parentLoaderCalls === 1) { + return initialData + } + + return new Promise((resolve) => { + resolveParent = resolve + }) + }) + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + beforeLoad: () => ({ version: contextVersion }), + loader: parentLoader, + staleTime: 0, + gcTime: 60_000, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + head: ({ matches }) => { + const parent = matches.find( + (match: any) => match.routeId === parentRoute.id, + )! + return { + meta: [ + { + title: `${parent.context.version} / ${(parent.loaderData as any).version}`, + }, + ], + } + }, + staleTime: Infinity, + gcTime: 60_000, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/parent/child' }) + const parentMatchId = router.state.matches.find( + (match) => match.routeId === parentRoute.id, + )!.id + const childMatchId = router.state.matches.find( + (match) => match.routeId === childRoute.id, + )!.id + + expect(getMatchById(router, parentMatchId)?.context).toMatchObject({ + version: 'old', + }) + expect(getMatchById(router, parentMatchId)?.loaderData).toEqual(initialData) + expect(getTitle(getMatchById(router, childMatchId))).toBe('old / old') + + const parentStore = router.stores.matchStores.get(parentMatchId)! as any + const childStore = router.stores.matchStores.get(childMatchId)! as any + const seen: Array<{ + contextVersion?: string + loaderVersion?: string + title?: string + }> = [] + const capture = () => { + const parent = getMatchById(router, parentMatchId) + const child = getMatchById(router, childMatchId) + seen.push({ + contextVersion: (parent?.context as any)?.version, + loaderVersion: (parent?.loaderData as any)?.version, + title: getTitle(child), + }) + } + const parentSubscription = parentStore.subscribe(capture) + const childSubscription = childStore.subscribe(capture) + + contextVersion = 'new' + await vi.advanceTimersByTimeAsync(1) + await router.load() + await vi.waitFor(() => expect(parentLoader).toHaveBeenCalledTimes(2)) + + expect(getMatchById(router, parentMatchId)?.context).toMatchObject({ + version: 'old', + }) + expect(getMatchById(router, parentMatchId)?.loaderData).toEqual(initialData) + expect(getTitle(getMatchById(router, childMatchId))).toBe('old / old') + expect(getMatchById(router, parentMatchId)?.isFetching).toBe('loader') + + resolveParent(freshData) + await vi.waitFor(() => + expect(getMatchById(router, parentMatchId)?.loaderData).toEqual( + freshData, + ), + ) + + expect(getMatchById(router, parentMatchId)?.context).toMatchObject({ + version: 'new', + }) + expect(getTitle(getMatchById(router, childMatchId))).toBe('new / new') + expect( + seen.some( + (snapshot) => + snapshot.contextVersion === 'new' && snapshot.title === 'old / old', + ), + ).toBe(false) + expect( + seen.some( + (snapshot) => + snapshot.loaderVersion === 'new' && snapshot.title === 'old / old', + ), + ).toBe(false) + + parentSubscription?.unsubscribe?.() + childSubscription?.unsubscribe?.() + }) + + test('pure same-url background revalidation does not perform a foreground commit', async () => { + let resolveStaleReload!: (data: { value: string }) => void + let loaderCalls = 0 + const loader = vi.fn(() => { + loaderCalls += 1 + if (loaderCalls === 1) { + return { value: 'first' } + } + + return new Promise<{ value: string }>((resolve) => { + resolveStaleReload = resolve + }) + }) + const onEnter = vi.fn() + const onLeave = vi.fn() + const onStay = vi.fn() + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader, + staleTime: 0, + gcTime: 60_000, + onEnter, + onLeave, + onStay, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute]), + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/foo' }) + const loadedAt = router.stores.loadedAt.get() + const cachedIds = router.stores.cachedMatches.get().map((match) => match.id) + onEnter.mockClear() + onLeave.mockClear() + onStay.mockClear() + + await vi.advanceTimersByTimeAsync(1) + await router.load() + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(2)) + + expect(router.stores.loadedAt.get()).toBe(loadedAt) + expect(onEnter).not.toHaveBeenCalled() + expect(onLeave).not.toHaveBeenCalled() + expect(onStay).not.toHaveBeenCalled() + expect(router.stores.cachedMatches.get().map((match) => match.id)).toEqual( + cachedIds, + ) + expect(getMatchById(router, '/foo/foo')?.isFetching).toBe('loader') + + resolveStaleReload({ value: 'second' }) + await vi.waitFor(() => + expect(getMatchById(router, '/foo/foo')?.loaderData).toEqual({ + value: 'second', + }), + ) + + expect(router.stores.loadedAt.get()).toBe(loadedAt) + expect(onEnter).not.toHaveBeenCalled() + expect(onLeave).not.toHaveBeenCalled() + expect(onStay).not.toHaveBeenCalled() + expect(router.stores.cachedMatches.get().map((match) => match.id)).toEqual( + cachedIds, + ) + }) + + test('blocking child reload and background parent reload commit coherent asset revisions', async () => { + const initialParentData = { title: 'old-parent' } + const freshParentData = { title: 'new-parent' } + const initialChildData = { title: 'old-child' } + const freshChildData = { title: 'new-child' } + let resolveParent!: (data: typeof freshParentData) => void + let parentLoaderCalls = 0 + let childLoaderCalls = 0 + const parentLoader = vi.fn(() => { + parentLoaderCalls += 1 + if (parentLoaderCalls === 1) { + return initialParentData + } + + return new Promise((resolve) => { + resolveParent = resolve + }) + }) + const childLoader = vi.fn(() => { + childLoaderCalls += 1 + return childLoaderCalls === 1 ? initialChildData : freshChildData + }) + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: parentLoader, + staleTime: 0, + gcTime: 60_000, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: { + handler: childLoader, + staleReloadMode: 'blocking', + } satisfies LoaderEntry, + head: ({ loaderData, matches }) => { + const parent = matches.find( + (match: any) => match.routeId === parentRoute.id, + )! + return { + meta: [ + { + title: `${(parent.loaderData as any).title} / ${(loaderData as any).title}`, + }, + ], + } + }, + staleTime: 0, + gcTime: 60_000, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/parent/child' }) + const parentMatchId = router.state.matches.find( + (match) => match.routeId === parentRoute.id, + )!.id + const childMatchId = router.state.matches.find( + (match) => match.routeId === childRoute.id, + )!.id + const childStore = router.stores.matchStores.get(childMatchId)! as any + const seen: Array<{ loaderTitle?: string; metaTitle?: string }> = [] + const subscription = childStore.subscribe(() => { + const child = getMatchById(router, childMatchId) + seen.push({ + loaderTitle: (child?.loaderData as any)?.title, + metaTitle: getTitle(child), + }) + }) + + await vi.advanceTimersByTimeAsync(1) + await router.load() + await vi.waitFor(() => expect(parentLoader).toHaveBeenCalledTimes(2)) + expect(childLoader).toHaveBeenCalledTimes(2) + + expect(getMatchById(router, parentMatchId)?.loaderData).toEqual( + initialParentData, + ) + expect(getMatchById(router, childMatchId)?.loaderData).toEqual( + freshChildData, + ) + expect(getTitle(getMatchById(router, childMatchId))).toBe( + 'old-parent / new-child', + ) + expect(getMatchById(router, parentMatchId)?.isFetching).toBe('loader') + + resolveParent(freshParentData) + await vi.waitFor(() => + expect(getMatchById(router, parentMatchId)?.loaderData).toEqual( + freshParentData, + ), + ) + + expect(getMatchById(router, childMatchId)?.loaderData).toEqual( + freshChildData, + ) + expect(getTitle(getMatchById(router, childMatchId))).toBe( + 'new-parent / new-child', + ) + expect( + seen.some( + (snapshot) => + snapshot.loaderTitle === 'new-child' && + !['old-parent / new-child', 'new-parent / new-child'].includes( + snapshot.metaTitle ?? '', + ), + ), + ).toBe(false) + + subscription?.unsubscribe?.() + }) + + test('same-url load with one background route and one pending route still performs a final foreground commit', async () => { + const initialParentData = { title: 'old-parent' } + const freshParentData = { title: 'new-parent' } + const childResolvers: Array<(data: string) => void> = [] + let resolveParent!: (data: typeof freshParentData) => void + let parentLoaderCalls = 0 + const parentLoader = vi.fn(() => { + parentLoaderCalls += 1 + if (parentLoaderCalls === 1) { + return initialParentData + } + + return new Promise((resolve) => { + resolveParent = resolve + }) + }) + const childLoader = vi.fn(() => { + if (childResolvers.length === 0) { + childResolvers.push(() => {}) + return 'initial child' + } + + return new Promise((resolve) => { + childResolvers.push(resolve) + }) + }) + const childHead = vi.fn(({ loaderData }) => ({ + meta: [{ title: loaderData }], + })) + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: parentLoader, + staleTime: 0, + gcTime: 60_000, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + pendingMs: 0, + pendingComponent: () => null, + loader: { + handler: childLoader, + staleReloadMode: 'blocking', + } satisfies LoaderEntry, + head: childHead, + staleTime: 0, + gcTime: 60_000, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + }) + + await router.load() + const parentMatchId = router.state.matches.find( + (match) => match.routeId === parentRoute.id, + )!.id + const childMatchId = router.state.matches.find( + (match) => match.routeId === childRoute.id, + )!.id + router.updateMatch(parentMatchId, (match) => ({ + ...match, + invalid: true, + })) + router.updateMatch(childMatchId, (match) => ({ + ...match, + status: 'pending', + isFetching: 'loader', + })) + + const secondLoad = router.invalidate() + await vi.waitFor(() => expect(childLoader).toHaveBeenCalledTimes(2)) + + expect(router.state.isLoading).toBe(true) + + childResolvers[1]!('fresh child') + await secondLoad + + const childMatch = router.state.matches.find( + (match) => match.routeId === childRoute.id, + ) + expect(childMatch?.status).toBe('success') + expect(childMatch?.loaderData).toBe('fresh child') + expect(getTitle(childMatch)).toBe('fresh child') + expect(router.state.isLoading).toBe(false) + + await vi.waitFor(() => expect(parentLoader).toHaveBeenCalledTimes(2)) + resolveParent(freshParentData) + await vi.waitFor(() => + expect( + router.state.matches.find((match) => match.routeId === parentRoute.id) + ?.loaderData, + ).toEqual(freshParentData), + ) + }) + + test('foreground final commit reprojects assets when only beforeLoad context changed', async () => { + let titleVersion = 'old' + const head = vi.fn(({ match }) => ({ + meta: [{ title: match.context.titleVersion }], + })) + const rootRoute = new BaseRootRoute({}) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + beforeLoad: () => ({ titleVersion }), + head, + staleTime: Infinity, + gcTime: 60_000, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([targetRoute]), + history: createMemoryHistory({ initialEntries: ['/target'] }), + }) + + await router.load() + const targetMatchId = router.state.matches.find( + (match) => match.routeId === targetRoute.id, + )!.id + const initialMatch = getMatchById(router, targetMatchId)! + expect(getTitle(initialMatch)).toBe('old') + head.mockClear() + + titleVersion = 'new' + await router.load({ sync: true }) + + const updatedMatch = getMatchById(router, targetMatchId)! + expect(updatedMatch.id).toBe(initialMatch.id) + expect(updatedMatch.loaderData).toBe(initialMatch.loaderData) + expect(updatedMatch.status).toBe(initialMatch.status) + expect(updatedMatch.error).toBe(initialMatch.error) + expect(getTitle(updatedMatch)).toBe('new') + expect(head).toHaveBeenCalledTimes(1) + }) + + test('stale cache-owned preload remains blocking', async () => { + let resolveStalePreload!: (data: { title: string }) => void + let loaderCalls = 0 + const loader = vi.fn(() => { + loaderCalls += 1 + if (loaderCalls === 1) { + return { title: 'old preload' } + } + + return new Promise<{ title: string }>((resolve) => { + resolveStalePreload = resolve + }) + }) + const seenLoaderData: Array = [] + const head = vi.fn(({ loaderData }) => { + seenLoaderData.push(loaderData) + return { meta: [{ title: loaderData.title }] } + }) + + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader, + head, + staleTime: 0, + preloadStaleTime: 0, + gcTime: 60_000, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute]), + history: createMemoryHistory(), + }) + + await router.preloadRoute({ to: '/foo' }) + expect(loader).toHaveBeenCalledTimes(1) + expect(head).toHaveBeenCalledTimes(1) + expect(seenLoaderData).toEqual([{ title: 'old preload' }]) + + head.mockClear() + seenLoaderData.length = 0 + + await vi.advanceTimersByTimeAsync(1) + let preloadSettled = false + const preload = router.preloadRoute({ to: '/foo' }).then((matches) => { + preloadSettled = true + return matches + }) + + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(2)) + expect(preloadSettled).toBe(false) + expect(head).not.toHaveBeenCalled() + + resolveStalePreload({ title: 'fresh preload' }) + const matches = await preload + const match = matches?.find((item) => item.id === '/foo/foo') + + expect(preloadSettled).toBe(true) + expect(match?.loaderData).toEqual({ title: 'fresh preload' }) + expect(head).toHaveBeenCalledTimes(1) + expect(seenLoaderData).toEqual([{ title: 'fresh preload' }]) + expect(getMatchById(router, '/foo/foo')?._.loadPromise).toBeUndefined() + }) + + test('sync background stale reload executes head once after loader work', async () => { + let loaderCalls = 0 + const loader = vi.fn(() => { + loaderCalls += 1 + return { + title: loaderCalls === 1 ? 'First title' : 'Second title', + } + }) + const seenLoaderData: Array = [] + const head = vi.fn(({ loaderData }) => { + seenLoaderData.push(loaderData) + return { + meta: [{ title: loaderData.title }], + } + }) + + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader, + head, + staleTime: 0, + gcTime: 60_000, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute]), + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/foo' }) + expect(head).toHaveBeenCalledTimes(1) + + head.mockClear() + seenLoaderData.length = 0 + + await vi.advanceTimersByTimeAsync(1) + await router.load() + + expect(loader).toHaveBeenCalledTimes(2) + await vi.waitFor(() => expect(head).toHaveBeenCalledTimes(1)) + expect(head).toHaveBeenCalledTimes(1) + expect(seenLoaderData).toEqual([{ title: 'Second title' }]) + + await Promise.resolve() + + expect(head).toHaveBeenCalledTimes(1) + }) + + test('same-url load while async background reload is pending lets latest batch win', async () => { + const resolvers: Array<(data: { title: string }) => void> = [] + let loaderCalls = 0 + const loader = vi.fn(() => { + loaderCalls += 1 + if (loaderCalls === 1) { + return { title: 'First title' } + } + + return new Promise<{ title: string }>((resolve) => { + resolvers.push(resolve) + }) + }) + const seenLoaderData: Array = [] + const head = vi.fn(({ loaderData }) => { + seenLoaderData.push(loaderData) + return { + meta: [{ title: loaderData.title }], + } + }) + + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader, + head, + staleTime: 0, + gcTime: 60_000, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute]), + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/foo' }) + head.mockClear() + seenLoaderData.length = 0 + + await vi.advanceTimersByTimeAsync(1) + await router.load() + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(2)) + + const firstBackground = router._backgroundLoad + expect(firstBackground).toBeDefined() + expect(getMatchById(router, '/foo/foo')?.isFetching).toBe('loader') + expect(head).not.toHaveBeenCalled() + + await router.load() + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(3)) + expect(router._backgroundLoad).toBeDefined() + expect(router._backgroundLoad).not.toBe(firstBackground) + expect(firstBackground?.controller.signal.aborted).toBe(true) + expect(head).not.toHaveBeenCalled() + + resolvers[0]!({ title: 'Stale title' }) + await Promise.resolve() + expect(head).not.toHaveBeenCalled() + + resolvers[1]!({ title: 'Second title' }) + await vi.waitFor(() => expect(head).toHaveBeenCalledTimes(1)) + + expect(seenLoaderData).toEqual([{ title: 'Second title' }]) + }) + + test('background batch that observed a pending navigation cannot later commit', async () => { + const initialParentData = { title: 'initial parent' } + const freshParentData = { title: 'fresh parent' } + const initialChildData = { title: 'initial child' } + const freshChildData = { title: 'fresh child' } + let resolveChild!: (data: typeof freshChildData) => void + let parentLoaderCalls = 0 + let childLoaderCalls = 0 + let router: RouterCore + let pendingNavigation: Promise | undefined + const parentHead = vi.fn(() => ({})) + const childHead = vi.fn(() => ({})) + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: vi.fn(() => { + parentLoaderCalls += 1 + if (parentLoaderCalls === 1) { + return initialParentData + } + + pendingNavigation = router.navigate({ to: '/bar' }) + return freshParentData + }), + head: parentHead, + staleTime: 0, + gcTime: 60_000, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: vi.fn(() => { + childLoaderCalls += 1 + if (childLoaderCalls === 1) { + return initialChildData + } + + return new Promise((resolve) => { + resolveChild = resolve + }) + }), + head: childHead, + staleTime: 0, + gcTime: 60_000, + }) + const barRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/bar', + }) + + const history = createMemoryHistory() + + router = createTestRouter({ + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([childRoute]), + barRoute, + ]), + history, + }) + + await router.navigate({ to: '/parent/child' }) + parentHead.mockClear() + childHead.mockClear() + // Pause auto-loading of the nested navigation so the background batch + // observes the same public pending-location marker a user navigation sets. + const unsubscribeHistory = history.subscribe(() => {}) + + const baseMatches = router.state.matches + const parentIndex = baseMatches.findIndex( + (match) => match.routeId === parentRoute.id, + ) + const childIndex = baseMatches.findIndex( + (match) => match.routeId === childRoute.id, + ) + + startBackgroundLoad(router, router.state.location, baseMatches, [ + childIndex, + parentIndex, + ]) + + await vi.waitFor(() => expect(parentLoaderCalls).toBe(2)) + const oldToken = router._backgroundLoad + + await vi.waitFor(() => + expect(oldToken?.controller.signal.aborted).toBe(true), + ) + + resolveChild(freshChildData) + await Promise.resolve() + await Promise.resolve() + + await vi.waitFor(() => expect(router._backgroundLoad).not.toBe(oldToken)) + expect(getMatchById(router, baseMatches[parentIndex]!.id)?.loaderData).toBe( + initialParentData, + ) + expect(getMatchById(router, baseMatches[childIndex]!.id)?.loaderData).toBe( + initialChildData, + ) + expect(getMatchById(router, baseMatches[parentIndex]!.id)?.isFetching).toBe( + false, + ) + expect(getMatchById(router, baseMatches[childIndex]!.id)?.isFetching).toBe( + false, + ) + expect(parentHead).not.toHaveBeenCalled() + expect(childHead).not.toHaveBeenCalled() + + unsubscribeHistory() + router.commitLocationPromise?.resolve() + await pendingNavigation + }) + + test.each(['error', 'notFound'] as const)( + 'background index below a foreground %s boundary is discarded', + async (outcome) => { + const parentError = new Error('parent failed') + let parentLoaderCalls = 0 + const parentLoader = vi.fn(() => { + parentLoaderCalls += 1 + if (parentLoaderCalls === 1) { + return { title: 'initial parent' } + } + + throw outcome === 'error' ? parentError : notFound() + }) + const childLoader = vi.fn(() => ({ title: 'initial child' })) + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: { + handler: parentLoader, + staleReloadMode: 'blocking', + } satisfies LoaderEntry, + errorComponent: () => null, + notFoundComponent: () => null, + staleTime: 0, + gcTime: 60_000, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: childLoader, + staleTime: 0, + gcTime: 60_000, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + }) + + await router.load() + await vi.advanceTimersByTimeAsync(1) + await router.load() + await Promise.resolve() + await Promise.resolve() + + expect(parentLoader).toHaveBeenCalledTimes(2) + expect(childLoader).toHaveBeenCalledTimes(1) + expect(router._backgroundLoad).toBeUndefined() + expect(router.state.matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + parentRoute.id, + ]) + expect(router.state.matches[1]?.status).toBe(outcome) + if (outcome === 'error') { + expect(router.state.matches[1]?.error).toBe(parentError) + } else { + expect(router.state.matches[1]?.error).toEqual( + expect.objectContaining({ isNotFound: true }), + ) + } + }, + ) + + test.each(['errorComponent', 'notFoundComponent'] as const)( + 'stale background %s preload rejection cancels the batch', + async (componentType) => { + const componentError = new Error('component failed') + const componentGate = createControlledPromise() + const componentPreload = vi.fn(() => componentGate) + let loaderCalls = 0 + const loader = vi.fn(() => { + loaderCalls += 1 + if (loaderCalls === 1) { + return { title: 'initial' } + } + + if (componentType === 'errorComponent') { + throw new Error('loader failed') + } + + throw notFound() + }) + + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader, + staleTime: 0, + gcTime: 60_000, + }) + const barRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/bar', + }) + const history = createMemoryHistory() + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute, barRoute]), + history, + }) + + await router.navigate({ to: '/foo' }) + fooRoute.options[componentType] = { preload: componentPreload } as any + ;(fooRoute as any)._componentsLoaded = false + const baseMatches = router.state.matches + const fooIndex = baseMatches.findIndex( + (match) => match.routeId === fooRoute.id, + ) + expect(fooIndex).not.toBe(-1) + startBackgroundLoad(router, router.state.location, baseMatches, [ + fooIndex, + ]) + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(2)) + await vi.waitFor(() => expect(componentPreload).toHaveBeenCalledTimes(1)) + + const oldToken = router._backgroundLoad + expect(oldToken).toBeDefined() + const unsubscribeHistory = history.subscribe(() => {}) + + componentGate.reject(componentError) + const pendingNavigation = router.navigate({ to: '/bar' }) + + await vi.waitFor(() => + expect(oldToken?.controller.signal.aborted).toBe(true), + ) + + unsubscribeHistory() + router.commitLocationPromise?.resolve() + await pendingNavigation + }, + ) + + test('successful background commit performs one active match publication', async () => { + const initialData = { title: 'initial' } + const freshData = { title: 'fresh' } + let resolveFresh!: (data: typeof freshData) => void + let loaderCalls = 0 + const loader = vi.fn(() => { + loaderCalls += 1 + if (loaderCalls === 1) { + return initialData + } + + return new Promise((resolve) => { + resolveFresh = resolve + }) + }) + + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader, + staleTime: 0, + gcTime: 60_000, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute]), + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/foo' }) + const matchId = router.state.matches.find( + (match) => match.routeId === fooRoute.id, + )!.id + const matchStore = router.stores.matchStores.get(matchId)! as any + const updates: Array<{ + isFetching: AnyRouteMatch['isFetching'] + title: string + }> = [] + const subscription = matchStore.subscribe(() => { + const match = getMatchById(router, matchId)! + updates.push({ + isFetching: match.isFetching, + title: (match.loaderData as typeof initialData).title, + }) + }) + + await vi.advanceTimersByTimeAsync(1) + await router.load() + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(2)) + resolveFresh(freshData) + await vi.waitFor(() => + expect(getMatchById(router, matchId)?.loaderData).toBe(freshData), + ) + subscription?.unsubscribe?.() + + expect(updates).toEqual([ + { isFetching: 'loader', title: 'initial' }, + { isFetching: false, title: 'fresh' }, + ]) + }) + + test.each([ + ['parent', 'child'], + ['child', 'parent'], + ] as const)( + 'multiple async background loaders flush heads after %s then %s resolve', + async (first, second) => { + const freshParentData = { title: 'fresh parent' } + const freshChildData = { title: 'fresh child' } + let resolveParent!: (data: typeof freshParentData) => void + let resolveChild!: (data: typeof freshChildData) => void + let parentLoaderCalls = 0 + let childLoaderCalls = 0 + const parentLoader = vi.fn(() => { + parentLoaderCalls += 1 + if (parentLoaderCalls === 1) { + return { title: 'initial parent' } + } + return new Promise((resolve) => { + resolveParent = resolve + }) + }) + const childLoader = vi.fn(() => { + childLoaderCalls += 1 + if (childLoaderCalls === 1) { + return { title: 'initial child' } + } + return new Promise((resolve) => { + resolveChild = resolve + }) + }) + const parentSeenData: Array = [] + const childSeenData: Array = [] + const parentHead = vi.fn(({ loaderData }) => { + parentSeenData.push(loaderData) + return { meta: [{ title: loaderData.title }] } + }) + const childHead = vi.fn(({ loaderData }) => { + childSeenData.push(loaderData) + return { meta: [{ title: loaderData.title }] } + }) + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: parentLoader, + head: parentHead, + staleTime: 0, + gcTime: 60_000, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: childLoader, + head: childHead, + staleTime: 0, + gcTime: 60_000, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/parent/child' }) + const parentMatchId = router.state.matches.find( + (match) => match.routeId === parentRoute.id, + )!.id + const childMatchId = router.state.matches.find( + (match) => match.routeId === childRoute.id, + )!.id + parentHead.mockClear() + childHead.mockClear() + parentSeenData.length = 0 + childSeenData.length = 0 + + await vi.advanceTimersByTimeAsync(1) + await router.load() + await vi.waitFor(() => expect(parentLoader).toHaveBeenCalledTimes(2)) + await vi.waitFor(() => expect(childLoader).toHaveBeenCalledTimes(2)) + + expect(getMatchById(router, parentMatchId)?.isFetching).toBe('loader') + expect(getMatchById(router, childMatchId)?.isFetching).toBe('loader') + expect(parentHead).not.toHaveBeenCalled() + expect(childHead).not.toHaveBeenCalled() + + if (first === 'parent') { + resolveParent(freshParentData) + } else { + resolveChild(freshChildData) + } + + await Promise.resolve() + expect(parentHead).not.toHaveBeenCalled() + expect(childHead).not.toHaveBeenCalled() + + if (second === 'parent') { + resolveParent(freshParentData) + } else { + resolveChild(freshChildData) + } + + await vi.waitFor(() => expect(parentHead).toHaveBeenCalledTimes(1)) + expect(childHead).toHaveBeenCalledTimes(1) + expect(parentSeenData).toEqual([freshParentData]) + expect(childSeenData).toEqual([freshChildData]) + }, + ) + + test.each([ + ['parent', 'child'], + ['child', 'parent'], + ] as const)( + 'background child redirect waits for parent error and then wins when %s settles first', + async (first, _second) => { + const parentError = new Error('parent failed') + let rejectParent!: (error: unknown) => void + let rejectChild!: (error: unknown) => void + let parentLoaderCalls = 0 + let childLoaderCalls = 0 + const parentLoader = vi.fn(() => { + parentLoaderCalls += 1 + if (parentLoaderCalls === 1) { + return { title: 'initial parent' } + } + return new Promise((_resolve, reject) => { + rejectParent = reject + }) + }) + const childLoader = vi.fn(() => { + childLoaderCalls += 1 + if (childLoaderCalls === 1) { + return { title: 'initial child' } + } + return new Promise((_resolve, reject) => { + rejectChild = reject + }) + }) + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: parentLoader, + staleTime: 0, + gcTime: 60_000, + errorComponent: () => null, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: childLoader, + staleTime: 0, + gcTime: 60_000, + }) + const barRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/bar', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([childRoute]), + barRoute, + ]), + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/parent/child' }) + await vi.advanceTimersByTimeAsync(1) + await router.load() + await vi.waitFor(() => expect(parentLoader).toHaveBeenCalledTimes(2)) + await vi.waitFor(() => expect(childLoader).toHaveBeenCalledTimes(2)) + + if (first === 'parent') { + rejectParent(parentError) + } else { + rejectChild(redirect({ to: '/bar' })) + } + await Promise.resolve() + expect(router.state.location.pathname).toBe('/parent/child') + + if (first === 'parent') { + rejectChild(redirect({ to: '/bar' })) + } else { + rejectParent(parentError) + } + + await vi.waitFor(() => + expect(router.state.location.pathname).toBe('/bar'), + ) + }, + ) + + test.each([ + ['parent', 'child'], + ['child', 'parent'], + ] as const)( + 'background parent error waits for child notFound and then wins when %s settles first', + async (first, _second) => { + const parentError = new Error('parent failed') + let rejectParent!: (error: unknown) => void + let rejectChild!: (error: unknown) => void + let parentLoaderCalls = 0 + let childLoaderCalls = 0 + const parentLoader = vi.fn(() => { + parentLoaderCalls += 1 + if (parentLoaderCalls === 1) { + return { title: 'initial parent' } + } + return new Promise((_resolve, reject) => { + rejectParent = reject + }) + }) + const childLoader = vi.fn(() => { + childLoaderCalls += 1 + if (childLoaderCalls === 1) { + return { title: 'initial child' } + } + return new Promise((_resolve, reject) => { + rejectChild = reject + }) + }) + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: parentLoader, + staleTime: 0, + gcTime: 60_000, + errorComponent: () => null, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: childLoader, + staleTime: 0, + gcTime: 60_000, + notFoundComponent: () => null, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/parent/child' }) + const parentMatchId = router.state.matches.find( + (match) => match.routeId === parentRoute.id, + )!.id + await vi.advanceTimersByTimeAsync(1) + await router.load() + await vi.waitFor(() => expect(parentLoader).toHaveBeenCalledTimes(2)) + await vi.waitFor(() => expect(childLoader).toHaveBeenCalledTimes(2)) + + if (first === 'parent') { + rejectParent(parentError) + } else { + rejectChild(notFound()) + } + await Promise.resolve() + expect(getMatchById(router, parentMatchId)?.status).toBe('success') + + if (first === 'parent') { + rejectChild(notFound()) + } else { + rejectParent(parentError) + } + + await vi.waitFor(() => + expect(getMatchById(router, parentMatchId)?.status).toBe('error'), + ) + expect(getMatchById(router, parentMatchId)?.error).toBe(parentError) + }, + ) + + test.each([ + ['parent', 'child'], + ['child', 'parent'], + ] as const)( + 'background shallow regular error waits for deep regular error and then wins when %s settles first', + async (first, _second) => { + const parentError = new Error('parent failed') + const childError = new Error('child failed') + let rejectParent!: (error: unknown) => void + let rejectChild!: (error: unknown) => void + let parentLoaderCalls = 0 + let childLoaderCalls = 0 + const parentLoader = vi.fn(() => { + parentLoaderCalls += 1 + if (parentLoaderCalls === 1) { + return { title: 'initial parent' } + } + return new Promise((_resolve, reject) => { + rejectParent = reject + }) + }) + const childLoader = vi.fn(() => { + childLoaderCalls += 1 + if (childLoaderCalls === 1) { + return { title: 'initial child' } + } + return new Promise((_resolve, reject) => { + rejectChild = reject + }) + }) + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: parentLoader, + staleTime: 0, + gcTime: 60_000, + errorComponent: () => null, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: childLoader, + staleTime: 0, + gcTime: 60_000, + errorComponent: () => null, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/parent/child' }) + const parentMatchId = router.state.matches.find( + (match) => match.routeId === parentRoute.id, + )!.id + const childMatchId = router.state.matches.find( + (match) => match.routeId === childRoute.id, + )!.id + await vi.advanceTimersByTimeAsync(1) + await router.load() + await vi.waitFor(() => expect(parentLoader).toHaveBeenCalledTimes(2)) + await vi.waitFor(() => expect(childLoader).toHaveBeenCalledTimes(2)) + + if (first === 'parent') { + rejectParent(parentError) + } else { + rejectChild(childError) + } + await Promise.resolve() + expect(getMatchById(router, parentMatchId)?.status).toBe('success') + expect(getMatchById(router, childMatchId)?.status).toBe('success') + + if (first === 'parent') { + rejectChild(childError) + } else { + rejectParent(parentError) + } + + await vi.waitFor(() => + expect(getMatchById(router, parentMatchId)?.status).toBe('error'), + ) + expect(getMatchById(router, parentMatchId)?.error).toBe(parentError) + expect(hasActiveMatch(router, childMatchId)).toBe(false) + }, + ) + + test('newer background batch supersedes older batch for the same lane', async () => { + const initialParentData = { title: 'initial parent' } + const initialChildData = { title: 'initial child' } + const freshParentData = { title: 'fresh parent' } + const freshChildData = { title: 'fresh child' } + let reloadParent = false + let reloadChild = false + let resolveParent!: (data: typeof freshParentData) => void + let resolveChild!: (data: typeof freshChildData) => void + let parentLoaderCalls = 0 + let childLoaderCalls = 0 + const parentLoader = vi.fn(() => { + parentLoaderCalls += 1 + if (parentLoaderCalls === 1) { + return initialParentData + } + return new Promise((resolve) => { + resolveParent = resolve + }) + }) + const childLoader = vi.fn(() => { + childLoaderCalls += 1 + if (childLoaderCalls === 1) { + return initialChildData + } + return new Promise((resolve) => { + resolveChild = resolve + }) + }) + const childSeenData: Array<{ + loaderData: unknown + parentLoaderData: unknown + }> = [] + const parentHead = vi.fn(({ loaderData }) => ({ + meta: [{ title: loaderData.title }], + })) + const childHead = vi.fn(({ loaderData, matches }) => { + childSeenData.push({ + loaderData, + parentLoaderData: matches.find( + (match: any) => match.routeId === parentRoute.id, + )?.loaderData, + }) + return { meta: [{ title: loaderData.title }] } + }) + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: parentLoader, + head: parentHead, + staleTime: Infinity, + gcTime: 60_000, + shouldReload: () => reloadParent, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: childLoader, + head: childHead, + staleTime: Infinity, + gcTime: 60_000, + shouldReload: () => reloadChild, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/parent/child' }) + const parentMatchId = router.state.matches.find( + (match) => match.routeId === parentRoute.id, + )!.id + const childMatchId = router.state.matches.find( + (match) => match.routeId === childRoute.id, + )!.id + parentHead.mockClear() + childHead.mockClear() + childSeenData.length = 0 + + reloadParent = true + reloadChild = false + await router.load() + await vi.waitFor(() => expect(parentLoader).toHaveBeenCalledTimes(2)) + const firstBackground = router._backgroundLoad + expect(getMatchById(router, parentMatchId)?.isFetching).toBe('loader') + + reloadParent = false + reloadChild = true + await router.load() + await vi.waitFor(() => expect(childLoader).toHaveBeenCalledTimes(2)) + expect(router._backgroundLoad).toBeDefined() + expect(router._backgroundLoad).not.toBe(firstBackground) + expect(firstBackground?.controller.signal.aborted).toBe(true) + expect(getMatchById(router, parentMatchId)?.isFetching).toBe(false) + expect(getMatchById(router, childMatchId)?.isFetching).toBe('loader') + expect(parentHead).not.toHaveBeenCalled() + expect(childHead).not.toHaveBeenCalled() + + resolveParent(freshParentData) + await Promise.resolve() + expect(getMatchById(router, parentMatchId)?.loaderData).toEqual( + initialParentData, + ) + expect(parentHead).not.toHaveBeenCalled() + expect(childHead).not.toHaveBeenCalled() + + resolveChild(freshChildData) + await vi.waitFor(() => expect(childHead).toHaveBeenCalledTimes(1)) + + expect(getMatchById(router, parentMatchId)?.loaderData).toEqual( + initialParentData, + ) + expect(childSeenData).toEqual([ + { + loaderData: freshChildData, + parentLoaderData: initialParentData, + }, + ]) + expect(router.state.matches.every((match) => !match.isFetching)).toBe(true) + }) + + test('latest same-url pass owns the deferred head boundary', async () => { + const freshParentData = { title: 'fresh parent' } + let reloadParent = false + let childNotFound = false + let parentLoaderCalls = 0 + let resolveParent!: (data: typeof freshParentData) => void + const parentLoader = vi.fn(() => { + parentLoaderCalls += 1 + if (parentLoaderCalls === 1) { + return { title: 'initial parent' } + } + return new Promise((resolve) => { + resolveParent = resolve + }) + }) + const childLoader = vi.fn(() => ({ title: 'initial child' })) + const parentHead = vi.fn(({ loaderData }) => ({ + meta: [{ title: loaderData.title }], + })) + const childHead = vi.fn(({ loaderData }) => ({ + meta: [{ title: loaderData.title }], + })) + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: parentLoader, + head: parentHead, + staleTime: Infinity, + gcTime: 60_000, + shouldReload: () => reloadParent, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + beforeLoad: () => { + if (childNotFound) { + throw notFound({ routeId: parentRoute.id }) + } + }, + loader: childLoader, + head: childHead, + staleTime: Infinity, + gcTime: 60_000, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/parent/child' }) + const parentMatchId = router.state.matches.find( + (match) => match.routeId === parentRoute.id, + )!.id + parentHead.mockClear() + childHead.mockClear() + + reloadParent = true + await router.load() + await vi.waitFor(() => expect(parentLoader).toHaveBeenCalledTimes(2)) + expect(getMatchById(router, parentMatchId)?.isFetching).toBe('loader') + + reloadParent = false + childNotFound = true + await router.load() + expect(parentHead).toHaveBeenCalledTimes(1) + expect(childHead).not.toHaveBeenCalled() + + resolveParent(freshParentData) + await Promise.resolve() + + expect(parentHead).toHaveBeenCalledTimes(1) + expect(childHead).not.toHaveBeenCalled() + expect( + router.state.matches.some( + (match) => + match.status === 'notFound' && + (match.error as { routeId?: string } | undefined)?.routeId === + parentRoute.id, + ), + ).toBe(true) + }) + + test.each([ + ['error', 'success'], + ['success', 'error'], + ] as const)( + 'successful background completion does not flush heads after another background match failed: %s then %s', + async (first, second) => { + void second + const parentError = new Error('parent failed') + const freshChildData = { title: 'fresh child' } + let rejectParent!: (error: unknown) => void + let resolveChild!: (data: typeof freshChildData) => void + let parentLoaderCalls = 0 + let childLoaderCalls = 0 + const parentLoader = vi.fn(() => { + parentLoaderCalls += 1 + if (parentLoaderCalls === 1) { + return { title: 'initial parent' } + } + return new Promise((_resolve, reject) => { + rejectParent = reject + }) + }) + const childLoader = vi.fn(() => { + childLoaderCalls += 1 + if (childLoaderCalls === 1) { + return { title: 'initial child' } + } + return new Promise((resolve) => { + resolveChild = resolve + }) + }) + const parentHead = vi.fn(({ loaderData }) => ({ + meta: [{ title: loaderData.title }], + })) + const childHead = vi.fn(({ loaderData }) => ({ + meta: [{ title: loaderData.title }], + })) + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: parentLoader, + head: parentHead, + staleTime: 0, + gcTime: 60_000, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: childLoader, + head: childHead, + staleTime: 0, + gcTime: 60_000, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/parent/child' }) + const parentMatchId = router.state.matches.find( + (match) => match.routeId === parentRoute.id, + )!.id + const childMatchId = router.state.matches.find( + (match) => match.routeId === childRoute.id, + )!.id + parentHead.mockClear() + childHead.mockClear() + + await vi.advanceTimersByTimeAsync(1) + await router.load() + await vi.waitFor(() => expect(parentLoader).toHaveBeenCalledTimes(2)) + await vi.waitFor(() => expect(childLoader).toHaveBeenCalledTimes(2)) + + expect(getMatchById(router, parentMatchId)?.isFetching).toBe('loader') + expect(getMatchById(router, childMatchId)?.isFetching).toBe('loader') + + if (first === 'error') { + rejectParent(parentError) + resolveChild(freshChildData) + } else { + resolveChild(freshChildData) + rejectParent(parentError) + } + + await vi.waitFor(() => + expect(getMatchById(router, parentMatchId)?.status).toBe('error'), + ) + expect(parentHead).toHaveBeenCalledTimes(1) + expect(childHead).not.toHaveBeenCalled() + }, + ) + + test('synchronous background loader error waits for the error component before executing boundary head', async () => { + const loaderError = new Error('sync background failed') + const errorGate = createControlledPromise() + let loaderCalls = 0 + const loader = vi.fn(() => { + loaderCalls += 1 + if (loaderCalls === 1) { + return { title: 'initial' } + } + throw loaderError + }) + const head = vi.fn(({ loaderData, match }) => ({ + meta: [{ title: match.error ? 'error' : loaderData.title }], + })) + const errorPreload = vi.fn(() => errorGate) + + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader, + head, + staleTime: 0, + gcTime: 60_000, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute]), + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/foo' }) + fooRoute.options.errorComponent = { preload: errorPreload } as any + ;(fooRoute as any)._componentsLoaded = false + head.mockClear() + + await vi.advanceTimersByTimeAsync(1) + await router.load() + + expect(loader).toHaveBeenCalledTimes(2) + await vi.waitFor(() => expect(errorPreload).toHaveBeenCalledTimes(1)) + expect(getMatchById(router, '/foo/foo')?.isFetching).toBe('loader') + expect(head).not.toHaveBeenCalled() + + errorGate.resolve() + + await vi.waitFor(() => + expect(getMatchById(router, '/foo/foo')?.status).toBe('error'), + ) + expect(head).toHaveBeenCalledTimes(1) + expect(getMatchById(router, '/foo/foo')?.meta).toEqual([{ title: 'error' }]) + }) + + test('synchronous background loader redirect does not execute source head', async () => { + let loaderCalls = 0 + const loader = vi.fn(() => { + loaderCalls += 1 + if (loaderCalls === 1) { + return { title: 'initial' } + } + throw redirect({ to: '/bar' }) + }) + const head = vi.fn(({ loaderData }) => ({ + meta: [{ title: loaderData.title }], + })) + + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader, + head, + staleTime: 0, + gcTime: 60_000, + }) + const barRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/bar', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute, barRoute]), + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/foo' }) + head.mockClear() + + await vi.advanceTimersByTimeAsync(1) + await router.load() + + expect(loader).toHaveBeenCalledTimes(2) + expect(head).not.toHaveBeenCalled() + await vi.waitFor(() => expect(router.state.location.pathname).toBe('/bar')) + expect(head).not.toHaveBeenCalled() + }) + + test('synchronous background loader notFound executes the selected boundary head', async () => { + let loaderCalls = 0 + const loader = vi.fn(() => { + loaderCalls += 1 + if (loaderCalls === 1) { + return { title: 'initial' } + } + throw notFound() + }) + const head = vi.fn(({ loaderData, match }) => ({ + meta: [{ title: match.error ? 'not-found' : loaderData.title }], + })) + + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader, + head, + staleTime: 0, + gcTime: 60_000, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute]), + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/foo' }) + head.mockClear() + + await vi.advanceTimersByTimeAsync(1) + await router.load() + + expect(loader).toHaveBeenCalledTimes(2) + expect(head).not.toHaveBeenCalled() + + await vi.waitFor(() => + expect(getMatchById(router, '/foo/foo')?.status).toBe('notFound'), + ) + expect(head).toHaveBeenCalledTimes(1) + expect(getMatchById(router, '/foo/foo')?.meta).toEqual([ + { title: 'not-found' }, + ]) + }) + + test('sync stale loader commits fresh data without reloading route chunk', async () => { + let loaderCalls = 0 + const loader = vi.fn(() => { + loaderCalls += 1 + return { title: loaderCalls === 1 ? 'initial' : 'fresh' } + }) + const lazyHead = vi.fn(({ loaderData }) => ({ + meta: [{ title: loaderData.title }], + })) + const lazyGate = createControlledPromise() + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader, + staleTime: 0, + gcTime: 60_000, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute]), + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/foo' }) + const lazyFn = vi.fn(() => lazyGate) + ;(fooRoute as any)._lazyLoaded = false + ;(fooRoute as any).lazyFn = lazyFn + + await vi.advanceTimersByTimeAsync(1) + await router.load() + + expect(loader).toHaveBeenCalledTimes(2) + expect(lazyFn).not.toHaveBeenCalled() + expect(lazyHead).not.toHaveBeenCalled() + expect(getMatchById(router, '/foo/foo')?.isFetching).toBe(false) + expect(getMatchById(router, '/foo/foo')?.loaderData).toEqual({ + title: 'fresh', + }) + + lazyGate.resolve({ options: { head: lazyHead } }) + await Promise.resolve() + expect(lazyFn).not.toHaveBeenCalled() + expect(lazyHead).not.toHaveBeenCalled() + expect(getMatchById(router, '/foo/foo')?.loaderData).toEqual({ + title: 'fresh', + }) + }) + + test('background reload resolving after route exit does not execute head', async () => { + let resolveStaleReload!: (data: { title: string }) => void + let loaderCalls = 0 + const loader = vi.fn(() => { + loaderCalls += 1 + if (loaderCalls === 1) { + return { title: 'initial' } + } + return new Promise<{ title: string }>((resolve) => { + resolveStaleReload = resolve + }) + }) + const head = vi.fn(() => ({ meta: [{ title: 'foo' }] })) + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader, + head, + staleTime: 0, + gcTime: 60_000, + }) + const barRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/bar', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute, barRoute]), + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/foo' }) + head.mockClear() + + await vi.advanceTimersByTimeAsync(1) + await router.load() + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(2)) + expect(getMatchById(router, '/foo/foo')?.isFetching).toBe('loader') + + await router.navigate({ to: '/bar' }) + resolveStaleReload({ title: 'fresh' }) + await Promise.resolve() + + expect(router.state.location.pathname).toBe('/bar') + expect(head).not.toHaveBeenCalled() + }) + + test('foreground navigation clears an active background fetching marker before commit', async () => { + let resolveStaleReload!: (data: { title: string }) => void + let loaderCalls = 0 + const loader = vi.fn(() => { + loaderCalls += 1 + if (loaderCalls === 1) { + return { title: 'initial' } + } + return new Promise<{ title: string }>((resolve) => { + resolveStaleReload = resolve + }) + }) + const barBeforeLoadGate = createControlledPromise() + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader, + staleTime: 0, + gcTime: 60_000, + }) + const barRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/bar', + beforeLoad: () => barBeforeLoadGate, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute, barRoute]), + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/foo' }) + await vi.advanceTimersByTimeAsync(1) + await router.load() + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(2)) + expect(getMatchById(router, '/foo/foo')?.isFetching).toBe('loader') + + const barNavigation = router.navigate({ to: '/bar' }) + await vi.waitFor(() => + expect(router.stores.pendingIds.get()).toContain('/bar/bar'), + ) + + expect(getMatchById(router, '/foo/foo')?.isFetching).toBe(false) + + resolveStaleReload({ title: 'fresh' }) + barBeforeLoadGate.resolve() + await barNavigation + expect(router.state.location.pathname).toBe('/bar') + }) + + test('background reload redirect does not execute deferred source head', async () => { + let rejectStaleReload!: (error: unknown) => void + let loaderCalls = 0 + const loader = vi.fn(() => { + loaderCalls += 1 + if (loaderCalls === 1) { + return { title: 'initial' } + } + return new Promise((_resolve, reject) => { + rejectStaleReload = reject + }) + }) + const head = vi.fn(() => ({ meta: [{ title: 'foo' }] })) + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader, + head, + staleTime: 0, + gcTime: 60_000, + }) + const barRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/bar', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute, barRoute]), + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/foo' }) + head.mockClear() + await vi.advanceTimersByTimeAsync(1) + await router.load() + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(2)) + expect(getMatchById(router, '/foo/foo')?.isFetching).toBe('loader') + + rejectStaleReload(redirect({ to: '/bar' })) + await vi.waitFor(() => expect(router.state.location.pathname).toBe('/bar')) + + expect(head).not.toHaveBeenCalled() + }) + + test('background reload error does not execute success head with stale data', async () => { + let rejectStaleReload!: (error: unknown) => void + let loaderCalls = 0 + const loader = vi.fn(() => { + loaderCalls += 1 + if (loaderCalls === 1) { + return { title: 'initial' } + } + return new Promise((_resolve, reject) => { + rejectStaleReload = reject + }) + }) + const head = vi.fn(({ match }) => ({ + meta: [{ title: match.error ? 'error' : 'foo' }], + })) + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader, + head, + staleTime: 0, + gcTime: 60_000, + errorComponent: () => null, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute]), + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/foo' }) + head.mockClear() + await vi.advanceTimersByTimeAsync(1) + await router.load() + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(2)) + expect(getMatchById(router, '/foo/foo')?.isFetching).toBe('loader') + + rejectStaleReload(new Error('background failed')) + await vi.waitFor(() => + expect(getMatchById(router, '/foo/foo')?.status).toBe('error'), + ) + + expect(head).toHaveBeenCalledTimes(1) + expect(getMatchById(router, '/foo/foo')?.meta).toEqual([{ title: 'error' }]) + }) + + test('background-atomicity keeps active data and head coherent until atomic commit', async () => { + let resolveStaleReload!: (value: { value: string }) => void + let resolveHead!: () => void + let loaderCalls = 0 + const loader = vi.fn(() => { + loaderCalls += 1 + if (loaderCalls === 1) { + return { value: 'old' } + } + + return new Promise<{ value: string }>((resolve) => { + resolveStaleReload = resolve + }) + }) + const head = vi.fn(({ loaderData }: { loaderData?: any }) => { + if (loaderData?.value === 'new') { + return new Promise<{ meta: Array<{ title: string }> }>((resolve) => { + resolveHead = () => resolve({ meta: [{ title: 'new' }] }) + }) + } + + return { meta: [{ title: 'old' }] } + }) + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader, + head, + staleTime: 0, + gcTime: 60_000, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute]), + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/foo' }) + expect(getMatchById(router, '/foo/foo')?.loaderData).toEqual({ + value: 'old', + }) + const initialMeta = getMatchById(router, '/foo/foo')?.meta + head.mockClear() + + await vi.advanceTimersByTimeAsync(1) + await router.load() + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(2)) + + expect(getMatchById(router, '/foo/foo')?.isFetching).toBe('loader') + + resolveStaleReload({ value: 'new' }) + await vi.waitFor(() => expect(resolveHead).toBeTypeOf('function')) + + const activeWhileHeadPending = getMatchById(router, '/foo/foo')! + expect(activeWhileHeadPending.loaderData).toEqual({ value: 'old' }) + expect(activeWhileHeadPending.meta).toBe(initialMeta) + expect(activeWhileHeadPending.isFetching).toBe('loader') + + resolveHead() + await vi.waitFor(() => + expect(getMatchById(router, '/foo/foo')?.loaderData).toEqual({ + value: 'new', + }), + ) + expect(getMatchById(router, '/foo/foo')?.meta).toEqual([{ title: 'new' }]) + expect(getMatchById(router, '/foo/foo')?.isFetching).toBe(false) + }) + + test('parent-only background reload republishes child head derived from parent loaderData', async () => { + const freshParentData = { title: 'fresh parent' } + let reloadParent = false + let resolveParent!: (data: typeof freshParentData) => void + let parentLoaderCalls = 0 + const parentLoader = vi.fn(() => { + parentLoaderCalls += 1 + if (parentLoaderCalls === 1) { + return { title: 'initial parent' } + } + return new Promise((resolve) => { + resolveParent = resolve + }) + }) + const childHead = vi.fn(({ matches }) => { + const parent = matches.find( + (match: any) => match.routeId === parentRoute.id, + ) + return { meta: [{ title: parent?.loaderData.title }] } + }) + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: parentLoader, + staleTime: Infinity, + gcTime: 60_000, + shouldReload: () => reloadParent, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + head: childHead, + staleTime: Infinity, + gcTime: 60_000, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/parent/child' }) + const childMatchId = router.state.matches.find( + (match) => match.routeId === childRoute.id, + )!.id + const childStore = router.stores.matchStores.get(childMatchId)! as any + const seen: Array = [] + const subscription = childStore.subscribe(() => { + seen.push(childStore.get().meta) + }) + childHead.mockClear() + + reloadParent = true + await router.load() + await vi.waitFor(() => expect(parentLoader).toHaveBeenCalledTimes(2)) + expect(childHead).not.toHaveBeenCalled() + + resolveParent(freshParentData) + await vi.waitFor(() => + expect(getMatchById(router, childMatchId)?.meta).toEqual([ + { title: freshParentData.title }, + ]), + ) + + expect(childHead).toHaveBeenCalledTimes(1) + expect(seen).toContainEqual([{ title: freshParentData.title }]) + subscription?.unsubscribe?.() + }) + test('blocks stale reloads when loader staleReloadMode is blocking', async () => { const { loader, resolveStaleReload } = createControlledStaleReload() const router = setup({ @@ -1152,6 +6798,286 @@ describe('stale loader reload triggers', () => { resolveStaleReload, ) }) + + test('active background reload redirect navigates while its location is still current', async () => { + let rejectStaleReload!: (error: unknown) => void + let loaderCalls = 0 + const loader = vi.fn(() => { + loaderCalls += 1 + if (loaderCalls === 1) { + return { value: 'first' } + } + + return new Promise((_resolve, reject) => { + rejectStaleReload = reject + }) + }) + const router = setup({ loader, staleTime: 0 }) + + await router.navigate({ to: '/foo' }) + expect(loader).toHaveBeenCalledTimes(1) + + await vi.advanceTimersByTimeAsync(1) + await router.load() + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(2)) + + expect(getMatchById(router, '/foo/foo')?.isFetching).toBe('loader') + + rejectStaleReload(redirect({ to: '/bar' })) + await vi.waitFor(() => expect(router.state.location.pathname).toBe('/bar')) + + expect( + router.stores.cachedMatches + .get() + .some((match) => match.id === '/foo/foo'), + ).toBe(true) + }) + + test('current background redirect bypasses navigation blockers and does not leave the source fetching', async () => { + let rejectStaleReload!: (error: unknown) => void + let loaderCalls = 0 + const loader = vi.fn(() => { + loaderCalls += 1 + if (loaderCalls === 1) { + return { value: 'first' } + } + + return new Promise((_resolve, reject) => { + rejectStaleReload = reject + }) + }) + const blockerFn = vi.fn(() => true) + const router = setup({ loader, staleTime: 0 }) + let unblock: (() => void) | undefined + + try { + await router.navigate({ to: '/foo' }) + expect(loader).toHaveBeenCalledTimes(1) + unblock = router.history.block({ + blockerFn, + enableBeforeUnload: false, + }) + + await vi.advanceTimersByTimeAsync(1) + await router.load() + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(2)) + + expect(getMatchById(router, '/foo/foo')?.isFetching).toBe('loader') + + rejectStaleReload(redirect({ to: '/bar' })) + await vi.waitFor(() => + expect(router.state.location.pathname).toBe('/bar'), + ) + + expect(blockerFn).not.toHaveBeenCalled() + const sourceMatch = + router.state.matches.find((match) => match.id === '/foo/foo') ?? + router.stores.cachedMatches + .get() + .find((match) => match.id === '/foo/foo') + expect(sourceMatch?.isFetching).not.toBe('loader') + } finally { + unblock?.() + } + }) + + test('exited background reload redirect is ignored without evicting the source entry', async () => { + let rejectStaleReload!: (error: unknown) => void + let loaderCalls = 0 + const loader = vi.fn(() => { + loaderCalls += 1 + if (loaderCalls === 1) { + return { value: 'first' } + } + + return new Promise((_resolve, reject) => { + rejectStaleReload = reject + }) + }) + const router = setup({ loader, staleTime: 0 }) + + await router.navigate({ to: '/foo' }) + await vi.advanceTimersByTimeAsync(1) + await router.load() + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(2)) + + expect(getMatchById(router, '/foo/foo')?.isFetching).toBe('loader') + + await router.navigate({ to: '/bar' }) + expect(router.state.location.pathname).toBe('/bar') + const sourceLoadPromise = getMatchById(router, '/foo/foo')?._.loadPromise + expect(sourceLoadPromise?.status).not.toBe('pending') + expect( + router.stores.cachedMatches + .get() + .some((match) => match.id === '/foo/foo'), + ).toBe(true) + expect( + router.stores.cachedMatches.get().find((match) => match.id === '/foo/foo') + ?._.loadPromise, + ).toBeUndefined() + expectNoCachedActiveOverlap(router) + + rejectStaleReload(redirect({ to: '/baz' })) + + expect(router.state.location.pathname).toBe('/bar') + await vi.waitFor(() => + expect( + router.stores.cachedMatches + .get() + .some((match) => match.id === '/foo/foo'), + ).toBe(true), + ) + expectNoCachedActiveOverlap(router) + }) + + test('background redirect is ignored while a newer navigation is pending, even though the old source match is still active', async () => { + let rejectStaleReload!: (error: unknown) => void + let loaderCalls = 0 + const fooLoader = vi.fn(() => { + loaderCalls += 1 + if (loaderCalls === 1) { + return { value: 'first' } + } + + return new Promise((_resolve, reject) => { + rejectStaleReload = reject + }) + }) + const barBeforeLoadGate = createControlledPromise() + const barBeforeLoad = vi.fn(() => barBeforeLoadGate) + const bazBeforeLoad = vi.fn() + + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader: fooLoader, + staleTime: 0, + gcTime: 60_000, + }) + const barRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/bar', + beforeLoad: barBeforeLoad, + }) + const bazRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/baz', + beforeLoad: bazBeforeLoad, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute, barRoute, bazRoute]), + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/foo' }) + await vi.advanceTimersByTimeAsync(1) + await router.load() + await vi.waitFor(() => expect(fooLoader).toHaveBeenCalledTimes(2)) + + expect(getMatchById(router, '/foo/foo')?.isFetching).toBe('loader') + + const barNavigation = router.navigate({ to: '/bar' }) + await vi.waitFor(() => expect(barBeforeLoad).toHaveBeenCalledTimes(1)) + expect(hasActiveMatch(router, '/foo/foo')).toBe(true) + expect(hasPendingMatch(router, '/bar/bar')).toBe(true) + + rejectStaleReload(redirect({ to: '/baz' })) + await Promise.resolve() + + expect(bazBeforeLoad).not.toHaveBeenCalled() + + barBeforeLoadGate.resolve() + await barNavigation + + expect(router.state.location.pathname).toBe('/bar') + expect(bazBeforeLoad).not.toHaveBeenCalled() + expectNoCachedActiveOverlap(router) + }) + + test('soft background AbortError preserves data and updatedAt and clears fetching', async () => { + let rejectStaleReload!: (error: unknown) => void + let loaderCalls = 0 + const loader = vi.fn(() => { + loaderCalls += 1 + if (loaderCalls === 1) { + return { value: 'old' } + } + + return new Promise((_resolve, reject) => { + rejectStaleReload = reject + }) + }) + const head = vi.fn(({ loaderData }) => ({ + meta: [{ title: loaderData.value }], + })) + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader, + head, + staleTime: 0, + gcTime: 60_000, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute]), + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/foo' }) + const initialMatch = getMatchById(router, '/foo/foo')! + const initialUpdatedAt = initialMatch.updatedAt + expect(initialMatch.loaderData).toEqual({ value: 'old' }) + expect(getTitle(initialMatch)).toBe('old') + head.mockClear() + + await vi.advanceTimersByTimeAsync(1) + await router.load() + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(2)) + + expect(getMatchById(router, '/foo/foo')?.isFetching).toBe('loader') + + const abortError = new Error('soft aborted') + abortError.name = 'AbortError' + rejectStaleReload(abortError) + + await vi.waitFor(() => + expect(getMatchById(router, '/foo/foo')?.isFetching).toBe(false), + ) + + const currentMatch = getMatchById(router, '/foo/foo')! + expect(currentMatch.loaderData).toEqual({ value: 'old' }) + expect(currentMatch.updatedAt).toBe(initialUpdatedAt) + expect(getTitle(currentMatch)).toBe('old') + expect(head).toHaveBeenCalledTimes(1) + }) + + test('pending preload error leaves no cache entry', async () => { + let rejectPreload!: (error: unknown) => void + const loader = vi.fn(() => { + return new Promise((_resolve, reject) => { + rejectPreload = reject + }) + }) + const router = setup({ loader }) + + const preload = router.preloadRoute({ to: '/foo' }) + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(1)) + + expect(getMatchById(router, '/foo/foo')).toBeUndefined() + expect(router.stores.cachedMatches.get()).toEqual([]) + + rejectPreload(new Error('preload failed')) + await preload + + expect( + router.stores.cachedMatches + .get() + .some((match) => match.id === '/foo/foo'), + ).toBe(false) + }) }) test('cancelMatches after pending timeout', async () => { @@ -1197,13 +7123,659 @@ test('cancelMatches after pending timeout', async () => { expect(router.state.location.pathname).toBe('/bar') - // Verify that abort was called and pending timeout was cleared + // Verify that abort was called and no stale pending route remains active. expect(onAbortMock).toHaveBeenCalled() const cancelledFooMatch = router.getMatch('/foo/foo') - expect(cancelledFooMatch?._nonReactive.pendingTimeout).toBeUndefined() + expect(cancelledFooMatch?.status).not.toBe('pending') +}) + +test('pending timeout stays scoped to the current load pass', async () => { + vi.useFakeTimers() + + try { + const WAIT_TIME = 5 + let resolveLoader!: () => void + const loader = vi.fn( + () => + new Promise((resolve) => { + resolveLoader = resolve + }), + ) + + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + pendingMs: WAIT_TIME, + loader, + pendingComponent: {}, + }) + const routeTree = rootRoute.addChildren([fooRoute]) + const router = createTestRouter({ + routeTree, + history: createMemoryHistory(), + }) + + await router.load() + const navigation = router.navigate({ to: '/foo' }) + await vi.advanceTimersByTimeAsync(WAIT_TIME * 2) + + const firstPendingMatch = router.getMatch('/foo/foo') + expect(firstPendingMatch?.status).toBe('pending') + + const joinedLoad = router.load() + await Promise.resolve() + + const rearmedMatch = router.getMatch('/foo/foo') + expect(rearmedMatch?.status).toBe('pending') + + await vi.advanceTimersByTimeAsync(WAIT_TIME * 2) + expect(rearmedMatch?.status).toBe('pending') + + resolveLoader() + await Promise.all([navigation, joinedLoad]) + expect(loader).toHaveBeenCalledTimes(2) + } finally { + vi.useRealTimers() + } +}) + +test('pendingMin wait does not throw after its match is canceled', async () => { + vi.useFakeTimers() + + try { + let resolveLoader!: () => void + const rootRoute = new BaseRootRoute({}) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + pendingMs: 0, + pendingMinMs: 100, + pendingComponent: () => null, + loader: () => + new Promise((resolve) => { + resolveLoader = resolve + }), + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([targetRoute]), + history: createMemoryHistory({ initialEntries: ['/target'] }), + }) + const location = router.latestLocation + const matches = router.matchRoutes(location) + router.stores.setPending(matches) + const targetMatch = matches.find( + (match) => match.routeId === targetRoute.id, + )! + + const loadPromise = loadMatches({ + router, + location, + matches, + onReady: (readyMatches) => { + const readyMatch = readyMatches.find( + (match) => match.routeId === targetRoute.id, + )! + const promise = readyMatch._.loadPromise + if (promise) { + promise.pendingUntil ??= Date.now() + 100 + } + }, + }) + + await vi.advanceTimersByTimeAsync(0) + expect(router.getMatch(targetMatch.id)?.status).toBe('pending') + + resolveLoader() + await Promise.resolve() + router.cancelMatches() + + await vi.advanceTimersByTimeAsync(100) + await expect(loadPromise).resolves.toBe(matches) + } finally { + vi.useRealTimers() + } +}) + +test('cancelMatches settles pending match load promises immediately', async () => { + let resolveLoader!: () => void + const rootRoute = new BaseRootRoute({}) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + loader: () => + new Promise((resolve) => { + resolveLoader = resolve + }), + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([targetRoute]), + history: createMemoryHistory({ initialEntries: ['/target'] }), + }) + const location = router.latestLocation + const matches = router.matchRoutes(location) + router.stores.setPending(matches) + const targetMatch = matches.find((match) => match.routeId === targetRoute.id)! + + const loadPromise = loadMatches({ router, location, matches }) + await vi.waitFor(() => + expect(router.getMatch(targetMatch.id)?._.loadPromise).toBeDefined(), + ) + + const matchLoadPromise = router.getMatch(targetMatch.id)?._.loadPromise + expect(matchLoadPromise?.status).toBe('pending') + + router.cancelMatches() + + expect(matchLoadPromise?.status).toBe('resolved') + + resolveLoader() + await expect(loadPromise).resolves.toBe(matches) +}) + +test('settles load promise for pending-visible match that redirects after exiting', async () => { + vi.useFakeTimers() + + try { + let rejectLoader!: (error: unknown) => void + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const fromRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/from', + pendingMs: 1, + pendingComponent: {}, + loader: () => + new Promise((_resolve, reject) => { + rejectLoader = reject + }), + }) + const toRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/to', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, fromRoute, toRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + + const navigation = router.navigate({ to: '/from' }) + await vi.waitFor(() => expect(router.state.status).toBe('pending')) + await vi.advanceTimersByTimeAsync(1) + await vi.waitFor(() => + expect( + router.state.matches.some( + (match) => match.id === '/from/from' && match.status === 'pending', + ), + ).toBe(true), + ) + + const fromMatch = router.state.matches.find( + (match) => match.id === '/from/from', + )! + const loadPromise = fromMatch._.loadPromise + + expect(loadPromise?.status).toBe('pending') + + rejectLoader(redirect({ to: '/to' })) + await navigation + + expect(router.state.location.pathname).toBe('/to') + expect(loadPromise?.status).toBe('resolved') + expect(fromMatch._.loadPromise).toBeUndefined() + expect( + router.stores.cachedMatches + .get() + .some((match) => match.id === '/from/from'), + ).toBe(false) + } finally { + vi.useRealTimers() + } +}) + +test('ignores late loader resolution after pending-visible match exits', async () => { + vi.useFakeTimers() + + try { + let resolveLoader!: () => void + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const fromRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/from', + pendingMs: 1, + pendingComponent: {}, + loader: () => + new Promise((resolve) => { + resolveLoader = resolve + }), + }) + const toRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/to', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, fromRoute, toRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + + const fromNavigation = router.navigate({ to: '/from' }) + await vi.waitFor(() => expect(router.state.status).toBe('pending')) + await vi.advanceTimersByTimeAsync(1) + await vi.waitFor(() => + expect( + router.state.matches.some( + (match) => match.id === '/from/from' && match.status === 'pending', + ), + ).toBe(true), + ) + + const fromMatch = router.state.matches.find( + (match) => match.id === '/from/from', + )! + const loadPromise = fromMatch._.loadPromise + loadPromise!.pendingUntil = Date.now() + 100 + + expect(loadPromise?.status).toBe('pending') + + await router.navigate({ to: '/to' }) + + expect(router.state.location.pathname).toBe('/to') + expect(loadPromise?.status).toBe('resolved') + expect(fromMatch._.loadPromise).toBeUndefined() + + resolveLoader() + await fromNavigation + + expect(router.state.location.pathname).toBe('/to') + expect( + router.stores.cachedMatches + .get() + .some((match) => match.id === '/from/from'), + ).toBe(false) + } finally { + vi.useRealTimers() + } +}) + +test('settles promises for pending-visible match whose loader rejects AbortError after exiting', async () => { + vi.useFakeTimers() + + try { + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const fromRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/from', + pendingMs: 1, + pendingComponent: {}, + loader: ({ abortController }) => + new Promise((_resolve, reject) => { + abortController.signal.addEventListener('abort', () => { + const abortError = new Error('aborted') + abortError.name = 'AbortError' + reject(abortError) + }) + }), + }) + const toRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/to', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, fromRoute, toRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + + const fromNavigation = router.navigate({ to: '/from' }) + await vi.waitFor(() => expect(router.state.status).toBe('pending')) + await vi.advanceTimersByTimeAsync(1) + await vi.waitFor(() => + expect( + router.state.matches.some( + (match) => match.id === '/from/from' && match.status === 'pending', + ), + ).toBe(true), + ) + + const fromMatch = router.state.matches.find( + (match) => match.id === '/from/from', + )! + const loadPromise = fromMatch._.loadPromise + + expect(loadPromise?.status).toBe('pending') + + await router.navigate({ to: '/to' }) + await fromNavigation + + expect(router.state.location.pathname).toBe('/to') + expect(loadPromise?.status).toBe('resolved') + expect(fromMatch._.loadPromise).toBeUndefined() + expect( + router.stores.cachedMatches + .get() + .some((match) => match.id === '/from/from'), + ).toBe(false) + } finally { + vi.useRealTimers() + } +}) + +test('loader AbortError respects pendingMinMs before committing error', async () => { + vi.useFakeTimers() + + try { + const abortError = new Error('soft aborted') + abortError.name = 'AbortError' + const rootRoute = new BaseRootRoute({}) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + pendingMs: 0, + pendingMinMs: 100, + pendingComponent: () => null, + loader: () => + new Promise((_resolve, reject) => { + setTimeout(() => { + reject(abortError) + }, 10) + }), + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([targetRoute]), + history: createMemoryHistory({ initialEntries: ['/target'] }), + }) + const location = router.latestLocation + const matches = router.matchRoutes(location) + router.stores.setPending(matches) + const targetMatch = matches.find( + (match) => match.routeId === targetRoute.id, + )! + const initialUpdatedAt = targetMatch.updatedAt + + const loadPromise = loadMatches({ + router, + location, + matches, + onReady: async (readyMatches) => { + const readyMatch = readyMatches.find( + (match) => match.routeId === targetRoute.id, + )! + readyMatch._.loadPromise!.pendingUntil = Date.now() + 100 + }, + }) + + await vi.advanceTimersByTimeAsync(0) + await vi.advanceTimersByTimeAsync(10) + await Promise.resolve() + + expect(router.getMatch(targetMatch.id)?.status).toBe('pending') + + await vi.advanceTimersByTimeAsync(89) + expect(router.getMatch(targetMatch.id)?.status).toBe('pending') + + await vi.advanceTimersByTimeAsync(1) + await loadPromise + + const updatedMatch = getLaneMatch(matches, targetMatch.id) + expect(updatedMatch?.status).toBe('error') + expect(updatedMatch?.error).toBe(abortError) + expect(updatedMatch?.updatedAt).toBeGreaterThan(initialUpdatedAt) + expect(updatedMatch?._.loadPromise).toBeUndefined() + } finally { + vi.useRealTimers() + } +}) + +test('loader AbortError waits for route component preload before committing error', async () => { + const abortError = new Error('soft aborted') + abortError.name = 'AbortError' + const componentGate = createControlledPromise() + const rootRoute = new BaseRootRoute({}) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + loader: () => { + throw abortError + }, + component: { preload: () => componentGate } as any, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([targetRoute]), + history: createMemoryHistory({ initialEntries: ['/target'] }), + }) + const location = router.latestLocation + const matches = router.matchRoutes(location) + router.stores.setPending(matches) + const targetMatch = matches.find((match) => match.routeId === targetRoute.id)! + + let loadSettled = false + const loadPromise = loadMatches({ router, location, matches }).finally(() => { + loadSettled = true + }) + + await vi.waitFor(() => + expect(router.getMatch(targetMatch.id)?._.loadPromise?.status).toBe( + 'pending', + ), + ) + expect(router.getMatch(targetMatch.id)?.status).toBe('pending') + expect(loadSettled).toBe(false) + + componentGate.resolve() + await loadPromise + + const updatedMatch = getLaneMatch(matches, targetMatch.id) + expect(updatedMatch?.status).toBe('error') + expect(updatedMatch?.error).toBe(abortError) + expect(updatedMatch?._.loadPromise).toBeUndefined() +}) + +test('loader AbortError followed by component preload failure commits error', async () => { + const chunkError = new Error('chunk failed') + const componentGate = createControlledPromise() + const rootRoute = new BaseRootRoute({}) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + loader: () => { + const abortError = new Error('soft aborted') + abortError.name = 'AbortError' + throw abortError + }, + component: { preload: () => componentGate } as any, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([targetRoute]), + history: createMemoryHistory({ initialEntries: ['/target'] }), + }) + const location = router.latestLocation + const matches = router.matchRoutes(location) + router.stores.setPending(matches) + const targetMatch = matches.find((match) => match.routeId === targetRoute.id)! + + const loadPromise = loadMatches({ router, location, matches }).then( + () => undefined, + (err) => err, + ) + + await vi.waitFor(() => + expect(router.getMatch(targetMatch.id)?._.loadPromise?.status).toBe( + 'pending', + ), + ) + + componentGate.reject(chunkError) + + await expect(loadPromise).resolves.toBeUndefined() + const updatedMatch = getLaneMatch(matches, targetMatch.id) + expect(updatedMatch?.status).toBe('error') + expect(updatedMatch?.error).toBe(chunkError) + expect(updatedMatch?._.loadPromise).toBeUndefined() +}) + +test('lazy route AbortError is not treated as a soft loader abort', async () => { + const abortError = new Error('lazy aborted') + abortError.name = 'AbortError' + const lazyGate = createControlledPromise() + const rootRoute = new BaseRootRoute({}) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + loader: () => 'loaded', + }).lazy(() => lazyGate) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([targetRoute]), + history: createMemoryHistory({ initialEntries: ['/target'] }), + }) + const location = router.latestLocation + const matches = router.matchRoutes(location) + router.stores.setPending(matches) + const targetMatch = matches.find((match) => match.routeId === targetRoute.id)! + + const loadPromise = loadMatches({ router, location, matches }).then( + () => undefined, + (err) => err, + ) + await vi.waitFor(() => + expect(router.getMatch(targetMatch.id)?._.loadPromise).toBeDefined(), + ) + + lazyGate.reject(abortError) + + await expect(loadPromise).resolves.toBeUndefined() + const updatedMatch = getLaneMatch(matches, targetMatch.id) + expect(updatedMatch?.status).toBe('error') + expect(updatedMatch?.error).toBe(abortError) + expect(updatedMatch?._.loadPromise).toBeUndefined() }) describe('head execution', () => { + test('client asset projection never mutates the input match object', async () => { + const oldMeta = [{ title: 'old' }] + const rootRoute = new BaseRootRoute({}) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + head: () => ({ meta: [{ title: 'new' }] }), + scripts: () => [{ children: 'target-script' }], + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([targetRoute]), + history: createMemoryHistory({ initialEntries: ['/target'] }), + }) + const matches = router.matchRoutes(router.stores.location.get()) + const original = matches.find((match) => match.routeId === targetRoute.id)! + original.meta = oldMeta + Object.freeze(original) + + await projectAssets({ router, matches }) + + const updated = matches[original.index]! + expect(updated).not.toBe(original) + expect(original.meta).toBe(oldMeta) + expect(updated.meta).toEqual([{ title: 'new' }]) + expect(updated.scripts).toEqual([{ children: 'target-script' }]) + }) + + test('client asset projection handles async head rejection after scripts throws', async () => { + const headGate = createControlledPromise<{ + meta: Array<{ title: string }> + }>() + const unhandledRejection = vi.fn() + const consoleError = vi + .spyOn(console, 'error') + .mockImplementation(() => undefined) + process.on('unhandledRejection', unhandledRejection) + + try { + const scriptsError = new Error('scripts failed') + const rootRoute = new BaseRootRoute({}) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + head: () => headGate, + scripts: () => { + throw scriptsError + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([targetRoute]), + history: createMemoryHistory({ initialEntries: ['/target'] }), + }) + const matches = router.matchRoutes(router.stores.location.get()) + + await projectAssets({ router, matches }) + headGate.reject(new Error('head failed late')) + await new Promise((resolve) => setTimeout(resolve, 0)) + + expect(unhandledRejection).not.toHaveBeenCalled() + } finally { + process.off('unhandledRejection', unhandledRejection) + consoleError.mockRestore() + } + }) + + test('server asset projection handles async head and scripts rejection after headers throws', async () => { + const headGate = createControlledPromise<{ + meta: Array<{ title: string }> + }>() + const scriptsGate = createControlledPromise>() + const unhandledRejection = vi.fn() + const consoleError = vi + .spyOn(console, 'error') + .mockImplementation(() => undefined) + process.on('unhandledRejection', unhandledRejection) + + try { + const headersError = new Error('headers failed') + const rootRoute = new BaseRootRoute({}) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + head: () => headGate, + scripts: () => scriptsGate, + headers: () => { + throw headersError + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([targetRoute]), + history: createMemoryHistory({ initialEntries: ['/target'] }), + isServer: true, + }) + const matches = router.matchRoutes(router.stores.location.get()) + const assets = projectServerRouteAssets(router, matches) + if (assets) { + await assets + } + + headGate.reject(new Error('head failed late')) + scriptsGate.reject(new Error('scripts failed late')) + await new Promise((resolve) => setTimeout(resolve, 0)) + + expect(unhandledRejection).not.toHaveBeenCalled() + } finally { + process.off('unhandledRejection', unhandledRejection) + consoleError.mockRestore() + } + }) + const setupBeforeLoadNotFoundHierarchy = (throwAtIndex: 1 | 2 | 3) => { const loaderResolvers: Array<(() => void) | undefined> = [] @@ -1291,6 +7863,99 @@ describe('head execution', () => { } } + test('head-triggered navigation prevents scripts and descendant assets from running', async () => { + let router!: AnyRouter + const staleScripts = vi.fn(() => []) + const staleChildHead = vi.fn(() => ({})) + const barBeforeLoad = vi.fn() + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + head: () => { + void router.navigate({ to: '/bar' }) + return {} + }, + scripts: staleScripts, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => fooRoute, + path: '/child', + head: staleChildHead, + }) + const barRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/bar', + beforeLoad: barBeforeLoad, + }) + + router = createTestRouter({ + routeTree: rootRoute.addChildren([ + fooRoute.addChildren([childRoute]), + barRoute, + ]), + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/foo/child' }).catch(() => undefined) + await vi.waitFor(() => expect(router.state.location.pathname).toBe('/bar')) + + expect(staleScripts).not.toHaveBeenCalled() + expect(staleChildHead).not.toHaveBeenCalled() + expect(barBeforeLoad).toHaveBeenCalledTimes(1) + }) + + test('same-href head reentry cannot run stale scripts or descendant heads', async () => { + let router!: AnyRouter + let reenter = false + let didNavigate = false + let headPass = 0 + let navigation: Promise | undefined + const scripts = vi.fn(() => []) + const childHead = vi.fn(() => ({})) + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + head: () => { + headPass += 1 + if (reenter && !didNavigate) { + didNavigate = true + navigation = Promise.resolve(router.navigate({ to: '/foo/child' })) + return { meta: [{ title: 'stale' }] } + } + return { meta: [{ title: 'fresh' }] } + }, + scripts, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => fooRoute, + path: '/child', + head: childHead, + }) + + router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/foo/child'] }), + }) + + await router.load() + scripts.mockClear() + childHead.mockClear() + headPass = 0 + reenter = true + + await router.load() + await navigation + + expect(headPass).toBe(2) + expect(scripts).toHaveBeenCalledTimes(1) + expect(childHead).toHaveBeenCalledTimes(1) + expect( + router.state.matches.find((match) => match.routeId === fooRoute.id)?.meta, + ).toEqual([{ title: 'fresh' }]) + }) + const assertBeforeLoadNotFoundHierarchy = async (throwAtIndex: 1 | 2 | 3) => { const { router, routes, loaders, heads, loaderResolvers } = setupBeforeLoadNotFoundHierarchy(throwAtIndex) @@ -1343,6 +8008,146 @@ describe('head execution', () => { }) }) + test('synchronous head hooks execute serially in the same turn', async () => { + let yielded = false + const parentHead = vi.fn(() => { + queueMicrotask(() => { + yielded = true + }) + return {} + }) + const childHead = vi.fn(() => { + expect(yielded).toBe(false) + return {} + }) + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + head: parentHead, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + head: childHead, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + }) + + await router.load() + + expect(parentHead).toHaveBeenCalledTimes(1) + expect(childHead).toHaveBeenCalledTimes(1) + + await Promise.resolve() + expect(yielded).toBe(true) + }) + + test('synchronous parent scripts do not insert a microtask before child head', async () => { + let yielded = false + const parentScripts = vi.fn(() => { + queueMicrotask(() => { + yielded = true + }) + return [] + }) + const childHead = vi.fn(() => { + expect(yielded).toBe(false) + return {} + }) + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + scripts: parentScripts, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + head: childHead, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + }) + + await router.load() + + expect(parentScripts).toHaveBeenCalledTimes(1) + expect(childHead).toHaveBeenCalledTimes(1) + + await Promise.resolve() + expect(yielded).toBe(true) + }) + + test('synchronous head that starts a newer navigation and throws stops the old pass', async () => { + const oldHeadError = new Error('old head') + const oldChildHead = vi.fn(() => ({})) + const oldOnReady = vi.fn() + const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}) + let current = true + + try { + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + head: () => { + current = false + void router.navigate({ to: '/bar' }) + throw oldHeadError + }, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => fooRoute, + path: '/child', + head: oldChildHead, + }) + const barRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/bar', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + fooRoute.addChildren([childRoute]), + barRoute, + ]), + history: createMemoryHistory(), + }) + + const location = router.buildLocation({ to: '/foo/child' }) + const matches = router.matchRoutes(location) + router.stores.setPending(matches) + + await loadMatches({ + router, + location, + matches, + onReady: async () => { + oldOnReady() + }, + }) + await projectAssets({ + router, + matches, + isCurrent: () => current, + }) + await vi.waitFor(() => + expect(router.state.location.pathname).toBe('/bar'), + ) + + expect(consoleError).not.toHaveBeenCalled() + expect(oldChildHead).not.toHaveBeenCalled() + expect(oldOnReady).not.toHaveBeenCalled() + } finally { + consoleError.mockRestore() + } + }) + test('executes head once when loader throws notFound', async () => { const head = vi.fn(() => ({ meta: [{ title: 'Test' }] })) const rootRoute = new BaseRootRoute({}) @@ -1400,14 +8205,12 @@ describe('head execution', () => { const matches = router.matchRoutes(location) router.stores.setPending(matches) - await expect( - loadMatches({ - router, - location, - matches, - updateMatch: router.updateMatch, - }), - ).rejects.toBe(beforeLoadError) + await loadMatches({ + router, + location, + matches, + }) + await projectAssets({ router, matches }) expect(rootLoader).toHaveBeenCalledTimes(1) expect(childLoader).toHaveBeenCalledTimes(0) @@ -1417,6 +8220,42 @@ describe('head execution', () => { expect(childHead).toHaveBeenCalledTimes(1) }) + test('settles loadPromise when beforeLoad throws non-notFound error', async () => { + const beforeLoadError = new Error('beforeLoad-sync-error') + const rootRoute = new BaseRootRoute({}) + + const childRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/test', + beforeLoad: () => { + throw beforeLoadError + }, + }) + + const routeTree = rootRoute.addChildren([childRoute]) + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/test'] }), + }) + + const location = router.latestLocation + const matches = router.matchRoutes(location) + const childMatch = matches[1]! + const loadPromise = childMatch._.loadPromise + router.stores.setPending(matches) + + await loadMatches({ + router, + location, + matches, + }) + + const updatedMatch = getLaneMatch(matches, childMatch.id) + expect(updatedMatch?.status).toBe('error') + expect(loadPromise?.status).toBe('resolved') + expect(updatedMatch?._.loadPromise).toBeUndefined() + }) + test('propagates async beforeLoad non-notFound error running ancestor loaders and heads', async () => { const beforeLoadError = new Error('beforeLoad-async-error') const rootLoader = vi.fn(() => ({ level: 0 })) @@ -1451,14 +8290,12 @@ describe('head execution', () => { const matches = router.matchRoutes(location) router.stores.setPending(matches) - await expect( - loadMatches({ - router, - location, - matches, - updateMatch: router.updateMatch, - }), - ).rejects.toBe(beforeLoadError) + await loadMatches({ + router, + location, + matches, + }) + await projectAssets({ router, matches }) expect(rootLoader).toHaveBeenCalledTimes(1) expect(childLoader).toHaveBeenCalledTimes(0) @@ -1470,13 +8307,13 @@ describe('head execution', () => { describe('beforeLoad notFound parent loader outcomes', () => { type ThrowAtIndex = 1 | 2 | 3 - type ParentFailure = 'notFound' | 'redirect' | 'error' + type ParentFailure = 'notFound' | 'redirect' type ParentFailureMap = Partial> type Scenario = { name: string throwAtIndex: ThrowAtIndex parentFailures: ParentFailureMap - expectedErrorKind: 'notFound' | 'redirect' | 'error' + expectedErrorKind: 'notFound' | 'redirect' expectedErrorSource?: string expectedErrorRouteIndex?: 0 | 1 | 2 | 3 expectedLoaderMaxIndex: number @@ -1485,7 +8322,6 @@ describe('head execution', () => { beforeLoadNotFoundFactory?: ( routes: readonly [any, any, any, any], ) => ReturnType - expectRootNotFoundComponentAssigned?: boolean } const setupScenario = ({ @@ -1552,14 +8388,6 @@ describe('head execution', () => { const routes = [rootRoute, level1Route, level2Route, level3Route] as const - ;([0, 1, 2] as const).forEach((index) => { - if (parentFailures[index] === 'error') { - ;(routes[index].options as any).shouldReload = () => { - throw new Error(`loader-${index}-error`) - } - } - }) - const throwRoute = routes[throwAtIndex]! throwRoute.options.beforeLoad = () => { const beforeLoadNotFound = beforeLoadNotFoundFactory @@ -1593,7 +8421,10 @@ describe('head execution', () => { } } - const runLoadMatchesAndCapture = async (router: AnyRouter) => { + const runLoadMatchesAndCapture = async ( + router: AnyRouter, + _headCount?: number, + ) => { const location = router.latestLocation const matches = router.matchRoutes(location) router.stores.setPending(matches) @@ -1603,12 +8434,15 @@ describe('head execution', () => { router, location, matches, - updateMatch: router.updateMatch, }) - return { error: undefined, matches } } catch (error) { + if (!isRedirect(error)) { + await projectAssets({ router, matches }) + } return { error, matches } } + await projectAssets({ router, matches }) + return { error: undefined, matches } } const scenarios = [ @@ -1692,7 +8526,7 @@ describe('head execution', () => { }), }, { - name: 'assigns defaultNotFoundComponent on root when unknown routeId falls back to root', + name: 'uses defaultNotFoundComponent without mutating root route when unknown routeId falls back to root', throwAtIndex: 3 as const, parentFailures: {} as ParentFailureMap, expectedErrorKind: 'notFound' as const, @@ -1700,7 +8534,6 @@ describe('head execution', () => { expectedLoaderMaxIndex: 0, expectedRenderedHeadMaxIndex: 0, withDefaultNotFoundComponent: true, - expectRootNotFoundComponentAssigned: true, beforeLoadNotFoundFactory: () => notFound({ routeId: '/does-not-exist' as never, @@ -1725,15 +8558,6 @@ describe('head execution', () => { expectedLoaderMaxIndex: 2, expectedRenderedHeadMaxIndex: -1, }, - { - name: 'propagates regular loader error when mixed with loader notFound in settled loaders', - throwAtIndex: 3 as const, - parentFailures: { 1: 'notFound', 2: 'error' } as ParentFailureMap, - expectedErrorKind: 'error' as const, - expectedErrorSource: 'loader-2-error', - expectedLoaderMaxIndex: 1, - expectedRenderedHeadMaxIndex: -1, - }, ] satisfies Array test.each(scenarios)('$name', async (scenario) => { @@ -1744,7 +8568,10 @@ describe('head execution', () => { withDefaultNotFoundComponent: scenario.withDefaultNotFoundComponent, }) - const { error, matches } = await runLoadMatchesAndCapture(router) + const { error, matches } = await runLoadMatchesAndCapture( + router, + scenario.expectedRenderedHeadMaxIndex + 1, + ) for (let i = 0; i < routes.length; i++) { const loader = loaders[i]! @@ -1761,7 +8588,6 @@ describe('head execution', () => { if (scenario.expectedErrorKind === 'redirect') { expect(error).toEqual( expect.objectContaining({ - redirectHandled: true, options: expect.objectContaining({ to: '/redirect-target', }), @@ -1770,12 +8596,6 @@ describe('head execution', () => { return } - if (scenario.expectedErrorKind === 'error') { - expect(error).toBeInstanceOf(Error) - expect((error as Error).message).toBe(scenario.expectedErrorSource) - return - } - expect(error).toEqual( expect.objectContaining({ isNotFound: true, @@ -1789,8 +8609,9 @@ describe('head execution', () => { ) } - if (scenario.expectRootNotFoundComponentAssigned) { - expect(routes[0].options.notFoundComponent).toBeTypeOf('function') + if (scenario.withDefaultNotFoundComponent) { + expect(routes[0].options.notFoundComponent).toBeUndefined() + expect(matches[0]?.globalNotFound).toBe(true) } }) @@ -1814,42 +8635,13 @@ describe('head execution', () => { }), ) - const rootMatch = router.stores.pendingMatches - .get() - .find((m) => m.routeId === routes[0].id) + const rootMatch = matches.find((m) => m.routeId === routes[0].id) expect(rootMatch?.globalNotFound).toBe(true) expect(rootMatch?.status).toBe('success') expect(rootMatch?.error).toBeUndefined() }) - test('clears stale root globalNotFound on subsequent successful load', async () => { - const { router, routes } = setupScenario({ - throwAtIndex: 3, - parentFailures: {}, - beforeLoadNotFoundFactory: (innerRoutes) => - notFound({ - routeId: innerRoutes[0].id as never, - data: { source: 'beforeLoad-root-explicit' }, - }), - }) - - const first = await runLoadMatchesAndCapture(router) - expect(first.error).toEqual(expect.objectContaining({ isNotFound: true })) - - const throwingRoute = routes[3] - throwingRoute.options.beforeLoad = undefined - - const second = await runLoadMatchesAndCapture(router) - expect(second.error).toBeUndefined() - - const rootMatch = router.stores.pendingMatches - .get() - .find((m) => m.routeId === routes[0].id) - - expect(rootMatch?.globalNotFound).toBe(false) - }) - test('clears stale root globalNotFound when root loader is skipped', async () => { const rootLoader = vi.fn(() => ({ level: 0 })) const rootRoute = new BaseRootRoute({ @@ -1871,51 +8663,69 @@ describe('head execution', () => { const router = createTestRouter({ routeTree, - history: createMemoryHistory({ initialEntries: ['/test'] }), + history: createMemoryHistory({ initialEntries: ['/missing'] }), }) - const first = await runLoadMatchesAndCapture(router) - expect(first.error).toBeUndefined() + await router.load() + const missingRootMatch = router.state.matches.find( + (m) => m.routeId === rootRoute.id, + ) + expect(missingRootMatch?.globalNotFound).toBe(true) expect(rootLoader).toHaveBeenCalledTimes(1) - const staleRootNotFound = notFound({ data: { source: 'stale-root' } }) - const currentRootMatchId = router.stores.pendingMatches - .get() - .find((m) => m.routeId === rootRoute.id)!.id - - router.updateMatch(currentRootMatchId, (prev) => ({ - ...prev, - status: 'success', - globalNotFound: true, - error: staleRootNotFound, - })) - - const location = router.latestLocation - const matches = router.matchRoutes(location) - const pendingRootMatch = matches.find((m) => m.routeId === rootRoute.id)! - pendingRootMatch.status = 'success' - pendingRootMatch.globalNotFound = false - pendingRootMatch.error = undefined - router.stores.setPending(matches) - - await expect( - loadMatches({ - router, - location, - matches, - updateMatch: router.updateMatch, - }), - ).resolves.toBe(matches) - + await router.navigate({ to: '/test' }) expect(rootLoader).toHaveBeenCalledTimes(1) + expect(childLoader).toHaveBeenCalledTimes(1) - const rootMatch = router.stores.pendingMatches - .get() - .find((m) => m.routeId === rootRoute.id) + const rootMatch = router.state.matches.find( + (m) => m.routeId === rootRoute.id, + ) expect(rootMatch?.globalNotFound).toBe(false) expect(rootMatch?.error).toBeUndefined() }) + + test('keeps root globalNotFound from overlapping stale initial load', async () => { + const rootRoute = new BaseRootRoute({ + notFoundComponent: () => null, + }) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, postsRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + const matchResult = router.getMatchedRoutes('/non-existent') + expect(matchResult.foundRoute).toBeUndefined() + expect(matchResult.matchedRoutes.map((route) => route.id)).toEqual([ + rootRoute.id, + ]) + + const initialLoad = router.load() + const notFoundNavigation = router.navigate({ + to: '/non-existent' as never, + }) + + await Promise.all([initialLoad, notFoundNavigation]) + + expect(router.state.location.pathname).toBe('/non-existent') + expect(router.state.matches).toHaveLength(1) + expect(router.state.matches[0]).toEqual( + expect.objectContaining({ + routeId: rootRoute.id, + status: 'success', + globalNotFound: true, + }), + ) + }) }) }) @@ -1975,7 +8785,6 @@ describe('params.parse notFound', () => { const match = router.state.matches.find((m) => m.routeId === testRoute.id) expect(match?.status).toBe('success') - expect(router.state.statusCode).toBe(200) }) }) @@ -2174,6 +8983,3331 @@ describe('routeId in context options', () => { }), ) }) + + test('context receives preload classification from the matching operation', async () => { + const contextCalls: Array<{ preload: boolean; deps: unknown }> = [] + const rootRoute = new BaseRootRoute({}) + + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loaderDeps: ({ search }: { search: Record }) => ({ + q: search['q'], + }), + loader: () => undefined, + context: ({ preload, deps }) => { + contextCalls.push({ preload, deps }) + }, + preloadStaleTime: Infinity, + staleTime: Infinity, + gcTime: Infinity, + }) + + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, fooRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.preloadRoute({ + to: '/foo', + search: { q: 'preload' }, + } as never) + await router.navigate({ + to: '/foo', + search: { q: 'navigate' }, + } as never) + await router.navigate({ + to: '/foo', + search: { q: 'preload' }, + } as never) + + expect(contextCalls).toEqual([ + { preload: true, deps: { q: 'preload' } }, + { preload: false, deps: { q: 'navigate' } }, + ]) + }) + + test('preload-created matches carry preload cause', async () => { + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader: () => undefined, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute]), + history: createMemoryHistory(), + }) + + const matches = await router.preloadRoute({ to: '/foo' }) + const fooMatch = matches?.find((match) => match.routeId === fooRoute.id) + + expect(fooMatch?.cause).toBe('preload') + }) +}) + +describe('beforeLoad context lifecycle', () => { + test('cached preload reload commits fresh beforeLoad context to returned match context', async () => { + let token = 'one' + const beforeLoad = vi.fn(() => ({ token })) + + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + beforeLoad, + preloadStaleTime: Infinity, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute]), + history: createMemoryHistory(), + }) + + const first = await router.preloadRoute({ to: '/foo' }) + const firstMatch = first?.find((match) => match.routeId === fooRoute.id) + + expect(firstMatch?.__beforeLoadContext).toEqual({ token: 'one' }) + expect(firstMatch?.context).toMatchObject({ token: 'one' }) + + token = 'two' + + const second = await router.preloadRoute({ to: '/foo' }) + const secondMatch = second?.find((match) => match.routeId === fooRoute.id) + + expect(beforeLoad).toHaveBeenCalledTimes(2) + expect(secondMatch?.__beforeLoadContext).toEqual({ token: 'two' }) + expect(secondMatch?.context).toMatchObject({ token: 'two' }) + }) + + test('clears stale beforeLoad context when a later run returns undefined', async () => { + let returnContext = true + const seenContexts: Array> = [] + + const rootRoute = new BaseRootRoute({ + beforeLoad: () => { + return returnContext ? { token: 'one' } : undefined + }, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/child', + staleTime: 0, + loader: ({ context }) => { + seenContexts.push(context) + }, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([childRoute]), + history: createMemoryHistory({ initialEntries: ['/child'] }), + }) + + await router.load() + expect(seenContexts.at(-1)).toMatchObject({ token: 'one' }) + + returnContext = false + await router.invalidate({ sync: true }) + + expect(seenContexts.at(-1)).not.toHaveProperty('token') + expect(router.state.matches[0]?.__beforeLoadContext).toBeUndefined() + }) +}) + +describe('match loadPromise lifecycle', () => { + const expectNotPendingWithoutLoadPromise = (match: any) => { + expect( + match?.status === 'pending' && match._.loadPromise === undefined, + ).toBe(false) + } + + const expectBeforeLoadPendingMinimum = async ( + outcome: 'error' | 'notFound' | 'redirect', + ) => { + vi.useFakeTimers() + try { + const beforeLoadError = new Error('beforeLoad failed') + const rootRoute = new BaseRootRoute({}) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + pendingMs: 0, + pendingMinMs: 100, + pendingComponent: () => null, + beforeLoad: async () => { + await new Promise((resolve) => { + setTimeout(resolve, 10) + }) + + if (outcome === 'error') { + throw beforeLoadError + } + + if (outcome === 'notFound') { + throw notFound() + } + + throw redirect({ to: '/redirected' }) + }, + errorComponent: () => null, + notFoundComponent: () => null, + }) + const redirectedRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/redirected', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([targetRoute, redirectedRoute]), + history: createMemoryHistory({ initialEntries: ['/target'] }), + }) + const location = router.latestLocation + const matches = router.matchRoutes(location) + router.stores.setPending(matches) + const targetMatch = matches.find( + (match) => match.routeId === targetRoute.id, + )! + + const loadPromise = loadMatches({ + router, + location, + matches, + onReady: async (readyMatches) => { + const readyMatch = readyMatches.find( + (match) => match.routeId === targetRoute.id, + )! + const promise = readyMatch._.loadPromise + if (promise) { + promise.pendingUntil ??= Date.now() + 100 + } + }, + }).then( + () => undefined, + (err) => err, + ) + + await vi.advanceTimersByTimeAsync(0) + await vi.advanceTimersByTimeAsync(10) + await Promise.resolve() + + expect(router.getMatch(targetMatch.id)?.status).toBe('pending') + + await vi.advanceTimersByTimeAsync(89) + expect(router.getMatch(targetMatch.id)?.status).toBe('pending') + + await vi.advanceTimersByTimeAsync(1) + const result = await loadPromise + + const updatedMatch = getLaneMatch(matches, targetMatch.id) + if (outcome === 'error') { + expect(result).toBeUndefined() + expect(updatedMatch?.status).toBe('error') + expect(updatedMatch?.error).toBe(beforeLoadError) + } else if (outcome === 'notFound') { + expect(result).toMatchObject({ isNotFound: true }) + expect(updatedMatch?.status).toBe('notFound') + } else { + expect(result).toMatchObject({ + options: expect.objectContaining({ to: '/redirected' }), + }) + } + } finally { + vi.useRealTimers() + } + } + + test('visible pending + beforeLoad Error honors pendingMinMs', async () => { + await expectBeforeLoadPendingMinimum('error') + }) + + test('visible pending + beforeLoad notFound honors pendingMinMs', async () => { + await expectBeforeLoadPendingMinimum('notFound') + }) + + test('visible pending + beforeLoad redirect honors pendingMinMs', async () => { + await expectBeforeLoadPendingMinimum('redirect') + }) + + test('visible pending remains until beforeLoad settles after pendingMs plus pendingMinMs', async () => { + vi.useFakeTimers() + try { + const beforeLoadGate = createControlledPromise<{ auth: string }>() + const rootRoute = new BaseRootRoute({}) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + pendingMs: 10, + pendingMinMs: 50, + pendingComponent: () => null, + beforeLoad: () => beforeLoadGate, + loader: () => 'loaded', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([targetRoute]), + history: createMemoryHistory({ initialEntries: ['/target'] }), + }) + const location = router.latestLocation + const matches = router.matchRoutes(location) + router.stores.setPending(matches) + const targetMatch = matches.find( + (match) => match.routeId === targetRoute.id, + )! + let renderedMatch: AnyRouteMatch | undefined + + const loadPromise = loadMatches({ + router, + location, + matches, + onReady: (readyMatches) => { + renderedMatch = readyMatches.find( + (match) => match.routeId === targetRoute.id, + ) + const promise = renderedMatch?._.loadPromise + if (promise) { + promise.pendingUntil ??= Date.now() + 50 + } + }, + }) + + await vi.advanceTimersByTimeAsync(9) + expect(renderedMatch).toBeUndefined() + + await vi.advanceTimersByTimeAsync(1) + expect(renderedMatch?.status).toBe('pending') + const loadGeneration = renderedMatch?._.loadPromise + expect(loadGeneration?.status).toBe('pending') + + await vi.advanceTimersByTimeAsync(50) + expect(loadGeneration?.status).toBe('pending') + expect(router.getMatch(targetMatch.id)?.status).toBe('pending') + + beforeLoadGate.resolve({ auth: 'ok' }) + await loadPromise + + const updatedMatch = getLaneMatch(matches, targetMatch.id) + expect(updatedMatch?.status).toBe('success') + expect(updatedMatch?.context).toMatchObject({ auth: 'ok' }) + expect(updatedMatch?.loaderData).toBe('loaded') + expect(loadGeneration?.status).toBe('resolved') + } finally { + vi.useRealTimers() + } + }) + + test('resolved ancestor pending timer does not publish a slower child early', async () => { + vi.useFakeTimers() + try { + const childLoaderGate = createControlledPromise() + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + pendingMs: 10, + pendingComponent: () => null, + loader: async () => { + await new Promise((resolve) => { + setTimeout(resolve, 1) + }) + return 'parent' + }, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + pendingMs: 100, + pendingComponent: () => null, + loader: () => childLoaderGate, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + }) + const location = router.latestLocation + const matches = router.matchRoutes(location) + router.stores.setPending(matches) + const readySnapshots: Array> = [] + + const loadPromise = loadMatches({ + router, + location, + matches, + onReady: (readyMatches) => { + readySnapshots.push( + readyMatches.map((match) => `${match.routeId}:${match.status}`), + ) + }, + }) + + await vi.advanceTimersByTimeAsync(1) + await vi.advanceTimersByTimeAsync(9) + expect(readySnapshots).toEqual([]) + + childLoaderGate.resolve('child') + await loadPromise + + expect(readySnapshots).toEqual([]) + const childMatch = matches.find( + (match) => match.routeId === childRoute.id, + ) + expect(childMatch?.status).toBe('success') + expect(childMatch?.loaderData).toBe('child') + } finally { + vi.useRealTimers() + } + }) + + test('publishing pending UI keeps isLoading true until the final lane commits', async () => { + vi.useFakeTimers() + + try { + const loaderGate = createControlledPromise() + const rootRoute = new BaseRootRoute({}) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + pendingMs: 0, + pendingComponent: () => null, + loader: () => loaderGate, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([targetRoute]), + history: createMemoryHistory({ initialEntries: ['/target'] }), + }) + + const loadPromise = router.load() + await vi.waitFor(() => + expect( + router.state.matches.some( + (match) => + match.routeId === targetRoute.id && match.status === 'pending', + ), + ).toBe(true), + ) + + expect(router.state.isLoading).toBe(true) + + loaderGate.resolve('loaded') + await loadPromise + + const targetMatch = router.state.matches.find( + (match) => match.routeId === targetRoute.id, + )! + expect(targetMatch.status).toBe('success') + expect(targetMatch.loaderData).toBe('loaded') + expect(router.state.isLoading).toBe(false) + } finally { + vi.useRealTimers() + } + }) + + test('stale beforeLoad failure cannot overwrite a newer same-id generation', async () => { + const staleError = new Error('stale beforeLoad failed') + const errorComponentGate = createControlledPromise() + const staleHead = vi.fn() + const freshHead = vi.fn() + const staleScripts = vi.fn() + const freshScripts = vi.fn() + const staleOnReady = vi.fn() + let errorPreloadRun = 0 + const errorPreload = vi.fn(() => { + errorPreloadRun++ + return errorPreloadRun === 1 ? errorComponentGate : undefined + }) + let beforeLoadRun = 0 + const getAssetPass = ({ matches }: any) => + matches.some((match: any) => match.search?.pass === 'stale') + ? 'stale' + : 'fresh' + + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + validateSearch: (search: Record) => ({ + pass: search.pass, + }), + beforeLoad: () => { + beforeLoadRun++ + if (beforeLoadRun === 1) { + throw staleError + } + }, + loader: () => 'fresh', + head: (ctx) => { + if (getAssetPass(ctx) === 'stale') { + staleHead() + } else { + freshHead() + } + return {} + }, + scripts: (ctx) => { + if (getAssetPass(ctx) === 'stale') { + staleScripts() + } else { + freshScripts() + } + return [] + }, + errorComponent: { preload: errorPreload } as any, + }) + const barRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/bar', + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute, barRoute]), + history: createMemoryHistory(), + }) + + const fooLocation = router.buildLocation({ + to: '/foo', + search: { pass: 'stale' }, + } as never) + const firstMatches = router.matchRoutes(fooLocation) + router.stores.setPending(firstMatches) + const staleLoad = loadMatches({ + router, + location: fooLocation, + matches: firstMatches, + onReady: async (readyMatches) => { + staleOnReady(readyMatches) + }, + }) + + await vi.waitFor(() => expect(errorPreload).toHaveBeenCalledTimes(1)) + + const barLocation = router.buildLocation({ to: '/bar' }) + router.cancelMatches() + router.stores.setPending(router.matchRoutes(barLocation)) + + const freshLocation = router.buildLocation({ + to: '/foo', + search: { pass: 'fresh' }, + } as never) + const secondMatches = router.matchRoutes(freshLocation) + router.stores.setPending(secondMatches) + await loadMatches({ + router, + location: freshLocation, + matches: secondMatches, + }) + await projectAssets({ router, matches: secondMatches }) + + const freshMatchBeforeRelease = getLaneMatch( + secondMatches, + secondMatches[1]!.id, + ) + expect(freshMatchBeforeRelease?.routeId).toBe(fooRoute.id) + expect(freshMatchBeforeRelease?.status).toBe('success') + expect(freshMatchBeforeRelease?.error).toBeUndefined() + + errorComponentGate.resolve() + await expect(staleLoad).resolves.toBe(firstMatches) + + const freshMatchAfterRelease = getLaneMatch( + secondMatches, + secondMatches[1]!.id, + ) + expect(freshMatchAfterRelease?.routeId).toBe(fooRoute.id) + expect(freshMatchAfterRelease?.status).toBe('success') + expect(freshMatchAfterRelease?.error).toBeUndefined() + expect(freshMatchAfterRelease?.loaderData).toBe('fresh') + expect(beforeLoadRun).toBe(2) + expect(staleHead).not.toHaveBeenCalled() + expect(staleScripts).not.toHaveBeenCalled() + expect(staleOnReady).not.toHaveBeenCalled() + expect(freshHead).toHaveBeenCalledTimes(1) + expect(freshScripts).toHaveBeenCalledTimes(1) + }) + + test('stale pass joining an existing loader generation cannot continue after a newer same-id pass', async () => { + const loaderGate = createControlledPromise() + const loader = vi.fn(() => loaderGate) + const initialHead = vi.fn() + const staleHead = vi.fn() + const freshHead = vi.fn() + const staleScripts = vi.fn() + const freshScripts = vi.fn() + const staleOnReady = vi.fn() + const getAssetPass = ({ matches }: any) => + matches.find((match: any) => match.routeId === '/foo')?.search?.pass + + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + validateSearch: (search: Record) => ({ + pass: search.pass, + }), + loader, + head: (ctx) => { + const pass = getAssetPass(ctx) + if (pass === 'stale') { + staleHead() + } else if (pass === 'fresh') { + freshHead() + } else { + initialHead() + } + return {} + }, + scripts: (ctx) => { + if (getAssetPass(ctx) === 'stale') { + staleScripts() + } else if (getAssetPass(ctx) === 'fresh') { + freshScripts() + } + return [] + }, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute]), + history: createMemoryHistory(), + }) + + const initialLocation = router.buildLocation({ + to: '/foo', + search: { pass: 'initial' }, + } as never) + const initialMatches = router.matchRoutes(initialLocation) + router.stores.setPending(initialMatches) + const initialLoad = loadMatches({ + router, + location: initialLocation, + matches: initialMatches, + }) + + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(1)) + const fooId = initialMatches[1]!.id + const initialController = router.getMatch(fooId)!.abortController + const initialGeneration = router.getMatch(fooId)!._.loadPromise + expect(initialGeneration?.status).toBe('pending') + + const staleLocation = router.buildLocation({ + to: '/foo', + search: { pass: 'stale' }, + } as never) + const staleMatches = router.matchRoutes(staleLocation) + router.stores.setPending(staleMatches) + const staleLoad = loadMatches({ + router, + location: staleLocation, + matches: staleMatches, + onReady: async (readyMatches) => { + staleOnReady(readyMatches) + }, + }) + const staleController = router.getMatch(fooId)!.abortController + expect(staleController).not.toBe(initialController) + + router.cancelMatches() + const freshLocation = router.buildLocation({ + to: '/foo', + search: { pass: 'fresh' }, + } as never) + const freshMatches = router.matchRoutes(freshLocation) + router.stores.setPending(freshMatches) + const freshLoad = (async () => { + await loadMatches({ + router, + location: freshLocation, + matches: freshMatches, + }) + await projectAssets({ router, matches: freshMatches }) + })() + const freshController = router.getMatch(fooId)!.abortController + expect(freshController).not.toBe(staleController) + + loaderGate.resolve('loaded') + await Promise.all([initialLoad, staleLoad, freshLoad]) + + const finalMatch = getLaneMatch(freshMatches, fooId) + expect(staleHead).not.toHaveBeenCalled() + expect(staleScripts).not.toHaveBeenCalled() + expect(staleOnReady).not.toHaveBeenCalled() + expect(freshHead).toHaveBeenCalledTimes(1) + expect(freshScripts).toHaveBeenCalledTimes(1) + expect(loader).toHaveBeenCalledTimes(3) + expect(finalMatch?.status).toBe('success') + expect(finalMatch?.abortController).toBe(freshController) + expect(finalMatch?._.loadPromise).toBeUndefined() + }) + + test('late rejection from an abandoned loader does not invoke onError or error-component preload', async () => { + const loaderError = new Error('abandoned loader failed') + const loaderGate = createControlledPromise() + const loader = vi.fn(() => loaderGate) + const onError = vi.fn() + const errorComponentPreload = vi.fn() + const fooHead = vi.fn(() => ({})) + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader, + onError, + head: fooHead, + errorComponent: { preload: errorComponentPreload } as any, + }) + const barRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/bar', + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute, barRoute]), + history: createMemoryHistory({ initialEntries: ['/foo'] }), + }) + const location = router.latestLocation + const matches = router.matchRoutes(location) + router.stores.setPending(matches) + + const staleLoad = loadMatches({ router, location, matches }) + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(1)) + + const fooMatch = router.getMatch(matches[1]!.id)! + const oldLoadPromise = fooMatch._.loadPromise + errorComponentPreload.mockClear() + + await router.navigate({ to: '/bar' }) + + loaderGate.reject(loaderError) + await expect(staleLoad).resolves.toBe(matches) + + expect(onError).not.toHaveBeenCalled() + expect(errorComponentPreload).not.toHaveBeenCalled() + expect(fooHead).not.toHaveBeenCalled() + expect(router.state.location.pathname).toBe('/bar') + expect( + router.state.matches.some((match) => match.routeId === fooRoute.id), + ).toBe(false) + expect(oldLoadPromise?.status).not.toBe('pending') + }) + + test('shouldReload-triggered navigation cancels the old pass before head and onReady', async () => { + const oldHead = vi.fn(() => ({})) + const oldScripts = vi.fn(() => []) + const oldOnReady = vi.fn() + let shouldNavigate = false + let navigation: Promise | undefined + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader: () => 'foo', + shouldReload: ({ navigate }) => { + if (shouldNavigate) { + navigation = Promise.resolve(navigate({ to: '/bar' })) + return false + } + return true + }, + head: oldHead, + scripts: oldScripts, + }) + const barRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/bar', + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute, barRoute]), + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/foo' }) + oldHead.mockClear() + oldScripts.mockClear() + shouldNavigate = true + + const location = router.buildLocation({ to: '/foo' }) + const matches = router.matchRoutes(location) + router.stores.setPending(matches) + + await loadMatches({ + router, + location, + matches, + onReady: async (readyMatches) => { + oldOnReady(readyMatches) + }, + }) + await navigation + + expect(router.state.location.pathname).toBe('/bar') + expect(oldHead).not.toHaveBeenCalled() + expect(oldScripts).not.toHaveBeenCalled() + expect(oldOnReady).not.toHaveBeenCalled() + }) + + test('shouldReload navigation that returns true cancels the old pass before loader, head, and onReady', async () => { + const staleLoader = vi.fn(() => 'stale') + const staleHead = vi.fn(() => ({})) + const staleScripts = vi.fn(() => []) + const staleOnReady = vi.fn() + let shouldNavigate = false + let navigation: Promise | undefined + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader: staleLoader, + shouldReload: ({ navigate }) => { + if (shouldNavigate) { + navigation = Promise.resolve(navigate({ to: '/bar' })) + return true + } + return true + }, + head: staleHead, + scripts: staleScripts, + }) + const barRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/bar', + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute, barRoute]), + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/foo' }) + staleLoader.mockClear() + staleHead.mockClear() + staleScripts.mockClear() + shouldNavigate = true + + const location = router.buildLocation({ to: '/foo' }) + const matches = router.matchRoutes(location) + router.stores.setPending(matches) + + await loadMatches({ + router, + location, + matches, + onReady: async (readyMatches) => { + staleOnReady(readyMatches) + }, + }) + await navigation + + expect(router.state.location.pathname).toBe('/bar') + expect(staleLoader).not.toHaveBeenCalled() + expect(staleHead).not.toHaveBeenCalled() + expect(staleScripts).not.toHaveBeenCalled() + expect(staleOnReady).not.toHaveBeenCalled() + }) + + test('same-href shouldReload reentry cannot start old loader work', async () => { + const loader = vi.fn(() => 'loaded') + let reenter = false + let didNavigate = false + let navigation: Promise | undefined + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader, + shouldReload: ({ navigate }) => { + if (reenter && !didNavigate) { + didNavigate = true + navigation = Promise.resolve(navigate({ to: '/foo' })) + return true + } + return true + }, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute]), + history: createMemoryHistory({ initialEntries: ['/foo'] }), + }) + + await router.load() + loader.mockClear() + reenter = true + + await router.load() + await navigation + + expect(loader).toHaveBeenCalledTimes(1) + expect(router.state.location.pathname).toBe('/foo') + }) + + test('aborted generation does not invoke shouldReload', async () => { + const shouldReload = vi.fn(() => true) + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader: () => 'foo', + staleTime: 0, + shouldReload, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute]), + history: createMemoryHistory({ initialEntries: ['/foo'] }), + }) + + await router.load() + shouldReload.mockClear() + + const location = router.buildLocation({ to: '/foo' }) + const matches = router.matchRoutes(location) + const fooMatch = matches.find((match) => match.routeId === fooRoute.id)! + router.stores.setPending(matches) + fooMatch.abortController.abort() + + await expect( + loadMatches({ + router, + location, + matches, + }), + ).resolves.toBe(matches) + + expect(shouldReload).not.toHaveBeenCalled() + }) + + test('shouldReload that starts a newer navigation and then throws does not invoke stale onError', async () => { + const staleError = new Error('stale shouldReload reentry failed') + const staleOnError = vi.fn() + const staleErrorPreload = vi.fn() + let shouldNavigate = false + let navigation: Promise | undefined + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader: () => 'foo', + shouldReload: ({ navigate }) => { + if (shouldNavigate) { + navigation = Promise.resolve(navigate({ to: '/bar' })) + throw staleError + } + return true + }, + onError: staleOnError, + errorComponent: { preload: staleErrorPreload } as any, + }) + const barRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/bar', + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute, barRoute]), + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/foo' }) + staleErrorPreload.mockClear() + shouldNavigate = true + + const location = router.buildLocation({ to: '/foo' }) + const matches = router.matchRoutes(location) + router.stores.setPending(matches) + + await loadMatches({ + router, + location, + matches, + }) + await navigation + + expect(staleOnError).not.toHaveBeenCalled() + expect(staleErrorPreload).not.toHaveBeenCalled() + expect(router.state.location.pathname).toBe('/bar') + }) + + test('same-href beforeLoad reentry does not invoke stale onError', async () => { + const staleError = new Error('stale beforeLoad reentry failed') + const staleOnError = vi.fn() + const staleErrorPreload = vi.fn() + let reenter = false + let didNavigate = false + let navigation: Promise | undefined + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + beforeLoad: ({ navigate }) => { + if (reenter && !didNavigate) { + didNavigate = true + navigation = Promise.resolve(navigate({ to: '/foo' })) + throw staleError + } + return { didNavigate } + }, + onError: staleOnError, + errorComponent: { preload: staleErrorPreload } as any, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute]), + history: createMemoryHistory({ initialEntries: ['/foo'] }), + }) + + await router.load() + staleErrorPreload.mockClear() + reenter = true + + await router.load() + await navigation + + expect(staleOnError).not.toHaveBeenCalled() + expect(staleErrorPreload).not.toHaveBeenCalled() + expect(router.state.location.pathname).toBe('/foo') + expect( + router.state.matches.some((match) => match.error === staleError), + ).toBe(false) + }) + + test('async head from a stale same-ID pass cannot overwrite a newer pass', async () => { + const staleHeadGate = createControlledPromise<{ + meta: Array<{ title: string }> + }>() + const staleHead = vi.fn(() => staleHeadGate) + const freshHead = vi.fn(() => ({ meta: [{ title: 'fresh' }] })) + const staleChildHead = vi.fn(() => ({})) + const freshChildHead = vi.fn(() => ({})) + const staleOnReady = vi.fn() + const freshOnReady = vi.fn() + const getAssetPass = ({ matches }: any) => + matches.find((match: any) => match.routeId === '/foo')?.search?.pass + + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + validateSearch: (search: Record) => ({ + pass: search.pass, + }), + loader: () => 'loaded', + head: (ctx) => { + if (getAssetPass(ctx) === 'stale') { + staleHead() + return staleHeadGate + } + return freshHead() + }, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => fooRoute, + path: '/child', + head: (ctx) => { + if (getAssetPass(ctx) === 'stale') { + staleChildHead() + } else { + freshChildHead() + } + return {} + }, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute.addChildren([childRoute])]), + history: createMemoryHistory(), + }) + + const staleLocation = router.buildLocation({ + to: '/foo/child', + search: { pass: 'stale' }, + } as never) + const staleMatches = router.matchRoutes(staleLocation) + router.stores.setPending(staleMatches) + const fooId = staleMatches.find( + (match) => match.routeId === fooRoute.id, + )!.id + const staleLoad = (async () => { + await loadMatches({ + router, + location: staleLocation, + matches: staleMatches, + onReady: async (readyMatches) => { + staleOnReady(readyMatches) + }, + }) + await projectAssets({ + router, + matches: staleMatches, + isCurrent: () => router.getMatch(fooId)?.search.pass === 'stale', + }) + return staleMatches + })() + + await vi.waitFor(() => expect(staleHead).toHaveBeenCalledTimes(1)) + + router.cancelMatches() + const freshLocation = router.buildLocation({ + to: '/foo/child', + search: { pass: 'fresh' }, + } as never) + const freshMatches = router.matchRoutes(freshLocation) + router.stores.setPending(freshMatches) + await loadMatches({ + router, + location: freshLocation, + matches: freshMatches, + onReady: async (readyMatches) => { + freshOnReady(readyMatches) + }, + }) + await projectAssets({ router, matches: freshMatches }) + router.stores.setPending(freshMatches) + + expect(router.getMatch(fooId)?.meta).toEqual([ + expect.objectContaining({ title: 'fresh' }), + ]) + + staleHeadGate.resolve({ meta: [{ title: 'stale' }] }) + await expect(staleLoad).resolves.toBe(staleMatches) + + expect(router.getMatch(fooId)?.meta).toEqual([ + expect.objectContaining({ title: 'fresh' }), + ]) + expect(staleChildHead).not.toHaveBeenCalled() + expect(staleOnReady).not.toHaveBeenCalled() + expect(freshHead).toHaveBeenCalledTimes(1) + expect(freshChildHead).toHaveBeenCalledTimes(1) + expect(freshOnReady).not.toHaveBeenCalled() + }) + + test('rejected async head from a stale same-ID pass is ignored', async () => { + const staleHeadGate = createControlledPromise<{ + meta: Array<{ title: string }> + }>() + const staleHead = vi.fn(() => staleHeadGate) + const freshHead = vi.fn(() => ({ meta: [{ title: 'fresh' }] })) + const staleChildHead = vi.fn(() => ({})) + const freshChildHead = vi.fn(() => ({})) + const staleOnReady = vi.fn() + const freshOnReady = vi.fn() + const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}) + const getAssetPass = ({ matches }: any) => + matches.find((match: any) => match.routeId === '/foo')?.search?.pass + + try { + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + validateSearch: (search: Record) => ({ + pass: search.pass, + }), + loader: () => 'loaded', + head: (ctx) => { + if (getAssetPass(ctx) === 'stale') { + staleHead() + return staleHeadGate + } + return freshHead() + }, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => fooRoute, + path: '/child', + head: (ctx) => { + if (getAssetPass(ctx) === 'stale') { + staleChildHead() + } else { + freshChildHead() + } + return {} + }, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute.addChildren([childRoute])]), + history: createMemoryHistory(), + }) + + const staleLocation = router.buildLocation({ + to: '/foo/child', + search: { pass: 'stale' }, + } as never) + const staleMatches = router.matchRoutes(staleLocation) + router.stores.setPending(staleMatches) + const fooId = staleMatches.find( + (match) => match.routeId === fooRoute.id, + )!.id + const staleLoad = (async () => { + await loadMatches({ + router, + location: staleLocation, + matches: staleMatches, + onReady: async (readyMatches) => { + staleOnReady(readyMatches) + }, + }) + await projectAssets({ + router, + matches: staleMatches, + isCurrent: () => router.getMatch(fooId)?.search.pass === 'stale', + }) + return staleMatches + })() + + await vi.waitFor(() => expect(staleHead).toHaveBeenCalledTimes(1)) + + router.cancelMatches() + const freshLocation = router.buildLocation({ + to: '/foo/child', + search: { pass: 'fresh' }, + } as never) + const freshMatches = router.matchRoutes(freshLocation) + router.stores.setPending(freshMatches) + await loadMatches({ + router, + location: freshLocation, + matches: freshMatches, + onReady: async (readyMatches) => { + freshOnReady(readyMatches) + }, + }) + await projectAssets({ router, matches: freshMatches }) + router.stores.setPending(freshMatches) + + staleHeadGate.reject(new Error('stale head failed')) + await expect(staleLoad).resolves.toBe(staleMatches) + + expect(consoleError).not.toHaveBeenCalled() + expect(router.getMatch(fooId)?.meta).toEqual([ + expect.objectContaining({ title: 'fresh' }), + ]) + expect(staleChildHead).not.toHaveBeenCalled() + expect(staleOnReady).not.toHaveBeenCalled() + expect(freshHead).toHaveBeenCalledTimes(1) + expect(freshChildHead).toHaveBeenCalledTimes(1) + expect(freshOnReady).not.toHaveBeenCalled() + } finally { + consoleError.mockRestore() + } + }) + + test('pending preload-owned match is cached only after async head work', async () => { + const headGate = createControlledPromise<{ + meta: Array<{ title: string }> + }>() + const parentHead = vi.fn(() => headGate) + const childHead = vi.fn(() => ({})) + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: () => 'parent', + head: parentHead, + gcTime: 60_000, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + head: childHead, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory(), + }) + + const preload = router.preloadRoute({ to: '/parent/child' }) + await vi.waitFor(() => expect(parentHead).toHaveBeenCalledTimes(1)) + expect(router.stores.cachedMatches.get()).toEqual([]) + + headGate.resolve({ meta: [{ title: 'detached' }] }) + await preload + + const parentMatch = router.stores.cachedMatches + .get() + .find((match) => match.routeId === parentRoute.id)! + expect(parentMatch.meta).toEqual([{ title: 'detached' }]) + expect(parentMatch.status).toBe('success') + expect(parentMatch._.loadPromise).toBeUndefined() + expect(parentMatch.error).toBeUndefined() + expect(childHead).toHaveBeenCalledTimes(1) + expectNoCachedActiveOverlap(router) + }) + + test('beforeLoad onError-triggered navigation cancels the old failure', async () => { + const failure = new Error('beforeLoad failed') + let router!: AnyRouter + const onError = vi.fn(() => { + void router.navigate({ to: '/bar' }) + }) + const fooHead = vi.fn(() => ({})) + const barBeforeLoad = vi.fn() + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + beforeLoad: () => { + throw failure + }, + onError, + head: fooHead, + errorComponent: () => null, + }) + const barRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/bar', + beforeLoad: barBeforeLoad, + }) + + router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute, barRoute]), + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/foo' }).catch(() => undefined) + await vi.waitFor(() => expect(router.state.location.pathname).toBe('/bar')) + + expect(onError).toHaveBeenCalledTimes(1) + expect(barBeforeLoad).toHaveBeenCalledTimes(1) + expect(fooHead).not.toHaveBeenCalled() + expect(router.state.matches.some((match) => match.error === failure)).toBe( + false, + ) + }) + + test('synchronous beforeLoad navigation cancels the old pass even when beforeLoad returns normally', async () => { + let router!: AnyRouter + const childLoader = vi.fn(() => 'stale child') + const oldHead = vi.fn(() => ({})) + const barBeforeLoad = vi.fn() + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + beforeLoad: () => { + void router.navigate({ to: '/bar' }) + return { staleContext: true } + }, + head: oldHead, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => fooRoute, + path: '/child', + loader: childLoader, + }) + const barRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/bar', + beforeLoad: barBeforeLoad, + }) + + router = createTestRouter({ + routeTree: rootRoute.addChildren([ + fooRoute.addChildren([childRoute]), + barRoute, + ]), + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/foo/child' }).catch(() => undefined) + await vi.waitFor(() => expect(router.state.location.pathname).toBe('/bar')) + + expect(childLoader).not.toHaveBeenCalled() + expect(oldHead).not.toHaveBeenCalled() + expect(barBeforeLoad).toHaveBeenCalledTimes(1) + }) + + test('synchronous beforeLoad navigation followed by redirect does not let the stale redirect win', async () => { + let router!: AnyRouter + const barBeforeLoad = vi.fn() + const bazBeforeLoad = vi.fn() + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + beforeLoad: () => { + void router.navigate({ to: '/bar' }) + return redirect({ to: '/baz' }) + }, + }) + const barRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/bar', + beforeLoad: barBeforeLoad, + }) + const bazRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/baz', + beforeLoad: bazBeforeLoad, + }) + + router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute, barRoute, bazRoute]), + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/foo' }).catch(() => undefined) + await vi.waitFor(() => expect(router.state.location.pathname).toBe('/bar')) + + expect(barBeforeLoad).toHaveBeenCalledTimes(1) + expect(bazBeforeLoad).not.toHaveBeenCalled() + }) + + test('loader onError-triggered navigation cancels stale error finalization', async () => { + const failure = new Error('loader failed') + let router!: AnyRouter + const onError = vi.fn(() => { + void router.navigate({ to: '/bar' }) + }) + const fooHead = vi.fn(() => ({})) + const barBeforeLoad = vi.fn() + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader: () => { + throw failure + }, + onError, + head: fooHead, + errorComponent: () => null, + }) + const barRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/bar', + beforeLoad: barBeforeLoad, + }) + + router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute, barRoute]), + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/foo' }).catch(() => undefined) + await vi.waitFor(() => expect(router.state.location.pathname).toBe('/bar')) + + expect(onError).toHaveBeenCalledTimes(1) + expect(barBeforeLoad).toHaveBeenCalledTimes(1) + expect(fooHead).not.toHaveBeenCalled() + expect(router.state.matches.some((match) => match.error === failure)).toBe( + false, + ) + }) + + test('loader that ignores abort cannot commit while a newer navigation is pending', async () => { + const fooLoaderGate = createControlledPromise<{ value: string }>() + const barBeforeLoadGate = createControlledPromise() + const fooLoader = vi.fn(() => fooLoaderGate) + const fooHead = vi.fn(() => ({})) + const fooScripts = vi.fn(() => []) + const barBeforeLoad = vi.fn(() => barBeforeLoadGate) + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader: fooLoader, + head: fooHead, + scripts: fooScripts, + }) + const barRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/bar', + beforeLoad: barBeforeLoad, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute, barRoute]), + history: createMemoryHistory(), + }) + + const fooNavigation = router.navigate({ to: '/foo' }).catch(() => undefined) + await vi.waitFor(() => expect(fooLoader).toHaveBeenCalledTimes(1)) + const fooMatch = router.getMatch('/foo/foo')! + expect(fooMatch._.loadPromise?.status).toBe('pending') + + const barNavigation = router.navigate({ to: '/bar' }) + await vi.waitFor(() => expect(barBeforeLoad).toHaveBeenCalledTimes(1)) + expect(fooMatch.abortController.signal.aborted).toBe(true) + + fooLoaderGate.resolve({ value: 'stale' }) + await Promise.resolve() + + expect(router.getMatch('/foo/foo')?.loaderData).toBeUndefined() + expect(fooHead).not.toHaveBeenCalled() + expect(fooScripts).not.toHaveBeenCalled() + + barBeforeLoadGate.resolve() + await barNavigation + await fooNavigation + + expect(router.state.location.pathname).toBe('/bar') + }) + + test('aborted async beforeLoad does not invoke onError, heads, or descendants', async () => { + const beforeLoadGate = createControlledPromise() + const onError = vi.fn() + const parentHead = vi.fn(() => ({})) + const parentScripts = vi.fn(() => []) + const childLoader = vi.fn(() => 'child') + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + beforeLoad: async () => { + await beforeLoadGate + throw new Error('aborted beforeLoad failed') + }, + onError, + head: parentHead, + scripts: parentScripts, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: childLoader, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + }) + const location = router.latestLocation + const matches = router.matchRoutes(location) + router.stores.setPending(matches) + + const loadPromise = loadMatches({ router, location, matches }) + await vi.waitFor(() => + expect(getLaneMatch(matches, matches[1]!.id)?.isFetching).toBe( + 'beforeLoad', + ), + ) + + router.cancelMatches() + beforeLoadGate.resolve() + + await expect(loadPromise).resolves.toBe(matches) + expect(onError).not.toHaveBeenCalled() + expect(parentHead).not.toHaveBeenCalled() + expect(parentScripts).not.toHaveBeenCalled() + expect(childLoader).not.toHaveBeenCalled() + }) + + test('applies pendingMinMs when pending renders during component preload', async () => { + vi.useFakeTimers() + try { + const componentGate = createControlledPromise() + const rootRoute = new BaseRootRoute({}) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + pendingMs: 0, + pendingMinMs: 100, + pendingComponent: () => null, + loader: () => 'loaded', + component: { preload: () => componentGate } as any, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([targetRoute as any]), + history: createMemoryHistory({ initialEntries: ['/target'] }), + }) + const location = router.latestLocation + const matches = router.matchRoutes(location) + router.stores.setPending(matches) + const targetMatch = matches.find( + (match) => match.routeId === targetRoute.id, + )! + + const loadPromise = loadMatches({ + router, + location, + matches, + onReady: async (readyMatches) => { + const readyMatch = readyMatches.find( + (match) => match.routeId === targetRoute.id, + )! + const promise = readyMatch._.loadPromise + if (promise) { + promise.pendingUntil ??= Date.now() + 100 + } + }, + }) + + await vi.advanceTimersByTimeAsync(0) + await vi.advanceTimersByTimeAsync(10) + componentGate.resolve() + await Promise.resolve() + + expect(router.getMatch(targetMatch.id)?.status).toBe('pending') + + await vi.advanceTimersByTimeAsync(89) + expect(router.getMatch(targetMatch.id)?.status).toBe('pending') + + await vi.advanceTimersByTimeAsync(1) + await loadPromise + + const updatedMatch = getLaneMatch(matches, targetMatch.id) + expect(updatedMatch?.status).toBe('success') + expect(updatedMatch?._.loadPromise).toBeUndefined() + } finally { + vi.useRealTimers() + } + }) + + test('applies pendingMinMs when pending renders during error component preload', async () => { + vi.useFakeTimers() + try { + const errorGate = createControlledPromise() + const rootRoute = new BaseRootRoute({}) + const errorRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/error', + pendingMs: 0, + pendingMinMs: 100, + pendingComponent: () => null, + loader: () => { + throw new Error('loader failed') + }, + errorComponent: { preload: () => errorGate } as any, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([errorRoute]), + history: createMemoryHistory({ initialEntries: ['/error'] }), + }) + const location = router.latestLocation + const matches = router.matchRoutes(location) + router.stores.setPending(matches) + const errorMatch = matches.find( + (match) => match.routeId === errorRoute.id, + )! + + const loadPromise = loadMatches({ + router, + location, + matches, + onReady: async (readyMatches) => { + const readyMatch = readyMatches.find( + (match) => match.routeId === errorRoute.id, + )! + const promise = readyMatch._.loadPromise + if (promise) { + promise.pendingUntil ??= Date.now() + 100 + } + }, + }) + + await vi.advanceTimersByTimeAsync(0) + await vi.advanceTimersByTimeAsync(10) + errorGate.resolve() + await Promise.resolve() + + expect(router.getMatch(errorMatch.id)?.status).toBe('pending') + + await vi.advanceTimersByTimeAsync(89) + expect(router.getMatch(errorMatch.id)?.status).toBe('pending') + + await vi.advanceTimersByTimeAsync(1) + await loadPromise + + const updatedMatch = getLaneMatch(matches, errorMatch.id) + expect(updatedMatch?.status).toBe('error') + expect(updatedMatch?._.loadPromise).toBeUndefined() + } finally { + vi.useRealTimers() + } + }) + + test('applies pendingMinMs when pending renders during notFound component preload', async () => { + vi.useFakeTimers() + try { + const notFoundGate = createControlledPromise() + const rootRoute = new BaseRootRoute({}) + const missingRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/missing', + pendingMs: 0, + pendingMinMs: 100, + pendingComponent: () => null, + loader: () => notFound(), + notFoundComponent: { preload: () => notFoundGate } as any, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([missingRoute]), + history: createMemoryHistory({ initialEntries: ['/missing'] }), + }) + const location = router.latestLocation + const matches = router.matchRoutes(location) + router.stores.setPending(matches) + const missingMatch = matches.find( + (match) => match.routeId === missingRoute.id, + )! + + const loadPromise = loadMatches({ + router, + location, + matches, + onReady: async (readyMatches) => { + const readyMatch = readyMatches.find( + (match) => match.routeId === missingRoute.id, + )! + const promise = readyMatch._.loadPromise + if (promise) { + promise.pendingUntil ??= Date.now() + 100 + } + }, + }).then( + () => undefined, + (err) => err, + ) + + await vi.advanceTimersByTimeAsync(0) + await vi.advanceTimersByTimeAsync(10) + notFoundGate.resolve() + await Promise.resolve() + + expect(router.getMatch(missingMatch.id)?.status).toBe('pending') + + await vi.advanceTimersByTimeAsync(89) + expect(router.getMatch(missingMatch.id)?.status).toBe('pending') + + await vi.advanceTimersByTimeAsync(1) + await expect(loadPromise).resolves.toMatchObject({ isNotFound: true }) + + const updatedMatch = getLaneMatch(matches, missingMatch.id) + expect(updatedMatch?.status).toBe('notFound') + expect(updatedMatch?._.loadPromise).toBeUndefined() + } finally { + vi.useRealTimers() + } + }) + + test('lazy route function throwing synchronously commits error and clears promises', async () => { + const lazyError = new Error('lazy failed') + const rootRoute = new BaseRootRoute({}) + const lazyRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/lazy', + }).lazy(() => { + throw lazyError + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([lazyRoute]), + history: createMemoryHistory({ initialEntries: ['/lazy'] }), + }) + const location = router.latestLocation + const matches = router.matchRoutes(location) + router.stores.setPending(matches) + const lazyMatch = matches.find((match) => match.routeId === lazyRoute.id)! + + await expect(loadMatches({ router, location, matches })).resolves.toBe( + matches, + ) + + const updatedMatch = getLaneMatch(matches, lazyMatch.id) + expect(updatedMatch?.status).toBe('error') + expect(updatedMatch?.error).toBe(lazyError) + expect(updatedMatch?._.loadPromise).toBeUndefined() + expectNotPendingWithoutLoadPromise(updatedMatch) + }) + + test('component preload throwing synchronously commits error and clears promises', async () => { + const preloadError = new Error('component failed') + const rootRoute = new BaseRootRoute({}) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + loader: () => 'loaded', + component: { + preload: () => { + throw preloadError + }, + } as any, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([targetRoute]), + history: createMemoryHistory({ initialEntries: ['/target'] }), + }) + const location = router.latestLocation + const matches = router.matchRoutes(location) + router.stores.setPending(matches) + const targetMatch = matches.find( + (match) => match.routeId === targetRoute.id, + )! + + await expect(loadMatches({ router, location, matches })).resolves.toBe( + matches, + ) + + const updatedMatch = getLaneMatch(matches, targetMatch.id) + expect(updatedMatch?.status).toBe('error') + expect(updatedMatch?.error).toBe(preloadError) + expect(updatedMatch?._.loadPromise).toBeUndefined() + expectNotPendingWithoutLoadPromise(updatedMatch) + }) + + test('sync errorComponent preload error replaces loader error and settles the match', async () => { + const preloadError = new Error('error boundary failed') + const rootRoute = new BaseRootRoute({}) + const errorRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/error', + loader: () => { + throw new Error('loader failed') + }, + errorComponent: { + preload: () => { + throw preloadError + }, + } as any, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([errorRoute]), + history: createMemoryHistory({ initialEntries: ['/error'] }), + }) + const location = router.latestLocation + const matches = router.matchRoutes(location) + router.stores.setPending(matches) + const errorMatch = matches.find((match) => match.routeId === errorRoute.id)! + + await expect(loadMatches({ router, location, matches })).resolves.toBe( + matches, + ) + + const updatedMatch = getLaneMatch(matches, errorMatch.id) + expect(updatedMatch?.status).toBe('error') + expect(updatedMatch?.error).toBe(preloadError) + expect(updatedMatch?._.loadPromise).toBeUndefined() + expectNotPendingWithoutLoadPromise(updatedMatch) + }) + + test('notFoundComponent preload throwing synchronously cannot leave status pending', async () => { + const preloadError = new Error('notFound boundary failed') + const rootRoute = new BaseRootRoute({}) + const missingRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/missing', + loader: () => notFound(), + notFoundComponent: { + preload: () => { + throw preloadError + }, + } as any, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([missingRoute]), + history: createMemoryHistory({ initialEntries: ['/missing'] }), + }) + const location = router.latestLocation + const matches = router.matchRoutes(location) + router.stores.setPending(matches) + const missingMatch = matches.find( + (match) => match.routeId === missingRoute.id, + )! + + await expect(loadMatches({ router, location, matches })).resolves.toBe( + matches, + ) + + const updatedMatch = getLaneMatch(matches, missingMatch.id) + expect(updatedMatch?.status).toBe('error') + expect(updatedMatch?.error).toBe(preloadError) + expect(updatedMatch?._.loadPromise).toBeUndefined() + expectNotPendingWithoutLoadPromise(updatedMatch) + }) + + test('ancestor notFoundComponent preload failure commits error at the ancestor boundary', async () => { + const boundaryError = new Error('ancestor notFound boundary failed') + const notFoundGate = createControlledPromise() + const notFoundPreload = vi.fn(() => notFoundGate) + const childHead = vi.fn(() => ({ meta: [{ title: 'Child' }] })) + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + ssr: 'data-only', + notFoundComponent: { preload: notFoundPreload } as any, + errorComponent: () => null, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: () => notFound({ routeId: parentRoute.id }), + head: childHead, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + isServer: true, + }) + + const location = router.latestLocation + const matches = router.matchRoutes(location) + router.stores.setPending(matches) + const load = loadMatches({ router, location, matches }).then( + () => undefined, + (err) => err, + ) + await vi.waitFor(() => expect(notFoundPreload).toHaveBeenCalledTimes(1)) + + notFoundGate.reject(boundaryError) + await expect(load).resolves.toBe(boundaryError) + + expect(matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + parentRoute.id, + ]) + + const parentMatch = matches.at(-1)! + expect(parentMatch.status).toBe('error') + expect(parentMatch.error).toBe(boundaryError) + expect(childHead).not.toHaveBeenCalled() + expect(notFoundPreload).toHaveBeenCalledTimes(1) + expect(parentMatch._.loadPromise).toBeUndefined() + }) + + test('onError throwing notFound calls notFoundComponent preload once', async () => { + const notFoundPreload = vi.fn() + const rootRoute = new BaseRootRoute({}) + const errorRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/error', + loader: () => { + throw new Error('loader failed') + }, + onError: () => { + throw notFound() + }, + notFoundComponent: { preload: notFoundPreload } as any, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([errorRoute]), + history: createMemoryHistory({ initialEntries: ['/error'] }), + }) + const location = router.latestLocation + const matches = router.matchRoutes(location) + router.stores.setPending(matches) + const errorMatch = matches.find((match) => match.routeId === errorRoute.id)! + + await expect( + loadMatches({ router, location, matches }), + ).rejects.toMatchObject({ isNotFound: true }) + + const updatedMatch = getLaneMatch(matches, errorMatch.id) + expect(updatedMatch?.status).toBe('notFound') + expect(updatedMatch?._.loadPromise).toBeUndefined() + expectNotPendingWithoutLoadPromise(updatedMatch) + expect(notFoundPreload).toHaveBeenCalledTimes(1) + }) + + test('onError throwing notFound targets the failing route boundary before descendants', async () => { + const parentNotFoundPreload = vi.fn() + const childNotFoundPreload = vi.fn() + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: () => { + throw new Error('parent failed') + }, + onError: () => { + throw notFound() + }, + notFoundComponent: { preload: parentNotFoundPreload } as any, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: 'child', + notFoundComponent: { preload: childNotFoundPreload } as any, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + }) + const location = router.latestLocation + const matches = router.matchRoutes(location) + router.stores.setPending(matches) + const parentMatch = matches.find( + (match) => match.routeId === parentRoute.id, + )! + + await expect( + loadMatches({ router, location, matches }), + ).rejects.toMatchObject({ isNotFound: true, routeId: parentRoute.id }) + + expect(matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + parentRoute.id, + ]) + expect(getLaneMatch(matches, parentMatch.id)?.status).toBe('notFound') + expect(parentNotFoundPreload).toHaveBeenCalledTimes(1) + }) + + test('loader errorComponent preload runs once', async () => { + const loaderError = new Error('loader failed') + const errorPreload = vi.fn() + const rootRoute = new BaseRootRoute({}) + const errorRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/error', + loader: () => { + throw loaderError + }, + errorComponent: { preload: errorPreload } as any, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([errorRoute]), + history: createMemoryHistory({ initialEntries: ['/error'] }), + }) + const location = router.latestLocation + const matches = router.matchRoutes(location) + router.stores.setPending(matches) + + await expect(loadMatches({ router, location, matches })).resolves.toBe( + matches, + ) + expect(errorPreload).toHaveBeenCalledTimes(1) + }) + + test('loader notFoundComponent preload runs once', async () => { + const notFoundPreload = vi.fn() + const rootRoute = new BaseRootRoute({}) + const missingRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/missing', + loader: () => notFound(), + notFoundComponent: { preload: notFoundPreload } as any, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([missingRoute]), + history: createMemoryHistory({ initialEntries: ['/missing'] }), + }) + const location = router.latestLocation + const matches = router.matchRoutes(location) + router.stores.setPending(matches) + + await expect( + loadMatches({ router, location, matches }), + ).rejects.toMatchObject({ isNotFound: true }) + expect(notFoundPreload).toHaveBeenCalledTimes(1) + }) + + test('beforeLoad errorComponent preload runs once', async () => { + const beforeLoadError = new Error('beforeLoad failed') + const errorPreload = vi.fn() + const rootRoute = new BaseRootRoute({}) + const errorRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/error', + beforeLoad: () => { + throw beforeLoadError + }, + errorComponent: { preload: errorPreload } as any, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([errorRoute]), + history: createMemoryHistory({ initialEntries: ['/error'] }), + }) + const location = router.latestLocation + const matches = router.matchRoutes(location) + router.stores.setPending(matches) + + await expect(loadMatches({ router, location, matches })).resolves.toBe( + matches, + ) + expect(errorPreload).toHaveBeenCalledTimes(1) + }) + + test('beforeLoad notFoundComponent preload runs once', async () => { + const notFoundPreload = vi.fn() + const rootRoute = new BaseRootRoute({}) + const missingRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/missing', + beforeLoad: () => notFound(), + notFoundComponent: { preload: notFoundPreload } as any, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([missingRoute]), + history: createMemoryHistory({ initialEntries: ['/missing'] }), + }) + const location = router.latestLocation + const matches = router.matchRoutes(location) + router.stores.setPending(matches) + + await expect( + loadMatches({ router, location, matches }), + ).rejects.toMatchObject({ isNotFound: true }) + expect(notFoundPreload).toHaveBeenCalledTimes(1) + }) + + test('beforeLoad throwing a thenable is committed as a route error', async () => { + const thenable = { then: vi.fn() } + const errorPreload = vi.fn() + const rootRoute = new BaseRootRoute({}) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + beforeLoad: () => { + throw thenable + }, + errorComponent: { preload: errorPreload } as any, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([targetRoute]), + history: createMemoryHistory({ initialEntries: ['/target'] }), + }) + const location = router.latestLocation + const matches = router.matchRoutes(location) + router.stores.setPending(matches) + const targetMatch = matches.find( + (match) => match.routeId === targetRoute.id, + )! + + await expect(loadMatches({ router, location, matches })).resolves.toBe( + matches, + ) + const updatedMatch = getLaneMatch(matches, targetMatch.id) + expect(updatedMatch?.status).toBe('error') + expect(updatedMatch?.error).toBe(thenable) + expect(updatedMatch?._.loadPromise).toBeUndefined() + expect(errorPreload).toHaveBeenCalledTimes(1) + }) + + test('onError throwing a thenable is committed as a route error', async () => { + const thenable = { then: vi.fn() } + const errorPreload = vi.fn() + const rootRoute = new BaseRootRoute({}) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + ssr: 'data-only', + loader: () => { + throw new Error('loader failed') + }, + onError: () => { + throw thenable + }, + errorComponent: { preload: errorPreload } as any, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([targetRoute]), + history: createMemoryHistory({ initialEntries: ['/target'] }), + isServer: true, + }) + const location = router.latestLocation + const matches = router.matchRoutes(location) + router.stores.setPending(matches) + const targetMatch = matches.find( + (match) => match.routeId === targetRoute.id, + )! + + let result: unknown + await loadMatches({ router, location, matches }).then( + () => { + throw new Error('Expected loadMatches to reject') + }, + (err) => { + result = err + }, + ) + + const updatedMatch = getLaneMatch(matches, targetMatch.id) + expect(result).toBe(thenable) + expect(updatedMatch?.status).toBe('error') + expect(updatedMatch?.error).toBe(thenable) + expect(updatedMatch?._.loadPromise).toBeUndefined() + expect(errorPreload).toHaveBeenCalledTimes(1) + }) + + test('client load executes head and scripts but never headers', async () => { + const existingHeaders = { 'x-existing': 'yes' } + const head = vi.fn(() => ({ meta: [{ title: 'Client' }] })) + const scripts = vi.fn(() => [{ children: 'client-script' }]) + const headers = vi.fn(() => ({ 'x-new': 'nope' })) + const rootRoute = new BaseRootRoute({}) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + loader: () => 'loaded', + head, + scripts, + headers, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([targetRoute]), + history: createMemoryHistory({ initialEntries: ['/target'] }), + isServer: false, + }) + const location = router.latestLocation + const matches = router.matchRoutes(location) + const targetMatch = matches.find( + (match) => match.routeId === targetRoute.id, + )! + targetMatch.headers = existingHeaders + router.stores.setPending(matches) + + await loadMatches({ + router, + location, + matches, + }) + await projectAssets({ router, matches }) + router.stores.setPending(matches) + + const updatedMatch = router.getMatch(targetMatch.id) + expect(head).toHaveBeenCalledTimes(1) + expect(scripts).toHaveBeenCalledTimes(1) + expect(headers).not.toHaveBeenCalled() + expect(updatedMatch?.headers).toBe(existingHeaders) + }) + + test('server load executes head, scripts, and headers', async () => { + const returnedHeaders = { 'x-server': 'yes' } + const head = vi.fn(() => ({ meta: [{ title: 'Server' }] })) + const scripts = vi.fn(() => [{ children: 'server-script' }]) + const headers = vi.fn(() => returnedHeaders) + const rootRoute = new BaseRootRoute({}) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + loader: () => 'loaded', + head, + scripts, + headers, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([targetRoute]), + history: createMemoryHistory({ initialEntries: ['/target'] }), + isServer: true, + }) + const location = router.latestLocation + const matches = router.matchRoutes(location) + router.stores.setPending(matches) + const targetMatch = matches.find( + (match) => match.routeId === targetRoute.id, + )! + + await loadMatches({ + router, + location, + matches, + }) + router.stores.setPending(matches) + + const updatedMatch = router.getMatch(targetMatch.id) + expect(head).toHaveBeenCalledTimes(1) + expect(scripts).toHaveBeenCalledTimes(1) + expect(headers).toHaveBeenCalledTimes(1) + expect(updatedMatch?.headers).toBe(returnedHeaders) + }) + + test('navigation owns a separate loadPromise from private pending preload', async () => { + const loaderGate = createControlledPromise() + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader: async () => { + await loaderGate + return 'foo' + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute]), + history: createMemoryHistory(), + }) + await router.load() + + const preloadPromise = router.preloadRoute({ to: '/foo' }) + await Promise.resolve() + expect(router.stores.cachedMatches.get()).toEqual([]) + expectNoCachedActiveOverlap(router) + + const navigationPromise = router.navigate({ to: '/foo' }) + await vi.waitFor(() => + expect(router.getMatch('/foo/foo', false)).toBeDefined(), + ) + const navigationMatch = router.getMatch('/foo/foo', false)! + const loadPromiseB = navigationMatch._.loadPromise! + + expect(loadPromiseB.status).toBe('pending') + + loaderGate.resolve() + await Promise.all([preloadPromise, navigationPromise]) + + const currentMatch = router.getMatch('/foo/foo', false)! + expect(currentMatch.status).toBe('success') + expect(currentMatch._.loadPromise).toBeUndefined() + expectNoCachedActiveOverlap(router) + }) + + test('preload-only work does not arm pendingUntil', async () => { + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + pendingMinMs: 10_000, + pendingComponent: () => null, + loader: () => 'target', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + defaultPendingMs: 0, + }) + + await router.load() + const matches = (await router.preloadRoute({ to: '/target' }))! + const targetMatch = matches.find( + (match) => match.routeId === targetRoute.id, + )! + + expect(targetMatch._.loadPromise?.pendingUntil).toBeUndefined() + }) + + test('background reload does not arm pendingUntil', async () => { + const reloadGate = createControlledPromise() + let loaderCalls = 0 + const rootRoute = new BaseRootRoute({}) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + pendingMinMs: 10_000, + pendingComponent: () => null, + loader: () => { + loaderCalls++ + return loaderCalls === 1 ? 'initial' : reloadGate + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([targetRoute]), + history: createMemoryHistory({ initialEntries: ['/target'] }), + defaultPendingMs: 0, + }) + + await router.load() + const targetMatch = router.state.matches.find( + (match) => match.routeId === targetRoute.id, + )! + expect(targetMatch.status).toBe('success') + expect(targetMatch.loaderData).toBe('initial') + + const reload = router.invalidate() + await vi.waitFor(() => expect(loaderCalls).toBe(2)) + + const reloadingMatch = router.getMatch(targetMatch.id)! + expect(reloadingMatch.status).toBe('success') + expect(reloadingMatch._.loadPromise).toBeUndefined() + expect(reloadingMatch._.loadPromise?.pendingUntil).toBeUndefined() + + reloadGate.resolve('reloaded') + await reload + + await vi.waitFor(() => + expect(router.getMatch(targetMatch.id)?.loaderData).toBe('reloaded'), + ) + }) + + test('reports undefined loader errors in development', async () => { + const rootRoute = new BaseRootRoute({}) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + loader: async () => { + throw undefined + }, + errorComponent: () => null, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([targetRoute]), + history: createMemoryHistory({ initialEntries: ['/target'] }), + }) + const location = router.latestLocation + const matches = router.matchRoutes(location) + router.stores.setPending(matches) + const targetMatch = matches.find( + (match) => match.routeId === targetRoute.id, + )! + + await expect( + loadMatches({ + router, + location, + matches, + }), + ).resolves.toBe(matches) + + const currentMatch = getLaneMatch(matches, targetMatch.id) + expect(currentMatch?.status).toBe('error') + expect(currentMatch?.error).toEqual( + expect.objectContaining({ + message: 'Route load failed with undefined', + }), + ) + }) + + test.each([ + ['client', false], + ['server', true], + ] as const)( + 'keeps a thrown undefined as an error match in production on the %s path', + async (_label, isServer) => { + const originalNodeEnv = process.env.NODE_ENV + process.env.NODE_ENV = 'production' + try { + const rootRoute = new BaseRootRoute({}) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + loader: async () => { + throw undefined + }, + errorComponent: () => null, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([targetRoute]), + history: createMemoryHistory({ initialEntries: ['/target'] }), + isServer, + }) + const location = router.latestLocation + const matches = router.matchRoutes(location) + router.stores.setPending(matches) + const targetMatch = matches.find( + (match) => match.routeId === targetRoute.id, + )! + + const result = await loadMatches({ + router, + location, + matches, + }).then( + () => ({ rejected: false as const }), + (error) => ({ rejected: true as const, error }), + ) + + const currentMatch = getLaneMatch(matches, targetMatch.id) + expect(result).toEqual( + isServer ? { rejected: true, error: undefined } : { rejected: false }, + ) + expect(currentMatch?.status).toBe('error') + expect(currentMatch?.error).toBeUndefined() + } finally { + process.env.NODE_ENV = originalNodeEnv + } + }, + ) + + test.each([ + ['beforeLoad', 'client', false], + ['beforeLoad', 'server', true], + ['loader', 'client', false], + ['loader', 'server', true], + ['shouldReload', 'client', false], + ] as const)( + 'keeps a thrown undefined from %s as a production error match on the %s path', + async (source, _label, isServer) => { + const originalNodeEnv = process.env.NODE_ENV + process.env.NODE_ENV = 'production' + try { + let shouldReloadThrows = false + const rootRoute = new BaseRootRoute({}) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + beforeLoad: + source === 'beforeLoad' + ? () => { + throw undefined + } + : undefined, + loader: + source === 'loader' + ? () => { + throw undefined + } + : () => 'loaded', + shouldReload: + source === 'shouldReload' + ? () => { + if (shouldReloadThrows) { + throw undefined + } + return true + } + : undefined, + staleTime: Infinity, + errorComponent: () => null, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([targetRoute]), + history: createMemoryHistory({ initialEntries: ['/target'] }), + isServer, + }) + + if (source === 'shouldReload') { + await router.load() + shouldReloadThrows = true + } + + await router.load({ sync: true }) + + const errorMatch = router.state.matches.find( + (match) => match.routeId === targetRoute.id, + ) + expect(errorMatch?.status).toBe('error') + expect(errorMatch?.error).toBeUndefined() + if (isServer) { + expect(router.statusCode).toBe(500) + } + } finally { + process.env.NODE_ENV = originalNodeEnv + } + }, + ) + ;[ + { name: 'false', value: false }, + { name: '0', value: 0 }, + { name: 'empty string', value: '' }, + { name: 'null', value: null }, + ].forEach(({ name, value }) => { + test(`wraps falsy validateSearch throw: ${name}`, () => { + const rootRoute = new BaseRootRoute({}) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + validateSearch: () => { + throw value + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([targetRoute as any]), + history: createMemoryHistory({ initialEntries: ['/target'] }), + }) + + expect(() => { + router.matchRoutes(router.latestLocation, { throwOnError: true }) + }).toThrow(SearchParamError) + expect(() => { + router.matchRoutes(router.latestLocation, { throwOnError: true }) + }).toThrow(String(value)) + }) + + test(`wraps falsy params parse throw: ${name}`, () => { + const rootRoute = new BaseRootRoute({}) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target/$id', + params: { + parse: () => { + throw value + }, + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([targetRoute as any]), + history: createMemoryHistory({ initialEntries: ['/target/1'] }), + }) + + expect(() => { + router.matchRoutes(router.latestLocation, { throwOnError: true }) + }).toThrow(PathParamError) + expect(() => { + router.matchRoutes(router.latestLocation, { throwOnError: true }) + }).toThrow(String(value)) + }) + }) + test('early pending onReady receives a stable lane snapshot before final trimming', async () => { + vi.useFakeTimers() + try { + const beforeLoadGate = createControlledPromise() + const onReadyGate = createControlledPromise() + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + pendingMs: 0, + pendingComponent: () => null, + beforeLoad: async () => { + await beforeLoadGate + throw new Error('parent failed') + }, + errorComponent: () => null, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + }) + const location = router.latestLocation + const matches = router.matchRoutes(location) + const initialIds = matches.map((match) => match.id) + router.stores.setPending(matches) + const calls: Array<{ ids: Array }> = [] + + const loadPromise = loadMatches({ + router, + location, + matches, + onReady: async (readyMatches) => { + calls.push({ + ids: readyMatches.map((match) => match.id), + }) + + await onReadyGate + }, + }) + + await vi.advanceTimersByTimeAsync(0) + await vi.waitFor(() => expect(calls).toHaveLength(1)) + + beforeLoadGate.resolve() + await Promise.resolve() + onReadyGate.resolve() + const loadedMatches = await loadPromise + + expect(calls).toEqual([{ ids: initialIds }]) + expect(loadedMatches.map((match) => match.id)).toEqual( + matches.slice(0, 2).map((match) => match.id), + ) + } finally { + vi.useRealTimers() + } + }) +}) + +describe('loadRouteChunk', () => { + test('partial notFoundComponent preload does not mark all components loaded', async () => { + const componentPreload = vi.fn() + const errorPreload = vi.fn() + const notFoundPreload = vi.fn() + const rootRoute = new BaseRootRoute({}) + const route = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/chunked', + component: { preload: componentPreload } as any, + errorComponent: { preload: errorPreload } as any, + notFoundComponent: { preload: notFoundPreload } as any, + }) + + await loadRouteChunk(route, 'notFoundComponent') + + expect(notFoundPreload).toHaveBeenCalledTimes(1) + expect(componentPreload).not.toHaveBeenCalled() + expect(errorPreload).not.toHaveBeenCalled() + expect((route as any)._componentsLoaded).not.toBe(true) + + await loadRouteChunk(route) + + expect(componentPreload).toHaveBeenCalledTimes(1) + expect(errorPreload).toHaveBeenCalledTimes(1) + expect(notFoundPreload).toHaveBeenCalledTimes(2) + expect((route as any)._componentsLoaded).toBe(true) + + await loadRouteChunk(route) + + expect(componentPreload).toHaveBeenCalledTimes(1) + expect(errorPreload).toHaveBeenCalledTimes(1) + expect(notFoundPreload).toHaveBeenCalledTimes(2) + }) + + test('dedupes concurrent full component preloads', async () => { + let resolveComponent!: () => void + const componentPreload = vi.fn( + () => + new Promise((resolve) => { + resolveComponent = resolve + }), + ) + const rootRoute = new BaseRootRoute({}) + const route = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/chunked', + component: { preload: componentPreload } as any, + }) + + const first = loadRouteChunk(route) + const second = loadRouteChunk(route) + + expect(componentPreload).toHaveBeenCalledTimes(1) + + resolveComponent() + await Promise.all([first, second]) + + expect((route as any)._componentsLoaded).toBe(true) + + await loadRouteChunk(route) + + expect(componentPreload).toHaveBeenCalledTimes(1) + }) +}) + +describe('settle errors do not leak across load generations', () => { + test('fresh cache hits do not install a loader generation', async () => { + let router: AnyRouter + const seenGenerations: Array | undefined> = [] + const loader = vi.fn(() => ({ value: 'loaded' })) + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader, + staleTime: Infinity, + shouldReload: () => { + const match = router.getMatch('/foo/foo') + seenGenerations.push(match?._.loadPromise) + return false + }, + }) + + router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute]), + history: createMemoryHistory({ initialEntries: ['/foo'] }), + }) + + await router.load() + await router.load() + + expect(loader).toHaveBeenCalledTimes(1) + expect(seenGenerations.map((promise) => promise?.status)).toEqual([ + 'resolved', + ]) + }) + + test('shouldReload exception commits a route error and trims descendants', async () => { + const thrown = new Error('shouldReload failed') + let shouldThrow = false + const parentLoader = vi.fn(() => ({ value: 'parent' })) + const childLoader = vi.fn(() => ({ value: 'child' })) + const childHead = vi.fn(() => ({ meta: [{ title: 'Child' }] })) + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: parentLoader, + shouldReload: () => { + if (shouldThrow) { + throw thrown + } + return true + }, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: childLoader, + head: childHead, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + }) + + await router.load() + expect(parentLoader).toHaveBeenCalledTimes(1) + + childLoader.mockClear() + childHead.mockClear() + shouldThrow = true + + await router.invalidate({ sync: true }) + + const parentMatch = router.state.matches.find( + (match) => match.routeId === parentRoute.id, + )! + + expect(parentMatch.status).toBe('error') + expect(parentMatch.error).toBe(thrown) + expect(router.state.matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + parentRoute.id, + ]) + expect(childHead).not.toHaveBeenCalled() + }) + + test('does not leave a loader generation when shouldReload throws', async () => { + const reloadError = new Error('shouldReload failed') + let shouldThrow = true + const loader = vi.fn(() => ({ value: 'loaded' })) + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader, + shouldReload: () => { + if (shouldThrow) { + throw reloadError + } + return true + }, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute]), + history: createMemoryHistory({ initialEntries: ['/foo'] }), + }) + + await router.load() + await router.invalidate({ sync: true }) + + const failedMatch = router.state.matches.find( + (match) => match.routeId === fooRoute.id, + )! + expect(failedMatch._.loadPromise).toBeUndefined() + + shouldThrow = false + await router.invalidate({ sync: true }) + + expect(loader).toHaveBeenCalledTimes(2) + expect( + router.state.matches.find((match) => match.routeId === fooRoute.id) + ?.loaderData, + ).toEqual({ value: 'loaded' }) + }) + ;[ + { name: 'false', value: false }, + { name: '0', value: 0 }, + { name: 'empty string', value: '' }, + { name: 'null', value: null }, + { name: 'undefined', value: undefined }, + ].forEach(({ name, value }) => { + test(`propagates falsy shouldReload throw: ${name}`, async () => { + const loader = vi.fn(() => ({ value: 'loaded' })) + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader, + shouldReload: () => { + throw value + }, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute]), + history: createMemoryHistory({ initialEntries: ['/foo'] }), + }) + + await router.load() + + const location = router.latestLocation + const matches = router.matchRoutes(location) + router.stores.setPending(matches) + + const result = loadMatches({ router, location, matches }).then( + () => ({ rejected: false, value: undefined }), + (err) => ({ rejected: true, value: err }), + ) + const expectedValue = + value === undefined + ? expect.objectContaining({ + message: 'Route load failed with undefined', + }) + : value + + await expect(result).resolves.toEqual({ + rejected: false, + value: undefined, + }) + + const failedMatch = getLaneMatch(matches, '/foo/foo') + expect(failedMatch?.status).toBe('error') + expect(failedMatch?.error).toEqual(expectedValue) + }) + }) + test('settles the generation when lazy route loading rejects', async () => { + const lazyError = new Error('lazy failed') + const lazyGate = createControlledPromise() + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + }).lazy(() => lazyGate) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute]), + history: createMemoryHistory({ initialEntries: ['/foo'] }), + }) + const location = router.latestLocation + const matches = router.matchRoutes(location) + router.stores.setPending(matches) + const fooMatch = matches.find((match) => match.routeId === fooRoute.id)! + + const load = loadMatches({ router, location, matches }).then( + () => undefined, + (err) => err, + ) + await vi.waitFor(() => + expect(router.getMatch(fooMatch.id)?._.loadPromise).toBeDefined(), + ) + const generation = router.getMatch(fooMatch.id)!._.loadPromise + + lazyGate.reject(lazyError) + + await expect(load).resolves.toBeUndefined() + expect(generation?.status).toBe('resolved') + const updatedMatch = getLaneMatch(matches, fooMatch.id) + expect(updatedMatch?.status).toBe('error') + expect(updatedMatch?.error).toBe(lazyError) + expect(updatedMatch?._.loadPromise).toBeUndefined() + expect( + updatedMatch?.status === 'pending' && !updatedMatch._.loadPromise, + ).toBe(false) + }) + + test('settles the generation when errorComponent preload rejects', async () => { + const componentError = new Error('error component failed') + const errorGate = createControlledPromise() + const errorPreload = vi.fn(() => errorGate) + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader: () => { + throw new Error('loader failed') + }, + errorComponent: { preload: errorPreload } as any, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute]), + history: createMemoryHistory({ initialEntries: ['/foo'] }), + }) + const location = router.latestLocation + const matches = router.matchRoutes(location) + router.stores.setPending(matches) + const fooMatch = matches.find((match) => match.routeId === fooRoute.id)! + + const load = loadMatches({ router, location, matches }).then( + () => undefined, + (err) => err, + ) + await vi.waitFor(() => + expect(router.getMatch(fooMatch.id)?._.loadPromise).toBeDefined(), + ) + const generation = router.getMatch(fooMatch.id)!._.loadPromise + + errorGate.reject(componentError) + + await expect(load).resolves.toBeUndefined() + expect(generation?.status).toBe('resolved') + expect(errorPreload).toHaveBeenCalledTimes(1) + const updatedMatch = getLaneMatch(matches, fooMatch.id) + expect(updatedMatch?.status).toBe('error') + expect(updatedMatch?.error).toBe(componentError) + expect(updatedMatch?._.loadPromise).toBeUndefined() + expect( + updatedMatch?.status === 'pending' && !updatedMatch._.loadPromise, + ).toBe(false) + }) + + test('settles the generation when notFoundComponent preload rejects', async () => { + const componentError = new Error('notFound component failed') + const notFoundGate = createControlledPromise() + const notFoundPreload = vi.fn(() => notFoundGate) + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader: () => notFound(), + notFoundComponent: { preload: notFoundPreload } as any, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute]), + history: createMemoryHistory({ initialEntries: ['/foo'] }), + }) + const location = router.latestLocation + const matches = router.matchRoutes(location) + router.stores.setPending(matches) + const fooMatch = matches.find((match) => match.routeId === fooRoute.id)! + + const load = loadMatches({ router, location, matches }).then( + () => undefined, + (err) => err, + ) + await vi.waitFor(() => + expect(router.getMatch(fooMatch.id)?._.loadPromise).toBeDefined(), + ) + const generation = router.getMatch(fooMatch.id)!._.loadPromise + + notFoundGate.reject(componentError) + + await expect(load).resolves.toBeUndefined() + expect(generation?.status).toBe('resolved') + expect(notFoundPreload).toHaveBeenCalledTimes(1) + const updatedMatch = getLaneMatch(matches, fooMatch.id) + expect(updatedMatch?.status).toBe('error') + expect(updatedMatch?.error).toBe(componentError) + expect(updatedMatch?._.loadPromise).toBeUndefined() + expect( + updatedMatch?.status === 'pending' && !updatedMatch._.loadPromise, + ).toBe(false) + }) + + test('navigation updates cached matches once during commit', async () => { + const loaderGate = createControlledPromise() + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader: () => 'foo', + }) + const barRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/bar', + loader: () => loaderGate, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute, barRoute]), + history: createMemoryHistory({ initialEntries: ['/foo'] }), + }) + await router.load() + + const setCached = vi.spyOn(router.stores, 'setCached') + try { + const navigation = router.navigate({ to: '/bar' }) + await vi.waitFor(() => + expect( + router.stores.pendingMatches + .get() + .some((match) => match.routeId === barRoute.id), + ).toBe(true), + ) + const setCachedAfterPending = setCached.mock.calls.length + + loaderGate.resolve('bar') + await navigation + + expect(setCached).toHaveBeenCalledTimes(setCachedAfterPending + 1) + expect( + router.stores.cachedMatches + .get() + .some((match) => match.routeId === fooRoute.id), + ).toBe(true) + } finally { + setCached.mockRestore() + } + }) + + test('internal updateMatch ignores cached match stores', async () => { + const rootRoute = new BaseRootRoute({}) + const cachedRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/cached', + loader: () => 'cached', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([cachedRoute]), + history: createMemoryHistory(), + }) + await router.load() + await router.preloadRoute({ to: '/cached' }) + + const cachedMatch = router.stores.cachedMatches + .get() + .find((match) => match.routeId === cachedRoute.id)! + + router.updateMatch(cachedMatch.id, (match) => ({ + ...match, + status: 'pending', + error: new Error('should not write through updateMatch'), + })) + + const currentCachedMatch = router.stores.cachedMatches + .get() + .find((match) => match.routeId === cachedRoute.id)! + expect(currentCachedMatch).toBe(cachedMatch) + expect(currentCachedMatch.status).toBe('success') + expect(currentCachedMatch.error).toBeUndefined() + }) + + test('invalidate forcePending keeps cached matches as invalid success snapshots', async () => { + let calls = 0 + const loader = vi.fn(() => ({ value: ++calls })) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const cachedRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/cached', + loader, + staleTime: Infinity, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, cachedRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.preloadRoute({ to: '/cached' }) + expect(loader).toHaveBeenCalledTimes(1) + + await router.invalidate({ forcePending: true, sync: true }) + + const cachedMatch = router.stores.cachedMatches + .get() + .find((match) => match.routeId === cachedRoute.id)! + expect(cachedMatch.status).toBe('success') + expect(cachedMatch.invalid).toBe(true) + expect( + router.stores.cachedMatches + .get() + .every((match) => match.status === 'success'), + ).toBe(true) + + await router.navigate({ to: '/cached' }) + + const activeMatch = router.state.matches.find( + (match) => match.routeId === cachedRoute.id, + )! + expect(loader).toHaveBeenCalledTimes(2) + expect(activeMatch.loaderData).toEqual({ value: 2 }) + expect(activeMatch.invalid).toBe(false) + }) + + test('successful preload cache entry expires and is evicted', async () => { + vi.useFakeTimers() + vi.setSystemTime(1_000) + + try { + const rootRoute = new BaseRootRoute({}) + const preloadRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/preload', + loader: () => 'preload', + preloadGcTime: 10, + }) + const nextRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/next', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([preloadRoute, nextRoute]), + history: createMemoryHistory(), + }) + + await router.load() + await router.preloadRoute({ to: '/preload' }) + + const preloadMatch = router.stores.cachedMatches + .get() + .find((match) => match.routeId === preloadRoute.id)! + + vi.setSystemTime(1_011) + await router.navigate({ to: '/next' }) + + expect( + router.stores.cachedMatches + .get() + .some((match) => match.routeId === preloadRoute.id), + ).toBe(false) + expect(preloadMatch.status).toBe('success') + } finally { + vi.useRealTimers() + } + }) + + test('successful navigation cache entry expires and is evicted', async () => { + vi.useFakeTimers() + vi.setSystemTime(1_000) + + try { + const rootRoute = new BaseRootRoute({}) + const cachedRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/cached', + loader: () => 'cached', + gcTime: 10, + }) + const nextRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/next', + }) + const otherRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/other', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([cachedRoute, nextRoute, otherRoute]), + history: createMemoryHistory({ initialEntries: ['/cached'] }), + }) + + await router.load() + await router.navigate({ to: '/next' }) + + expect( + router.stores.cachedMatches + .get() + .some((match) => match.routeId === cachedRoute.id), + ).toBe(true) + + vi.setSystemTime(1_011) + await router.navigate({ to: '/other' }) + + expect( + router.stores.cachedMatches + .get() + .some((match) => match.routeId === cachedRoute.id), + ).toBe(false) + } finally { + vi.useRealTimers() + } + }) + + test('a stale redirect resolving after a newer navigation does not navigate or update redirect state', async () => { + const slowBeforeLoadStarted = vi.fn() + const slowBeforeLoadGate = createControlledPromise() + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const slowRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/slow', + beforeLoad: async () => { + slowBeforeLoadStarted() + await slowBeforeLoadGate + throw redirect({ to: '/redirected' }) + }, + }) + const safeRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/safe', + }) + const redirectedRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/redirected', + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + slowRoute, + safeRoute, + redirectedRoute, + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + await router.load() + + const staleNavigation = router.navigate({ to: '/slow' }) + await vi.waitFor(() => expect(slowBeforeLoadStarted).toHaveBeenCalled()) + + await router.navigate({ to: '/safe' }) + expect(router.state.location.pathname).toBe('/safe') + + slowBeforeLoadGate.resolve() + await staleNavigation + + expect(router.state.location.pathname).toBe('/safe') + expect(router.redirect).toBeUndefined() + }) + + test('notFound preload is evicted and does not affect a later navigation', async () => { + let calls = 0 + const loader = vi.fn(async () => { + calls++ + if (calls === 1) { + throw notFound() + } + + return { value: 'fresh' } + }) + + const rootRoute = new BaseRootRoute({}) + const staleRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/stale', + loader, + staleTime: 0, + gcTime: 60_000, + }) + const routeTree = rootRoute.addChildren([staleRoute]) + const router = createTestRouter({ + routeTree, + history: createMemoryHistory(), + }) + await router.load() + + await router.preloadRoute({ to: '/stale' }) + expect( + router.stores.cachedMatches + .get() + .some((match) => match.routeId === staleRoute.id), + ).toBe(false) + + await router.navigate({ to: '/stale' }) + + const match = router.state.matches.find((m) => m.routeId === staleRoute.id)! + expect(loader).toHaveBeenCalledTimes(2) + expect(match.status).toBe('success') + expect(match.loaderData).toEqual({ value: 'fresh' }) + }) + + test('redirecting preload is not cached and does not poison a later navigation', async () => { + let calls = 0 + const loader = vi.fn(async () => { + calls++ + if (calls === 1) { + throw redirect({ to: '/other' }) + } + + return { value: 'fresh' } + }) + + const rootRoute = new BaseRootRoute({}) + const staleRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/stale', + loader, + staleTime: 0, + gcTime: 60_000, + }) + const otherRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/other', + }) + const routeTree = rootRoute.addChildren([staleRoute, otherRoute]) + const router = createTestRouter({ + routeTree, + history: createMemoryHistory(), + }) + await router.load() + + await router.preloadRoute({ to: '/stale' }) + expect(loader).toHaveBeenCalledTimes(1) + expect( + router.stores.cachedMatches + .get() + .some((match) => match.routeId === staleRoute.id), + ).toBe(false) + + await router.navigate({ to: '/stale' }) + + expect(router.state.location.pathname).toBe('/stale') + const match = router.state.matches.find((m) => m.routeId === staleRoute.id)! + expect(loader).toHaveBeenCalledTimes(2) + expect(match.status).toBe('success') + expect(match.loaderData).toEqual({ value: 'fresh' }) + }) }) function sleep(ms: number) { diff --git a/packages/router-devtools-core/src/AgeTicker.tsx b/packages/router-devtools-core/src/AgeTicker.tsx index 27d179fda1..6f1b386f57 100644 --- a/packages/router-devtools-core/src/AgeTicker.tsx +++ b/packages/router-devtools-core/src/AgeTicker.tsx @@ -35,7 +35,7 @@ export function AgeTicker({ return null } - const route = router().looseRoutesById[match.routeId]! + const route = router().routesById[match.routeId]! if (!route.options.loader) { return null diff --git a/packages/router-devtools-core/src/useStyles.tsx b/packages/router-devtools-core/src/useStyles.tsx index 5524ed0ae8..32908c524d 100644 --- a/packages/router-devtools-core/src/useStyles.tsx +++ b/packages/router-devtools-core/src/useStyles.tsx @@ -428,7 +428,7 @@ const stylesFactory = (shadowDOMTarget?: ShadowRoot) => { line-height: ${tokens.font.lineHeight.sm}; `, matchStatus: ( - status: 'pending' | 'success' | 'error' | 'notFound' | 'redirected', + status: 'pending' | 'success' | 'error' | 'notFound', isFetching: false | 'beforeLoad' | 'loader', ) => { const colorMap = { @@ -436,7 +436,6 @@ const stylesFactory = (shadowDOMTarget?: ShadowRoot) => { success: 'green', error: 'red', notFound: 'purple', - redirected: 'gray', } as const const color = diff --git a/packages/router-devtools-core/src/utils.tsx b/packages/router-devtools-core/src/utils.tsx index c14bfd80be..962cdaf0f3 100644 --- a/packages/router-devtools-core/src/utils.tsx +++ b/packages/router-devtools-core/src/utils.tsx @@ -25,7 +25,6 @@ export function getStatusColor(match: AnyRouteMatch) { success: 'green', error: 'red', notFound: 'purple', - redirected: 'gray', } as const return match.isFetching && match.status === 'success' diff --git a/packages/router-plugin/src/core/hmr/handle-route-update.ts b/packages/router-plugin/src/core/hmr/handle-route-update.ts index c0325b06e9..8731b19ac5 100644 --- a/packages/router-plugin/src/core/hmr/handle-route-update.ts +++ b/packages/router-plugin/src/core/hmr/handle-route-update.ts @@ -124,9 +124,8 @@ function handleRouteUpdate( // match from the store (via ...existingMatch spread) and the stale // loaderData / __beforeLoadContext survives the reload cycle. // - // We must update the store directly (not via router.updateMatch) because - // updateMatch wraps in startTransition which may defer the state update, - // and we need the clear to be visible before invalidate reads the store. + // We update the store directly so the clear is visible before invalidate + // reads the store and rematches the route. if (removedKeys.has('loader') || removedKeys.has('beforeLoad')) { const matchIds = [ activeMatch?.id, diff --git a/packages/solid-router/src/Match.tsx b/packages/solid-router/src/Match.tsx index 205e778689..2d0146c36e 100644 --- a/packages/solid-router/src/Match.tsx +++ b/packages/solid-router/src/Match.tsx @@ -1,10 +1,8 @@ import * as Solid from 'solid-js' import { - createControlledPromise, getLocationChangeInfo, invariant, isNotFound, - isRedirect, rootRouteId, } from '@tanstack/router-core' import { isServer } from '@tanstack/router-core/isServer' @@ -16,6 +14,7 @@ import { nearestMatchContext } from './matchContext' import { SafeFragment } from './SafeFragment' import { renderRouteNotFound } from './renderRouteNotFound' import { ScrollRestoration } from './scroll-restoration' +import { ClientOnly } from './ClientOnly' import type { AnyRoute, RootRouteOptions } from '@tanstack/router-core' export const Match = (props: { matchId: string }) => { @@ -165,15 +164,17 @@ export const Match = (props: { matchId: string }) => { }} > + + + - } > - + @@ -254,8 +255,7 @@ export const MatchInner = (): any => { id: currentMatch.id, status: currentMatch.status, error: currentMatch.error, - _forcePending: currentMatch._forcePending ?? false, - _displayPending: currentMatch._displayPending ?? false, + _: currentMatch._, }, } }) @@ -270,6 +270,49 @@ export const MatchInner = (): any => { const componentKey = () => currentMatchState().key ?? currentMatchState().match.id + const PendingComponent = () => + route().options.pendingComponent ?? + router.options.defaultPendingComponent + + const pendingReplacement = () => { + return router.stores.pendingMatches + .get() + .find( + (pending) => + pending.routeId === currentMatchState().routeId && + pending.status === 'pending' && + pending.id !== currentMatch().id, + ) + } + + const armPending = (pendingMatch: any) => { + const FallbackComponent = PendingComponent() + const pendingMinMs = + route().options.pendingMinMs ?? router.options.defaultPendingMinMs + const loadPromise = pendingMatch._.loadPromise + const promise = + loadPromise?.status === 'pending' + ? loadPromise + : router.latestLoadPromise + + if (process.env.NODE_ENV !== 'production' && !promise) { + throw new Error( + `Invariant failed: pending match "${pendingMatch.id}" has no loadPromise`, + ) + } + + if ( + !(isServer ?? router.isServer) && + FallbackComponent && + pendingMinMs && + loadPromise?.status === 'pending' + ) { + loadPromise.pendingUntil ??= Date.now() + pendingMinMs + } + + return FallbackComponent + } + const out = () => { const Comp = route().options.component ?? router.options.defaultComponent @@ -279,22 +322,6 @@ export const MatchInner = (): any => { return } - const getLoadPromise = ( - matchId: string, - fallbackMatch: - | { - _nonReactive: { - loadPromise?: Promise - } - } - | undefined, - ) => { - return ( - router.getMatch(matchId)?._nonReactive.loadPromise ?? - fallbackMatch?._nonReactive.loadPromise - ) - } - const keyedOut = () => ( {(_key) => out()} @@ -303,69 +330,41 @@ export const MatchInner = (): any => { return ( - - {(_) => { - const [displayPendingResult] = Solid.createResource( - () => - router.getMatch(currentMatch().id)?._nonReactive - .displayPendingPromise, - ) - - return <>{displayPendingResult()} - }} - - - {(_) => { - const [minPendingResult] = Solid.createResource( - () => - router.getMatch(currentMatch().id)?._nonReactive - .minPendingPromise, - ) - - return <>{minPendingResult()} + + {(pendingMatch) => { + const FallbackComponent = armPending(pendingMatch()) + return FallbackComponent ? ( + + ) : null }} {(_) => { - const pendingMinMs = - route().options.pendingMinMs ?? - router.options.defaultPendingMinMs + const loadPromise = currentMatch()._.loadPromise + const promise = + loadPromise?.status === 'pending' + ? loadPromise + : router.latestLoadPromise - if (pendingMinMs) { - const routerMatch = router.getMatch(currentMatch().id) - if ( - routerMatch && - !routerMatch._nonReactive.minPendingPromise - ) { - // Create a promise that will resolve after the minPendingMs - if (!(isServer ?? router.isServer)) { - const minPendingPromise = createControlledPromise() - - routerMatch._nonReactive.minPendingPromise = - minPendingPromise - - setTimeout(() => { - minPendingPromise.resolve() - // We've handled the minPendingPromise, so we can delete it - routerMatch._nonReactive.minPendingPromise = undefined - }, pendingMinMs) - } - } + if (process.env.NODE_ENV !== 'production' && !promise) { + throw new Error( + `Invariant failed: pending match "${currentMatch().id}" has no loadPromise`, + ) } + const FallbackComponent = + loadPromise?.status === 'pending' + ? armPending(currentMatch()) + : PendingComponent() + const [loaderResult] = Solid.createResource(async () => { await Promise.resolve() - return router.getMatch(currentMatch().id)?._nonReactive - .loadPromise + return promise }) - const FallbackComponent = - route().options.pendingComponent ?? - router.options.defaultPendingComponent - return ( <> - {FallbackComponent && pendingMinMs > 0 ? ( + {FallbackComponent ? ( ) : null} {loaderResult()} @@ -395,29 +394,6 @@ export const MatchInner = (): any => { ) }} - - {(_) => { - const matchId = currentMatch().id - const routerMatch = router.getMatch(matchId) - - if (!isRedirect(currentMatch().error)) { - if (process.env.NODE_ENV !== 'production') { - throw new Error( - 'Invariant failed: Expected a redirect error', - ) - } - - invariant() - } - - const [loaderResult] = Solid.createResource(async () => { - await Promise.resolve() - return getLoadPromise(matchId, routerMatch) - }) - - return <>{loaderResult()} - }} - {(_) => { if (isServer ?? router.isServer) { @@ -469,14 +445,7 @@ export const Outlet = () => { : undefined }) - const childMatchStatus = Solid.createMemo(() => { - const id = childMatchId() - if (!id) return undefined - return router.stores.matchStores.get(id)?.get().status - }) - - const shouldShowNotFound = () => - childMatchStatus() !== 'redirected' && parentGlobalNotFound() + const shouldShowNotFound = () => parentGlobalNotFound() const childRouteKey = Solid.createMemo(() => { if (shouldShowNotFound()) return undefined diff --git a/packages/solid-router/src/ssr/renderRouterToStream.tsx b/packages/solid-router/src/ssr/renderRouterToStream.tsx index 8914c117d9..01eb189dea 100644 --- a/packages/solid-router/src/ssr/renderRouterToStream.tsx +++ b/packages/solid-router/src/ssr/renderRouterToStream.tsx @@ -172,7 +172,7 @@ export const renderRouterToStream = async ({ return createSsrStreamResponse( router, new Response(responseStream as any, { - status: router.stores.statusCode.get(), + status: router.statusCode, headers: responseHeaders, }), ) diff --git a/packages/solid-router/src/ssr/renderRouterToString.tsx b/packages/solid-router/src/ssr/renderRouterToString.tsx index 7da982b392..a8745e9b5f 100644 --- a/packages/solid-router/src/ssr/renderRouterToString.tsx +++ b/packages/solid-router/src/ssr/renderRouterToString.tsx @@ -32,7 +32,7 @@ export const renderRouterToString = ({ html = html.replace(``, () => `${injectedHtml}`) } return new Response(`${html}`, { - status: router.stores.statusCode.get(), + status: router.statusCode, headers: responseHeaders, }) } catch (error) { diff --git a/packages/solid-router/src/useMatch.tsx b/packages/solid-router/src/useMatch.tsx index 858d75be6b..cd2b50a237 100644 --- a/packages/solid-router/src/useMatch.tsx +++ b/packages/solid-router/src/useMatch.tsx @@ -91,11 +91,7 @@ export function useMatch< ? Boolean(router.stores.pendingRouteIds.get()[opts.from!]) : (nearestMatch?.hasPending() ?? false) - if ( - !hasPendingMatch && - !router.stores.isTransitioning.get() && - (opts.shouldThrow ?? true) - ) { + if (!hasPendingMatch && (opts.shouldThrow ?? true)) { if (process.env.NODE_ENV !== 'production') { throw new Error( `Invariant failed: Could not find ${opts.from ? `an active match from "${opts.from}"` : 'a nearest match!'}`, @@ -114,10 +110,7 @@ export function useMatch< ? Boolean(router.stores.pendingRouteIds.get()[opts.from!]) : (nearestMatch?.hasPending() ?? false) - if ( - prev !== undefined && - (hasPendingMatch || router.stores.isTransitioning.get()) - ) { + if (prev !== undefined && hasPendingMatch) { return prev } diff --git a/packages/solid-router/tests/Matches.test.tsx b/packages/solid-router/tests/Matches.test.tsx index 2685500fd0..253a016372 100644 --- a/packages/solid-router/tests/Matches.test.tsx +++ b/packages/solid-router/tests/Matches.test.tsx @@ -1,4 +1,4 @@ -import { afterEach, describe, expect, test } from 'vitest' +import { afterEach, describe, expect, test, vi } from 'vitest' import { createSignal } from 'solid-js' import { cleanup, @@ -8,6 +8,7 @@ import { waitFor, } from '@solidjs/testing-library' import { createMemoryHistory } from '@tanstack/history' +import { createControlledPromise } from '@tanstack/router-core' import { Link, MatchRoute, @@ -154,6 +155,158 @@ test('should show pendingComponent of root route', async () => { expect(await rendered.findByTestId('root-content')).toBeInTheDocument() }) +test('pending fallback remains visible through pendingMinMs', async () => { + vi.useFakeTimers() + + try { + const root = createRootRoute({ + component: () => , + }) + const index = createRoute({ + getParentRoute: () => root, + path: '/', + component: () =>
Index
, + }) + const slow = createRoute({ + getParentRoute: () => root, + path: '/slow', + pendingMs: 0, + pendingMinMs: 100, + pendingComponent: () =>
Slow pending
, + loader: async () => { + await new Promise((resolve) => setTimeout(resolve, 10)) + }, + component: () =>
Slow content
, + }) + const router = createRouter({ + routeTree: root.addChildren([index, slow]), + history: createMemoryHistory({ initialEntries: ['/'] }), + defaultPendingMs: 0, + }) + + render(() => ) + expect(await screen.findByText('Index')).toBeInTheDocument() + + const navigation = router.navigate({ to: '/slow' }) + await vi.advanceTimersByTimeAsync(0) + expect(await screen.findByText('Slow pending')).toBeInTheDocument() + + await vi.advanceTimersByTimeAsync(99) + expect(screen.getByText('Slow pending')).toBeInTheDocument() + expect(screen.queryByText('Slow content')).not.toBeInTheDocument() + + await vi.advanceTimersByTimeAsync(1) + await navigation + expect(await screen.findByText('Slow content')).toBeInTheDocument() + } finally { + cleanup() + vi.useRealTimers() + } +}) + +test('pending match without fallback does not arm pendingMinMs', async () => { + vi.useFakeTimers() + + try { + const loaderGate = createControlledPromise() + const root = createRootRoute({ + component: () => , + }) + const slow = createRoute({ + getParentRoute: () => root, + path: '/slow', + pendingMinMs: 100, + loader: async () => { + await loaderGate + }, + component: () =>
Slow content
, + }) + const router = createRouter({ + routeTree: root.addChildren([slow]), + history: createMemoryHistory({ initialEntries: ['/slow'] }), + defaultPendingMs: 0, + }) + router.stores.setMatches(router.matchRoutes(router.latestLocation)) + + render(() => ) + + await vi.advanceTimersByTimeAsync(0) + + const slowMatch = router.state.matches.find( + (match) => match.routeId === slow.id, + )! + const loadPromise = slowMatch._.loadPromise + + expect(slowMatch.status).toBe('pending') + expect(loadPromise?.pendingUntil).toBeUndefined() + + loadPromise?.resolve() + loaderGate.resolve() + } finally { + cleanup() + vi.useRealTimers() + } +}) + +test('same-route pending replacement respects pendingMinMs', async () => { + const page2Gate = createControlledPromise() + const history = createMemoryHistory({ initialEntries: ['/posts?page=1'] }) + const root = createRootRoute({ + component: () => , + }) + + function Posts() { + const data = postsRoute.useLoaderData() + return
{data()}
+ } + + const postsRoute = createRoute({ + getParentRoute: () => root, + path: '/posts', + validateSearch: (search) => ({ + page: Number(search.page ?? 1), + }), + loaderDeps: ({ search }) => ({ page: search.page }), + pendingMs: 0, + pendingMinMs: 100, + pendingComponent: () =>
, + loader: async ({ deps }) => { + if (deps.page === 2) { + await page2Gate + } + + return `Page ${deps.page}` + }, + component: Posts, + }) + const router = createRouter({ + routeTree: root.addChildren([postsRoute]), + history, + defaultPendingMs: 0, + }) + + render(() => ) + expect(await screen.findByText('Page 1')).toBeInTheDocument() + + const navigation = router.navigate({ + to: '/posts', + search: { page: 2 }, + }) + + expect(await screen.findByTestId('replacement-pending')).toBeInTheDocument() + + const pendingMatch = router.stores.pendingMatches + .get() + .find((match) => match.routeId === postsRoute.id)! + + expect(pendingMatch._.loadPromise?.pendingUntil).toBeTypeOf('number') + + page2Gate.resolve() + await navigation + + expect(await screen.findByText('Page 2')).toBeInTheDocument() +}) + test('MatchRoute updates for navigation and reactive params changes', async () => { function Layout() { const [postId, setPostId] = createSignal('123') diff --git a/packages/solid-router/tests/loaders.test.tsx b/packages/solid-router/tests/loaders.test.tsx index 063660f592..4ecee0521e 100644 --- a/packages/solid-router/tests/loaders.test.tsx +++ b/packages/solid-router/tests/loaders.test.tsx @@ -342,12 +342,39 @@ test('throw abortError from loader upon initial load with basepath', async () => render(() => ) - const indexElement = await screen.findByText('Index route content') - expect(indexElement).toBeInTheDocument() - expect(screen.queryByTestId('index-error')).not.toBeInTheDocument() + const errorElement = await screen.findByTestId('index-error') + expect(errorElement).toBeInTheDocument() + expect(screen.queryByText('Index route content')).not.toBeInTheDocument() expect(window.location.pathname.startsWith('/app')).toBe(true) }) +test('aborted loader does not render the route component with undefined loaderData', async () => { + const rootRoute = createRootRoute({}) + + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + loader: async (): Promise<{ value: string }> => { + return Promise.reject(new DOMException('Aborted', 'AbortError')) + }, + component: () => { + const data = indexRoute.useLoaderData() + return
value: {data().value}
+ }, + errorComponent: () => ( +
indexErrorComponent
+ ), + }) + + const routeTree = rootRoute.addChildren([indexRoute]) + const router = createRouter({ routeTree }) + + render(() => ) + + expect(await screen.findByTestId('index-error')).toBeInTheDocument() + expect(screen.queryByTestId('index-content')).not.toBeInTheDocument() +}) + test('reproducer #4245', async () => { const LOADER_WAIT_TIME = 500 const rootRoute = createRootRoute({}) diff --git a/packages/solid-router/tests/redirect.test.tsx b/packages/solid-router/tests/redirect.test.tsx index 81bd1f6bc6..a9ec6f6ea4 100644 --- a/packages/solid-router/tests/redirect.test.tsx +++ b/packages/solid-router/tests/redirect.test.tsx @@ -337,9 +337,9 @@ describe('redirect', () => { await router.load() - expect(router.state.redirect).toBeDefined() - expect(router.state.redirect).toBeInstanceOf(Response) - const redirectResponse = router.state.redirect! + expect(router.redirect).toBeDefined() + expect(router.redirect).toBeInstanceOf(Response) + const redirectResponse = router.redirect! expect(redirectResponse.options).toEqual({ _fromLocation: expect.objectContaining({ @@ -388,7 +388,7 @@ describe('redirect', () => { await router.load() - const currentRedirect = router.state.redirect + const currentRedirect = router.redirect expect(currentRedirect).toBeDefined() expect(currentRedirect).toBeInstanceOf(Response) diff --git a/packages/solid-router/tests/renderRouterToStream.test.tsx b/packages/solid-router/tests/renderRouterToStream.test.tsx index ba5ee51ca0..691516a808 100644 --- a/packages/solid-router/tests/renderRouterToStream.test.tsx +++ b/packages/solid-router/tests/renderRouterToStream.test.tsx @@ -37,9 +37,9 @@ async function buildRouter() { }) const router = createRouter({ history: createMemoryHistory({ initialEntries: ['/'] }), + isServer: true, routeTree: rootRoute, }) - router.isServer = true attachRouterServerSsrUtils({ router, manifest: undefined }) await router.load() return router diff --git a/packages/solid-router/tests/route.test-d.tsx b/packages/solid-router/tests/route.test-d.tsx index f2dfcada86..adf83e39ec 100644 --- a/packages/solid-router/tests/route.test-d.tsx +++ b/packages/solid-router/tests/route.test-d.tsx @@ -9,7 +9,6 @@ import { import type { Accessor } from 'solid-js' import type { BuildLocationFn, - ControlledPromise, NavigateFn, NavigateOptions, ParsedLocation, @@ -1291,8 +1290,6 @@ test('when creating a child route with context, search, params, loader, loaderDe search: TExpectedSearch context: TExpectedContext loaderDeps: { detailPage: number; invoicePage: number } - beforeLoadPromise?: ControlledPromise - loaderPromise?: ControlledPromise componentsPromise?: Promise> loaderData?: TExpectedLoaderData } diff --git a/packages/solid-router/tests/routeContext.test.tsx b/packages/solid-router/tests/routeContext.test.tsx index b7e0a902a9..aa5ec20ad7 100644 --- a/packages/solid-router/tests/routeContext.test.tsx +++ b/packages/solid-router/tests/routeContext.test.tsx @@ -2451,6 +2451,82 @@ describe('useRouteContext in the component', () => { expect(allContextsValid).toBe(true) }) + test('context value from beforeLoad is propagated when a sub-route is re-entered while its loader reloads in the background', async () => { + let sawUndefinedContext = false + const loaderTime = WAIT_TIME * 3 + + const rootRoute = createRootRoute({ + component: () => , + }) + const homeRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
Home page
, + }) + const reloadInFlightRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/reload-in-flight', + beforeLoad: () => ({ number: 42 }), + component: () => , + }) + const reloadInFlightIndexRoute = createRoute({ + getParentRoute: () => reloadInFlightRoute, + path: '/', + staleTime: 0, + loader: async () => { + await sleep(loaderTime) + }, + component: () => { + const context = reloadInFlightIndexRoute.useRouteContext() + const number = () => context().number + sawUndefinedContext ||= number() === undefined + + return ( +
+ number = {String(number())}, saw undefined ={' '} + {String(sawUndefinedContext)} +
+ ) + }, + }) + + const routeTree = rootRoute.addChildren([ + homeRoute, + reloadInFlightRoute.addChildren([reloadInFlightIndexRoute]), + ]) + const router = createRouter({ routeTree, history }) + + render(() => ) + + await router.navigate({ to: '/reload-in-flight' }) + + expect( + await screen.findByText('number = 42, saw undefined = false'), + ).toBeInTheDocument() + + await router.navigate({ to: '/' }) + expect(await screen.findByText('Home page')).toBeInTheDocument() + router.history.back() + + expect( + await screen.findByText('number = 42, saw undefined = false'), + ).toBeInTheDocument() + + await router.navigate({ to: '/' }) + expect(await screen.findByText('Home page')).toBeInTheDocument() + router.history.back() + + expect( + await screen.findByText('number = 42, saw undefined = false'), + ).toBeInTheDocument() + + await sleep(loaderTime + 50) + + expect( + await screen.findByText('number = 42, saw undefined = false'), + ).toBeInTheDocument() + }) + test('route context (sleep in loader), present root route', async () => { const rootRoute = createRootRoute({ loader: async () => { diff --git a/packages/solid-router/tests/router.test.tsx b/packages/solid-router/tests/router.test.tsx index 1ee017937a..8ca5833e5a 100644 --- a/packages/solid-router/tests/router.test.tsx +++ b/packages/solid-router/tests/router.test.tsx @@ -1720,48 +1720,9 @@ describe('does not strip search params if search validation fails', () => { }) }) -describe('statusCode reset on navigation', () => { - it('should reset statusCode to 200 when navigating from 404 to valid route', async () => { - const history = createMemoryHistory({ initialEntries: ['/'] }) - - const rootRoute = createRootRoute({ - component: () => , - }) - - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: () =>
Home
, - }) - - const validRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/valid', - component: () =>
Valid Route
, - }) - - const routeTree = rootRoute.addChildren([indexRoute, validRoute]) - const router = createRouter({ routeTree, history }) - - render(() => ) - - expect(router.state.statusCode).toBe(200) - - await router.navigate({ to: '/' }) - await waitFor(() => expect(router.state.statusCode).toBe(200)) - - await router.navigate({ to: '/non-existing' }) - await waitFor(() => expect(router.state.statusCode).toBe(404)) - - await router.navigate({ to: '/valid' }) - await waitFor(() => expect(router.state.statusCode).toBe(200)) - - await router.navigate({ to: '/another-non-existing' }) - await waitFor(() => expect(router.state.statusCode).toBe(404)) - }) - +describe('route error rendering', () => { describe.each([true, false])( - 'status code is set when loader/beforeLoad throws (isAsync=%s)', + 'loader/beforeLoad errors render the matching boundary (isAsync=%s)', (isAsync) => { const throwingFun = isAsync ? (toThrow: () => void) => async () => { @@ -1776,7 +1737,7 @@ describe('statusCode reset on navigation', () => { const throwError = throwingFun(() => { throw new Error('test-error') }) - it('should set statusCode to 404 when a route loader throws a notFound()', async () => { + it('renders notFound when a route loader throws a notFound()', async () => { const history = createMemoryHistory({ initialEntries: ['/'] }) const rootRoute = createRootRoute() @@ -1804,17 +1765,14 @@ describe('statusCode reset on navigation', () => { render(() => ) - expect(router.state.statusCode).toBe(200) - await router.navigate({ to: '/loader-throws-not-found' }) - await waitFor(() => expect(router.state.statusCode).toBe(404)) expect( await screen.findByTestId('not-found-component'), ).toBeInTheDocument() expect(screen.queryByTestId('route-component')).not.toBeInTheDocument() }) - it('should set statusCode to 404 when a route beforeLoad throws a notFound()', async () => { + it('renders notFound when a route beforeLoad throws a notFound()', async () => { const history = createMemoryHistory({ initialEntries: ['/'] }) const rootRoute = createRootRoute({ @@ -1849,17 +1807,14 @@ describe('statusCode reset on navigation', () => { render(() => ) - expect(router.state.statusCode).toBe(200) - await router.navigate({ to: '/beforeload-throws-not-found' }) - await waitFor(() => expect(router.state.statusCode).toBe(404)) expect( await screen.findByTestId('not-found-component'), ).toBeInTheDocument() expect(screen.queryByTestId('route-component')).not.toBeInTheDocument() }) - it('should set statusCode to 500 when a route loader throws an Error', async () => { + it('renders error when a route loader throws an Error', async () => { const history = createMemoryHistory({ initialEntries: ['/'] }) const rootRoute = createRootRoute() @@ -1885,15 +1840,12 @@ describe('statusCode reset on navigation', () => { render(() => ) - expect(router.state.statusCode).toBe(200) - await router.navigate({ to: '/loader-throws-error' }) - await waitFor(() => expect(router.state.statusCode).toBe(500)) expect(await screen.findByTestId('error-component')).toBeInTheDocument() expect(screen.queryByTestId('route-component')).not.toBeInTheDocument() }) - it('should set statusCode to 500 when a route beforeLoad throws an Error', async () => { + it('renders error when a route beforeLoad throws an Error', async () => { const history = createMemoryHistory({ initialEntries: ['/'] }) const rootRoute = createRootRoute() @@ -1922,10 +1874,7 @@ describe('statusCode reset on navigation', () => { render(() => ) - expect(router.state.statusCode).toBe(200) - await router.navigate({ to: '/beforeload-throws-error' }) - await waitFor(() => expect(router.state.statusCode).toBe(500)) expect(await screen.findByTestId('error-component')).toBeInTheDocument() expect(screen.queryByTestId('route-component')).not.toBeInTheDocument() }) @@ -2057,7 +2006,6 @@ describe('basepath', () => { }) expect(router.state.location.pathname).toBe('/') - expect(router.state.statusCode).toBe(200) }, ) diff --git a/packages/solid-router/tests/server/errorComponent.test.tsx b/packages/solid-router/tests/server/errorComponent.test.tsx index f342aaae0d..f8851f0aee 100644 --- a/packages/solid-router/tests/server/errorComponent.test.tsx +++ b/packages/solid-router/tests/server/errorComponent.test.tsx @@ -39,7 +39,7 @@ describe('errorComponent (server)', () => { )) - expect(router.state.statusCode).toBe(500) + expect(router.statusCode).toBe(500) expect(html).toContain('data-testid="error-component"') expect(html).toContain('loader boom') expect(html).not.toContain('Index route') diff --git a/packages/solid-router/tests/store-updates-during-navigation.test.tsx b/packages/solid-router/tests/store-updates-during-navigation.test.tsx index 69b570122d..c25b933586 100644 --- a/packages/solid-router/tests/store-updates-during-navigation.test.tsx +++ b/packages/solid-router/tests/store-updates-during-navigation.test.tsx @@ -136,7 +136,7 @@ describe("Store doesn't update *too many* times during navigation", () => { // This number should be as small as possible to minimize the amount of work // that needs to be done during a navigation. // Any change that increases this number should be investigated. - expect(updates).toBe(9) + expect(updates).toBe(4) }) test('redirection in preload', async () => { @@ -156,6 +156,11 @@ describe("Store doesn't update *too many* times during navigation", () => { // Any change that increases this number should be investigated. // Note: Solid has different update counts than React due to different reactivity expect(updates).toBe(2) + expect( + router.stores.cachedMatches + .get() + .some((match) => match.pathname === '/posts'), + ).toBe(false) }) test('sync beforeLoad', async () => { @@ -172,7 +177,7 @@ describe("Store doesn't update *too many* times during navigation", () => { // that needs to be done during a navigation. // Any change that increases this number should be investigated. // Note: Solid has different update counts than React due to different reactivity - expect(updates).toBe(5) + expect(updates).toBe(4) }) test('nothing', async () => { @@ -198,7 +203,7 @@ describe("Store doesn't update *too many* times during navigation", () => { // This number should be as small as possible to minimize the amount of work // that needs to be done during a navigation. // Any change that increases this number should be investigated. - expect(updates).toBe(4) + expect(updates).toBe(3) }) test('hover preload, then navigate, w/ async loaders', async () => { diff --git a/packages/start-server-core/src/createStartHandler.ts b/packages/start-server-core/src/createStartHandler.ts index 90d4e706f9..bbca84916e 100644 --- a/packages/start-server-core/src/createStartHandler.ts +++ b/packages/start-server-core/src/createStartHandler.ts @@ -589,8 +589,8 @@ export function createStartHandler( routerInstance.options.additionalContext = { serverContext } await routerInstance.load() - if (routerInstance.state.redirect) { - return normalizeSsrResponse(routerInstance.state.redirect) + if (routerInstance.redirect) { + return normalizeSsrResponse(routerInstance.redirect) } earlyHints?.collectDynamic(routerInstance.stores.matches.get()) diff --git a/packages/vue-router/src/Match.tsx b/packages/vue-router/src/Match.tsx index 44e9aca0cd..4e39e77575 100644 --- a/packages/vue-router/src/Match.tsx +++ b/packages/vue-router/src/Match.tsx @@ -1,10 +1,8 @@ import * as Vue from 'vue' import { - createControlledPromise, getLocationChangeInfo, invariant, isNotFound, - isRedirect, rootRouteId, } from '@tanstack/router-core' import { isServer } from '@tanstack/router-core/isServer' @@ -93,9 +91,8 @@ export const Match = Vue.defineComponent({ router?.options?.defaultPendingComponent, ) - const pendingElement = Vue.computed(() => - PendingComponent.value ? Vue.h(PendingComponent.value) : undefined, - ) + const pendingElement = () => + PendingComponent.value ? Vue.h(PendingComponent.value) : undefined const routeErrorComponent = Vue.computed( () => @@ -148,19 +145,19 @@ export const Match = Vue.defineComponent({ resolvedNoSsr || !!matchData.value?._displayPending const renderMatchContent = (): VNode => { - const matchInner = Vue.h(MatchInner, { matchId: actualMatchId }) + const matchInner = () => Vue.h(MatchInner, { matchId: actualMatchId }) let content: VNode = shouldClientOnly ? Vue.h( ClientOnly, { - fallback: pendingElement.value, + fallback: pendingElement(), }, { - default: () => matchInner, + default: matchInner, }, ) - : matchInner + : matchInner() // Wrap in NotFound boundary if needed if (routeNotFoundComponent.value) { @@ -333,9 +330,7 @@ export const MatchInner = Vue.defineComponent({ status: match.status, error: match.error, ssr: match.ssr, - _forcePending: match._forcePending, - _displayPending: match._displayPending, - _nonReactive: match._nonReactive, + _: match._, }, remountKey, } @@ -349,43 +344,10 @@ export const MatchInner = Vue.defineComponent({ const match = Vue.computed(() => combinedState.value?.match) const remountKey = Vue.computed(() => combinedState.value?.remountKey) - const getMatchPromise = ( - match: { - id: string - _nonReactive: { - displayPendingPromise?: Promise - minPendingPromise?: Promise - loadPromise?: Promise - } - }, - key: 'displayPendingPromise' | 'minPendingPromise' | 'loadPromise', - ) => { - return ( - router.getMatch(match.id)?._nonReactive[key] ?? match._nonReactive[key] - ) - } - return (): VNode | null => { // If match doesn't exist, return null (component is being unmounted or not ready) if (!combinedState.value || !match.value || !route.value) return null - // Handle different match statuses - if (match.value._displayPending) { - const PendingComponent = - route.value.options.pendingComponent ?? - router.options.defaultPendingComponent - - return PendingComponent ? Vue.h(PendingComponent) : null - } - - if (match.value._forcePending) { - const PendingComponent = - route.value.options.pendingComponent ?? - router.options.defaultPendingComponent - - return PendingComponent ? Vue.h(PendingComponent) : null - } - if (match.value.status === 'notFound') { if (!isNotFound(match.value.error)) { if (process.env.NODE_ENV !== 'production') { @@ -397,17 +359,6 @@ export const MatchInner = Vue.defineComponent({ return renderRouteNotFound(router, route.value, match.value.error) } - if (match.value.status === 'redirected') { - if (!isRedirect(match.value.error)) { - if (process.env.NODE_ENV !== 'production') { - throw new Error('Invariant failed: Expected a redirect error') - } - - invariant() - } - throw getMatchPromise(match.value, 'loadPromise') - } - if (match.value.status === 'error') { // Check if this route or any parent has an error component const RouteErrorComponent = @@ -434,29 +385,6 @@ export const MatchInner = Vue.defineComponent({ } if (match.value.status === 'pending') { - const pendingMinMs = - route.value.options.pendingMinMs ?? router.options.defaultPendingMinMs - - const routerMatch = router.getMatch(match.value.id) - if ( - pendingMinMs && - routerMatch && - !routerMatch._nonReactive.minPendingPromise - ) { - // Create a promise that will resolve after the minPendingMs - if (!(isServer ?? router.isServer)) { - const minPendingPromise = createControlledPromise() - - routerMatch._nonReactive.minPendingPromise = minPendingPromise - - setTimeout(() => { - minPendingPromise.resolve() - // We've handled the minPendingPromise, so we can delete it - routerMatch._nonReactive.minPendingPromise = undefined - }, pendingMinMs) - } - } - // In Vue, we render the pending component directly instead of throwing a promise // because Vue's Suspense doesn't catch thrown promises like React does const PendingComponent = @@ -464,6 +392,19 @@ export const MatchInner = Vue.defineComponent({ router.options.defaultPendingComponent if (PendingComponent) { + const promise = Vue.toRaw(match.value._).loadPromise + const pendingMinMs = + route.value.options.pendingMinMs ?? + router.options.defaultPendingMinMs + + if (process.env.NODE_ENV !== 'production' && !promise) { + invariant() + } + + if (promise && !(isServer ?? router.isServer) && pendingMinMs) { + promise.pendingUntil ??= Date.now() + pendingMinMs + } + return Vue.h(PendingComponent) } diff --git a/packages/vue-router/src/Transitioner.tsx b/packages/vue-router/src/Transitioner.tsx index b0133d965c..b3869f0e70 100644 --- a/packages/vue-router/src/Transitioner.tsx +++ b/packages/vue-router/src/Transitioner.tsx @@ -46,45 +46,28 @@ export function useTransitionerSetup() { // Implement startTransition similar to React/Solid // Vue doesn't have a native useTransition like React 18, so we simulate it - // We also update the router state's isTransitioning flag so useMatch can check it - router.startTransition = (fn: () => void | Promise) => { + router.startTransition = (fn: () => void) => { isTransitioning.value = true - // Also update the router state so useMatch knows we're transitioning try { - router.stores.isTransitioning.set(true) - } catch { - // Ignore errors if component is unmounted - } - - // Helper to end the transition - const endTransition = () => { + fn() + } finally { // Use nextTick to ensure Vue has processed all reactive updates - Vue.nextTick(() => { + void Vue.nextTick(() => { try { isTransitioning.value = false - router.stores.isTransitioning.set(false) } catch { // Ignore errors if component is unmounted } }) } - - // Execute the function synchronously - // The function internally may call startViewTransition which schedules async work - // via document.startViewTransition, but we don't need to wait for it here - // because Vue's reactivity will trigger re-renders when state changes - fn() - - // End the transition on next tick to allow Vue to process reactive updates - endTransition() } // Vue updates DOM asynchronously (next tick). The View Transitions API expects the // update callback promise to resolve only after the DOM has been updated. // Wrap the router-core implementation to await a Vue flush before resolving. - const originalStartViewTransition: - | undefined - | ((fn: () => Promise) => void) = + const originalStartViewTransition: ( + fn: () => Promise, + ) => Promise = (router as any).__tsrOriginalStartViewTransition ?? router.startViewTransition @@ -200,6 +183,12 @@ export function useTransitionerSetup() { router.stores.resolvedLocation.get(), ), }) + if (router.stores.status.get() === 'pending') { + batch(() => { + router.stores.status.set('idle') + router.stores.resolvedLocation.set(router.stores.location.get()) + }) + } } } catch { // Ignore errors if component is unmounted diff --git a/packages/vue-router/src/ssr/renderRouterToStream.tsx b/packages/vue-router/src/ssr/renderRouterToStream.tsx index efad4fc2eb..698695e697 100644 --- a/packages/vue-router/src/ssr/renderRouterToStream.tsx +++ b/packages/vue-router/src/ssr/renderRouterToStream.tsx @@ -112,7 +112,7 @@ export const renderRouterToStream = async ({ } return new Response(`${fullHtml}`, { - status: router.stores.statusCode.get(), + status: router.statusCode, headers: responseHeaders, }) } finally { @@ -217,7 +217,7 @@ export const renderRouterToStream = async ({ return createSsrStreamResponse( router, new Response(responseStream as any, { - status: router.stores.statusCode.get(), + status: router.statusCode, headers: responseHeaders, }), ) diff --git a/packages/vue-router/src/ssr/renderRouterToString.tsx b/packages/vue-router/src/ssr/renderRouterToString.tsx index b551dc5dfc..56ae7ce089 100644 --- a/packages/vue-router/src/ssr/renderRouterToString.tsx +++ b/packages/vue-router/src/ssr/renderRouterToString.tsx @@ -24,7 +24,7 @@ export const renderRouterToString = async ({ } return new Response(`${html}`, { - status: router.stores.statusCode.get(), + status: router.statusCode, headers: responseHeaders, }) } catch (error) { diff --git a/packages/vue-router/src/useMatch.tsx b/packages/vue-router/src/useMatch.tsx index 29047e5d48..f039eff944 100644 --- a/packages/vue-router/src/useMatch.tsx +++ b/packages/vue-router/src/useMatch.tsx @@ -144,11 +144,6 @@ export function useMatch< const hasPendingRouteMatch = opts.from ? useStore(router.stores.pendingRouteIds, (ids) => ids) : undefined - const isTransitioning = useStore( - router.stores.isTransitioning, - (value) => value, - { equal: Object.is }, - ) const result = Vue.computed(() => { const selectedMatch = match.value @@ -156,11 +151,7 @@ export function useMatch< const hasPendingMatch = opts.from ? Boolean(hasPendingRouteMatch?.value[opts.from!]) : hasPendingNearestMatch.value - if ( - !hasPendingMatch && - !isTransitioning.value && - (opts.shouldThrow ?? true) - ) { + if (!hasPendingMatch && (opts.shouldThrow ?? true)) { if (process.env.NODE_ENV !== 'production') { throw new Error( `Invariant failed: Could not find ${opts.from ? `an active match from "${opts.from}"` : 'a nearest match!'}`, diff --git a/packages/vue-router/tests/Matches.test.tsx b/packages/vue-router/tests/Matches.test.tsx index 4e9e9afa51..7e1b0cdb00 100644 --- a/packages/vue-router/tests/Matches.test.tsx +++ b/packages/vue-router/tests/Matches.test.tsx @@ -1,4 +1,4 @@ -import { afterEach, describe, expect, test } from 'vitest' +import { afterEach, describe, expect, test, vi } from 'vitest' import { cleanup, fireEvent, @@ -7,6 +7,7 @@ import { waitFor, } from '@testing-library/vue' import { createMemoryHistory } from '@tanstack/history' +import { createControlledPromise } from '@tanstack/router-core' import { Link, Outlet, @@ -158,6 +159,103 @@ test('should show pendingComponent of root route', async () => { expect(await rendered.findByTestId('root-content')).toBeInTheDocument() }) +test('pending fallback remains visible through pendingMinMs', async () => { + vi.useFakeTimers() + + try { + const root = createRootRoute({ + component: () => , + }) + const index = createRoute({ + getParentRoute: () => root, + path: '/', + component: () =>
Index
, + }) + const slow = createRoute({ + getParentRoute: () => root, + path: '/slow', + pendingMs: 0, + pendingMinMs: 100, + pendingComponent: () =>
Slow pending
, + loader: async () => { + await new Promise((resolve) => setTimeout(resolve, 10)) + }, + component: () =>
Slow content
, + }) + const router = createRouter({ + routeTree: root.addChildren([index, slow]), + history: createMemoryHistory({ initialEntries: ['/'] }), + defaultPendingMs: 0, + }) + + render() + expect(await screen.findByText('Index')).toBeInTheDocument() + + const navigation = router.navigate({ to: '/slow' }) + await vi.advanceTimersByTimeAsync(0) + expect(await screen.findByText('Slow pending')).toBeInTheDocument() + + await vi.advanceTimersByTimeAsync(99) + expect(screen.getByText('Slow pending')).toBeInTheDocument() + expect(screen.queryByText('Slow content')).not.toBeInTheDocument() + + await vi.advanceTimersByTimeAsync(1) + await navigation + expect(await screen.findByText('Slow content')).toBeInTheDocument() + } finally { + cleanup() + vi.useRealTimers() + } +}) + +test('pending match without fallback does not arm pendingMinMs', async () => { + vi.useFakeTimers() + + try { + const loaderGate = createControlledPromise() + const root = createRootRoute({ + component: () => , + }) + const slow = createRoute({ + getParentRoute: () => root, + path: '/slow', + pendingMinMs: 100, + loader: async () => { + await loaderGate + }, + component: () =>
Slow content
, + }) + const router = createRouter({ + routeTree: root.addChildren([slow]), + history: createMemoryHistory({ initialEntries: ['/slow'] }), + defaultPendingMs: 0, + }) + router.stores.setMatches(router.matchRoutes(router.latestLocation)) + + render() + + await vi.advanceTimersByTimeAsync(0) + + const slowMatch = router.state.matches.find( + (match) => match.routeId === slow.id, + )! + const loadPromise = slowMatch._.loadPromise + + expect(slowMatch.status).toBe('pending') + expect(loadPromise?.pendingUntil).toBeUndefined() + + loaderGate.resolve() + + await vi.advanceTimersByTimeAsync(0) + await router.latestLoadPromise + + expect(screen.getByText('Slow content')).toBeInTheDocument() + } finally { + cleanup() + vi.useRealTimers() + } +}) + describe('matching on different param types', () => { const testCases = [ { diff --git a/packages/vue-router/tests/link.test.tsx b/packages/vue-router/tests/link.test.tsx index e047fe5993..d8988a394a 100644 --- a/packages/vue-router/tests/link.test.tsx +++ b/packages/vue-router/tests/link.test.tsx @@ -1372,8 +1372,10 @@ describe('Link', () => { expect(window.location.pathname).toBe('/posts') expect(window.location.search).toBe('?page=2&filter=inactive') - expect(updatedPage).toHaveTextContent('Page: 2') - expect(updatedFilter).toHaveTextContent('Filter: inactive') + await waitFor(() => { + expect(updatedPage).toHaveTextContent('Page: 2') + expect(updatedFilter).toHaveTextContent('Filter: inactive') + }) }) test('when navigation to . from /posts while updating search from / and using base path', async () => { @@ -1493,8 +1495,10 @@ describe('Link', () => { const updatedPage = await screen.findByTestId('current-page') const updatedFilter = await screen.findByTestId('current-filter') - expect(updatedPage).toHaveTextContent('Page: 2') - expect(updatedFilter).toHaveTextContent('Filter: inactive') + await waitFor(() => { + expect(updatedPage).toHaveTextContent('Page: 2') + expect(updatedFilter).toHaveTextContent('Filter: inactive') + }) }) test('when navigating to /posts with invalid search', async () => { @@ -4153,6 +4157,7 @@ describe('Link', () => { const router = createRouter({ routeTree, defaultPreload: 'intent', + history, }) render() @@ -4454,6 +4459,7 @@ describe('Link', () => { const router = createRouter({ routeTree, defaultPreload: 'intent', + history, }) render() @@ -4557,6 +4563,7 @@ describe('Link', () => { const router = createRouter({ routeTree, defaultPreload: 'intent', + history, }) render() diff --git a/packages/vue-router/tests/loaders.test.tsx b/packages/vue-router/tests/loaders.test.tsx index ae267ac2ae..d69ff1022b 100644 --- a/packages/vue-router/tests/loaders.test.tsx +++ b/packages/vue-router/tests/loaders.test.tsx @@ -1,4 +1,10 @@ -import { cleanup, fireEvent, render, screen } from '@testing-library/vue' +import { + cleanup, + fireEvent, + render, + screen, + waitFor, +} from '@testing-library/vue' import { afterEach, describe, expect, test, vi } from 'vitest' @@ -276,6 +282,33 @@ test('throw error from loader upon initial load', async () => { expect(errorElement).toBeInTheDocument() }) +test('aborted loader does not render the route component with undefined loaderData', async () => { + const rootRoute = createRootRoute({}) + + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + loader: async (): Promise<{ value: string }> => { + return Promise.reject(new DOMException('Aborted', 'AbortError')) + }, + component: () => { + const data = indexRoute.useLoaderData() + return
value: {data.value.value}
+ }, + errorComponent: () => ( +
indexErrorComponent
+ ), + }) + + const routeTree = rootRoute.addChildren([indexRoute]) + const router = createRouter({ routeTree }) + + render() + + expect(await screen.findByTestId('index-error')).toBeInTheDocument() + expect(screen.queryByTestId('index-content')).not.toBeInTheDocument() +}) + test('throw error from beforeLoad when navigating to route', async () => { const rootRoute = createRootRoute({}) @@ -600,8 +633,9 @@ test('reproducer #4546', async () => { const routeContext = await screen.findByTestId('index-route-context') expect(routeContext).toHaveTextContent('3') - const loaderData = await screen.findByTestId('index-loader-data') - expect(loaderData).toHaveTextContent('3') + await waitFor(() => + expect(screen.getByTestId('index-loader-data')).toHaveTextContent('3'), + ) } fireEvent.click(invalidateRouterButton) @@ -615,8 +649,9 @@ test('reproducer #4546', async () => { const routeContext = await screen.findByTestId('index-route-context') expect(routeContext).toHaveTextContent('4') - const loaderData = await screen.findByTestId('index-loader-data') - expect(loaderData).toHaveTextContent('4') + await waitFor(() => + expect(screen.getByTestId('index-loader-data')).toHaveTextContent('4'), + ) } fireEvent.click(idLink) @@ -630,8 +665,9 @@ test('reproducer #4546', async () => { const routeContext = await screen.findByTestId('id-route-context') expect(routeContext).toHaveTextContent('5') - const loaderData = await screen.findByTestId('id-loader-data') - expect(loaderData).toHaveTextContent('5') + await waitFor(() => + expect(screen.getByTestId('id-loader-data')).toHaveTextContent('5'), + ) } }) diff --git a/packages/vue-router/tests/redirect.test.tsx b/packages/vue-router/tests/redirect.test.tsx index b7ba2e1af3..60286980b9 100644 --- a/packages/vue-router/tests/redirect.test.tsx +++ b/packages/vue-router/tests/redirect.test.tsx @@ -134,9 +134,14 @@ describe('redirect', () => { // The lazy target route adds the async boundary that exposes the stale // redirected-match render path this regression is guarding. - expect(await screen.findByTestId('lazy-route-page')).toBeInTheDocument() + expect( + await screen.findByTestId('lazy-route-page', undefined, { + timeout: 5_000, + }), + ).toBeInTheDocument() expect(screen.queryByTestId('pending')).not.toBeInTheDocument() expect(router.state.location.href).toBe('/posts') + expect(router.state.status).toBe('idle') expect(consoleError).not.toHaveBeenCalled() }) @@ -326,9 +331,9 @@ describe('redirect', () => { await router.load() - expect(router.state.redirect).toBeDefined() - expect(router.state.redirect).toBeInstanceOf(Response) - const redirectResponse = router.state.redirect! + expect(router.redirect).toBeDefined() + expect(router.redirect).toBeInstanceOf(Response) + const redirectResponse = router.redirect! expect(redirectResponse.options).toEqual({ _fromLocation: expect.objectContaining({ @@ -376,7 +381,7 @@ describe('redirect', () => { await router.load() - const currentRedirect = router.state.redirect + const currentRedirect = router.redirect expect(currentRedirect).toBeDefined() expect(currentRedirect).toBeInstanceOf(Response) diff --git a/packages/vue-router/tests/renderRouterToStream.test.tsx b/packages/vue-router/tests/renderRouterToStream.test.tsx index 527bfa0e03..fd904ff21b 100644 --- a/packages/vue-router/tests/renderRouterToStream.test.tsx +++ b/packages/vue-router/tests/renderRouterToStream.test.tsx @@ -43,9 +43,9 @@ async function buildRouter() { }) const router = createRouter({ history: createMemoryHistory({ initialEntries: ['/'] }), + isServer: true, routeTree: rootRoute, }) - router.isServer = true attachRouterServerSsrUtils({ router, manifest: undefined }) await router.load() return router diff --git a/packages/vue-router/tests/route.test-d.tsx b/packages/vue-router/tests/route.test-d.tsx index 5e32017413..b3b84d5193 100644 --- a/packages/vue-router/tests/route.test-d.tsx +++ b/packages/vue-router/tests/route.test-d.tsx @@ -9,7 +9,6 @@ import { import type * as Vue from 'vue' import type { BuildLocationFn, - ControlledPromise, NavigateFn, NavigateOptions, ParsedLocation, @@ -1285,8 +1284,6 @@ test('when creating a child route with context, search, params, loader, loaderDe search: TExpectedSearch context: TExpectedContext loaderDeps: { detailPage: number; invoicePage: number } - beforeLoadPromise?: ControlledPromise - loaderPromise?: ControlledPromise componentsPromise?: Promise> loaderData?: TExpectedLoaderData } diff --git a/packages/vue-router/tests/router.test.tsx b/packages/vue-router/tests/router.test.tsx index 44a7acd43c..6521d9fa13 100644 --- a/packages/vue-router/tests/router.test.tsx +++ b/packages/vue-router/tests/router.test.tsx @@ -1724,219 +1724,6 @@ describe('does not strip search params if search validation fails', () => { }) }) -describe('statusCode reset on navigation', () => { - it('should reset statusCode to 200 when navigating from 404 to valid route', async () => { - const history = createMemoryHistory({ initialEntries: ['/'] }) - - const rootRoute = createRootRoute({ - component: () => , - }) - - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: () =>
Home
, - }) - - const validRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/valid', - component: () =>
Valid Route
, - }) - - const routeTree = rootRoute.addChildren([indexRoute, validRoute]) - const router = createRouter({ routeTree, history }) - - render() - - expect(router.state.statusCode).toBe(200) - - await router.navigate({ to: '/' }) - await waitFor(() => expect(router.state.statusCode).toBe(200)) - - await router.navigate({ to: '/non-existing' }) - await waitFor(() => expect(router.state.statusCode).toBe(404)) - - await router.navigate({ to: '/valid' }) - await waitFor(() => expect(router.state.statusCode).toBe(200)) - - await router.navigate({ to: '/another-non-existing' }) - await waitFor(() => expect(router.state.statusCode).toBe(404)) - }) - - describe.each([true, false])( - 'status code is set when loader/beforeLoad throws (isAsync=%s)', - (isAsync) => { - const throwingFun = isAsync - ? (toThrow: () => void) => async () => { - await new Promise((resolve) => setTimeout(resolve, 10)) - toThrow() - } - : (toThrow: () => void) => toThrow - - const throwNotFound = throwingFun(() => { - throw notFound() - }) - const throwError = throwingFun(() => { - throw new Error('test-error') - }) - it('should set statusCode to 404 when a route loader throws a notFound()', async () => { - const history = createMemoryHistory({ initialEntries: ['/'] }) - - const rootRoute = createRootRoute() - - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: () =>
Home
, - }) - - const loaderThrowsRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/loader-throws-not-found', - loader: throwNotFound, - component: () => ( -
loader will throw
- ), - notFoundComponent: () => ( -
Not Found
- ), - }) - - const routeTree = rootRoute.addChildren([indexRoute, loaderThrowsRoute]) - const router = createRouter({ routeTree, history }) - - render() - - expect(router.state.statusCode).toBe(200) - - await router.navigate({ to: '/loader-throws-not-found' }) - await waitFor(() => expect(router.state.statusCode).toBe(404)) - expect( - await screen.findByTestId('not-found-component'), - ).toBeInTheDocument() - expect(screen.queryByTestId('route-component')).not.toBeInTheDocument() - }) - - it('should set statusCode to 404 when a route beforeLoad throws a notFound()', async () => { - const history = createMemoryHistory({ initialEntries: ['/'] }) - - const rootRoute = createRootRoute({ - notFoundComponent: () => ( -
Not Found
- ), - }) - - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: () =>
Home
, - }) - - const beforeLoadThrowsRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/beforeload-throws-not-found', - beforeLoad: throwNotFound, - component: () => ( -
beforeLoad will throw
- ), - notFoundComponent: () => ( -
Not Found
- ), - }) - - const routeTree = rootRoute.addChildren([ - indexRoute, - beforeLoadThrowsRoute, - ]) - const router = createRouter({ routeTree, history }) - - render() - - expect(router.state.statusCode).toBe(200) - - await router.navigate({ to: '/beforeload-throws-not-found' }) - await waitFor(() => expect(router.state.statusCode).toBe(404)) - expect( - await screen.findByTestId('not-found-component'), - ).toBeInTheDocument() - expect(screen.queryByTestId('route-component')).not.toBeInTheDocument() - }) - - it('should set statusCode to 500 when a route loader throws an Error', async () => { - const history = createMemoryHistory({ initialEntries: ['/'] }) - - const rootRoute = createRootRoute() - - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: () =>
Home
, - }) - - const loaderThrowsRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/loader-throws-error', - loader: throwError, - component: () => ( -
loader will throw
- ), - errorComponent: () =>
Error
, - }) - - const routeTree = rootRoute.addChildren([indexRoute, loaderThrowsRoute]) - const router = createRouter({ routeTree, history }) - - render() - - expect(router.state.statusCode).toBe(200) - - await router.navigate({ to: '/loader-throws-error' }) - await waitFor(() => expect(router.state.statusCode).toBe(500)) - expect(await screen.findByTestId('error-component')).toBeInTheDocument() - expect(screen.queryByTestId('route-component')).not.toBeInTheDocument() - }) - - it('should set statusCode to 500 when a route beforeLoad throws an Error', async () => { - const history = createMemoryHistory({ initialEntries: ['/'] }) - - const rootRoute = createRootRoute() - - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: () =>
Home
, - }) - - const beforeLoadThrowsRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/beforeload-throws-error', - beforeLoad: throwError, - component: () => ( -
beforeLoad will throw
- ), - errorComponent: () =>
Error
, - }) - - const routeTree = rootRoute.addChildren([ - indexRoute, - beforeLoadThrowsRoute, - ]) - const router = createRouter({ routeTree, history }) - - render() - - expect(router.state.statusCode).toBe(200) - - await router.navigate({ to: '/beforeload-throws-error' }) - await waitFor(() => expect(router.state.statusCode).toBe(500)) - expect(await screen.findByTestId('error-component')).toBeInTheDocument() - expect(screen.queryByTestId('route-component')).not.toBeInTheDocument() - }) - }, - ) -}) - describe('basepath', () => { it('should handle basic basepath rewriting with input', async () => { const rootRoute = createRootRoute({ @@ -2061,7 +1848,6 @@ describe('basepath', () => { }) expect(router.state.location.pathname).toBe('/') - expect(router.state.statusCode).toBe(200) }, ) diff --git a/packages/vue-router/tests/store-updates-during-navigation.test.tsx b/packages/vue-router/tests/store-updates-during-navigation.test.tsx index 1c40bf7be7..42a93972c2 100644 --- a/packages/vue-router/tests/store-updates-during-navigation.test.tsx +++ b/packages/vue-router/tests/store-updates-during-navigation.test.tsx @@ -138,7 +138,7 @@ describe("Store doesn't update *too many* times during navigation", () => { // that needs to be done during a navigation. // Any change that increases this number should be investigated. // Note: Vue has different update counts than React/Solid due to different reactivity - expect(updates).toBe(16) + expect(updates).toBe(4) }) test('redirection in preload', async () => { @@ -148,6 +148,7 @@ describe("Store doesn't update *too many* times during navigation", () => { }, }) + await waitFor(() => expect(router.stores.status.get()).toBe('idle')) const before = select.mock.calls.length await router.preloadRoute({ to: '/posts' }) const after = select.mock.calls.length @@ -157,7 +158,12 @@ describe("Store doesn't update *too many* times during navigation", () => { // that needs to be done during a navigation. // Any change that increases this number should be investigated. // Note: Vue has different update counts than React/Solid due to different reactivity - expect(updates).toBe(5) + expect(updates).toBe(0) + expect( + router.stores.cachedMatches + .get() + .some((match) => match.pathname === '/posts'), + ).toBe(false) }) test('sync beforeLoad', async () => { @@ -174,7 +180,7 @@ describe("Store doesn't update *too many* times during navigation", () => { // that needs to be done during a navigation. // Any change that increases this number should be investigated. // Note: Vue has different update counts than React/Solid due to different reactivity - expect(updates).toBe(12) + expect(updates).toBe(4) }) test('nothing', async () => { @@ -186,7 +192,7 @@ describe("Store doesn't update *too many* times during navigation", () => { // that needs to be done during a navigation. // Any change that increases this number should be investigated. // Note: Vue has different update counts than React/Solid due to different reactivity - expect(updates).toBe(6) + expect(updates).toBe(3) }) test('not found in beforeLoad', async () => { @@ -202,7 +208,7 @@ describe("Store doesn't update *too many* times during navigation", () => { // that needs to be done during a navigation. // Any change that increases this number should be investigated. // Note: Vue has different update counts than React/Solid due to different reactivity - expect(updates).toBe(9) + expect(updates).toBe(3) }) test('hover preload, then navigate, w/ async loaders', async () => { @@ -229,7 +235,7 @@ describe("Store doesn't update *too many* times during navigation", () => { // that needs to be done during a navigation. // Any change that increases this number should be investigated. // Note: Vue has different update counts than React/Solid due to different reactivity - expect(updates).toBe(17) + expect(updates).toBe(3) }) test('navigate, w/ preloaded & async loaders', async () => { @@ -246,7 +252,7 @@ describe("Store doesn't update *too many* times during navigation", () => { // that needs to be done during a navigation. // Any change that increases this number should be investigated. // Note: Vue has different update counts than React/Solid due to different reactivity - expect(updates).toBe(10) + expect(updates).toBe(3) }) test('navigate, w/ preloaded & sync loaders', async () => { @@ -263,7 +269,7 @@ describe("Store doesn't update *too many* times during navigation", () => { // that needs to be done during a navigation. // Any change that increases this number should be investigated. // Note: Vue has different update counts than React/Solid due to different reactivity - expect(updates).toBe(6) + expect(updates).toBe(3) }) test('navigate, w/ previous navigation & async loader', async () => { @@ -280,7 +286,7 @@ describe("Store doesn't update *too many* times during navigation", () => { // that needs to be done during a navigation. // Any change that increases this number should be investigated. // Note: Vue has different update counts than React/Solid due to different reactivity - expect(updates).toBe(6) + expect(updates).toBe(3) }) test('preload a preloaded route w/ async loader', async () => { @@ -299,6 +305,6 @@ describe("Store doesn't update *too many* times during navigation", () => { // that needs to be done during a navigation. // Any change that increases this number should be investigated. // Note: Vue has different update counts than React/Solid due to different reactivity - expect(updates).toBe(2) + expect(updates).toBe(0) }) }) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 7a7c3a7348..a9c9b8077c 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1148,6 +1148,71 @@ importers: specifier: ^8.0.14 version: 8.0.14(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.7.0)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.9.0) + e2e/react-router/issue-7120: + dependencies: + '@tanstack/react-router': + specifier: workspace:* + version: link:../../../packages/react-router + react: + specifier: ^19.2.3 + version: 19.2.3 + react-dom: + specifier: ^19.2.3 + version: 19.2.3(react@19.2.3) + devDependencies: + '@playwright/test': + specifier: ^1.57.0 + version: 1.58.0 + '@tanstack/router-e2e-utils': + specifier: workspace:^ + version: link:../../e2e-utils + '@types/react': + specifier: ^19.2.8 + version: 19.2.9 + '@types/react-dom': + specifier: ^19.2.3 + version: 19.2.3(@types/react@19.2.9) + '@vitejs/plugin-react': + specifier: ^6.0.1 + version: 6.0.1(vite@8.0.14(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.7.0)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.9.0)) + vite: + specifier: ^8.0.14 + version: 8.0.14(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.7.0)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.9.0) + + e2e/react-router/issue-7457: + dependencies: + '@tanstack/react-router': + specifier: workspace:* + version: link:../../../packages/react-router + '@tanstack/router-plugin': + specifier: workspace:* + version: link:../../../packages/router-plugin + react: + specifier: ^19.2.3 + version: 19.2.3 + react-dom: + specifier: ^19.2.3 + version: 19.2.3(react@19.2.3) + devDependencies: + '@playwright/test': + specifier: ^1.57.0 + version: 1.58.0 + '@tanstack/router-e2e-utils': + specifier: workspace:^ + version: link:../../e2e-utils + '@types/react': + specifier: ^19.2.8 + version: 19.2.9 + '@types/react-dom': + specifier: ^19.2.3 + version: 19.2.3(@types/react@19.2.9) + '@vitejs/plugin-react': + specifier: ^6.0.1 + version: 6.0.1(vite@8.0.14(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.7.0)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.9.0)) + vite: + specifier: ^8.0.14 + version: 8.0.14(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.7.0)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.9.0) + e2e/react-router/js-only-file-based: dependencies: '@tailwindcss/vite': @@ -2524,6 +2589,49 @@ importers: specifier: ^8.0.14 version: 8.0.14(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.7.0)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.9.0) + e2e/react-start/issue-6221: + dependencies: + '@tanstack/react-router': + specifier: workspace:* + version: link:../../../packages/react-router + '@tanstack/react-start': + specifier: workspace:* + version: link:../../../packages/react-start + react: + specifier: ^19.2.3 + version: 19.2.3 + react-dom: + specifier: ^19.2.3 + version: 19.2.3(react@19.2.3) + devDependencies: + '@playwright/test': + specifier: ^1.57.0 + version: 1.58.0 + '@tanstack/router-e2e-utils': + specifier: workspace:^ + version: link:../../e2e-utils + '@types/node': + specifier: 25.0.9 + version: 25.0.9 + '@types/react': + specifier: ^19.2.8 + version: 19.2.9 + '@types/react-dom': + specifier: ^19.2.3 + version: 19.2.3(@types/react@19.2.9) + '@vitejs/plugin-react': + specifier: ^6.0.1 + version: 6.0.1(vite@8.0.14(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.7.0)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.9.0)) + srvx: + specifier: ^0.11.9 + version: 0.11.15 + typescript: + specifier: ^6.0.2 + version: 6.0.2 + vite: + specifier: ^8.0.14 + version: 8.0.14(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.7.0)(sass@1.97.2)(terser@5.37.0)(tsx@4.20.3)(yaml@2.9.0) + e2e/react-start/query-integration: dependencies: '@tanstack/react-query': diff --git a/skills/bundle-size-optimization/SKILL.md b/skills/bundle-size-optimization/SKILL.md index d24538be69..3cdffc303e 100644 --- a/skills/bundle-size-optimization/SKILL.md +++ b/skills/bundle-size-optimization/SKILL.md @@ -113,6 +113,13 @@ Useful patterns: remove prod-only strings, remove unused exports, flatten wrappe Rolldown removes code only when unused and side-effect-free. Property reads may trigger getters; storage/global access can observe or throw. +### `isServer` DCE + +- `@tanstack/router-core/isServer` is conditionally exported: browser/client builds use `client.ts` (`isServer = false`), server builds use `server.ts` (`isServer = process.env.NODE_ENV === 'test' ? undefined : true`), and development/test builds use `development.ts` (`isServer = undefined`). The `undefined` value intentionally lets code fall back to `router.isServer` in tests and development. +- Do not assume `const onServer = isServer ?? this.isServer` will treeshake client-only code. In production browser bundles it can become a local `const onServer = false`, while guarded branches like `onServer && redirect.headers.set(...)` or `else if (onServer)` may still remain in emitted JS. +- Prefer inlining `isServer ?? this.isServer` at the server-only branch site instead of assigning it to a local alias. The inline form preserves test/development fallback and gives the browser build a better chance to fold the branch away. +- When a server-only branch should disappear from client bundles, inspect emitted JS in `benchmarks/bundle-size/dist//assets/*.js` to confirm it actually disappeared. + | Annotation | Valid | Unsafe | | ----------------------------------------- | --------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | | `/* @__PURE__ */ call()` | immediately before a call/new expression whose unused result can be dropped | declarations, property reads, setup, storage, DOM/history/listener code | From f35f9c3e20b96a638cb4e3084d32cc218265894a Mon Sep 17 00:00:00 2001 From: Sheraff Date: Fri, 3 Jul 2026 23:04:43 +0200 Subject: [PATCH 02/54] test: import edge-case reproductions from #7713 Covers: boundary component chunk isolation, chunk failure lifecycle, superseded load await, server headers surviving head() failure, preload during pending publication, background asset projection failure, Solid same-route pending blanking, and SSR hydration of server-capped match lists (e2e). Co-Authored-By: Claude Fable 5 --- e2e/react-start/basic/src/routeTree.gen.ts | 56 +++++++++ .../routes/hydration-capped-assets/child.tsx | 25 ++++ .../routes/hydration-capped-assets/route.tsx | 11 ++ .../tests/hydration-capped-assets.spec.ts | 47 +++++++ .../tests/background-assets-stale.test.ts | 86 +++++++++++++ .../tests/boundary-component-chunk.test.ts | 78 ++++++++++++ .../tests/chunk-failure-lifecycle.test.ts | 46 +++++++ .../tests/preload-pending-publication.test.ts | 93 ++++++++++++++ .../server-headers-asset-failure.test.ts | 63 ++++++++++ .../tests/superseded-load-await.test.ts | 85 +++++++++++++ .../tests/same-route-pending-blank.test.tsx | 119 ++++++++++++++++++ 11 files changed, 709 insertions(+) create mode 100644 e2e/react-start/basic/src/routes/hydration-capped-assets/child.tsx create mode 100644 e2e/react-start/basic/src/routes/hydration-capped-assets/route.tsx create mode 100644 e2e/react-start/basic/tests/hydration-capped-assets.spec.ts create mode 100644 packages/router-core/tests/background-assets-stale.test.ts create mode 100644 packages/router-core/tests/boundary-component-chunk.test.ts create mode 100644 packages/router-core/tests/chunk-failure-lifecycle.test.ts create mode 100644 packages/router-core/tests/preload-pending-publication.test.ts create mode 100644 packages/router-core/tests/server-headers-asset-failure.test.ts create mode 100644 packages/router-core/tests/superseded-load-await.test.ts create mode 100644 packages/solid-router/tests/same-route-pending-blank.test.tsx diff --git a/e2e/react-start/basic/src/routeTree.gen.ts b/e2e/react-start/basic/src/routeTree.gen.ts index 103853f3b8..dbd1d7a754 100644 --- a/e2e/react-start/basic/src/routeTree.gen.ts +++ b/e2e/react-start/basic/src/routeTree.gen.ts @@ -26,6 +26,7 @@ import { Route as LayoutRouteImport } from './routes/_layout' import { Route as SpecialCharsRouteRouteImport } from './routes/specialChars/route' import { Route as SearchParamsRouteRouteImport } from './routes/search-params/route' import { Route as NotFoundRouteRouteImport } from './routes/not-found/route' +import { Route as HydrationCappedAssetsRouteRouteImport } from './routes/hydration-capped-assets/route' import { Route as IndexRouteImport } from './routes/index' import { Route as UsersIndexRouteImport } from './routes/users.index' import { Route as SearchParamsIndexRouteImport } from './routes/search-params/index' @@ -53,6 +54,7 @@ import { Route as NotFoundViaLoaderRouteImport } from './routes/not-found/via-lo import { Route as NotFoundViaBeforeLoadTargetRootRouteImport } from './routes/not-found/via-beforeLoad-target-root' import { Route as NotFoundViaBeforeLoadRouteImport } from './routes/not-found/via-beforeLoad' import { Route as MultiCookieRedirectTargetRouteImport } from './routes/multi-cookie-redirect/target' +import { Route as HydrationCappedAssetsChildRouteImport } from './routes/hydration-capped-assets/child' import { Route as ApiUsersRouteImport } from './routes/api.users' import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' import { Route as SpecialCharsMalformedRouteRouteImport } from './routes/specialChars/malformed/route' @@ -165,6 +167,12 @@ const NotFoundRouteRoute = NotFoundRouteRouteImport.update({ path: '/not-found', getParentRoute: () => rootRouteImport, } as any) +const HydrationCappedAssetsRouteRoute = + HydrationCappedAssetsRouteRouteImport.update({ + id: '/hydration-capped-assets', + path: '/hydration-capped-assets', + getParentRoute: () => rootRouteImport, + } as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', @@ -305,6 +313,12 @@ const MultiCookieRedirectTargetRoute = path: '/multi-cookie-redirect/target', getParentRoute: () => rootRouteImport, } as any) +const HydrationCappedAssetsChildRoute = + HydrationCappedAssetsChildRouteImport.update({ + id: '/child', + path: '/child', + getParentRoute: () => HydrationCappedAssetsRouteRoute, + } as any) const ApiUsersRoute = ApiUsersRouteImport.update({ id: '/api/users', path: '/api/users', @@ -448,6 +462,7 @@ const NotFoundDeepBCDRoute = NotFoundDeepBCDRouteImport.update({ export interface FileRoutesByFullPath { '/': typeof IndexRoute + '/hydration-capped-assets': typeof HydrationCappedAssetsRouteRouteWithChildren '/not-found': typeof NotFoundRouteRouteWithChildren '/search-params': typeof SearchParamsRouteRouteWithChildren '/specialChars': typeof SpecialCharsRouteRouteWithChildren @@ -468,6 +483,7 @@ export interface FileRoutesByFullPath { '/not-found/parent-boundary': typeof NotFoundParentBoundaryRouteRouteWithChildren '/specialChars/malformed': typeof SpecialCharsMalformedRouteRouteWithChildren '/api/users': typeof ApiUsersRouteWithChildren + '/hydration-capped-assets/child': typeof HydrationCappedAssetsChildRoute '/multi-cookie-redirect/target': typeof MultiCookieRedirectTargetRoute '/not-found/via-beforeLoad': typeof NotFoundViaBeforeLoadRoute '/not-found/via-beforeLoad-target-root': typeof NotFoundViaBeforeLoadTargetRootRoute @@ -518,6 +534,7 @@ export interface FileRoutesByFullPath { } export interface FileRoutesByTo { '/': typeof IndexRoute + '/hydration-capped-assets': typeof HydrationCappedAssetsRouteRouteWithChildren '/specialChars': typeof SpecialCharsRouteRouteWithChildren '/async-scripts': typeof AsyncScriptsRoute '/client-only': typeof ClientOnlyRoute @@ -531,6 +548,7 @@ export interface FileRoutesByTo { '/type-only-reexport': typeof TypeOnlyReexportRoute '/specialChars/malformed': typeof SpecialCharsMalformedRouteRouteWithChildren '/api/users': typeof ApiUsersRouteWithChildren + '/hydration-capped-assets/child': typeof HydrationCappedAssetsChildRoute '/multi-cookie-redirect/target': typeof MultiCookieRedirectTargetRoute '/not-found/via-beforeLoad': typeof NotFoundViaBeforeLoadRoute '/not-found/via-beforeLoad-target-root': typeof NotFoundViaBeforeLoadTargetRootRoute @@ -580,6 +598,7 @@ export interface FileRoutesByTo { export interface FileRoutesById { __root__: typeof rootRouteImport '/': typeof IndexRoute + '/hydration-capped-assets': typeof HydrationCappedAssetsRouteRouteWithChildren '/not-found': typeof NotFoundRouteRouteWithChildren '/search-params': typeof SearchParamsRouteRouteWithChildren '/specialChars': typeof SpecialCharsRouteRouteWithChildren @@ -602,6 +621,7 @@ export interface FileRoutesById { '/specialChars/malformed': typeof SpecialCharsMalformedRouteRouteWithChildren '/_layout/_layout-2': typeof LayoutLayout2RouteWithChildren '/api/users': typeof ApiUsersRouteWithChildren + '/hydration-capped-assets/child': typeof HydrationCappedAssetsChildRoute '/multi-cookie-redirect/target': typeof MultiCookieRedirectTargetRoute '/not-found/via-beforeLoad': typeof NotFoundViaBeforeLoadRoute '/not-found/via-beforeLoad-target-root': typeof NotFoundViaBeforeLoadTargetRootRoute @@ -654,6 +674,7 @@ export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath fullPaths: | '/' + | '/hydration-capped-assets' | '/not-found' | '/search-params' | '/specialChars' @@ -674,6 +695,7 @@ export interface FileRouteTypes { | '/not-found/parent-boundary' | '/specialChars/malformed' | '/api/users' + | '/hydration-capped-assets/child' | '/multi-cookie-redirect/target' | '/not-found/via-beforeLoad' | '/not-found/via-beforeLoad-target-root' @@ -724,6 +746,7 @@ export interface FileRouteTypes { fileRoutesByTo: FileRoutesByTo to: | '/' + | '/hydration-capped-assets' | '/specialChars' | '/async-scripts' | '/client-only' @@ -737,6 +760,7 @@ export interface FileRouteTypes { | '/type-only-reexport' | '/specialChars/malformed' | '/api/users' + | '/hydration-capped-assets/child' | '/multi-cookie-redirect/target' | '/not-found/via-beforeLoad' | '/not-found/via-beforeLoad-target-root' @@ -785,6 +809,7 @@ export interface FileRouteTypes { id: | '__root__' | '/' + | '/hydration-capped-assets' | '/not-found' | '/search-params' | '/specialChars' @@ -807,6 +832,7 @@ export interface FileRouteTypes { | '/specialChars/malformed' | '/_layout/_layout-2' | '/api/users' + | '/hydration-capped-assets/child' | '/multi-cookie-redirect/target' | '/not-found/via-beforeLoad' | '/not-found/via-beforeLoad-target-root' @@ -858,6 +884,7 @@ export interface FileRouteTypes { } export interface RootRouteChildren { IndexRoute: typeof IndexRoute + HydrationCappedAssetsRouteRoute: typeof HydrationCappedAssetsRouteRouteWithChildren NotFoundRouteRoute: typeof NotFoundRouteRouteWithChildren SearchParamsRouteRoute: typeof SearchParamsRouteRouteWithChildren SpecialCharsRouteRoute: typeof SpecialCharsRouteRouteWithChildren @@ -1005,6 +1032,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof NotFoundRouteRouteImport parentRoute: typeof rootRouteImport } + '/hydration-capped-assets': { + id: '/hydration-capped-assets' + path: '/hydration-capped-assets' + fullPath: '/hydration-capped-assets' + preLoaderRoute: typeof HydrationCappedAssetsRouteRouteImport + parentRoute: typeof rootRouteImport + } '/': { id: '/' path: '/' @@ -1194,6 +1228,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof MultiCookieRedirectTargetRouteImport parentRoute: typeof rootRouteImport } + '/hydration-capped-assets/child': { + id: '/hydration-capped-assets/child' + path: '/child' + fullPath: '/hydration-capped-assets/child' + preLoaderRoute: typeof HydrationCappedAssetsChildRouteImport + parentRoute: typeof HydrationCappedAssetsRouteRoute + } '/api/users': { id: '/api/users' path: '/api/users' @@ -1379,6 +1420,20 @@ declare module '@tanstack/react-router' { } } +interface HydrationCappedAssetsRouteRouteChildren { + HydrationCappedAssetsChildRoute: typeof HydrationCappedAssetsChildRoute +} + +const HydrationCappedAssetsRouteRouteChildren: HydrationCappedAssetsRouteRouteChildren = + { + HydrationCappedAssetsChildRoute: HydrationCappedAssetsChildRoute, + } + +const HydrationCappedAssetsRouteRouteWithChildren = + HydrationCappedAssetsRouteRoute._addFileChildren( + HydrationCappedAssetsRouteRouteChildren, + ) + interface NotFoundDeepBCRouteRouteChildren { NotFoundDeepBCDRoute: typeof NotFoundDeepBCDRoute } @@ -1630,6 +1685,7 @@ const FooBarQuxHereRouteWithChildren = FooBarQuxHereRoute._addFileChildren( const rootRouteChildren: RootRouteChildren = { IndexRoute: IndexRoute, + HydrationCappedAssetsRouteRoute: HydrationCappedAssetsRouteRouteWithChildren, NotFoundRouteRoute: NotFoundRouteRouteWithChildren, SearchParamsRouteRoute: SearchParamsRouteRouteWithChildren, SpecialCharsRouteRoute: SpecialCharsRouteRouteWithChildren, diff --git a/e2e/react-start/basic/src/routes/hydration-capped-assets/child.tsx b/e2e/react-start/basic/src/routes/hydration-capped-assets/child.tsx new file mode 100644 index 0000000000..7506747d00 --- /dev/null +++ b/e2e/react-start/basic/src/routes/hydration-capped-assets/child.tsx @@ -0,0 +1,25 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/hydration-capped-assets/child')({ + loader: () => ({ + title: 'child loader data', + }), + head: ({ loaderData }) => ({ + meta: [ + { + name: 'capped-assets-child-head', + content: loaderData?.title ?? 'missing-loader-data', + }, + ], + }), + scripts: ({ loaderData }) => [ + { + children: `window.__CAPPED_ASSETS_CHILD_SCRIPT = ${JSON.stringify( + loaderData?.title ?? 'missing-loader-data', + )}`, + }, + ], + component: () => ( +
Child route
+ ), +}) diff --git a/e2e/react-start/basic/src/routes/hydration-capped-assets/route.tsx b/e2e/react-start/basic/src/routes/hydration-capped-assets/route.tsx new file mode 100644 index 0000000000..b0bec629be --- /dev/null +++ b/e2e/react-start/basic/src/routes/hydration-capped-assets/route.tsx @@ -0,0 +1,11 @@ +import { Outlet, createFileRoute, notFound } from '@tanstack/react-router' + +export const Route = createFileRoute('/hydration-capped-assets')({ + beforeLoad: () => { + throw notFound() + }, + notFoundComponent: () => ( +
Parent not found
+ ), + component: () => , +}) diff --git a/e2e/react-start/basic/tests/hydration-capped-assets.spec.ts b/e2e/react-start/basic/tests/hydration-capped-assets.spec.ts new file mode 100644 index 0000000000..2e4cba70f5 --- /dev/null +++ b/e2e/react-start/basic/tests/hydration-capped-assets.spec.ts @@ -0,0 +1,47 @@ +import { expect } from '@playwright/test' +import { test } from '@tanstack/router-e2e-utils' +import { isPrerender } from './utils/isPrerender' +import { isSpaMode } from './utils/isSpaMode' + +/** + * On a direct SSR hard load, the server can intentionally cap the + * committed match list at a parent notFound/error boundary. Hydration should not + * project head/scripts for the child route that was omitted from the server + * match list, because those assets can be added with missing or stale loader + * data before the follow-up client load enforces the same boundary. + * + * This Playwright repro uses the real React Start app, a real browser page load, + * the real SSR response, and normal client hydration. The parent route throws + * notFound from beforeLoad, while its child route defines a meta tag and inline + * script; neither child asset should appear after loading the capped parent + * boundary response. + */ + +test.use({ + whitelistErrors: [ + 'Failed to load resource: the server responded with a status of 404', + ], +}) + +test.describe('SSR hydration capped route assets', () => { + test.skip(isSpaMode || isPrerender, 'SSR hydration repro only') + + test('does not project assets for a child route omitted by the server boundary', async ({ + page, + }) => { + await page.goto('/hydration-capped-assets/child') + await page.waitForLoadState('networkidle') + + await expect(page.getByTestId('capped-assets-parent-not-found')).toBeInViewport() + await expect( + page.getByTestId('capped-assets-child-component'), + ).not.toBeInViewport() + + await expect(page.locator('meta[name="capped-assets-child-head"]')).toHaveCount(0) + expect( + await page.evaluate(() => + Boolean((window as any).__CAPPED_ASSETS_CHILD_SCRIPT), + ), + ).toBe(false) + }) +}) diff --git a/packages/router-core/tests/background-assets-stale.test.ts b/packages/router-core/tests/background-assets-stale.test.ts new file mode 100644 index 0000000000..696c45101f --- /dev/null +++ b/packages/router-core/tests/background-assets-stale.test.ts @@ -0,0 +1,86 @@ +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +/** + * background reloads should not commit fresh loaderData when route + * asset projection for that fresh data fails. Otherwise the router can expose + * new data while meta/scripts still describe the previous data snapshot. + * + * This test performs a real same-location background reload after the route is + * stale. The second loader returns fresh data and head throws for that data; + * the active match should keep the old loaderData and old projected assets. + */ + +describe('background asset projection failure', () => { + beforeEach(() => { + vi.useFakeTimers() + vi.setSystemTime(0) + }) + + afterEach(() => { + vi.useRealTimers() + }) + + test('does not commit fresh loaderData when background asset projection fails', async () => { + let resolveStaleReload!: (data: { title: string }) => void + let loaderCalls = 0 + let headCalls = 0 + const loader = () => { + loaderCalls += 1 + if (loaderCalls === 1) { + return { title: 'old' } + } + + return new Promise<{ title: string }>((resolve) => { + resolveStaleReload = resolve + }) + } + + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader, + head: ({ loaderData }) => { + headCalls += 1 + if (loaderData.title === 'fresh') { + throw new Error('head projection failed') + } + + return { + meta: [{ title: loaderData.title }], + } + }, + staleTime: 0, + gcTime: 60_000, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute]), + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/foo' }) + const matchId = router.state.matches.find( + (match) => match.routeId === fooRoute.id, + )!.id + const getMatch = () => + router.state.matches.find((match) => match.id === matchId) + + expect(getMatch()?.loaderData).toEqual({ title: 'old' }) + expect(getMatch()?.meta).toEqual([{ title: 'old' }]) + + await vi.advanceTimersByTimeAsync(1) + await router.load() + await vi.waitFor(() => expect(loaderCalls).toBe(2)) + expect(getMatch()?.isFetching).toBe('loader') + + resolveStaleReload({ title: 'fresh' }) + await vi.waitFor(() => expect(getMatch()?.isFetching).toBe(false)) + + expect(headCalls).toBe(2) + expect(getMatch()?.loaderData).toEqual({ title: 'old' }) + expect(getMatch()?.meta).toEqual([{ title: 'old' }]) + }) +}) diff --git a/packages/router-core/tests/boundary-component-chunk.test.ts b/packages/router-core/tests/boundary-component-chunk.test.ts new file mode 100644 index 0000000000..46447bc472 --- /dev/null +++ b/packages/router-core/tests/boundary-component-chunk.test.ts @@ -0,0 +1,78 @@ +import { afterEach, describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, createControlledPromise } from '../src' +import { createTestRouter } from './routerTestUtils' + +/** + * boundary component preloads should not be blocked by an unrelated + * normal route component preload. A route load starts the normal component + * preload before the loader settles; if that loader throws, the error boundary + * asks to load only the route's errorComponent. + * + * This test uses a real client router load. It keeps the normal route component + * preload pending, resolves the errorComponent preload, and expects the route + * error state to be committed without waiting for the normal component chunk. + */ + +const pendingGates: Array>> = [] +const pendingLoads: Array> = [] + +afterEach(async () => { + for (const gate of pendingGates) { + gate.resolve() + } + + await Promise.allSettled(pendingLoads) + + pendingGates.length = 0 + pendingLoads.length = 0 +}) + +describe('route boundary component preloads', () => { + test('errorComponent preload resolves without waiting for a pending route component preload', async () => { + const componentGate = createControlledPromise() + const errorComponentGate = createControlledPromise() + const routeError = new Error('loader failed') + let errorComponentPreloadCalls = 0 + pendingGates.push(componentGate, errorComponentGate) + + const SlowRouteComponent = Object.assign(() => null, { + preload: () => componentGate, + }) + const ErrorBoundary = Object.assign(() => null, { + preload: () => { + errorComponentPreloadCalls++ + return errorComponentGate + }, + }) + + const rootRoute = new BaseRootRoute({}) + const route = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/chunked', + loader: () => { + throw routeError + }, + component: SlowRouteComponent as any, + errorComponent: ErrorBoundary as any, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([route]), + history: createMemoryHistory({ initialEntries: ['/chunked'] }), + }) + + const loadPromise = router.load() + pendingLoads.push(loadPromise) + + await vi.waitFor(() => expect(errorComponentPreloadCalls).toBe(1)) + errorComponentGate.resolve() + await Promise.resolve() + + const match = router.state.matches.find((item) => item.routeId === route.id) + expect(match?.status).toBe('error') + expect(match?.error).toBe(routeError) + + componentGate.resolve() + await loadPromise + }) +}) diff --git a/packages/router-core/tests/chunk-failure-lifecycle.test.ts b/packages/router-core/tests/chunk-failure-lifecycle.test.ts new file mode 100644 index 0000000000..0be78cb535 --- /dev/null +++ b/packages/router-core/tests/chunk-failure-lifecycle.test.ts @@ -0,0 +1,46 @@ +import { describe, expect, test } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +/** + * primary route chunk failures should go through the same route-error + * lifecycle as loader and beforeLoad failures. Skipping normalization means + * route onError callbacks, redirects, and notFound values from lazy/chunk + * loading can behave differently from other route failures. + * + * This test uses a real router navigation to a lazy route whose chunk rejects. + * The match reaches error state with the chunk error, but the route's onError + * callback should also receive that error as part of normal route failure + * handling. + */ + +describe('route chunk failure lifecycle', () => { + test('calls route onError when lazy route chunk rejects during navigation', async () => { + const chunkError = new Error('lazy chunk failed') + let capturedError: unknown + + const rootRoute = new BaseRootRoute({}) + const lazyRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/lazy', + onError: (error) => { + capturedError = error + }, + }).lazy(() => Promise.reject(chunkError)) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([lazyRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.navigate({ to: '/lazy' }) + + const lazyMatch = router.state.matches.find( + (match) => match.routeId === lazyRoute.id, + ) + expect(lazyMatch?.status).toBe('error') + expect(lazyMatch?.error).toBe(chunkError) + expect(capturedError).toBe(chunkError) + }) +}) diff --git a/packages/router-core/tests/preload-pending-publication.test.ts b/packages/router-core/tests/preload-pending-publication.test.ts new file mode 100644 index 0000000000..200e9447c5 --- /dev/null +++ b/packages/router-core/tests/preload-pending-publication.test.ts @@ -0,0 +1,93 @@ +import { describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, createControlledPromise } from '../src' +import { createTestRouter } from './routerTestUtils' + +/** + * a preload started after foreground pending publication should not + * be dropped just because it borrows an active match that is still pending. + * After commitReady moves pending matches into active stores, preload joining + * must still wait for the foreground load instead of abandoning descendants. + * + * This test performs a real foreground navigation to /parent, publishes the + * pending parent match, then preloads /parent/child while final commit is held + * open by async head projection. The descendant preload loader should still run + * and cache the child match. + */ + +describe('preload during foreground pending publication', () => { + test('preload started after pending publication still loads and caches descendant routes', async () => { + const parentLoaderGate = createControlledPromise<{ parent: string }>() + const parentHeadGate = createControlledPromise<{ + meta: Array<{ title: string }> + }>() + const parentLoader = vi.fn(() => parentLoaderGate) + const parentHead = vi.fn(() => parentHeadGate) + const childLoader = vi.fn(() => ({ child: 'preloaded' })) + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: parentLoader, + head: parentHead, + pendingMs: 0, + pendingComponent: {}, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: childLoader, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + + const navigation = router.navigate({ to: '/parent' }) + await vi.waitFor(() => expect(parentLoader).toHaveBeenCalledTimes(1)) + + await vi.waitFor(() => { + const activeParent = router.state.matches.find( + (match) => match.routeId === parentRoute.id, + ) + expect(activeParent?.status).toBe('pending') + expect(router.stores.pendingIds.get()).toEqual([]) + }) + + const preload = router.preloadRoute({ to: '/parent/child' }) + await Promise.resolve() + expect(childLoader).not.toHaveBeenCalled() + + parentLoaderGate.resolve({ parent: 'loaded' }) + await vi.waitFor(() => expect(parentHead).toHaveBeenCalledTimes(1)) + + expect( + router.state.matches.find((match) => match.routeId === parentRoute.id) + ?.status, + ).toBe('pending') + + parentHeadGate.resolve({ meta: [{ title: 'Parent' }] }) + const [, preloadMatches] = await Promise.all([navigation, preload]) + + expect(childLoader).toHaveBeenCalledTimes(1) + expect( + preloadMatches?.some((match) => match.routeId === childRoute.id), + ).toBe(true) + expect( + router.stores.cachedMatches + .get() + .find((match) => match.routeId === childRoute.id)?.loaderData, + ).toEqual({ child: 'preloaded' }) + }) +}) diff --git a/packages/router-core/tests/server-headers-asset-failure.test.ts b/packages/router-core/tests/server-headers-asset-failure.test.ts new file mode 100644 index 0000000000..a7884274aa --- /dev/null +++ b/packages/router-core/tests/server-headers-asset-failure.test.ts @@ -0,0 +1,63 @@ +import { createMemoryHistory } from '@tanstack/history' +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +/** + * route headers are response behavior and should not be dropped just + * because decorative server assets fail. Server route asset projection currently + * commits head, scripts, and headers as one unit. + * + * This test uses a real server router load. The route's headers option succeeds + * while head fails, and the loaded route match should still expose the header + * that Start later merges into the HTTP response. + */ + +const expectedHeaders = { 'x-route-header': 'kept' } + +beforeEach(() => { + vi.spyOn(console, 'error').mockImplementation(() => {}) +}) + +afterEach(() => { + vi.restoreAllMocks() +}) + +async function loadTargetRoute(options: { asyncHead: boolean }) { + const rootRoute = new BaseRootRoute({}) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + head: options.asyncHead + ? async () => { + throw new Error('head failed') + } + : () => { + throw new Error('head failed') + }, + headers: () => expectedHeaders, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([targetRoute]), + history: createMemoryHistory({ initialEntries: ['/target'] }), + isServer: true, + }) + + await router.load() + + return router.state.matches.find((match) => match.routeId === targetRoute.id) +} + +describe('server asset projection route headers', () => { + test('keeps route headers when head throws synchronously', async () => { + const targetMatch = await loadTargetRoute({ asyncHead: false }) + expect(targetMatch).toBeDefined() + expect(targetMatch!.headers).toEqual(expectedHeaders) + }) + + test('keeps route headers when head rejects asynchronously', async () => { + const targetMatch = await loadTargetRoute({ asyncHead: true }) + expect(targetMatch).toBeDefined() + expect(targetMatch!.headers).toEqual(expectedHeaders) + }) +}) diff --git a/packages/router-core/tests/superseded-load-await.test.ts b/packages/router-core/tests/superseded-load-await.test.ts new file mode 100644 index 0000000000..471fb9b189 --- /dev/null +++ b/packages/router-core/tests/superseded-load-await.test.ts @@ -0,0 +1,85 @@ +import { describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, createControlledPromise } from '../src' +import { createTestRouter } from './routerTestUtils' + +/** + * awaiting router.load() or router.invalidate() should remain a + * reliable synchronization point even when that load is superseded. If the + * abandoned load resolves immediately, callers can observe router state before + * the newer load has settled. + * + * This test starts a real public router.load() for /one, supersedes it with a + * real navigation to /two, and resolves only the abandoned /one loader. The + * original await should not settle until the superseding /two loader settles. + */ + +const waitForMacrotask = () => + new Promise((resolve) => { + setTimeout(resolve, 0) + }) + +describe('superseded load await', () => { + test('router.load waits for a superseding navigation load to settle', async () => { + const firstLoaderGate = createControlledPromise() + const secondLoaderGate = createControlledPromise() + let firstLoaderCalls = 0 + let secondLoaderCalls = 0 + let secondLoaderSettled = false + let supersededLoadSettled = false + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const firstRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/one', + loader: async () => { + firstLoaderCalls++ + await firstLoaderGate + return 'one' + }, + }) + const secondRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/two', + loader: async () => { + secondLoaderCalls++ + await secondLoaderGate + secondLoaderSettled = true + return 'two' + }, + }) + + const history = createMemoryHistory({ initialEntries: ['/'] }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, firstRoute, secondRoute]), + history, + }) + + await router.load() + + history.push('/one') + const supersededLoad = router.load().then(() => { + supersededLoadSettled = true + }) + await vi.waitFor(() => expect(firstLoaderCalls).toBe(1)) + + const latestNavigation = router.navigate({ to: '/two' }) + await vi.waitFor(() => expect(secondLoaderCalls).toBe(1)) + + firstLoaderGate.resolve() + await waitForMacrotask() + + expect(secondLoaderSettled).toBe(false) + expect(supersededLoadSettled).toBe(false) + + secondLoaderGate.resolve() + await Promise.all([supersededLoad, latestNavigation]) + + expect(secondLoaderSettled).toBe(true) + expect(supersededLoadSettled).toBe(true) + }) +}) diff --git a/packages/solid-router/tests/same-route-pending-blank.test.tsx b/packages/solid-router/tests/same-route-pending-blank.test.tsx new file mode 100644 index 0000000000..df89ca7c77 --- /dev/null +++ b/packages/solid-router/tests/same-route-pending-blank.test.tsx @@ -0,0 +1,119 @@ +import { cleanup, render, screen, waitFor } from '@solidjs/testing-library' +import { afterEach, expect, test } from 'vitest' +import { + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +/** + * Solid same-route pending replacement should not blank stale content + * before pending UI is ready. Core can expose a replacement pending match while + * the route has no pending fallback and a long pendingMs delay. + * + * This test renders a real Solid RouterProvider, navigates from page 1 to page + * 2 on the same route, and leaves the page 2 loader unresolved. Until pendingMs + * elapses, the previously committed page 1 content should remain visible. + */ + +let resolvePendingPage2: (() => void) | undefined +let pendingNavigation: Promise | undefined + +afterEach(async () => { + resolvePendingPage2?.() + if (pendingNavigation) { + await Promise.allSettled([pendingNavigation]) + } + resolvePendingPage2 = undefined + pendingNavigation = undefined + cleanup() +}) + +function deferred() { + let resolve!: (value: T | PromiseLike) => void + const promise = new Promise((resolver) => { + resolve = resolver + }) + + return { promise, resolve } +} + +test('same-route pending replacement without fallback keeps stale content until pendingMs', async () => { + const pendingMs = 10_000 + const page2Gate = deferred() + resolvePendingPage2 = page2Gate.resolve + const history = createMemoryHistory({ initialEntries: ['/posts?page=1'] }) + const root = createRootRoute({ + component: () => , + }) + + function Posts() { + const data = postsRoute.useLoaderData() + return
{data()}
+ } + + const postsRoute = createRoute({ + getParentRoute: () => root, + path: '/posts', + validateSearch: (search) => ({ + page: Number(search.page ?? 1), + }), + loaderDeps: ({ search }) => ({ page: search.page }), + pendingMs, + loader: async ({ deps }) => { + if (deps.page === 2) { + await page2Gate.promise + } + + return `Page ${deps.page}` + }, + component: Posts, + }) + const router = createRouter({ + routeTree: root.addChildren([postsRoute]), + history, + defaultPendingMs: pendingMs, + }) + + render(() => ) + expect(await screen.findByText('Page 1')).toBeInTheDocument() + + const currentMatch = () => + router.stores.matches.get().find((match) => match.routeId === postsRoute.id) + const navigation = router.navigate({ + to: '/posts', + search: { page: 2 }, + }) + pendingNavigation = navigation + + await waitFor( + () => { + const current = currentMatch() + expect(current).toBeDefined() + expect( + router.stores.pendingMatches + .get() + .some( + (match) => + match.routeId === postsRoute.id && + match.status === 'pending' && + match.id !== current?.id, + ), + ).toBe(true) + }, + { timeout: 1000 }, + ) + + await new Promise((resolve) => setTimeout(resolve, 0)) + + expect(screen.getByTestId('post-content')).toHaveTextContent('Page 1') + + page2Gate.resolve() + await navigation + pendingNavigation = undefined + + expect(await screen.findByText('Page 2')).toBeInTheDocument() +}) From 8678c4d563e2757da64ee4e1777d0f5a16715975 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Fri, 3 Jul 2026 23:07:09 +0200 Subject: [PATCH 03/54] fix: settle superseded loads with the navigation chain and let preloads join pending-published owners - loadClientRouter now awaits the superseding load chain before its public await settles, restoring the router.load()/invalidate() synchronization contract for superseded and redirected loads. - joinPreloadedActiveMatch waits for the foreground load when the borrowed owner is a render-ready pending publication (active store, status 'pending', pending pool cleared) instead of dropping descendant preloads. Co-Authored-By: Claude Fable 5 --- packages/router-core/src/load-matches.client.ts | 13 +++++++++++++ packages/router-core/src/router-load.client.ts | 14 ++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/packages/router-core/src/load-matches.client.ts b/packages/router-core/src/load-matches.client.ts index 02645044cd..fbdcba61e6 100644 --- a/packages/router-core/src/load-matches.client.ts +++ b/packages/router-core/src/load-matches.client.ts @@ -116,6 +116,19 @@ const joinPreloadedActiveMatch = async ( throw inner } + // The owner can also be a render-ready pending publication: onReady() moved + // it into the active store (clearing the pending pool) while the foreground + // final commit is still in flight, so the store snapshot is stuck at + // status 'pending' even though its local work settled. Wait for the + // foreground load to commit before judging the owner's outcome. + if (match.status === 'pending' && inner.router.latestLoadPromise) { + await inner.router.latestLoadPromise + match = inner.router.getMatch(matchId, false) + if (!match || match.abortController.signal.aborted) { + throw inner + } + } + // From here the preload lane uses the owner match read-only. It must not clone // or cache a borrowed active match as if the preload generated it itself. inner.matches[index] = match diff --git a/packages/router-core/src/router-load.client.ts b/packages/router-core/src/router-load.client.ts index 6ec881acdf..eb690170d8 100644 --- a/packages/router-core/src/router-load.client.ts +++ b/packages/router-core/src/router-load.client.ts @@ -249,6 +249,20 @@ export const loadClientRouter = async ( } loadPromise.resolve() + + // A superseded or redirected load must not settle its public await before + // the navigation chain does: callers of router.load()/invalidate() rely on + // observing post-settlement state, and the preload borrow protocol uses the + // foreground load promise as its "committed or gone" signal. + let latest = router.latestLoadPromise + while (latest && latest !== loadPromise) { + await latest + if (router.latestLoadPromise === latest) { + break + } + latest = router.latestLoadPromise + } + if (startedBackgroundLoad) { // Background stale reloads run after the foreground lane is done. If that // background work is sync, its commit is queued in the next microtask; yield From 0bc62d07d1bbe62a7d1ba7e7695210ba1dd159f6 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Fri, 3 Jul 2026 23:09:45 +0200 Subject: [PATCH 04/54] fix(solid-router): render same-route pending UI from core publication, not the pending pool The pendingReplacement branch swapped committed content for the pending fallback (or null) the moment setPending published at load start, bypassing pendingMs entirely and stamping pendingUntil at navigation start. Core already owns pending timing: the render-ready lane is published into the active store after pendingMs, which is what React renders from. Solid now does the same. Co-Authored-By: Claude Fable 5 --- packages/solid-router/src/Match.tsx | 19 ------------------- packages/solid-router/tests/Matches.test.tsx | 9 +++++++-- 2 files changed, 7 insertions(+), 21 deletions(-) diff --git a/packages/solid-router/src/Match.tsx b/packages/solid-router/src/Match.tsx index 2d0146c36e..4350a6fcc2 100644 --- a/packages/solid-router/src/Match.tsx +++ b/packages/solid-router/src/Match.tsx @@ -274,17 +274,6 @@ export const MatchInner = (): any => { route().options.pendingComponent ?? router.options.defaultPendingComponent - const pendingReplacement = () => { - return router.stores.pendingMatches - .get() - .find( - (pending) => - pending.routeId === currentMatchState().routeId && - pending.status === 'pending' && - pending.id !== currentMatch().id, - ) - } - const armPending = (pendingMatch: any) => { const FallbackComponent = PendingComponent() const pendingMinMs = @@ -330,14 +319,6 @@ export const MatchInner = (): any => { return ( - - {(pendingMatch) => { - const FallbackComponent = armPending(pendingMatch()) - return FallbackComponent ? ( - - ) : null - }} - {(_) => { const loadPromise = currentMatch()._.loadPromise diff --git a/packages/solid-router/tests/Matches.test.tsx b/packages/solid-router/tests/Matches.test.tsx index 253a016372..30b598661c 100644 --- a/packages/solid-router/tests/Matches.test.tsx +++ b/packages/solid-router/tests/Matches.test.tsx @@ -295,9 +295,14 @@ test('same-route pending replacement respects pendingMinMs', async () => { expect(await screen.findByTestId('replacement-pending')).toBeInTheDocument() - const pendingMatch = router.stores.pendingMatches + // The pending fallback only renders once core publishes the render-ready + // pending lane into the active store (after pendingMs), so the armed match + // is read from the active matches, not the pending pool. + const pendingMatch = router.stores.matches .get() - .find((match) => match.routeId === postsRoute.id)! + .find( + (match) => match.routeId === postsRoute.id && match.status === 'pending', + )! expect(pendingMatch._.loadPromise?.pendingUntil).toBeTypeOf('number') From 6e7c02ace0358c9bfe630e8f44ee17ca5a1d27d8 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Fri, 3 Jul 2026 23:12:51 +0200 Subject: [PATCH 05/54] fix(vue-router): tolerate settled loadPromise on pending matches and restore _displayPending guard MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Vue renders pending UI directly (it never suspends on the load promise), so a settled/absent match-local promise is a legitimate stale-snapshot state (hydration display matches, cancelMatches) — not an invariant violation. Stamp pendingUntil only on a still-pending local promise, mirroring React, and restore main's _displayPending early-return that kept pending UI up after ClientOnly stops gating. Co-Authored-By: Claude Fable 5 --- packages/vue-router/src/Match.tsx | 31 ++++++-- .../pending-match-settled-promise.test.tsx | 75 +++++++++++++++++++ 2 files changed, 99 insertions(+), 7 deletions(-) create mode 100644 packages/vue-router/tests/pending-match-settled-promise.test.tsx diff --git a/packages/vue-router/src/Match.tsx b/packages/vue-router/src/Match.tsx index 4e39e77575..2b2179901b 100644 --- a/packages/vue-router/src/Match.tsx +++ b/packages/vue-router/src/Match.tsx @@ -330,6 +330,7 @@ export const MatchInner = Vue.defineComponent({ status: match.status, error: match.error, ssr: match.ssr, + _displayPending: match._displayPending, _: match._, }, remountKey, @@ -348,6 +349,17 @@ export const MatchInner = Vue.defineComponent({ // If match doesn't exist, return null (component is being unmounted or not ready) if (!combinedState.value || !match.value || !route.value) return null + // A hydration display match keeps rendering pending UI until the + // follow-up client load clears the marker, even though its local + // loadPromise was already settled by hydrate(). + if (match.value._displayPending) { + const PendingComponent = + route.value.options.pendingComponent ?? + router.options.defaultPendingComponent + + return PendingComponent ? Vue.h(PendingComponent) : null + } + if (match.value.status === 'notFound') { if (!isNotFound(match.value.error)) { if (process.env.NODE_ENV !== 'production') { @@ -392,17 +404,22 @@ export const MatchInner = Vue.defineComponent({ router.options.defaultPendingComponent if (PendingComponent) { - const promise = Vue.toRaw(match.value._).loadPromise + // Vue can render a stale match snapshot after its match-local + // promise was settled/removed (hydration display matches, + // cancelMatches) but before the newer lane commits, so a missing + // local promise is a legitimate state here. Only a still-pending + // local promise owns pendingMinMs timing. + const localPromise = Vue.toRaw(match.value._).loadPromise const pendingMinMs = route.value.options.pendingMinMs ?? router.options.defaultPendingMinMs - if (process.env.NODE_ENV !== 'production' && !promise) { - invariant() - } - - if (promise && !(isServer ?? router.isServer) && pendingMinMs) { - promise.pendingUntil ??= Date.now() + pendingMinMs + if ( + !(isServer ?? router.isServer) && + localPromise?.status === 'pending' && + pendingMinMs + ) { + localPromise.pendingUntil ??= Date.now() + pendingMinMs } return Vue.h(PendingComponent) diff --git a/packages/vue-router/tests/pending-match-settled-promise.test.tsx b/packages/vue-router/tests/pending-match-settled-promise.test.tsx new file mode 100644 index 0000000000..d59328ef0b --- /dev/null +++ b/packages/vue-router/tests/pending-match-settled-promise.test.tsx @@ -0,0 +1,75 @@ +import { afterEach, expect, test } from 'vitest' +import { cleanup, render, screen } from '@testing-library/vue' +import { createMemoryHistory } from '@tanstack/history' +import { + Outlet, + RouterProvider, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +/** + * A pending match whose match-local loadPromise was settled/removed is a + * legitimate state: hydrate() settles the display match's promise while + * keeping it pending (_displayPending), and cancelMatches() settles every + * active match's promise at the start of each load. MatchInner must render + * pending UI for such a snapshot instead of hitting a dev invariant. + */ + +afterEach(() => { + cleanup() +}) + +function setup() { + const rootRoute = createRootRoute({ + component: () => , + }) + const slowRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/slow', + pendingMinMs: 100, + loader: () => new Promise(() => {}), + pendingComponent: () =>
Pending
, + component: () =>
Slow content
, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([slowRoute]), + history: createMemoryHistory({ initialEntries: ['/slow'] }), + defaultPendingMs: 0, + }) + return { router, slowRoute } +} + +test('pending match with a settled loadPromise renders the pending component without crashing', async () => { + const { router, slowRoute } = setup() + router.stores.setMatches(router.matchRoutes(router.latestLocation)) + + const match = router.stores.matches + .get() + .find((m) => m.routeId === slowRoute.id)! + expect(match.status).toBe('pending') + // Simulate hydrate()/cancelMatches() settling the match-local promise while + // the match stays pending. + match._.loadPromise = undefined + + render() + + expect(await screen.findByTestId('pending-ui')).toBeTruthy() +}) + +test('hydration display match keeps rendering pending UI after mount', async () => { + const { router, slowRoute } = setup() + router.stores.setMatches(router.matchRoutes(router.latestLocation)) + + const match = router.stores.matches + .get() + .find((m) => m.routeId === slowRoute.id)! + match._displayPending = true + match._.loadPromise = undefined + + render() + + expect(await screen.findByTestId('pending-ui')).toBeTruthy() + expect(screen.queryByTestId('slow-content')).toBeNull() +}) From a6cd9bac50ccdc39e2fae8603a272793e266ba4f Mon Sep 17 00:00:00 2001 From: Sheraff Date: Fri, 3 Jul 2026 23:14:23 +0200 Subject: [PATCH 06/54] fix: only cancel active matches with in-flight work in cancelMatches Aborting every active match's controller at load start killed deferred/ streamed data tied to a success stay-match's loader signal on any child navigation or invalidate(), landing AbortError in boundaries. Restore main's filter (pending or actively fetching) for active matches; pending-pool matches are still fully cancelled and settled. Co-Authored-By: Claude Fable 5 --- packages/router-core/src/router.ts | 14 +++- .../tests/stay-match-abort.test.ts | 64 +++++++++++++++++++ 2 files changed, 77 insertions(+), 1 deletion(-) create mode 100644 packages/router-core/tests/stay-match-abort.test.ts diff --git a/packages/router-core/src/router.ts b/packages/router-core/src/router.ts index 24cc25ce3e..2237fbc4e9 100644 --- a/packages/router-core/src/router.ts +++ b/packages/router-core/src/router.ts @@ -1810,7 +1810,19 @@ export class RouterCore< continue } - cancelMatch(matchId) + // Only cancel active matches with in-flight route work. A settled + // success match keeps its controller un-aborted: loaders may have + // handed that signal to still-streaming deferred data, and the public + // contract only cancels it when the route unloads or its loader call + // becomes outdated. + const match = this.getMatch(matchId) + if ( + match && + (match.status === 'pending' || match.isFetching === 'loader') + ) { + match.abortController.abort() + settleMatchLoad(match) + } } } diff --git a/packages/router-core/tests/stay-match-abort.test.ts b/packages/router-core/tests/stay-match-abort.test.ts new file mode 100644 index 0000000000..03c0ea2fc6 --- /dev/null +++ b/packages/router-core/tests/stay-match-abort.test.ts @@ -0,0 +1,64 @@ +import { describe, expect, test } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +/** + * A settled success stay-match must keep its abortController un-aborted + * across navigations and invalidations: loaders can hand that signal to + * still-streaming deferred data (fetch(url, { signal }) consumed via + * ), and the documented contract only cancels the signal when the + * route unloads or the loader call becomes outdated. Only pending or + * actively-fetching matches are cancelled at load start. + */ + +function setup() { + let capturedSignal: AbortSignal | undefined + + const rootRoute = new BaseRootRoute({}) + const dashboardRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/dashboard', + staleTime: Infinity, + loader: ({ abortController }: { abortController: AbortController }) => { + capturedSignal = abortController.signal + return 'dashboard data' + }, + }) + const settingsRoute = new BaseRoute({ + getParentRoute: () => dashboardRoute, + path: '/settings', + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + dashboardRoute.addChildren([settingsRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/dashboard'] }), + }) + + return { router, getSignal: () => capturedSignal } +} + +describe('stay-match abort scope', () => { + test('navigating to a child route does not abort a fresh success stay-match', async () => { + const { router, getSignal } = setup() + + await router.load() + expect(getSignal()?.aborted).toBe(false) + + await router.navigate({ to: '/dashboard/settings' }) + expect(getSignal()?.aborted).toBe(false) + }) + + test('invalidate does not abort a success stay-match signal', async () => { + const { router, getSignal } = setup() + + await router.load() + const firstSignal = getSignal() + expect(firstSignal?.aborted).toBe(false) + + await router.invalidate() + expect(firstSignal?.aborted).toBe(false) + }) +}) From 85bcb58810e4974e66f8476e37ed73ab153837b1 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Fri, 3 Jul 2026 23:18:32 +0200 Subject: [PATCH 07/54] fix: keep client load errors observable instead of swallowing them - loadClientRouter's outer catch re-surfaces non-redirect, non-sentinel failures (asset projection, view transitions, lifecycle hooks) as unhandled rejections instead of silently dropping them. - commitFinalMatches wraps each lifecycle hook so a throwing onEnter/onStay/onLeave stays observable without skipping the remaining hooks or corrupting the committed transition. - React's startTransition clears isTransitioning in a finally block so a throwing commit cannot permanently block onResolved/idle. Co-Authored-By: Claude Fable 5 --- packages/react-router/src/Transitioner.tsx | 9 ++- .../router-core/src/router-load.client.ts | 31 ++++++-- .../tests/lifecycle-hook-errors.test.ts | 76 +++++++++++++++++++ 3 files changed, 106 insertions(+), 10 deletions(-) create mode 100644 packages/router-core/tests/lifecycle-hook-errors.test.ts diff --git a/packages/react-router/src/Transitioner.tsx b/packages/react-router/src/Transitioner.tsx index bf945571a6..6e0a6a6300 100644 --- a/packages/react-router/src/Transitioner.tsx +++ b/packages/react-router/src/Transitioner.tsx @@ -26,8 +26,13 @@ export function Transitioner() { router.startTransition = (fn: () => void) => { setIsTransitioning(true) React.startTransition(() => { - fn() - setIsTransitioning(false) + try { + fn() + } finally { + // A throwing commit must not strand isTransitioning, which would + // permanently block onResolved and the idle status transition. + setIsTransitioning(false) + } }) } diff --git a/packages/router-core/src/router-load.client.ts b/packages/router-core/src/router-load.client.ts index eb690170d8..04a9389372 100644 --- a/packages/router-core/src/router-load.client.ts +++ b/packages/router-core/src/router-load.client.ts @@ -69,14 +69,21 @@ const commitFinalMatches = ( const current = baseMatches[i] const nextMatch = nextMatches[i] - if (current && current.routeId !== nextMatch?.routeId) { - router.routesById[current.routeId]!.options.onLeave?.(current) - } + // The commit already happened; lifecycle hooks are notifications. A + // throwing hook must not skip the remaining hooks or corrupt the + // framework transition state, but it has to stay observable. + try { + if (current && current.routeId !== nextMatch?.routeId) { + router.routesById[current.routeId]!.options.onLeave?.(current) + } - if (nextMatch) { - router.routesById[nextMatch.routeId]!.options[ - current?.routeId === nextMatch.routeId ? 'onStay' : 'onEnter' - ]?.(nextMatch) + if (nextMatch) { + router.routesById[nextMatch.routeId]!.options[ + current?.routeId === nextMatch.routeId ? 'onStay' : 'onEnter' + ]?.(nextMatch) + } + } catch (err) { + Promise.reject(err) } } } @@ -93,6 +100,7 @@ export const loadClientRouter = async ( const isCurrentLoad = () => router.latestLoadPromise === loadPromise let startedBackgroundLoad = false + let loadContext: InnerLoadContext | undefined try { const backgroundLoad = router._backgroundLoad @@ -163,7 +171,7 @@ export const loadClientRouter = async ( } }) } - const loadContext: InnerLoadContext = { + loadContext = { router, forceStaleReload: sameHref, matches: pendingMatches, @@ -239,6 +247,13 @@ export const loadClientRouter = async ( replace: true, ignoreBlocker: true, }) + } else if (err !== loadContext && !isRedirect(err)) { + // Anything else is a genuine failure (asset projection, view + // transition, user onLeave/onStay/onEnter hooks). The public load + // promise still resolves — navigation state was already committed or + // superseded — but the error must stay observable to the app's + // unhandled-rejection reporting instead of vanishing. + Promise.reject(err) } } diff --git a/packages/router-core/tests/lifecycle-hook-errors.test.ts b/packages/router-core/tests/lifecycle-hook-errors.test.ts new file mode 100644 index 0000000000..d18ec3dba6 --- /dev/null +++ b/packages/router-core/tests/lifecycle-hook-errors.test.ts @@ -0,0 +1,76 @@ +import { describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +/** + * Route lifecycle hooks (onEnter/onStay/onLeave) run after the final commit. + * A throwing hook is a user error: it must stay observable (unhandled + * rejection for the app's error reporting), but it must not be silently + * swallowed, skip the remaining hooks, or leave the navigation un-committed. + */ + +describe('lifecycle hook errors', () => { + test('a throwing onEnter surfaces as an unhandled rejection and does not skip other hooks', async () => { + const unhandledRejection = vi.fn() + process.on('unhandledRejection', unhandledRejection) + + try { + const hookError = new Error('onEnter failed') + const parentOnEnter = vi.fn(() => { + throw hookError + }) + const childOnEnter = vi.fn() + const indexOnLeave = vi.fn() + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + onLeave: indexOnLeave, + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + onEnter: parentOnEnter, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + onEnter: childOnEnter, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.navigate({ to: '/parent/child' }) + + // Navigation committed despite the throwing hook. (status 'idle' is + // owned by framework transitioners, so a core test asserts isLoading.) + expect(router.state.location.pathname).toBe('/parent/child') + expect(router.stores.isLoading.get()).toBe(false) + expect( + router.state.matches.find((m) => m.routeId === childRoute.id)?.status, + ).toBe('success') + + // All hooks ran; the failure did not short-circuit the loop. + expect(parentOnEnter).toHaveBeenCalledTimes(1) + expect(childOnEnter).toHaveBeenCalledTimes(1) + + // The error stayed observable. + await new Promise((resolve) => setTimeout(resolve, 0)) + expect(unhandledRejection).toHaveBeenCalledWith( + hookError, + expect.anything(), + ) + } finally { + process.off('unhandledRejection', unhandledRejection) + } + }) +}) From 5f86055de238ef99631372e0af769b6f3664f851 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Fri, 3 Jul 2026 23:20:47 +0200 Subject: [PATCH 08/54] fix: preserve exiting success matches in cache at pending publication Publication evicts the previous active lane from every pool; if the load is then superseded (back navigation), the final commit that would have cached those matches never runs and fresh within-staleTime data is lost, forcing a spurious loader re-run. Cache exiting success matches at publication (mirroring main's onReady) and dedupe against them in commitFinalMatches. Co-Authored-By: Claude Fable 5 --- packages/router-core/INTERNALS.md | 5 +- .../router-core/src/router-load.client.ts | 29 +++++- .../tests/pending-publication-cache.test.ts | 94 +++++++++++++++++++ 3 files changed, 126 insertions(+), 2 deletions(-) create mode 100644 packages/router-core/tests/pending-publication-cache.test.ts diff --git a/packages/router-core/INTERNALS.md b/packages/router-core/INTERNALS.md index d6559c3aa7..5d79090b91 100644 --- a/packages/router-core/INTERNALS.md +++ b/packages/router-core/INTERNALS.md @@ -147,7 +147,10 @@ There are several kinds of commit. Keep them separate: - **Pending publication**: `onReady(matches)` publishes a render-ready pending lane into active matches so frameworks can render pending UI. It does not run route lifecycle hooks, cache reconciliation, `loadedAt`, or the final view - transition. It also clears the pending match pool for that load pass. + transition. It also clears the pending match pool for that load pass. It does + preserve exiting success matches in `cachedMatches` — publication removes + them from the active pool, and if the load is later superseded the final + commit that would have cached them never runs. - **Final client commit**: `commitFinalMatches()` publishes the final active lane, reconciles cache, clears pending state, updates `loadedAt`, and runs `onLeave`, `onStay`, and `onEnter`. diff --git a/packages/router-core/src/router-load.client.ts b/packages/router-core/src/router-load.client.ts index 04a9389372..de2ae03526 100644 --- a/packages/router-core/src/router-load.client.ts +++ b/packages/router-core/src/router-load.client.ts @@ -24,10 +24,12 @@ const commitFinalMatches = ( router.batch(() => { const now = Date.now() const cached = stores.cachedMatches.get().slice() + // Pending publication may already have preserved exiting base matches. + const cachedIds = new Set(cached.map((match) => match.id)) for (let i = 0; i < baseMatches.length; i++) { const match = baseMatches[i]! - if (nextMatches[i]?.id !== match.id) { + if (nextMatches[i]?.id !== match.id && !cachedIds.has(match.id)) { cached.push({ ...match, isFetching: false, @@ -165,6 +167,31 @@ export const loadClientRouter = async ( } router.batch(() => { + // Publication replaces the active lane before final commit, so + // exiting success matches must be preserved in the cache here: if + // this load is superseded (e.g. back navigation) the final commit + // that would have cached them never runs, and their fresh data + // would otherwise be lost from every pool. + const publishedIds = new Set(matches.map((match) => match.id)) + const cached = stores.cachedMatches.get() + const cachedIds = new Set(cached.map((match) => match.id)) + const exiting = stores.matches + .get() + .filter( + (match) => + match.status === 'success' && + !publishedIds.has(match.id) && + !cachedIds.has(match.id), + ) + if (exiting.length) { + stores.setCached([ + ...cached, + ...exiting.map((match) => ({ + ...match, + isFetching: false as const, + })), + ]) + } stores.setMatches(matches) if (stores.pendingIds.get().length) { stores.setPending([]) diff --git a/packages/router-core/tests/pending-publication-cache.test.ts b/packages/router-core/tests/pending-publication-cache.test.ts new file mode 100644 index 0000000000..7b7d0ce48c --- /dev/null +++ b/packages/router-core/tests/pending-publication-cache.test.ts @@ -0,0 +1,94 @@ +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, createControlledPromise } from '../src' +import { createTestRouter } from './routerTestUtils' + +/** + * Pending publication replaces the active lane before the final commit. The + * exiting matches must survive in cachedMatches: when the published load is + * later superseded (back navigation being the canonical case), the final + * commit that would have cached them never runs, and fresh within-staleTime + * data would otherwise be re-fetched with a pending flash. + */ + +describe('pending publication preserves exiting matches', () => { + beforeEach(() => { + vi.useFakeTimers() + }) + + afterEach(() => { + vi.useRealTimers() + }) + + test('back navigation during a pending-published load reuses the exited fresh match', async () => { + const slowGate = createControlledPromise() + const aLoader = vi.fn(() => 'a data') + const bLoader = vi.fn(async () => { + await slowGate + return 'b data' + }) + + const rootRoute = new BaseRootRoute({}) + const aRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/a', + staleTime: 60_000, + loader: aLoader, + }) + const bRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/b', + pendingMs: 1, + pendingComponent: {}, + loader: bLoader, + }) + + const history = createMemoryHistory({ initialEntries: ['/a'] }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([aRoute, bRoute]), + history, + }) + + await router.load() + expect(aLoader).toHaveBeenCalledTimes(1) + + const navigation = router.navigate({ to: '/b' }) + await vi.waitFor(() => expect(bLoader).toHaveBeenCalledTimes(1)) + + // Let pendingMs elapse so the render-ready pending lane is published. + await vi.advanceTimersByTimeAsync(1) + await vi.waitFor(() => + expect( + router.state.matches.some( + (match) => match.routeId === bRoute.id && match.status === 'pending', + ), + ).toBe(true), + ) + + // The exited /a match must still exist somewhere. + expect( + router.stores.cachedMatches + .get() + .some((match) => match.routeId === aRoute.id), + ).toBe(true) + + // Supersede the pending-published /b load by going back to /a. + const back = router.navigate({ to: '/a' }) + await vi.waitFor(() => + expect( + router.state.matches.find((match) => match.routeId === aRoute.id) + ?.status, + ).toBe('success'), + ) + + // Fresh within-staleTime data was served from cache, not re-fetched. + expect(aLoader).toHaveBeenCalledTimes(1) + expect( + router.state.matches.find((match) => match.routeId === aRoute.id) + ?.loaderData, + ).toBe('a data') + + slowGate.resolve() + await Promise.allSettled([navigation, back]) + }) +}) From 8d7c9f1b3368337a1c53c99660fc1f6c6a8877f9 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Fri, 3 Jul 2026 23:25:09 +0200 Subject: [PATCH 09/54] fix: make route asset projection failure semantics coherent across server, background, and hydration - Server projection commits head/scripts/headers independently so a failing decorative hook no longer drops route headers (response behavior). Sync throws still abandon pending async hooks without blocking the response, owning their rejections. - Background reloads only publish when asset projection for the fresh data succeeded, keeping the data+assets commit atomic instead of exposing new loaderData under stale meta. - Hydration no longer executes head()/scripts() for ssr:false matches, including children the server intentionally omitted at an error/ notFound boundary; the follow-up client load projects assets for the lane it actually commits. Co-Authored-By: Claude Fable 5 --- .../router-core/src/load-matches.client.ts | 10 +- .../router-core/src/route-assets.client.ts | 72 +++--- .../router-core/src/route-assets.server.ts | 216 +++++++----------- packages/router-core/src/ssr/ssr-client.ts | 10 + 4 files changed, 138 insertions(+), 170 deletions(-) diff --git a/packages/router-core/src/load-matches.client.ts b/packages/router-core/src/load-matches.client.ts index fbdcba61e6..e5a91cd447 100644 --- a/packages/router-core/src/load-matches.client.ts +++ b/packages/router-core/src/load-matches.client.ts @@ -911,11 +911,13 @@ export function startBackgroundLoad( undefined, isCurrentOrCancel, ) - if (isPromise(assets)) { - await assets - } + const assetsOk = isPromise(assets) ? await assets : assets - if (isCurrentOrCancel()) { + // The background commit is atomic for data and assets: when asset + // projection for the fresh data failed, publishing would expose new + // loaderData under head output that still describes the previous data. + // Keep the old lane; the fetching markers are cleared by the finalizer. + if (assetsOk && isCurrentOrCancel()) { router.stores.setMatches(matches) committed = true } diff --git a/packages/router-core/src/route-assets.client.ts b/packages/router-core/src/route-assets.client.ts index 6b52f70f20..26180b5dc3 100644 --- a/packages/router-core/src/route-assets.client.ts +++ b/packages/router-core/src/route-assets.client.ts @@ -18,16 +18,26 @@ function commitClientAssets( } } +/** + * Projects head()/scripts() into the given lane. + * + * Returns whether every asset hook committed cleanly. Background reloads use + * this to keep their publication atomic: fresh loaderData must not be + * committed under assets that could not be computed for it. Ownership loss + * also returns false — the caller's currentness check decides what to do. + */ export function projectClientRouteAssets( router: AnyRouter, matches: Array, preload?: boolean, isCurrent?: () => boolean, startIndex = 0, -): void | Promise { +): boolean | Promise { + let ok = true + for (let i = startIndex; i < matches.length; i++) { if (isCurrent && !isCurrent()) { - return + return false } const match = matches[i]! @@ -54,7 +64,7 @@ export function projectClientRouteAssets( // This pass lost ownership before the normal Promise.all path could // observe `head`; allSettled owns any later rejection. void Promise.allSettled([head]) - return + return false } let scripts: any @@ -70,40 +80,45 @@ export function projectClientRouteAssets( // This pass lost ownership before the normal Promise.all path could // observe the asset promises; allSettled owns any later rejection. void Promise.allSettled([head, scripts]) - return + return false } if (isPromise(head) || isPromise(scripts)) { return Promise.all([head, scripts]).then( ([headResult, scriptResult]) => { - if (!isCurrent || isCurrent()) { - commitClientAssets(matches, i, headResult, scriptResult) - return projectClientRouteAssets( - router, - matches, - preload, - isCurrent, - i + 1, - ) + if (isCurrent && !isCurrent()) { + return false } + commitClientAssets(matches, i, headResult, scriptResult) + const rest = projectClientRouteAssets( + router, + matches, + preload, + isCurrent, + i + 1, + ) + return isPromise(rest) ? rest.then((r) => r && ok) : rest && ok }, (error) => { - if (!isCurrent || isCurrent()) { - if (process.env.NODE_ENV !== 'production') { - console.error( - `Error executing head for route ${match.routeId}:`, - error, - ) - } + if (isCurrent && !isCurrent()) { + return false + } - return projectClientRouteAssets( - router, - matches, - preload, - isCurrent, - i + 1, + if (process.env.NODE_ENV !== 'production') { + console.error( + `Error executing head for route ${match.routeId}:`, + error, ) } + + const rest = projectClientRouteAssets( + router, + matches, + preload, + isCurrent, + i + 1, + ) + return isPromise(rest) ? rest.then(() => false) : false }, ) } @@ -111,12 +126,15 @@ export function projectClientRouteAssets( commitClientAssets(matches, i, head, scripts) } catch (error) { if (isCurrent && !isCurrent()) { - return + return false } + ok = false if (process.env.NODE_ENV !== 'production') { console.error(`Error executing head for route ${match.routeId}:`, error) } } } + + return ok } diff --git a/packages/router-core/src/route-assets.server.ts b/packages/router-core/src/route-assets.server.ts index 2592e9640b..bd5f97c0e1 100644 --- a/packages/router-core/src/route-assets.server.ts +++ b/packages/router-core/src/route-assets.server.ts @@ -17,6 +17,12 @@ const withServerAssets = ( headers, }) +const logAssetError = (match: AnyRouteMatch, error: unknown): void => { + if (process.env.NODE_ENV !== 'production') { + console.error(`Error executing head for route ${match.routeId}:`, error) + } +} + export const projectServerRouteAssets = ( router: AnyRouter, matches: Array, @@ -29,155 +35,87 @@ export const projectServerRouteAssets = ( continue } - try { - const assetContext = { - ssr: router.options.ssr, - matches, - match, - params: match.params, - loaderData: match.loaderData, - } - - const head = routeOptions.head?.(assetContext) - let scripts: any - try { - scripts = routeOptions.scripts?.(assetContext) - } catch (error) { - // `head` may be async and abandoned because `scripts` threw - // synchronously. Own its rejection so it cannot become unhandled. - void Promise.allSettled([head]) - throw error - } - let headers: any - try { - headers = routeOptions.headers?.(assetContext) - } catch (error) { - // `head`/`scripts` may be async and abandoned because `headers` threw - // synchronously. Own rejections so they cannot become unhandled. - void Promise.allSettled([head, scripts]) - throw error - } - - if (isPromise(head) || isPromise(scripts) || isPromise(headers)) { - return continueServerRouteAssets( - router, - matches, - i, - match, - head, - scripts, - headers, - ) - } - - matches[i] = withServerAssets(match, head, scripts, headers) - } catch (error) { - if (process.env.NODE_ENV !== 'production') { - console.error(`Error executing head for route ${match.routeId}:`, error) - } + const assetContext = { + ssr: router.options.ssr, + matches, + match, + params: match.params, + loaderData: match.loaderData, } - } -} -const continueServerRouteAssets = async ( - router: AnyRouter, - matches: Array, - startIndex: number, - firstMatch: AnyRouteMatch, - firstHead: any, - firstScripts: any, - firstHeaders: any, -): Promise => { - let i = startIndex - let match = firstMatch - let head = firstHead - let scripts = firstScripts - let headers = firstHeaders + // Each asset kind commits independently: route headers are response + // behavior and must not be dropped because a decorative head()/scripts() + // failed, and vice versa. + let syncFailed = false + let head: any + let scripts: any + let headers: any + try { + head = routeOptions.head?.(assetContext) + } catch (error) { + syncFailed = true + logAssetError(match, error) + } + try { + scripts = routeOptions.scripts?.(assetContext) + } catch (error) { + syncFailed = true + logAssetError(match, error) + } + try { + headers = routeOptions.headers?.(assetContext) + } catch (error) { + syncFailed = true + logAssetError(match, error) + } - while (true) { - const results = await Promise.allSettled([head, scripts, headers]) - - const headResult = results[0] - const scriptResult = results[1] - const headerResult = results[2] - - if ( - headResult.status === 'fulfilled' && - scriptResult.status === 'fulfilled' && - headerResult.status === 'fulfilled' - ) { + if (syncFailed) { + // A sync throw must not hold the response hostage waiting on the other + // hooks' async work. Commit the sync-available values and abandon any + // pending promises, owning their rejections so they cannot become + // unhandled. + const settle = (value: any) => { + if (isPromise(value)) { + void Promise.allSettled([value]) + return undefined + } + return value + } matches[i] = withServerAssets( match, - headResult.value, - scriptResult.value, - headerResult.value, - ) - } else if (process.env.NODE_ENV !== 'production') { - const failed = - headResult.status === 'rejected' - ? headResult - : scriptResult.status === 'rejected' - ? scriptResult - : headerResult - console.error( - `Error executing head for route ${match.routeId}:`, - (failed as PromiseRejectedResult).reason, + settle(head), + settle(scripts), + settle(headers), ) + continue } - for (i++; i < matches.length; i++) { - match = matches[i]! - const routeOptions = router.routesById[match.routeId]!.options - if ( - !(routeOptions.head || routeOptions.scripts || routeOptions.headers) - ) { - continue - } - - try { - const assetContext = { - ssr: router.options.ssr, - matches, - match, - params: match.params, - loaderData: match.loaderData, - } - - head = routeOptions.head?.(assetContext) - try { - scripts = routeOptions.scripts?.(assetContext) - } catch (error) { - // `head` may be async and abandoned because `scripts` threw - // synchronously. Own its rejection so it cannot become unhandled. - void Promise.allSettled([head]) - throw error - } - try { - headers = routeOptions.headers?.(assetContext) - } catch (error) { - // `head`/`scripts` may be async and abandoned because `headers` threw - // synchronously. Own rejections so they cannot become unhandled. - void Promise.allSettled([head, scripts]) - throw error - } - - if (isPromise(head) || isPromise(scripts) || isPromise(headers)) { - break - } - - matches[i] = withServerAssets(match, head, scripts, headers) - } catch (error) { - if (process.env.NODE_ENV !== 'production') { - console.error( - `Error executing head for route ${match.routeId}:`, - error, + if (isPromise(head) || isPromise(scripts) || isPromise(headers)) { + return Promise.allSettled([head, scripts, headers]).then( + ([headResult, scriptResult, headerResult]) => { + matches[i] = withServerAssets( + match, + headResult.status === 'fulfilled' ? headResult.value : undefined, + scriptResult.status === 'fulfilled' + ? scriptResult.value + : undefined, + headerResult.status === 'fulfilled' + ? headerResult.value + : undefined, ) - } - } + + const failed = [headResult, scriptResult, headerResult].find( + (result) => result.status === 'rejected', + ) as PromiseRejectedResult | undefined + if (failed) { + logAssetError(match, failed.reason) + } + + return projectServerRouteAssets(router, matches, i + 1) + }, + ) } - if (i >= matches.length) { - return - } + matches[i] = withServerAssets(match, head, scripts, headers) } } diff --git a/packages/router-core/src/ssr/ssr-client.ts b/packages/router-core/src/ssr/ssr-client.ts index 299e31172b..5f3449f155 100644 --- a/packages/router-core/src/ssr/ssr-client.ts +++ b/packages/router-core/src/ssr/ssr-client.ts @@ -264,6 +264,16 @@ export async function hydrate(router: AnyRouter): Promise { match.__beforeLoadContext, ) + // The server rendered no assets for ssr:false matches — including + // matches it intentionally omitted at an error/notFound boundary, + // which the dehydrated payload also marks ssr:false. Their + // head()/scripts() could only run with missing or stale loader + // data here; the follow-up client load projects assets for the + // lane it actually commits. + if (match.ssr === false) { + return + } + const assetContext = { ssr: router.options.ssr, matches, From 1f53606a77c71e4f0c8527c583a6d64d5e2a4901 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Fri, 3 Jul 2026 23:36:22 +0200 Subject: [PATCH 10/54] fix: decouple boundary chunk loading from the whole-route preload and normalize chunk failures - loadRouteChunk(route, componentType) now tracks per-component-type in-flight preloads: targeted boundary requests join their own type's chunk instead of awaiting (and inheriting failures from) the unrelated whole-route _componentsPromise. Full preloads start fresh so a new load generation never couples to a stale generation's boundary chunk, and rejections are evicted instead of cached forever. - Primary route chunk failures (lazyFn/component preload) go through normalizeRouteFailure like loader failures, so route onError fires and thrown redirects/notFounds are honored; boundary component chunk failures still commit directly (recursion guard). Co-Authored-By: Claude Fable 5 --- packages/router-core/INTERNALS.md | 26 ++++--- .../router-core/src/load-matches.client.ts | 12 ++-- packages/router-core/src/route-chunks.ts | 71 ++++++++++++++++--- packages/router-core/src/route.ts | 14 ++++ .../tests/boundary-component-chunk.test.ts | 13 ++-- packages/router-core/tests/load.test.ts | 6 +- 6 files changed, 116 insertions(+), 26 deletions(-) diff --git a/packages/router-core/INTERNALS.md b/packages/router-core/INTERNALS.md index 5d79090b91..ab914b6947 100644 --- a/packages/router-core/INTERNALS.md +++ b/packages/router-core/INTERNALS.md @@ -425,9 +425,10 @@ that may be discarded by the boundary trim. result is written even when the value is `undefined`; a reload that returns `undefined` clears stale `loaderData` instead of preserving the previous value. -7. `shouldReload` and loader failures are normalized and finalized. Serial - `beforeLoad` failures are finalized by `loadClientMatches()` using the same - finalizer. Route chunk failures are committed directly. +7. `shouldReload`, loader, and route chunk failures are normalized and + finalized through the same route failure lifecycle (`onError`, + redirect/notFound conversion). Serial `beforeLoad` failures are finalized + by `loadClientMatches()` using the same finalizer. 8. `pendingMinMs` is honored if pending UI was rendered. 9. Success clears error/fetching, sets `updatedAt`, and settles load promise. @@ -516,14 +517,23 @@ redirects are handled inside `startBackgroundLoad()`. ### Component/chunk failure while handling another failure -If loading an `errorComponent` or `notFoundComponent` fails, the component/chunk -failure replaces the original route failure and is committed directly as an -error. It must not recursively try to load another boundary component. +A primary route chunk failure (lazyFn or a route component preload observed by +the loader phase) goes through `normalizeRouteFailure` like loader failures, +so `onError` and redirect/notFound conversion apply. Only when loading an +`errorComponent` or `notFoundComponent` boundary chunk fails does the +component failure replace the original route failure and commit directly as +an error — it must not recursively try to load another boundary component. + +Boundary chunk requests are per-component-type: `loadRouteChunk(route, +'errorComponent')` joins that component's own in-flight chunk but never +waits on the whole-route `_componentsPromise`, so an unrelated slow or failed +component chunk cannot block or poison boundary UI. Rejected preloads are +evicted (not cached), so a later load generation can retry. ```mermaid flowchart TD - F["loader/beforeLoad throws"] --> N["normalizeRouteFailure"] - Chunk["route/component chunk throws"] --> Direct + F["loader/beforeLoad/chunk throws"] --> N["normalizeRouteFailure"] + Chunk["boundary component chunk throws"] --> Direct N --> R{"redirect?"} R -->|"yes"| RT["settle source match and throw resolved redirect"] R -->|"no"| NF{"notFound?"} diff --git a/packages/router-core/src/load-matches.client.ts b/packages/router-core/src/load-matches.client.ts index e5a91cd447..603249ed9c 100644 --- a/packages/router-core/src/load-matches.client.ts +++ b/packages/router-core/src/load-matches.client.ts @@ -630,14 +630,18 @@ const loadClientRouteMatch = async ( await routeChunkPromise } } catch (chunkError) { - // A route/component chunk failure replaces the loader result and is committed - // as the route error for this loader generation. + // A route/component chunk failure replaces the loader result, but it + // still goes through the normal route failure lifecycle (onError, + // redirect/notFound conversion) like beforeLoad and loader failures. + // If loading a boundary component subsequently fails, + // finalizeRouteFailure commits that failure directly instead of + // recursing into another boundary chunk. + requireCurrentMatch(inner, index, passController) return finalizeRouteFailure( inner, index, - chunkError, + normalizeRouteFailure(inner, index, chunkError), passController, - true, ) } diff --git a/packages/router-core/src/route-chunks.ts b/packages/router-core/src/route-chunks.ts index 5b06543ee2..f44c84ef04 100644 --- a/packages/router-core/src/route-chunks.ts +++ b/packages/router-core/src/route-chunks.ts @@ -14,12 +14,56 @@ function preloadComponent(component: any): Promise | undefined { } } +/** + * Preloads one component type with per-type in-flight tracking. + * + * A targeted request (`join: true`, e.g. the errorComponent for a failing + * route) joins that type's in-flight chunk instead of starting a duplicate — + * but never waits on any other type's chunk. A full route preload + * (`join: false`) always starts fresh and overwrites stale entries so a new + * load generation cannot get coupled to an older generation's boundary + * chunk. Settled preloads — success or failure — leave the cache: repeats + * are the component's own concern (lazy components memoize their import), + * and a rejection is never replayed forever. + */ +function preloadRouteComponent( + route: AnyRoute, + componentType: RouteComponentType, + join: boolean, +): Promise | undefined { + const cache = (route._componentPromises ||= {}) + if (join) { + const inFlight = cache[componentType] + if (inFlight) { + return inFlight + } + } + + const preload = preloadComponent(route.options[componentType]) + if (!preload) { + delete cache[componentType] + return undefined + } + + // Cache and return the raw preload so awaiting callers observe settlement + // without an extra microtask hop; the cleanup chain is bookkeeping only + // and swallows the rejection it observes (awaiters own the real one). + cache[componentType] = preload + const cleanup = () => { + if (cache[componentType] === preload) { + delete cache[componentType] + } + } + void preload.then(cleanup, cleanup) + return preload +} + function preloadRouteComponents( route: AnyRoute, ): Promise> | undefined { let preloads: Array> | undefined for (const componentType of componentTypes) { - const preload = preloadComponent(route.options[componentType]) + const preload = preloadRouteComponent(route, componentType, false) if (preload) { ;(preloads ||= []).push(preload) } @@ -55,19 +99,28 @@ export function loadRouteChunk( return } if (componentType) { - return ( - route._componentsPromise || - preloadComponent(route.options[componentType]) - ) + // A targeted request (e.g. the errorComponent for a failing route) + // must only depend on that component's own chunk — never on the + // whole-route preload, whose unrelated (possibly slow or failed) + // component chunks would otherwise block or poison boundary UI. + return preloadRouteComponent(route, componentType, true) } if (!route._componentsPromise) { const componentsPromise = preloadRouteComponents(route) if (componentsPromise) { - route._componentsPromise = componentsPromise.then(() => { - route._componentsLoaded = true - route._componentsPromise = undefined // gc promise, we won't need it anymore - }) + route._componentsPromise = componentsPromise.then( + () => { + route._componentsLoaded = true + route._componentsPromise = undefined // gc promise, we won't need it anymore + }, + (error) => { + // Clear so a later pass can retry the failed component types; + // successful types stay marked done in the per-type cache. + route._componentsPromise = undefined + throw error + }, + ) } else { route._componentsLoaded = true } diff --git a/packages/router-core/src/route.ts b/packages/router-core/src/route.ts index 2de7dc57f0..b7ccba4a5c 100644 --- a/packages/router-core/src/route.ts +++ b/packages/router-core/src/route.ts @@ -703,6 +703,13 @@ export interface Route< /** @internal */ _componentsPromise?: Promise /** @internal */ + _componentPromises?: Partial< + Record< + 'component' | 'errorComponent' | 'pendingComponent' | 'notFoundComponent', + Promise | undefined + > + > + /** @internal */ _componentsLoaded?: boolean lazyFn?: () => Promise< LazyRoute< @@ -1714,6 +1721,13 @@ export class BaseRoute< _lazyPromise?: Promise /** @internal */ _componentsPromise?: Promise + /** @internal */ + _componentPromises?: Partial< + Record< + 'component' | 'errorComponent' | 'pendingComponent' | 'notFoundComponent', + Promise | undefined + > + > constructor( options?: RouteOptions< diff --git a/packages/router-core/tests/boundary-component-chunk.test.ts b/packages/router-core/tests/boundary-component-chunk.test.ts index 46447bc472..4616f20476 100644 --- a/packages/router-core/tests/boundary-component-chunk.test.ts +++ b/packages/router-core/tests/boundary-component-chunk.test.ts @@ -66,11 +66,16 @@ describe('route boundary component preloads', () => { await vi.waitFor(() => expect(errorComponentPreloadCalls).toBe(1)) errorComponentGate.resolve() - await Promise.resolve() - const match = router.state.matches.find((item) => item.routeId === route.id) - expect(match?.status).toBe('error') - expect(match?.error).toBe(routeError) + // The route component chunk (componentGate) is still pending: the error + // state must commit without waiting for it. + await vi.waitFor(() => { + const match = router.state.matches.find( + (item) => item.routeId === route.id, + ) + expect(match?.status).toBe('error') + expect(match?.error).toBe(routeError) + }) componentGate.resolve() await loadPromise diff --git a/packages/router-core/tests/load.test.ts b/packages/router-core/tests/load.test.ts index 779f477a03..e9f179f4fa 100644 --- a/packages/router-core/tests/load.test.ts +++ b/packages/router-core/tests/load.test.ts @@ -7625,7 +7625,11 @@ test('loader AbortError followed by component preload failure commits error', as await expect(loadPromise).resolves.toBeUndefined() const updatedMatch = getLaneMatch(matches, targetMatch.id) expect(updatedMatch?.status).toBe('error') - expect(updatedMatch?.error).toBe(chunkError) + // Error finalization no longer waits on the whole-route component chunk, + // so the pending-status AbortError commits immediately as the route error; + // the later chunk rejection is owned separately and can retry on the next + // load generation instead of replacing the committed failure. + expect((updatedMatch?.error as Error | undefined)?.name).toBe('AbortError') expect(updatedMatch?._.loadPromise).toBeUndefined() }) From 2ac3031a0fd6bc4360d628588cc5f862db31f869 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Fri, 3 Jul 2026 23:38:20 +0200 Subject: [PATCH 11/54] feat: cache the successful ancestor prefix of a failed preload A descendant notFound/error no longer discards successful expensive ancestor loads: the leading run of success matches is projected and cached (owned matches only), so repeated hovers and the eventual navigation reuse them within preloadStaleTime. Failed, pending, and borrowed entries still never enter the cache. Co-Authored-By: Claude Fable 5 --- packages/router-core/INTERNALS.md | 6 +- .../router-core/src/router-preload.client.ts | 73 ++++++++++------ .../tests/preload-prefix-cache.test.ts | 85 +++++++++++++++++++ 3 files changed, 137 insertions(+), 27 deletions(-) create mode 100644 packages/router-core/tests/preload-prefix-cache.test.ts diff --git a/packages/router-core/INTERNALS.md b/packages/router-core/INTERNALS.md index ab914b6947..5a4d5a3a6f 100644 --- a/packages/router-core/INTERNALS.md +++ b/packages/router-core/INTERNALS.md @@ -619,9 +619,9 @@ sequenceDiagram else lane completed L-->>P: loaded preload lane end - alt every match success - P->>P: project and await preload assets - P->>C: cache owned preload matches only + alt successful prefix non-empty + P->>P: project and await assets for the success prefix + P->>C: cache owned success-prefix matches only end P->>P: settle preload-owned load promises ``` diff --git a/packages/router-core/src/router-preload.client.ts b/packages/router-core/src/router-preload.client.ts index 1845e94729..38aed22561 100644 --- a/packages/router-core/src/router-preload.client.ts +++ b/packages/router-core/src/router-preload.client.ts @@ -28,33 +28,53 @@ export const preloadClientRoute = async ( .concat(router.stores.pendingIds.get()), } + // A failed descendant must not discard the work of its successful + // ancestors: the leading run of success matches is projected and cached so + // repeated hovers (and the eventual navigation) can reuse those loads. The + // cache invariant still holds — only owned success snapshots enter the + // cache; the failed/pending tail never does. + const cacheSuccessfulPrefix = async (): Promise => { + let prefixEnd = 0 + while ( + prefixEnd < matches.length && + matches[prefixEnd]!.status === 'success' + ) { + prefixEnd++ + } + if (!prefixEnd) { + return + } + + const prefix = + prefixEnd === matches.length ? matches : matches.slice(0, prefixEnd) + const assets = projectClientRouteAssets(router, prefix, true) + if (isPromise(assets)) { + await assets + } + + let ownedMatches: Array | undefined + for (const match of prefix) { + if (match.preload && !router.getMatch(match.id, false)) { + ;(ownedMatches ||= []).push(match) + } + } + if (ownedMatches) { + router.stores.setCached([ + ...router.stores.cachedMatches + .get() + .filter( + (cachedMatch) => + !ownedMatches.some((match) => match.id === cachedMatch.id), + ), + ...ownedMatches, + ]) + } + } + try { matches = await loadClientMatches(loadContext) - if (matches.every((match) => match.status === 'success')) { - const assets = projectClientRouteAssets(router, matches, true) - if (isPromise(assets)) { - await assets - } - - let ownedMatches: Array | undefined - for (const match of matches) { - if (match.preload && !router.getMatch(match.id, false)) { - ;(ownedMatches ||= []).push(match) - } - } - if (ownedMatches) { - router.stores.setCached([ - ...router.stores.cachedMatches - .get() - .filter( - (cachedMatch) => - !ownedMatches.some((match) => match.id === cachedMatch.id), - ), - ...ownedMatches, - ]) - } - } + await cacheSuccessfulPrefix() return matches } catch (err) { @@ -73,6 +93,11 @@ export const preloadClientRoute = async ( _fromLocation: next, }) } + + // notFound/error outcomes are not fatal to the app, and the successful + // ancestor prefix is still valid cacheable work. + await cacheSuccessfulPrefix() + if (process.env.NODE_ENV !== 'production' && !isNotFound(err)) { // Preload errors are not fatal, but we should still log them console.error(err) diff --git a/packages/router-core/tests/preload-prefix-cache.test.ts b/packages/router-core/tests/preload-prefix-cache.test.ts new file mode 100644 index 0000000000..6a32078345 --- /dev/null +++ b/packages/router-core/tests/preload-prefix-cache.test.ts @@ -0,0 +1,85 @@ +import { describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, notFound } from '../src' +import { createTestRouter } from './routerTestUtils' + +/** + * A failed descendant preload must not discard its successful ancestors' + * work: the leading run of success matches is cached (within + * preloadStaleTime) so repeated hovers do not re-run expensive ancestor + * loaders. The failed match itself is never cached. + */ + +function setup(failure: 'notFound' | 'error') { + const aLoader = vi.fn(() => 'a data') + const bLoader = vi.fn(() => 'b data') + const cLoader = vi.fn(() => { + if (failure === 'notFound') { + throw notFound() + } + throw new Error('c failed') + }) + + const rootRoute = new BaseRootRoute({}) + const aRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/a', + loader: aLoader, + }) + const bRoute = new BaseRoute({ + getParentRoute: () => aRoute, + path: '/b', + loader: bLoader, + }) + const cRoute = new BaseRoute({ + getParentRoute: () => bRoute, + path: '/c', + loader: cLoader, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + aRoute.addChildren([bRoute.addChildren([cRoute])]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + return { router, aLoader, bLoader, cLoader, aRoute, bRoute, cRoute } +} + +describe.each(['notFound', 'error'] as const)( + 'preload with %s descendant', + (failure) => { + test('caches the successful ancestor prefix and not the failed match', async () => { + const consoleError = vi + .spyOn(console, 'error') + .mockImplementation(() => undefined) + + try { + const { router, aLoader, bLoader, cLoader, aRoute, bRoute, cRoute } = + setup(failure) + + await router.preloadRoute({ to: '/a/b/c' } as any) + + expect(aLoader).toHaveBeenCalledTimes(1) + expect(bLoader).toHaveBeenCalledTimes(1) + expect(cLoader).toHaveBeenCalledTimes(1) + + const cached = router.stores.cachedMatches.get() + expect(cached.some((match) => match.routeId === aRoute.id)).toBe(true) + expect(cached.some((match) => match.routeId === bRoute.id)).toBe(true) + expect(cached.some((match) => match.routeId === cRoute.id)).toBe(false) + + // A second hover reuses the cached ancestors (fresh within + // preloadStaleTime) and only retries the failed descendant. + await router.preloadRoute({ to: '/a/b/c' } as any) + + expect(aLoader).toHaveBeenCalledTimes(1) + expect(bLoader).toHaveBeenCalledTimes(1) + expect(cLoader).toHaveBeenCalledTimes(2) + } finally { + consoleError.mockRestore() + } + }) + }, +) From e154e904b35238c7d4e571156751ca1a5b7f2692 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Fri, 3 Jul 2026 23:41:45 +0200 Subject: [PATCH 12/54] refactor: share byte-identical twin helpers and trim dead server-load code MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - commitMatch and getLoader move to the shared load-matches.ts (they were byte-identical in the client/server twins; getLoader was additionally re-inlined in the server loader path). - loadServerMatches no longer copies preload/background/onReady/forceReload into its context — those are client-side semantics the server pipeline never reads. - loadServerRouter's catch no longer duplicates the 404/500/200 derivation that the committed-match pass below already owns. Co-Authored-By: Claude Fable 5 --- .../router-core/src/load-matches.client.ts | 16 ++----------- .../router-core/src/load-matches.server.ts | 23 ++++-------------- packages/router-core/src/load-matches.ts | 15 ++++++++++++ .../router-core/src/router-load.server.ts | 24 ++++++++++--------- 4 files changed, 35 insertions(+), 43 deletions(-) diff --git a/packages/router-core/src/load-matches.client.ts b/packages/router-core/src/load-matches.client.ts index 603249ed9c..9c596d413c 100644 --- a/packages/router-core/src/load-matches.client.ts +++ b/packages/router-core/src/load-matches.client.ts @@ -4,6 +4,8 @@ import { isRedirect } from './redirect' import { loadRouteChunk } from './route-chunks' import { projectClientRouteAssets } from './route-assets.client' import { + commitMatch, + getLoader, getMatchContext, getNotFoundBoundaryIndex, getNotFoundBoundaryPatch, @@ -24,9 +26,6 @@ import type { InnerLoadContext, SerialFailure } from './load-matches' const isRouteControl = (error: unknown) => isRedirect(error) || isNotFound(error) -const getLoader = (loaderOption: AnyRoute['options']['loader']) => - typeof loaderOption === 'function' ? loaderOption : loaderOption?.handler - // Route work may only commit while it still owns the lane entry it is about to // mutate. Each client load pass stamps its matches with an AbortController: // starting a newer load replaces the controller, cancellation aborts its signal, @@ -59,17 +58,6 @@ const requireCurrentMatch = ( return match } -const commitMatch = ( - inner: InnerLoadContext, - index: number, - patch: Partial, -): AnyRouteMatch => { - return (inner.matches[index] = { - ...inner.matches[index]!, - ...patch, - }) -} - function getNavigate(inner: InnerLoadContext) { return (opts: any) => inner.router.navigate({ diff --git a/packages/router-core/src/load-matches.server.ts b/packages/router-core/src/load-matches.server.ts index b207157169..0176a1f5e0 100644 --- a/packages/router-core/src/load-matches.server.ts +++ b/packages/router-core/src/load-matches.server.ts @@ -5,6 +5,8 @@ import { isRedirect } from './redirect' import { loadRouteChunk } from './route-chunks' import { projectServerRouteAssets } from './route-assets.server' import { + commitMatch, + getLoader, getMatchContext, getNotFoundBoundaryIndex, markError, @@ -21,17 +23,6 @@ import type { AnyRouteMatch, MakeRouteMatch } from './Matches' import type { SSROption } from './router' import type { InnerLoadContext, LoadMatchesArg } from './load-matches' -const commitMatch = ( - inner: InnerLoadContext, - index: number, - patch: Partial, -): AnyRouteMatch => { - return (inner.matches[index] = { - ...inner.matches[index]!, - ...patch, - }) -} - const handleServerRedirectOrNotFound = ( inner: InnerLoadContext, index: number, @@ -346,9 +337,7 @@ const loadServerRouteMatch = async ( const initialMatch = inner.matches[index]! const { routeId } = initialMatch const route = inner.router.routesById[routeId]! - const loaderOption = route.options.loader - const loader = - typeof loaderOption === 'function' ? loaderOption : loaderOption?.handler + const loader = getLoader(route.options.loader) const routeChunkPromise = initialMatch.ssr === true ? loadRouteChunk(route) : undefined @@ -407,14 +396,12 @@ const loadServerRouteMatch = async ( export const loadServerMatches = async ( arg: LoadMatchesArg, ): Promise> => { + // The server pipeline is request-local: preload, background, and pending + // publication are client-side semantics and are deliberately not copied. const inner: InnerLoadContext = { router: arg.router, location: arg.location, matches: arg.matches, - preload: arg.preload, - forceStaleReload: arg.forceReload, - background: arg.background, - onReady: arg.onReady, } const matchPromises: Array> = [] diff --git a/packages/router-core/src/load-matches.ts b/packages/router-core/src/load-matches.ts index f5e77df2b9..3bdccc7c6b 100644 --- a/packages/router-core/src/load-matches.ts +++ b/packages/router-core/src/load-matches.ts @@ -3,6 +3,7 @@ import { isRedirect } from './redirect' import { rootRouteId } from './root' import type { NotFoundError } from './not-found' import type { ParsedLocation } from './location' +import type { AnyRoute } from './route' import type { AnyRouteMatch } from './Matches' import type { AnyRouter } from './router' @@ -57,6 +58,20 @@ export const markError = (inner: InnerLoadContext, index: number) => { inner.badIndex = Math.min(inner.badIndex ?? index, index) } +export const commitMatch = ( + inner: InnerLoadContext, + index: number, + patch: Partial, +): AnyRouteMatch => { + return (inner.matches[index] = { + ...inner.matches[index]!, + ...patch, + }) +} + +export const getLoader = (loaderOption: AnyRoute['options']['loader']) => + typeof loaderOption === 'function' ? loaderOption : loaderOption?.handler + export const getMatchContext = ( inner: Pick, index: number, diff --git a/packages/router-core/src/router-load.server.ts b/packages/router-core/src/router-load.server.ts index b768e3d958..c31acb8e64 100644 --- a/packages/router-core/src/router-load.server.ts +++ b/packages/router-core/src/router-load.server.ts @@ -68,13 +68,14 @@ export const loadServerRouter = async ( router.stores.setMatches(matchedMatches) } - router.statusCode = resolvedRedirect - ? (resolvedRedirect.options as any).statusCode - : isNotFound(err) - ? 404 - : router.stores.matches.get().some((d) => d.status === 'error') - ? 500 - : 200 + // Committed-match state owns the 404/500 derivation below; here only the + // outcomes it cannot see are recorded (redirect metadata, and a notFound + // that may not have a committed boundary match). + if (resolvedRedirect) { + router.statusCode = (resolvedRedirect.options as any).statusCode + } else if (isNotFound(err)) { + router.statusCode = 404 + } router.redirect = resolvedRedirect } finally { const commitLocationPromise = router.commitLocationPromise @@ -83,11 +84,12 @@ export const loadServerRouter = async ( commitLocationPromise?.resolve() } - const newStatusCode = router.stores.matches - .get() - .some((d) => d.status === 'notFound' || d.globalNotFound) + const finalMatches = router.stores.matches.get() + const newStatusCode = finalMatches.some( + (d) => d.status === 'notFound' || d.globalNotFound, + ) ? 404 - : router.stores.matches.get().some((d) => d.status === 'error') + : finalMatches.some((d) => d.status === 'error') ? 500 : undefined if (newStatusCode) { From ff13fb21a35f0ff296117eda42ceeb1cdd64c73d Mon Sep 17 00:00:00 2001 From: Sheraff Date: Fri, 3 Jul 2026 23:43:54 +0200 Subject: [PATCH 13/54] docs: document behavior changes in the match-loading changeset Co-Authored-By: Claude Fable 5 --- .changeset/violet-poets-wait.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.changeset/violet-poets-wait.md b/.changeset/violet-poets-wait.md index 9cb332593a..0608526748 100644 --- a/.changeset/violet-poets-wait.md +++ b/.changeset/violet-poets-wait.md @@ -15,3 +15,8 @@ Fix match loading consistency across client navigation, preloading, background r - SSR hydration now handles dehydrated and data-only matches in a dedicated hydration pass, restoring route context and assets without rerunning client loaders. - Server loading now has a dedicated path for status codes, redirects, notFound and error responses. - React, Solid, and Vue match rendering now consume the simplified match readiness model, including aborted loader errors, SSR/data-only pending fallbacks, and stale render snapshots. +- Awaiting `router.load()` or `router.invalidate()` now settles only when the whole navigation chain settles, including superseded and redirected loads; preloads that borrow a pending-published foreground match wait for its commit instead of being dropped. +- Behavior change: a navigation that starts while a hover/intent preload for the same route is in flight no longer adopts the preload's loader run — the navigation runs its own loader with `preload: false` semantics, so loaders may execute twice in that window. Use your data layer (e.g. an external cache) to dedupe fetches. +- Preloads now cache the successful ancestor prefix even when a descendant throws an error or `notFound`, so repeated hovers do not re-run expensive ancestor loaders. +- Route chunk (lazy import) failures now run the normal route failure lifecycle: `onError` fires and thrown redirects/notFounds are honored. Error/notFound boundary chunks load independently of the route's other component chunks, and failed chunk preloads are retried on the next load instead of being cached forever. +- Server rendering keeps route `headers()` when a decorative `head()`/`scripts()` hook fails, background reloads never publish fresh `loaderData` whose asset projection failed, and hydration no longer executes `head()`/`scripts()` for matches the server omitted (`ssr: false` or a server-side error/notFound boundary). From 00108a4ea84a432c0b457aeacf0a42a80e25322c Mon Sep 17 00:00:00 2001 From: Sheraff Date: Sat, 4 Jul 2026 00:13:58 +0200 Subject: [PATCH 14/54] fix: drop unnecessary type assertion in server asset projection Co-Authored-By: Claude Fable 5 --- packages/router-core/src/route-assets.server.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/router-core/src/route-assets.server.ts b/packages/router-core/src/route-assets.server.ts index bd5f97c0e1..4710e98d5d 100644 --- a/packages/router-core/src/route-assets.server.ts +++ b/packages/router-core/src/route-assets.server.ts @@ -106,7 +106,7 @@ export const projectServerRouteAssets = ( const failed = [headResult, scriptResult, headerResult].find( (result) => result.status === 'rejected', - ) as PromiseRejectedResult | undefined + ) if (failed) { logAssetError(match, failed.reason) } From a9e6ce220dea7767d211e8359dec6be169a80cb2 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Sat, 4 Jul 2026 00:57:42 +0200 Subject: [PATCH 15/54] fix: replay dehydrated notFound/error boundaries in the follow-up client load MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When the server caps the match lane at a notFound/error boundary, the follow-up client load after hydration skipped the dehydrated parent's beforeLoad and happily loaded, committed, and asset-projected the child routes the server omitted — injecting head/scripts computed from missing loader data. A dehydrated failure boundary now replays as the pass's serial failure, capping the lane exactly like the server did. Also excludes /hydration-capped-assets from the e2e prerender crawl (the route 404s by design). Co-Authored-By: Claude Fable 5 --- e2e/react-start/basic/start-mode-config.ts | 1 + packages/router-core/src/load-matches.client.ts | 14 ++++++++++++++ 2 files changed, 15 insertions(+) diff --git a/e2e/react-start/basic/start-mode-config.ts b/e2e/react-start/basic/start-mode-config.ts index 39ad676625..b1968c299c 100644 --- a/e2e/react-start/basic/start-mode-config.ts +++ b/e2e/react-start/basic/start-mode-config.ts @@ -32,6 +32,7 @@ export function getStartModeConfig() { '/redirect', '/i-do-not-exist', '/not-found', + '/hydration-capped-assets', '/primitive-beforeload-error', '/specialChars/search', '/specialChars/hash', diff --git a/packages/router-core/src/load-matches.client.ts b/packages/router-core/src/load-matches.client.ts index 9c596d413c..1df9484090 100644 --- a/packages/router-core/src/load-matches.client.ts +++ b/packages/router-core/src/load-matches.client.ts @@ -943,6 +943,20 @@ export async function loadClientMatches( } if (inner.matches[i]!._.dehydrated) { + const dehydratedMatch = inner.matches[i]! + // A dehydrated notFound/error is a server-committed boundary: the + // server intentionally omitted every match below it. Replay it as + // this pass's serial failure so the follow-up client load caps the + // lane the same way instead of loading, committing, and projecting + // assets for descendants the server never rendered. + if ( + (dehydratedMatch.status === 'notFound' && + isNotFound(dehydratedMatch.error)) || + dehydratedMatch.status === 'error' + ) { + failure = [i, dehydratedMatch.error] + break + } matchPromises[i] = loadClientRouteMatch(inner, matchPromises, i) continue } From 142915cb7d61bb53043494e836d6f8e38deb6dae Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Fri, 3 Jul 2026 23:10:49 +0000 Subject: [PATCH 16/54] ci: apply automated fixes --- .../basic/tests/hydration-capped-assets.spec.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/e2e/react-start/basic/tests/hydration-capped-assets.spec.ts b/e2e/react-start/basic/tests/hydration-capped-assets.spec.ts index 2e4cba70f5..25866a57d7 100644 --- a/e2e/react-start/basic/tests/hydration-capped-assets.spec.ts +++ b/e2e/react-start/basic/tests/hydration-capped-assets.spec.ts @@ -32,12 +32,16 @@ test.describe('SSR hydration capped route assets', () => { await page.goto('/hydration-capped-assets/child') await page.waitForLoadState('networkidle') - await expect(page.getByTestId('capped-assets-parent-not-found')).toBeInViewport() + await expect( + page.getByTestId('capped-assets-parent-not-found'), + ).toBeInViewport() await expect( page.getByTestId('capped-assets-child-component'), ).not.toBeInViewport() - await expect(page.locator('meta[name="capped-assets-child-head"]')).toHaveCount(0) + await expect( + page.locator('meta[name="capped-assets-child-head"]'), + ).toHaveCount(0) expect( await page.evaluate(() => Boolean((window as any).__CAPPED_ASSETS_CHILD_SCRIPT), From beed0d226b9f53738448f9e730b4015a32c71c97 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Sat, 4 Jul 2026 01:15:55 +0200 Subject: [PATCH 17/54] perf: avoid per-commit Set allocations in match cache reconciliation The exiting/cached id scans operate on small arrays; linear some() scans drop two Set allocations per final commit and per pending publication. Bundle-size impact is neutral (gzip); measured across all targets. Co-Authored-By: Claude Fable 5 --- packages/router-core/src/router-load.client.ts | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/packages/router-core/src/router-load.client.ts b/packages/router-core/src/router-load.client.ts index de2ae03526..2533bfd257 100644 --- a/packages/router-core/src/router-load.client.ts +++ b/packages/router-core/src/router-load.client.ts @@ -24,12 +24,15 @@ const commitFinalMatches = ( router.batch(() => { const now = Date.now() const cached = stores.cachedMatches.get().slice() - // Pending publication may already have preserved exiting base matches. - const cachedIds = new Set(cached.map((match) => match.id)) for (let i = 0; i < baseMatches.length; i++) { const match = baseMatches[i]! - if (nextMatches[i]?.id !== match.id && !cachedIds.has(match.id)) { + // Pending publication may already have preserved exiting base matches; + // base match ids are unique, so scanning pushed entries is harmless. + if ( + nextMatches[i]?.id !== match.id && + !cached.some((c) => c.id === match.id) + ) { cached.push({ ...match, isFetching: false, @@ -172,16 +175,14 @@ export const loadClientRouter = async ( // this load is superseded (e.g. back navigation) the final commit // that would have cached them never runs, and their fresh data // would otherwise be lost from every pool. - const publishedIds = new Set(matches.map((match) => match.id)) const cached = stores.cachedMatches.get() - const cachedIds = new Set(cached.map((match) => match.id)) const exiting = stores.matches .get() .filter( (match) => match.status === 'success' && - !publishedIds.has(match.id) && - !cachedIds.has(match.id), + !matches.some((m) => m.id === match.id) && + !cached.some((m) => m.id === match.id), ) if (exiting.length) { stores.setCached([ From 1be22be01f17fe3b48a6df50fce8f1d64c1fe0c2 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Sat, 4 Jul 2026 02:05:10 +0200 Subject: [PATCH 18/54] fix: address self-review findings on the review branch MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Server asset projection awaits a pending async headers() even when a decorative head()/scripts() hook throws synchronously — route headers are response behavior and are never dropped for a decorative failure. - cancelMatches treats any fetching marker (beforeLoad included) as in-flight work when deciding to abort an active match. - A rejected lazy-route chunk promise is evicted so the next load generation retries the import instead of replaying the failure forever. - commitFinalMatches isolates onLeave from the same index's onEnter/onStay, so a throwing leave hook cannot skip the entered route's hooks; exiting-match cache preservation is shared between pending publication and final commit via one helper. - joinPreloadedActiveMatch's wait/re-read stanzas are unified into one loop that also survives a newer load re-publishing a pending lane. - HMR route updates clear the new per-type component chunk cache. Co-Authored-By: Claude Fable 5 --- .../router-core/src/load-matches.client.ts | 51 ++++++------ .../router-core/src/route-assets.server.ts | 36 ++++++--- packages/router-core/src/route-chunks.ts | 12 +++ .../router-core/src/router-load.client.ts | 78 +++++++++++-------- packages/router-core/src/router.ts | 25 +++--- .../tests/chunk-failure-lifecycle.test.ts | 36 +++++++++ .../tests/lifecycle-hook-errors.test.ts | 43 ++++++++++ .../server-headers-asset-failure.test.ts | 24 ++++++ .../tests/stay-match-abort.test.ts | 34 +++++++- .../src/core/hmr/handle-route-update.ts | 1 + .../snapshots/react/arrow-function@true.tsx | 1 + .../react/arrow-function@webpack-hot.tsx | 1 + .../createRootRoute-inline-component@true.tsx | 1 + .../snapshots/react/createRootRoute@true.tsx | 1 + ...ateRootRouteWithContext-type-args@true.tsx | 1 + .../explicit-undefined-component@true.tsx | 1 + .../react/function-declaration@true.tsx | 1 + .../snapshots/react/multi-component@true.tsx | 1 + .../react/string-literal-keys@true.tsx | 1 + .../snapshots/solid/arrow-function@true.tsx | 1 + 20 files changed, 270 insertions(+), 80 deletions(-) diff --git a/packages/router-core/src/load-matches.client.ts b/packages/router-core/src/load-matches.client.ts index 1df9484090..2ca9996def 100644 --- a/packages/router-core/src/load-matches.client.ts +++ b/packages/router-core/src/load-matches.client.ts @@ -89,32 +89,39 @@ const joinPreloadedActiveMatch = async ( await match._.loadPromise } - // If the borrowed match still lives in the pending store, its local readiness - // may have settled before the foreground load committed the lane. Wait for the - // foreground load so the preload observes the committed owner, not a transient - // pending-store snapshot. - if (inner.router.stores.pendingMatchStores.has(matchId)) { - await inner.router.latestLoadPromise - } - - // Re-read after the waits because the owner may have committed, redirected, - // disappeared, or been aborted while this preload was observing it. - match = inner.router.getMatch(matchId, false) - if (!match || match.abortController.signal.aborted) { - throw inner - } - - // The owner can also be a render-ready pending publication: onReady() moved - // it into the active store (clearing the pending pool) while the foreground - // final commit is still in flight, so the store snapshot is stuck at - // status 'pending' even though its local work settled. Wait for the - // foreground load to commit before judging the owner's outcome. - if (match.status === 'pending' && inner.router.latestLoadPromise) { - await inner.router.latestLoadPromise + // The borrowed match's local readiness can settle before the foreground + // load commits the lane: the owner may still sit in the pending store, or + // be a render-ready pending publication (onReady() moved it into the + // active store, clearing the pending pool, while the final commit is + // still in flight — the snapshot is stuck at status 'pending' even though + // its local work settled). Wait for the foreground load and re-read until + // the owner reaches a committed state; each iteration re-reads because a + // newer load can re-publish a pending lane for the same match. + while (true) { match = inner.router.getMatch(matchId, false) if (!match || match.abortController.signal.aborted) { throw inner } + + const foreground = inner.router.latestLoadPromise + if ( + !foreground || + (match.status !== 'pending' && + !inner.router.stores.pendingMatchStores.has(matchId)) + ) { + break + } + + await foreground + if (inner.router.latestLoadPromise === foreground) { + // The chain settled without being replaced; a final re-read below + // decides the outcome instead of spinning on the same promise. + match = inner.router.getMatch(matchId, false) + if (!match || match.abortController.signal.aborted) { + throw inner + } + break + } } // From here the preload lane uses the owner match read-only. It must not clone diff --git a/packages/router-core/src/route-assets.server.ts b/packages/router-core/src/route-assets.server.ts index 4710e98d5d..f00e081d88 100644 --- a/packages/router-core/src/route-assets.server.ts +++ b/packages/router-core/src/route-assets.server.ts @@ -71,9 +71,10 @@ export const projectServerRouteAssets = ( if (syncFailed) { // A sync throw must not hold the response hostage waiting on the other - // hooks' async work. Commit the sync-available values and abandon any - // pending promises, owning their rejections so they cannot become - // unhandled. + // DECORATIVE hooks' async work: commit sync-available head/scripts and + // abandon pending ones, owning their rejections so they cannot become + // unhandled. A pending headers() promise is different — headers are + // response behavior, so it is always awaited. const settle = (value: any) => { if (isPromise(value)) { void Promise.allSettled([value]) @@ -81,12 +82,29 @@ export const projectServerRouteAssets = ( } return value } - matches[i] = withServerAssets( - match, - settle(head), - settle(scripts), - settle(headers), - ) + const syncHead = settle(head) + const syncScripts = settle(scripts) + + if (isPromise(headers)) { + return (headers as Promise).then( + (headerValue) => { + matches[i] = withServerAssets( + match, + syncHead, + syncScripts, + headerValue, + ) + return projectServerRouteAssets(router, matches, i + 1) + }, + (error) => { + logAssetError(match, error) + matches[i] = withServerAssets(match, syncHead, syncScripts, undefined) + return projectServerRouteAssets(router, matches, i + 1) + }, + ) + } + + matches[i] = withServerAssets(match, syncHead, syncScripts, headers) continue } diff --git a/packages/router-core/src/route-chunks.ts b/packages/router-core/src/route-chunks.ts index f44c84ef04..5f6e91ea07 100644 --- a/packages/router-core/src/route-chunks.ts +++ b/packages/router-core/src/route-chunks.ts @@ -89,6 +89,18 @@ export function loadRouteChunk( } catch (error) { route._lazyPromise = Promise.reject(error) } + + // A rejected lazy chunk must not be replayed forever: evict it so the + // next load generation retries the import, like component chunk + // preloads. Awaiters of the evicted promise still own the rejection. + const lazyPromise = route._lazyPromise + if (lazyPromise) { + void lazyPromise.then(null, () => { + if (route._lazyPromise === lazyPromise) { + route._lazyPromise = undefined + } + }) + } } else { route._lazyLoaded = true } diff --git a/packages/router-core/src/router-load.client.ts b/packages/router-core/src/router-load.client.ts index 2533bfd257..46ce9bbe43 100644 --- a/packages/router-core/src/router-load.client.ts +++ b/packages/router-core/src/router-load.client.ts @@ -15,6 +15,22 @@ import type { AnyRouteMatch } from './Matches' import type { AnyRouter, LoadFn } from './router' import type { InnerLoadContext } from './load-matches' +// Exiting matches are preserved in the cache both at pending publication and +// at final commit; the dedup + isFetching-reset shape must stay identical in +// both paths. Exiting match ids are unique per lane, so a linear scan over +// the (small) cache is sufficient. +const pushExitingMatch = ( + cached: Array, + match: AnyRouteMatch, +): void => { + if (!cached.some((c) => c.id === match.id)) { + cached.push({ + ...match, + isFetching: false, + }) + } +} + const commitFinalMatches = ( router: AnyRouter, baseMatches: Array, @@ -27,16 +43,8 @@ const commitFinalMatches = ( for (let i = 0; i < baseMatches.length; i++) { const match = baseMatches[i]! - // Pending publication may already have preserved exiting base matches; - // base match ids are unique, so scanning pushed entries is harmless. - if ( - nextMatches[i]?.id !== match.id && - !cached.some((c) => c.id === match.id) - ) { - cached.push({ - ...match, - isFetching: false, - }) + if (nextMatches[i]?.id !== match.id) { + pushExitingMatch(cached, match) } } @@ -75,20 +83,25 @@ const commitFinalMatches = ( const nextMatch = nextMatches[i] // The commit already happened; lifecycle hooks are notifications. A - // throwing hook must not skip the remaining hooks or corrupt the - // framework transition state, but it has to stay observable. - try { - if (current && current.routeId !== nextMatch?.routeId) { + // throwing hook must not skip the remaining hooks — including the same + // index's enter/stay hook — or corrupt the framework transition state, + // but it has to stay observable. + if (current && current.routeId !== nextMatch?.routeId) { + try { router.routesById[current.routeId]!.options.onLeave?.(current) + } catch (err) { + Promise.reject(err) } + } - if (nextMatch) { + if (nextMatch) { + try { router.routesById[nextMatch.routeId]!.options[ current?.routeId === nextMatch.routeId ? 'onStay' : 'onEnter' ]?.(nextMatch) + } catch (err) { + Promise.reject(err) } - } catch (err) { - Promise.reject(err) } } } @@ -175,23 +188,20 @@ export const loadClientRouter = async ( // this load is superseded (e.g. back navigation) the final commit // that would have cached them never runs, and their fresh data // would otherwise be lost from every pool. - const cached = stores.cachedMatches.get() - const exiting = stores.matches - .get() - .filter( - (match) => - match.status === 'success' && - !matches.some((m) => m.id === match.id) && - !cached.some((m) => m.id === match.id), - ) - if (exiting.length) { - stores.setCached([ - ...cached, - ...exiting.map((match) => ({ - ...match, - isFetching: false as const, - })), - ]) + let cached: Array | undefined + for (const match of stores.matches.get()) { + if ( + match.status === 'success' && + !matches.some((m) => m.id === match.id) + ) { + pushExitingMatch( + (cached ||= stores.cachedMatches.get().slice()), + match, + ) + } + } + if (cached) { + stores.setCached(cached) } stores.setMatches(matches) if (stores.pendingIds.get().length) { diff --git a/packages/router-core/src/router.ts b/packages/router-core/src/router.ts index 2237fbc4e9..4a8bd85297 100644 --- a/packages/router-core/src/router.ts +++ b/packages/router-core/src/router.ts @@ -1793,16 +1793,16 @@ export class RouterCore< } cancelMatches() { - const cancelMatch = (matchId: string) => { - const match = this.getMatch(matchId) - if (match) { - match.abortController.abort() - settleMatchLoad(match) - } + const cancelMatch = (match: AnyRouteMatch) => { + match.abortController.abort() + settleMatchLoad(match) } for (const matchId of this.stores.pendingIds.get()) { - cancelMatch(matchId) + const match = this.getMatch(matchId) + if (match) { + cancelMatch(match) + } } for (const matchId of this.stores.matchesId.get()) { @@ -1810,18 +1810,15 @@ export class RouterCore< continue } - // Only cancel active matches with in-flight route work. A settled + // Only cancel active matches with in-flight route work (pending, or + // any fetching marker — beforeLoad and loader alike). A settled idle // success match keeps its controller un-aborted: loaders may have // handed that signal to still-streaming deferred data, and the public // contract only cancels it when the route unloads or its loader call // becomes outdated. const match = this.getMatch(matchId) - if ( - match && - (match.status === 'pending' || match.isFetching === 'loader') - ) { - match.abortController.abort() - settleMatchLoad(match) + if (match && (match.status === 'pending' || match.isFetching !== false)) { + cancelMatch(match) } } } diff --git a/packages/router-core/tests/chunk-failure-lifecycle.test.ts b/packages/router-core/tests/chunk-failure-lifecycle.test.ts index 0be78cb535..bf9fa369d4 100644 --- a/packages/router-core/tests/chunk-failure-lifecycle.test.ts +++ b/packages/router-core/tests/chunk-failure-lifecycle.test.ts @@ -16,6 +16,42 @@ import { createTestRouter } from './routerTestUtils' */ describe('route chunk failure lifecycle', () => { + test('a rejected lazy chunk is retried on the next load instead of replaying forever', async () => { + let lazyCalls = 0 + const chunkError = new Error('lazy chunk failed once') + + const rootRoute = new BaseRootRoute({}) + const lazyRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/lazy', + loader: () => 'loaded', + }).lazy(() => { + lazyCalls++ + if (lazyCalls === 1) { + return Promise.reject(chunkError) + } + return Promise.resolve({ options: {} } as any) + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([lazyRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.navigate({ to: '/lazy' }) + expect( + router.state.matches.find((match) => match.routeId === lazyRoute.id) + ?.status, + ).toBe('error') + + await router.invalidate() + expect(lazyCalls).toBe(2) + expect( + router.state.matches.find((match) => match.routeId === lazyRoute.id) + ?.status, + ).toBe('success') + }) + test('calls route onError when lazy route chunk rejects during navigation', async () => { const chunkError = new Error('lazy chunk failed') let capturedError: unknown diff --git a/packages/router-core/tests/lifecycle-hook-errors.test.ts b/packages/router-core/tests/lifecycle-hook-errors.test.ts index d18ec3dba6..3d938693b0 100644 --- a/packages/router-core/tests/lifecycle-hook-errors.test.ts +++ b/packages/router-core/tests/lifecycle-hook-errors.test.ts @@ -73,4 +73,47 @@ describe('lifecycle hook errors', () => { process.off('unhandledRejection', unhandledRejection) } }) + test('a throwing onLeave does not skip the entered route hooks at the same index', async () => { + const unhandledRejection = vi.fn() + process.on('unhandledRejection', unhandledRejection) + + try { + const leaveError = new Error('onLeave failed') + const aOnLeave = vi.fn(() => { + throw leaveError + }) + const bOnEnter = vi.fn() + + const rootRoute = new BaseRootRoute({}) + const aRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/a', + onLeave: aOnLeave, + }) + const bRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/b', + onEnter: bOnEnter, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([aRoute, bRoute]), + history: createMemoryHistory({ initialEntries: ['/a'] }), + }) + + await router.load() + await router.navigate({ to: '/b' }) + + expect(aOnLeave).toHaveBeenCalledTimes(1) + expect(bOnEnter).toHaveBeenCalledTimes(1) + + await new Promise((resolve) => setTimeout(resolve, 0)) + expect(unhandledRejection).toHaveBeenCalledWith( + leaveError, + expect.anything(), + ) + } finally { + process.off('unhandledRejection', unhandledRejection) + } + }) }) diff --git a/packages/router-core/tests/server-headers-asset-failure.test.ts b/packages/router-core/tests/server-headers-asset-failure.test.ts index a7884274aa..2afb198c66 100644 --- a/packages/router-core/tests/server-headers-asset-failure.test.ts +++ b/packages/router-core/tests/server-headers-asset-failure.test.ts @@ -60,4 +60,28 @@ describe('server asset projection route headers', () => { expect(targetMatch).toBeDefined() expect(targetMatch!.headers).toEqual(expectedHeaders) }) + + test('awaits async route headers when head throws synchronously', async () => { + const rootRoute = new BaseRootRoute({}) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + head: () => { + throw new Error('head failed') + }, + headers: async () => expectedHeaders, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([targetRoute]), + history: createMemoryHistory({ initialEntries: ['/target'] }), + isServer: true, + }) + + await router.load() + + const targetMatch = router.state.matches.find( + (match) => match.routeId === targetRoute.id, + ) + expect(targetMatch!.headers).toEqual(expectedHeaders) + }) }) diff --git a/packages/router-core/tests/stay-match-abort.test.ts b/packages/router-core/tests/stay-match-abort.test.ts index 03c0ea2fc6..7ea7fdae4e 100644 --- a/packages/router-core/tests/stay-match-abort.test.ts +++ b/packages/router-core/tests/stay-match-abort.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, test } from 'vitest' +import { describe, expect, test, vi } from 'vitest' import { createMemoryHistory } from '@tanstack/history' import { BaseRootRoute, BaseRoute } from '../src' import { createTestRouter } from './routerTestUtils' @@ -51,6 +51,38 @@ describe('stay-match abort scope', () => { expect(getSignal()?.aborted).toBe(false) }) + test('cancelMatches aborts an active match with an in-flight beforeLoad marker', async () => { + // A pending publication can move a lane into the active store while an + // ancestor stay match is still mid-beforeLoad (status 'success', + // isFetching 'beforeLoad', pending pool cleared). cancelMatches must + // treat any fetching marker as in-flight work and abort it. + const rootRoute = new BaseRootRoute({}) + const aRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/a', + loader: () => 'a data', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([aRoute]), + history: createMemoryHistory({ initialEntries: ['/a'] }), + }) + + await router.load() + + const matchId = router.state.matches.find( + (match) => match.routeId === aRoute.id, + )!.id + router.updateMatch(matchId, (match) => ({ + ...match, + isFetching: 'beforeLoad' as const, + })) + const signal = router.getMatch(matchId)!.abortController.signal + expect(signal.aborted).toBe(false) + + router.cancelMatches() + expect(signal.aborted).toBe(true) + }) + test('invalidate does not abort a success stay-match signal', async () => { const { router, getSignal } = setup() diff --git a/packages/router-plugin/src/core/hmr/handle-route-update.ts b/packages/router-plugin/src/core/hmr/handle-route-update.ts index 8731b19ac5..f7b55daeb1 100644 --- a/packages/router-plugin/src/core/hmr/handle-route-update.ts +++ b/packages/router-plugin/src/core/hmr/handle-route-update.ts @@ -107,6 +107,7 @@ function handleRouteUpdate( oldRoute.options = nextOptions oldRoute.update(nextOptions) oldRoute._componentsPromise = undefined + oldRoute._componentPromises = undefined oldRoute._lazyPromise = undefined router.setRoutes(router.buildRouteTree()) diff --git a/packages/router-plugin/tests/add-hmr/snapshots/react/arrow-function@true.tsx b/packages/router-plugin/tests/add-hmr/snapshots/react/arrow-function@true.tsx index a463d9ab22..578b28f7b5 100644 --- a/packages/router-plugin/tests/add-hmr/snapshots/react/arrow-function@true.tsx +++ b/packages/router-plugin/tests/add-hmr/snapshots/react/arrow-function@true.tsx @@ -78,6 +78,7 @@ if (import.meta.hot) { oldRoute.options = nextOptions; oldRoute.update(nextOptions); oldRoute._componentsPromise = undefined; + oldRoute._componentPromises = undefined; oldRoute._lazyPromise = undefined; router.setRoutes(router.buildRouteTree()); syncHotRouteExport(oldRoute); diff --git a/packages/router-plugin/tests/add-hmr/snapshots/react/arrow-function@webpack-hot.tsx b/packages/router-plugin/tests/add-hmr/snapshots/react/arrow-function@webpack-hot.tsx index 44908e32a9..12dec482ce 100644 --- a/packages/router-plugin/tests/add-hmr/snapshots/react/arrow-function@webpack-hot.tsx +++ b/packages/router-plugin/tests/add-hmr/snapshots/react/arrow-function@webpack-hot.tsx @@ -64,6 +64,7 @@ if (import.meta.webpackHot) { oldRoute.options = nextOptions; oldRoute.update(nextOptions); oldRoute._componentsPromise = undefined; + oldRoute._componentPromises = undefined; oldRoute._lazyPromise = undefined; router.setRoutes(router.buildRouteTree()); syncHotRouteExport(oldRoute); diff --git a/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRoute-inline-component@true.tsx b/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRoute-inline-component@true.tsx index 9ef182f4b7..4a96c5167f 100644 --- a/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRoute-inline-component@true.tsx +++ b/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRoute-inline-component@true.tsx @@ -67,6 +67,7 @@ if (import.meta.hot) { oldRoute.options = nextOptions; oldRoute.update(nextOptions); oldRoute._componentsPromise = undefined; + oldRoute._componentPromises = undefined; oldRoute._lazyPromise = undefined; router.setRoutes(router.buildRouteTree()); syncHotRouteExport(oldRoute); diff --git a/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRoute@true.tsx b/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRoute@true.tsx index 9789370efc..421c61943e 100644 --- a/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRoute@true.tsx +++ b/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRoute@true.tsx @@ -69,6 +69,7 @@ if (import.meta.hot) { oldRoute.options = nextOptions; oldRoute.update(nextOptions); oldRoute._componentsPromise = undefined; + oldRoute._componentPromises = undefined; oldRoute._lazyPromise = undefined; router.setRoutes(router.buildRouteTree()); syncHotRouteExport(oldRoute); diff --git a/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRouteWithContext-type-args@true.tsx b/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRouteWithContext-type-args@true.tsx index 6c7073a8f3..12c26d9abf 100644 --- a/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRouteWithContext-type-args@true.tsx +++ b/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRouteWithContext-type-args@true.tsx @@ -72,6 +72,7 @@ if (import.meta.hot) { oldRoute.options = nextOptions; oldRoute.update(nextOptions); oldRoute._componentsPromise = undefined; + oldRoute._componentPromises = undefined; oldRoute._lazyPromise = undefined; router.setRoutes(router.buildRouteTree()); syncHotRouteExport(oldRoute); diff --git a/packages/router-plugin/tests/add-hmr/snapshots/react/explicit-undefined-component@true.tsx b/packages/router-plugin/tests/add-hmr/snapshots/react/explicit-undefined-component@true.tsx index bee793d372..d7dd3606c9 100644 --- a/packages/router-plugin/tests/add-hmr/snapshots/react/explicit-undefined-component@true.tsx +++ b/packages/router-plugin/tests/add-hmr/snapshots/react/explicit-undefined-component@true.tsx @@ -66,6 +66,7 @@ if (import.meta.hot) { oldRoute.options = nextOptions; oldRoute.update(nextOptions); oldRoute._componentsPromise = undefined; + oldRoute._componentPromises = undefined; oldRoute._lazyPromise = undefined; router.setRoutes(router.buildRouteTree()); syncHotRouteExport(oldRoute); diff --git a/packages/router-plugin/tests/add-hmr/snapshots/react/function-declaration@true.tsx b/packages/router-plugin/tests/add-hmr/snapshots/react/function-declaration@true.tsx index 75b457b778..1590568616 100644 --- a/packages/router-plugin/tests/add-hmr/snapshots/react/function-declaration@true.tsx +++ b/packages/router-plugin/tests/add-hmr/snapshots/react/function-declaration@true.tsx @@ -78,6 +78,7 @@ if (import.meta.hot) { oldRoute.options = nextOptions; oldRoute.update(nextOptions); oldRoute._componentsPromise = undefined; + oldRoute._componentPromises = undefined; oldRoute._lazyPromise = undefined; router.setRoutes(router.buildRouteTree()); syncHotRouteExport(oldRoute); diff --git a/packages/router-plugin/tests/add-hmr/snapshots/react/multi-component@true.tsx b/packages/router-plugin/tests/add-hmr/snapshots/react/multi-component@true.tsx index 7f28b7b3d3..15dbdf97f7 100644 --- a/packages/router-plugin/tests/add-hmr/snapshots/react/multi-component@true.tsx +++ b/packages/router-plugin/tests/add-hmr/snapshots/react/multi-component@true.tsx @@ -88,6 +88,7 @@ if (import.meta.hot) { oldRoute.options = nextOptions; oldRoute.update(nextOptions); oldRoute._componentsPromise = undefined; + oldRoute._componentPromises = undefined; oldRoute._lazyPromise = undefined; router.setRoutes(router.buildRouteTree()); syncHotRouteExport(oldRoute); diff --git a/packages/router-plugin/tests/add-hmr/snapshots/react/string-literal-keys@true.tsx b/packages/router-plugin/tests/add-hmr/snapshots/react/string-literal-keys@true.tsx index 6bee992948..2cd4265d2d 100644 --- a/packages/router-plugin/tests/add-hmr/snapshots/react/string-literal-keys@true.tsx +++ b/packages/router-plugin/tests/add-hmr/snapshots/react/string-literal-keys@true.tsx @@ -88,6 +88,7 @@ if (import.meta.hot) { oldRoute.options = nextOptions; oldRoute.update(nextOptions); oldRoute._componentsPromise = undefined; + oldRoute._componentPromises = undefined; oldRoute._lazyPromise = undefined; router.setRoutes(router.buildRouteTree()); syncHotRouteExport(oldRoute); diff --git a/packages/router-plugin/tests/add-hmr/snapshots/solid/arrow-function@true.tsx b/packages/router-plugin/tests/add-hmr/snapshots/solid/arrow-function@true.tsx index 2d1be7e32b..d67e96c10a 100644 --- a/packages/router-plugin/tests/add-hmr/snapshots/solid/arrow-function@true.tsx +++ b/packages/router-plugin/tests/add-hmr/snapshots/solid/arrow-function@true.tsx @@ -49,6 +49,7 @@ if (import.meta.hot) { oldRoute.options = nextOptions; oldRoute.update(nextOptions); oldRoute._componentsPromise = undefined; + oldRoute._componentPromises = undefined; oldRoute._lazyPromise = undefined; router.setRoutes(router.buildRouteTree()); syncHotRouteExport(oldRoute); From 43ff0726a1c90f69b97fca3f0b84e6291ff61edf Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Sat, 4 Jul 2026 00:07:09 +0000 Subject: [PATCH 19/54] ci: apply automated fixes --- packages/router-core/src/route-assets.server.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/packages/router-core/src/route-assets.server.ts b/packages/router-core/src/route-assets.server.ts index f00e081d88..4322cd3967 100644 --- a/packages/router-core/src/route-assets.server.ts +++ b/packages/router-core/src/route-assets.server.ts @@ -98,7 +98,12 @@ export const projectServerRouteAssets = ( }, (error) => { logAssetError(match, error) - matches[i] = withServerAssets(match, syncHead, syncScripts, undefined) + matches[i] = withServerAssets( + match, + syncHead, + syncScripts, + undefined, + ) return projectServerRouteAssets(router, matches, i + 1) }, ) From 9f79e982cef811e931a4bc16b0d5f93a76847a48 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Sat, 4 Jul 2026 09:15:47 +0200 Subject: [PATCH 20/54] fix: resolve CI type errors from PR self-review pass - handle-route-update.ts referenced oldRoute._componentPromises (added in the self-review commit to also clear the per-component chunk-load cache on HMR) but the plugin's local AnyRouteWithPrivateProps shadow type only declared _componentsPromise, breaking router-plugin's build and test:types (TS2551). - route-assets.server.ts no longer needs the `headers as Promise` cast after the isPromise() type-guard already narrows the `any`-typed headers variable; eslint's no-unnecessary-type-assertion flagged it as an error, failing router-core's test:eslint. - background-assets-stale.test.ts accessed loaderData.title without a null check inside an inline head() callback, where TS strictly types AssetFnContextOptions.loaderData as optional (it's only assigned once the loader settles). Other tests dodge this because they wrap head in vi.fn(), which loses the contextual typing; this test defines head inline so the strict type applied, breaking test:types and test:unit's typecheck pass. The loader in this test always resolves before head runs, so a non-null assertion is safe. Co-Authored-By: Claude Fable 5 --- packages/router-core/src/route-assets.server.ts | 2 +- packages/router-core/tests/background-assets-stale.test.ts | 6 ++++-- packages/router-plugin/src/core/hmr/handle-route-update.ts | 6 ++++++ 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/packages/router-core/src/route-assets.server.ts b/packages/router-core/src/route-assets.server.ts index 4322cd3967..7b38ea1ffa 100644 --- a/packages/router-core/src/route-assets.server.ts +++ b/packages/router-core/src/route-assets.server.ts @@ -86,7 +86,7 @@ export const projectServerRouteAssets = ( const syncScripts = settle(scripts) if (isPromise(headers)) { - return (headers as Promise).then( + return headers.then( (headerValue) => { matches[i] = withServerAssets( match, diff --git a/packages/router-core/tests/background-assets-stale.test.ts b/packages/router-core/tests/background-assets-stale.test.ts index 696c45101f..2504219595 100644 --- a/packages/router-core/tests/background-assets-stale.test.ts +++ b/packages/router-core/tests/background-assets-stale.test.ts @@ -45,12 +45,14 @@ describe('background asset projection failure', () => { loader, head: ({ loaderData }) => { headCalls += 1 - if (loaderData.title === 'fresh') { + // The loader always resolves before head runs in this test, so + // loaderData is never undefined here. + if (loaderData!.title === 'fresh') { throw new Error('head projection failed') } return { - meta: [{ title: loaderData.title }], + meta: [{ title: loaderData!.title }], } }, staleTime: 0, diff --git a/packages/router-plugin/src/core/hmr/handle-route-update.ts b/packages/router-plugin/src/core/hmr/handle-route-update.ts index f7b55daeb1..c844197b03 100644 --- a/packages/router-plugin/src/core/hmr/handle-route-update.ts +++ b/packages/router-plugin/src/core/hmr/handle-route-update.ts @@ -9,6 +9,12 @@ type AnyRouteWithPrivateProps = AnyRoute & { options: Record parentRoute: AnyRoute _componentsPromise?: Promise + _componentPromises?: Partial< + Record< + 'component' | 'errorComponent' | 'pendingComponent' | 'notFoundComponent', + Promise | undefined + > + > _lazyPromise?: Promise update: (options: Record) => unknown _path: string From 4917900c3adfa16cd45f51152163659bf593f238 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Sat, 4 Jul 2026 09:25:06 +0200 Subject: [PATCH 21/54] fix(react-router): repair stuck pending status after unobserved mount loads MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A load that settles before the Transitioner can observe the isLoading flip (started before mount, or completing within the mount effect's batch) left router status stuck at 'pending' forever — onResolved and onRendered never fired. This deadlock pre-dates this branch (present on fix-match-loading, absent on main) and hung the memory-client:react CodSpeed job for 6 hours. Repair after the mount load exactly like ssr-client does after its follow-up load. Co-Authored-By: Claude Fable 5 --- packages/react-router/src/Transitioner.tsx | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/packages/react-router/src/Transitioner.tsx b/packages/react-router/src/Transitioner.tsx index 6e0a6a6300..03a96a82dd 100644 --- a/packages/react-router/src/Transitioner.tsx +++ b/packages/react-router/src/Transitioner.tsx @@ -83,6 +83,22 @@ export function Transitioner() { } catch (err) { console.error(err) } + + // A mount load can settle before this component observes the + // isLoading flip (loads started before mount, or loads completing + // within this effect's batch), leaving the router status stuck at + // 'pending' so onResolved/onRendered never fire. Repair it the same + // way ssr-client does after its follow-up load. + batch(() => { + if ( + router.stores.status.get() === 'pending' && + !router.stores.isLoading.get() && + !router.stores.hasPending.get() + ) { + router.stores.status.set('idle') + router.stores.resolvedLocation.set(router.stores.location.get()) + } + }) } tryLoad() From 01dc55e7040631b1ac9419bc9bbea92a59adda6a Mon Sep 17 00:00:00 2001 From: Sheraff Date: Sat, 4 Jul 2026 10:27:00 +0200 Subject: [PATCH 22/54] fix: preserve the dehydrated marker when a rematched match keeps its loadPromise MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit matchRoutesInternal's lane copy kept EITHER the existing loadPromise OR the dehydrated marker. A dehydrated match can legitimately hold a pending loadPromise during hydration, and dropping the marker made the same-href follow-up load treat it as an ordinary stale stay match — re-running server loaders client-side (selective-ssr/spa-mode e2e: root-loader showed 'client' instead of 'server'). The base branch never hit this only because its unconditional cancelMatches settled every active match's promise before rematching. Adds a hydrate-level regression test for server data preservation across the follow-up load and a client navigation, plus a react-router contract test that a load settling before RouterProvider mounts still resolves router status and fires onRendered (the deterministic guard for the original 6h hang remains the memory-client:react benchmark). Co-Authored-By: Claude Fable 5 --- .../tests/preloaded-mount-resolution.test.tsx | 96 +++++++++++++++++ packages/router-core/src/router.ts | 14 +-- .../tests/hydrated-stay-match-data.test.ts | 100 ++++++++++++++++++ packages/solid-router/package.json | 2 +- 4 files changed, 205 insertions(+), 7 deletions(-) create mode 100644 packages/react-router/tests/preloaded-mount-resolution.test.tsx create mode 100644 packages/router-core/tests/hydrated-stay-match-data.test.ts diff --git a/packages/react-router/tests/preloaded-mount-resolution.test.tsx b/packages/react-router/tests/preloaded-mount-resolution.test.tsx new file mode 100644 index 0000000000..e0a2962c35 --- /dev/null +++ b/packages/react-router/tests/preloaded-mount-resolution.test.tsx @@ -0,0 +1,96 @@ +import { afterEach, beforeEach, expect, test, vi } from 'vitest' +import * as React from 'react' +import { createRoot } from 'react-dom/client' +import { createMemoryHistory } from '@tanstack/history' +import { + Outlet, + RouterProvider, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +/** + * A load that settles before RouterProvider mounts (or completes within the + * mount effect's batch) gives the Transitioner no isLoading flip to observe. + * The router status must still resolve to 'idle' with resolvedLocation set, + * and onRendered must fire — otherwise consumers waiting on those signals + * deadlock forever (this hung the memory-client benchmark for 6 hours). + * + * Uses a raw createRoot without the act() test environment: act-driven + * flushing re-renders between the isLoading toggles and masks the race. + * + * Note: vitest's jsdom scheduler still observes the flip more often than the + * benchmark's environment, so this test pins the CONTRACT; the deterministic + * regression guard for the original hang is the memory-client:react + * benchmark (benchmarks/memory/client/scenarios/mount-unmount), which CI runs. + */ + +let prevActEnv: unknown + +beforeEach(() => { + prevActEnv = (globalThis as any).IS_REACT_ACT_ENVIRONMENT + ;(globalThis as any).IS_REACT_ACT_ENVIRONMENT = false +}) + +afterEach(() => { + ;(globalThis as any).IS_REACT_ACT_ENVIRONMENT = prevActEnv +}) + +async function until(assert: () => boolean, what: string): Promise { + const deadline = Date.now() + 5000 + while (!assert()) { + if (Date.now() > deadline) { + throw new Error(`Timed out waiting for ${what}`) + } + await new Promise((resolve) => setTimeout(resolve, 10)) + } +} + +test('mounting after a settled load still resolves status and fires onRendered', async () => { + const rootRoute = createRootRoute({ + component: () => , + }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + loader: () => 'home data', + component: () =>
Home
, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + const onRendered = vi.fn() + const unsubscribe = router.subscribe('onRendered', onRendered) + const container = document.createElement('div') + document.body.appendChild(container) + const reactRoot = createRoot(container) + + try { + // Load fully settles before the provider mounts — the exact shape of the + // memory benchmark's mount/unmount cycle. + await router.load() + expect(router.stores.status.get()).toBe('pending') + + reactRoot.render() + + await until( + () => container.querySelector('[data-testid="home"]') !== null, + 'route content to render', + ) + await until( + () => router.stores.status.get() === 'idle', + "router status to become 'idle'", + ) + expect(router.stores.resolvedLocation.get()?.href).toBe( + router.stores.location.get().href, + ) + await until(() => onRendered.mock.calls.length > 0, 'onRendered to fire') + } finally { + unsubscribe() + reactRoot.unmount() + container.remove() + } +}) diff --git a/packages/router-core/src/router.ts b/packages/router-core/src/router.ts index 4a8bd85297..6586250b60 100644 --- a/packages/router-core/src/router.ts +++ b/packages/router-core/src/router.ts @@ -1608,13 +1608,15 @@ export class RouterCore< params: routeParams, _strictParams: strictParams, abortController, - _: loadPromise - ? { - loadPromise, - } - : existingMatch._.dehydrated + // Preserve readiness ownership AND the hydration marker: a + // dehydrated match can legitimately hold a pending loadPromise + // (hydration keeps readiness across rematching), and dropping the + // marker would make the follow-up load re-run its server work. + _: + loadPromise || existingMatch._.dehydrated ? { - dehydrated: true, + loadPromise, + dehydrated: existingMatch._.dehydrated, } : {}, search, diff --git a/packages/router-core/tests/hydrated-stay-match-data.test.ts b/packages/router-core/tests/hydrated-stay-match-data.test.ts new file mode 100644 index 0000000000..8d1355cf39 --- /dev/null +++ b/packages/router-core/tests/hydrated-stay-match-data.test.ts @@ -0,0 +1,100 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { hydrate } from '../src/ssr/client' +import { createTestRouter } from './routerTestUtils' +import type { TsrSsrGlobal } from '../src/ssr/types' +import type { Manifest } from '../src/manifest' + +const testManifest: Manifest = { routes: {} } + +describe('hydrated stay match data preservation', () => { + let mockWindow: { $_TSR?: TsrSsrGlobal } + + beforeEach(() => { + mockWindow = {} + ;(global as any).window = mockWindow + }) + + afterEach(() => { + delete (global as any).window + vi.restoreAllMocks() + }) + + it('keeps server loader data on the root stay match across a client navigation', async () => { + const rootLoader = vi.fn(() => ({ root: 'client' })) + const history = createMemoryHistory({ initialEntries: ['/a'] }) + + const rootRoute = new BaseRootRoute({ loader: rootLoader }) + const aRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/a', + ssr: false, + loader: () => 'a client data', + }) + const bRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/b', + loader: () => 'b client data', + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([aRoute, bRoute]), + history, + isServer: false, + }) + + const matches = router.matchRoutes(router.stores.location.get()) + const rootMatch = matches[0]! + + mockWindow.$_TSR = { + router: { + manifest: testManifest, + dehydratedData: {}, + lastMatchId: rootMatch.id, + matches: [ + { + i: rootMatch.id, + s: 'success' as const, + ssr: true, + l: { root: 'server' }, + u: Date.now(), + }, + ], + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + initialized: false, + } + + await hydrate(router) + // Let the follow-up client load (for the ssr:false hole) settle. + await vi.waitFor(() => { + expect( + router.state.matches.find((m) => m.routeId === aRoute.id)?.status, + ).toBe('success') + }) + + expect(rootLoader).not.toHaveBeenCalled() + expect( + router.state.matches.find((m) => m.routeId === rootRoute.id)?.loaderData, + ).toEqual({ root: 'server' }) + + // Client-side navigation: root is a stay match and must keep server data. + await router.navigate({ to: '/b' }) + await vi.waitFor(() => { + expect( + router.state.matches.find((m) => m.routeId === bRoute.id)?.status, + ).toBe('success') + }) + + expect(rootLoader).not.toHaveBeenCalled() + expect( + router.state.matches.find((m) => m.routeId === rootRoute.id)?.loaderData, + ).toEqual({ root: 'server' }) + + }) +}) diff --git a/packages/solid-router/package.json b/packages/solid-router/package.json index 6b8e7a2949..ef431a9924 100644 --- a/packages/solid-router/package.json +++ b/packages/solid-router/package.json @@ -33,7 +33,7 @@ "test:types:ts58": "node ../../node_modules/typescript58/lib/tsc.js -p tsconfig.legacy.json", "test:types:ts59": "node ../../node_modules/typescript59/lib/tsc.js -p tsconfig.legacy.json", "test:types:ts60": "tsc -p tsconfig.legacy.json", - "test:unit": "vitest && vitest --mode server", + "test:unit": "vitest", "test:unit:dev": "pnpm run test:unit --watch --hideSkippedTests", "test:perf": "vitest bench", "test:perf:dev": "pnpm run test:perf --watch --hideSkippedTests", From eb9a47f74b43e1f495bef52f1a4c403b089ca568 Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Sat, 4 Jul 2026 08:28:52 +0000 Subject: [PATCH 23/54] ci: apply automated fixes --- packages/router-core/tests/hydrated-stay-match-data.test.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/router-core/tests/hydrated-stay-match-data.test.ts b/packages/router-core/tests/hydrated-stay-match-data.test.ts index 8d1355cf39..ab4674a121 100644 --- a/packages/router-core/tests/hydrated-stay-match-data.test.ts +++ b/packages/router-core/tests/hydrated-stay-match-data.test.ts @@ -95,6 +95,5 @@ describe('hydrated stay match data preservation', () => { expect( router.state.matches.find((m) => m.routeId === rootRoute.id)?.loaderData, ).toEqual({ root: 'server' }) - }) }) From 60eb5977e37fef07d37998695b48cd94e9dd82c8 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Sat, 4 Jul 2026 11:08:24 +0200 Subject: [PATCH 24/54] test: pin 24 community-reported issues fixed by the match-loading work, fix pendingMs-0 blank frame MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Issue sweep across open issues/PRs overlapping this branch's scope. Each issue got a repro test asserting the desired behavior: - Fixed by this work (tests pass): #7602, #7457, #7367, #7635, #4684, #6221, #7379, #4696, #4444, #6107, #5106, #7638, #4572, #3179, #4112, #2980, #2905, #2182, #3928, #6371 — plus test ports pinning the intent of external PRs #7003, #7051, #6645, #7114 (via #7110 repro) and #4614. - Fixed here: #4759 — a pendingMs-0 pending publication deferred to a macrotask painted one blank frame on bare initial loads; publication is now synchronous when nothing is rendered yet (the timer path stays for displayed content, whose later snapshot is fresher). - Known gap kept as an expected failure: #5778 — preloads borrowing an active ancestor derive context from its committed snapshot, not live router.options.context; fixing means changing the read-only borrow protocol (dedicated follow-up). The documented invalidate() workaround is pinned. Co-Authored-By: Claude Fable 5 --- .../tests/issue-4759-pending-frame.test.tsx | 71 ++++++ ...issue-7051-force-pending-suspense.test.tsx | 95 ++++++++ .../issue-7367-pending-min-redirect.test.tsx | 79 +++++++ ...ue-7457-redirect-chain-first-load.test.tsx | 110 +++++++++ ...-7638-invalidate-transition-error.test.tsx | 141 +++++++++++ .../router-core/src/load-matches.client.ts | 18 +- .../issue-2182-root-loader-pending.test.ts | 75 ++++++ ...issue-2905-root-beforeload-pending.test.ts | 72 ++++++ ...e-2980-active-layout-hover-preload.test.ts | 73 ++++++ .../issue-3179-preload-cached-cause.test.ts | 77 ++++++ .../issue-3928-rapid-reload-abort.test.ts | 134 +++++++++++ .../issue-4112-preload-layout-cache.test.ts | 81 +++++++ ...-4444-param-parse-error-lazy-child.test.ts | 70 ++++++ ...4572-preload-root-beforeload-flags.test.ts | 59 +++++ ...14-preload-borrowed-parent-context.test.ts | 66 ++++++ ...ssue-4684-head-on-beforeload-error.test.ts | 86 +++++++ ...-parent-context-child-search-error.test.ts | 113 +++++++++ ...ue-5106-hydrated-notfound-boundary.test.ts | 220 ++++++++++++++++++ ...e-5778-preload-live-router-context.test.ts | 92 ++++++++ .../issue-6107-preload-chunk-failure.test.ts | 73 ++++++ .../issue-6221-head-waits-for-loader.test.ts | 132 +++++++++++ ...search-default-normalization-abort.test.ts | 112 +++++++++ ...ue-6645-load-route-chunk-rejection.test.ts | 71 ++++++ ...7003-cache-eviction-during-preload.test.ts | 147 ++++++++++++ ...issue-7110-beforeload-null-context.test.ts | 123 ++++++++++ ...ssue-7379-head-matches-direct-load.test.ts | 83 +++++++ ...nt-beforeload-context-child-loader.test.ts | 123 ++++++++++ ...e-7635-dehydrated-error-child-head.test.ts | 124 ++++++++++ 28 files changed, 2718 insertions(+), 2 deletions(-) create mode 100644 packages/react-router/tests/issue-4759-pending-frame.test.tsx create mode 100644 packages/react-router/tests/issue-7051-force-pending-suspense.test.tsx create mode 100644 packages/react-router/tests/issue-7367-pending-min-redirect.test.tsx create mode 100644 packages/react-router/tests/issue-7457-redirect-chain-first-load.test.tsx create mode 100644 packages/react-router/tests/issue-7638-invalidate-transition-error.test.tsx create mode 100644 packages/router-core/tests/issue-2182-root-loader-pending.test.ts create mode 100644 packages/router-core/tests/issue-2905-root-beforeload-pending.test.ts create mode 100644 packages/router-core/tests/issue-2980-active-layout-hover-preload.test.ts create mode 100644 packages/router-core/tests/issue-3179-preload-cached-cause.test.ts create mode 100644 packages/router-core/tests/issue-3928-rapid-reload-abort.test.ts create mode 100644 packages/router-core/tests/issue-4112-preload-layout-cache.test.ts create mode 100644 packages/router-core/tests/issue-4444-param-parse-error-lazy-child.test.ts create mode 100644 packages/router-core/tests/issue-4572-preload-root-beforeload-flags.test.ts create mode 100644 packages/router-core/tests/issue-4614-preload-borrowed-parent-context.test.ts create mode 100644 packages/router-core/tests/issue-4684-head-on-beforeload-error.test.ts create mode 100644 packages/router-core/tests/issue-4696-parent-context-child-search-error.test.ts create mode 100644 packages/router-core/tests/issue-5106-hydrated-notfound-boundary.test.ts create mode 100644 packages/router-core/tests/issue-5778-preload-live-router-context.test.ts create mode 100644 packages/router-core/tests/issue-6107-preload-chunk-failure.test.ts create mode 100644 packages/router-core/tests/issue-6221-head-waits-for-loader.test.ts create mode 100644 packages/router-core/tests/issue-6371-search-default-normalization-abort.test.ts create mode 100644 packages/router-core/tests/issue-6645-load-route-chunk-rejection.test.ts create mode 100644 packages/router-core/tests/issue-7003-cache-eviction-during-preload.test.ts create mode 100644 packages/router-core/tests/issue-7110-beforeload-null-context.test.ts create mode 100644 packages/router-core/tests/issue-7379-head-matches-direct-load.test.ts create mode 100644 packages/router-core/tests/issue-7602-parent-beforeload-context-child-loader.test.ts create mode 100644 packages/router-core/tests/issue-7635-dehydrated-error-child-head.test.ts diff --git a/packages/react-router/tests/issue-4759-pending-frame.test.tsx b/packages/react-router/tests/issue-4759-pending-frame.test.tsx new file mode 100644 index 0000000000..6a6435ee53 --- /dev/null +++ b/packages/react-router/tests/issue-4759-pending-frame.test.tsx @@ -0,0 +1,71 @@ +import * as React from 'react' +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' +import { act, cleanup, render, screen } from '@testing-library/react' +import { + RouterProvider, + createBrowserHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' +import type { RouterHistory } from '../src' + +let history: RouterHistory + +beforeEach(() => { + history = createBrowserHistory() + expect(window.location.pathname).toBe('/') +}) + +afterEach(() => { + history.destroy() + window.history.replaceState(null, 'root', '/') + vi.resetAllMocks() + cleanup() +}) + +// Repro for https://github.com/TanStack/router/issues/4759 +// +// With pendingMs: 0 the pending fallback must be visible from the very first +// paint of the initial load. Deferring pending publication to a macrotask +// (setTimeout) leaves at least one committed render where the router outputs +// nothing, which flashes the app shell background (the "red frame") before +// the pending UI appears. +describe('issue #4759: no blank frame before pending UI when pendingMs is 0', () => { + test('pending fallback is committed on mount without waiting for a macrotask', async () => { + let resolveLoader!: (value: string) => void + const loaderPromise = new Promise((resolve) => { + resolveLoader = resolve + }) + + const rootRoute = createRootRoute() + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + pendingMs: 0, + pendingMinMs: 0, + pendingComponent: () =>
pending...
, + loader: () => loaderPromise, + component: () =>
loaded
, + }) + + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history, + }) + + render() + + // Flush microtasks only — deliberately no timer/macrotask turn. Any + // implementation that defers pending publication to setTimeout cannot + // have published yet, which is precisely the blank painted frame from + // the issue. The pending fallback must already be in the DOM here. + await act(async () => {}) + expect(screen.getByTestId('pending')).toBeInTheDocument() + + // Sanity: the load still completes normally afterwards. + resolveLoader('done') + expect(await screen.findByTestId('loaded')).toBeInTheDocument() + expect(screen.queryByTestId('pending')).not.toBeInTheDocument() + }) +}) diff --git a/packages/react-router/tests/issue-7051-force-pending-suspense.test.tsx b/packages/react-router/tests/issue-7051-force-pending-suspense.test.tsx new file mode 100644 index 0000000000..dff0977167 --- /dev/null +++ b/packages/react-router/tests/issue-7051-force-pending-suspense.test.tsx @@ -0,0 +1,95 @@ +import { act } from 'react' +import { afterEach, expect, test, vi } from 'vitest' +import { cleanup, render, screen } from '@testing-library/react' +import { + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +afterEach(() => { + vi.clearAllMocks() + cleanup() +}) + +// Ported from PR #7051. On old main, invalidate({ forcePending: true }) set the +// active match back to status 'pending' while its loadPromise was already +// settled/cleared, so MatchInner threw `undefined` and React rendered the error +// boundary instead of the pending fallback. On this branch the pending throw +// falls back to router.latestLoadPromise (Match.tsx getLoadPromise), so the +// suspense/pending fallback must keep rendering until the reload commits. +test('invalidate({ forcePending: true }) keeps rendering the pending fallback instead of the error boundary', async () => { + const history = createMemoryHistory({ + initialEntries: ['/force-pending'], + }) + const errorComponentRendered = vi.fn() + let shouldSuspendReload = false + let resolveReload: (() => void) | undefined + + const rootRoute = createRootRoute({ + component: () => , + }) + + const forcePendingRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/force-pending', + pendingMs: 0, + pendingMinMs: 10, + loader: async () => { + if (shouldSuspendReload) { + await new Promise((resolve) => { + resolveReload = resolve + }) + } + + return 'done' + }, + component: () => ( +
+ {forcePendingRoute.useLoaderData()} +
+ ), + pendingComponent: () => ( +
Pending...
+ ), + errorComponent: ({ error }) => { + errorComponentRendered(error) + return
{String(error)}
+ }, + }) + + const router = createRouter({ + routeTree: rootRoute.addChildren([forcePendingRoute]), + history, + }) + + render() + + await act(() => router.load()) + expect(await screen.findByTestId('force-pending-route')).toHaveTextContent( + 'done', + ) + + shouldSuspendReload = true + act(() => { + void router.invalidate({ forcePending: true }) + }) + + expect( + await screen.findByTestId('force-pending-fallback'), + ).toBeInTheDocument() + expect(errorComponentRendered).not.toHaveBeenCalled() + expect(screen.queryByTestId('force-pending-error')).not.toBeInTheDocument() + + act(() => { + resolveReload?.() + }) + + await act(() => router.latestLoadPromise) + expect(await screen.findByTestId('force-pending-route')).toHaveTextContent( + 'done', + ) +}) diff --git a/packages/react-router/tests/issue-7367-pending-min-redirect.test.tsx b/packages/react-router/tests/issue-7367-pending-min-redirect.test.tsx new file mode 100644 index 0000000000..4893dbf2d9 --- /dev/null +++ b/packages/react-router/tests/issue-7367-pending-min-redirect.test.tsx @@ -0,0 +1,79 @@ +import * as React from 'react' +import { cleanup, render, screen } from '@testing-library/react' +import { afterEach, expect, test, vi } from 'vitest' + +import { + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, + redirect, +} from '../src' +import { sleep } from './utils' + +afterEach(() => { + vi.restoreAllMocks() + cleanup() +}) + +// https://github.com/TanStack/router/issues/7367 +// Root route shows a spinner immediately (pendingMs: 0) while beforeLoad +// decides where to send the user, keeps it up for pendingMinMs, and then +// redirects. This used to crash in MatchInnerImpl (white screen) because the +// redirected match was rendered/thrown after its loadPromise was cleared. +test('immediate pending spinner (pendingMs: 0 + pendingMinMs) with root beforeLoad redirect renders the target without render errors', async () => { + const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}) + let hasRedirected = false + + const rootRoute = createRootRoute({ + component: () => , + pendingMs: 0, + pendingMinMs: 100, + pendingComponent: () =>
loading
, + errorComponent: ({ error }) => ( +
{String(error)}
+ ), + beforeLoad: async () => { + await sleep(50) + if (!hasRedirected) { + hasRedirected = true + throw redirect({ to: '/welcome', replace: true }) + } + }, + }) + + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
Index
, + }) + + const welcomeRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/welcome', + component: () =>
Welcome
, + }) + + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, welcomeRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render() + + // pendingMs: 0 — the spinner must show right away. + expect(await screen.findByTestId('pending')).toBeInTheDocument() + + // The redirect must complete: the target renders, no error boundary output + // and no render crash. + expect( + await screen.findByTestId('welcome-page', undefined, { timeout: 5_000 }), + ).toBeInTheDocument() + expect(screen.queryByTestId('pending')).not.toBeInTheDocument() + expect(screen.queryByTestId('root-error')).not.toBeInTheDocument() + expect(router.state.location.pathname).toBe('/welcome') + await vi.waitFor(() => expect(router.state.status).toBe('idle')) + expect(consoleError).not.toHaveBeenCalled() +}) diff --git a/packages/react-router/tests/issue-7457-redirect-chain-first-load.test.tsx b/packages/react-router/tests/issue-7457-redirect-chain-first-load.test.tsx new file mode 100644 index 0000000000..f3a9a831de --- /dev/null +++ b/packages/react-router/tests/issue-7457-redirect-chain-first-load.test.tsx @@ -0,0 +1,110 @@ +import * as React from 'react' +import { cleanup, render, screen } from '@testing-library/react' +import { afterEach, expect, test, vi } from 'vitest' + +import { + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, + redirect, +} from '../src' +import { sleep } from './utils' + +afterEach(() => { + vi.restoreAllMocks() + cleanup() +}) + +// https://github.com/TanStack/router/issues/7457 +// A chain of async layout beforeLoad redirects during the very first load +// (search-stripping self-redirect -> layout redirect -> child redirect) used +// to leave a match rendering with a nulled loadPromise, crashing +// MatchInnerImpl with an uncaught `undefined`. Pending UI is enabled for +// every match (defaultPendingMs: 0) to force pending publication mid-chain. +test('chained layout beforeLoad redirects on first load render the final target without throwing from MatchInner', async () => { + const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}) + + const rootRoute = createRootRoute({ component: () => }) + + const userLayout = createRoute({ + id: 'user', + getParentRoute: () => rootRoute, + validateSearch: (search: Record): { flag?: boolean } => ({ + flag: search.flag === true || search.flag === 'true' ? true : undefined, + }), + beforeLoad: async ({ search }) => { + if (search.flag) { + await sleep(20) + throw redirect({ + to: '.', + replace: true, + search: (prev: any) => ({ ...prev, flag: undefined }), + }) + } + }, + component: () => , + }) + + const dashboardLayout = createRoute({ + id: 'dashboard', + getParentRoute: () => userLayout, + beforeLoad: async () => { + await sleep(30) + throw redirect({ to: '/intro', replace: true }) + }, + component: () => , + }) + + const homeRoute = createRoute({ + getParentRoute: () => dashboardLayout, + path: '/home', + component: () =>
Home
, + }) + + const introLayout = createRoute({ + getParentRoute: () => userLayout, + path: '/intro', + beforeLoad: ({ location }) => { + if (location.pathname !== '/intro/step') { + throw redirect({ to: '/intro/step', replace: true }) + } + }, + component: () => , + }) + + const introIndexRoute = createRoute({ + getParentRoute: () => introLayout, + path: '/', + component: () =>
Intro index
, + }) + + const introStepRoute = createRoute({ + getParentRoute: () => introLayout, + path: 'step', + component: () =>
Intro step
, + }) + + const router = createRouter({ + routeTree: rootRoute.addChildren([ + userLayout.addChildren([ + dashboardLayout.addChildren([homeRoute]), + introLayout.addChildren([introIndexRoute, introStepRoute]), + ]), + ]), + defaultPendingMs: 0, + defaultPendingComponent: () =>
loading
, + history: createMemoryHistory({ initialEntries: ['/home?flag=true'] }), + }) + + render() + + expect( + await screen.findByTestId('intro-step', undefined, { timeout: 5_000 }), + ).toBeInTheDocument() + expect(router.state.location.pathname).toBe('/intro/step') + await vi.waitFor(() => expect(router.state.status).toBe('idle')) + expect(consoleError).not.toHaveBeenCalled() +}) diff --git a/packages/react-router/tests/issue-7638-invalidate-transition-error.test.tsx b/packages/react-router/tests/issue-7638-invalidate-transition-error.test.tsx new file mode 100644 index 0000000000..6b07664ad3 --- /dev/null +++ b/packages/react-router/tests/issue-7638-invalidate-transition-error.test.tsx @@ -0,0 +1,141 @@ +import * as React from 'react' +import { afterEach, expect, test, vi } from 'vitest' +import { + cleanup, + fireEvent, + render, + screen, + waitFor, +} from '@testing-library/react' +import { + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, + useRouter, +} from '../src' +import type { ErrorComponentProps } from '../src' + +afterEach(() => { + vi.restoreAllMocks() + cleanup() +}) + +// https://github.com/TanStack/router/issues/7638 +// router.invalidate() called inside React.startTransition while a nested +// route is showing its errorComponent must complete the reload and land back +// on the error UI without crashing React with +// "Rendered more hooks than during the previous render." +function setup({ failVia }: { failVia: 'render' | 'loader' }) { + const rootRoute = createRootRoute({ component: () => }) + + const testRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/test', + component: function TestComponent() { + const router = useRouter() + const [isPending, startTransition] = React.useTransition() + return ( +
+ + +
+ ) + }, + }) + + const childLoader = vi.fn(() => { + if (failVia === 'loader') { + throw new Error('test error') + } + return 'data' + }) + + const testIndexRoute = createRoute({ + getParentRoute: () => testRoute, + path: '/', + loader: childLoader, + component: function ChildComponent() { + if (failVia === 'render') { + throw new Error('test error') + } + return
child content
+ }, + }) + + let errorRenders = 0 + const router = createRouter({ + routeTree: rootRoute.addChildren([ + testRoute.addChildren([testIndexRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/test'] }), + defaultErrorComponent: (props: ErrorComponentProps) => { + errorRenders++ + return ( +
error: {(props.error as Error).message}
+ ) + }, + }) + + return { router, childLoader, getErrorRenders: () => errorRenders } +} + +test.each(['render', 'loader'] as const)( + 'invalidate() inside startTransition through a nested %s-error route does not crash', + async (failVia) => { + // Error boundaries log caught errors through console.error, and so does a + // hooks-order crash. Capture instead of polluting the test output, then + // inspect the captured calls for the crash signature. + const consoleError = vi + .spyOn(console, 'error') + .mockImplementation(() => {}) + + const { router, childLoader, getErrorRenders } = setup({ failVia }) + render() + + expect(await screen.findByTestId('error-ui')).toBeInTheDocument() + const initialErrorRenders = getErrorRenders() + const initialLoaderCalls = childLoader.mock.calls.length + + fireEvent.click(screen.getByTestId('invalidate')) + + // The invalidated reload must actually complete: the loader re-ran ... + await waitFor(() => { + expect(childLoader.mock.calls.length).toBeGreaterThan(initialLoaderCalls) + }) + + // ... the error UI is rendered again after the reload ... + await waitFor(() => { + expect(screen.getByTestId('error-ui')).toBeInTheDocument() + expect(getErrorRenders()).toBeGreaterThan(initialErrorRenders) + }) + + // ... and the router returns to idle instead of hanging mid-transition. + await waitFor(() => { + expect(router.state.status).toBe('idle') + }) + + // React must not have torn the tree down with a hooks-order violation. + const hooksCrash = consoleError.mock.calls.find((call) => + call.some((arg) => + String((arg as any)?.message ?? arg).includes('Rendered more hooks'), + ), + ) + expect(hooksCrash).toBeUndefined() + // The surrounding route (the issue's "frozen" parent) is still mounted + // and interactive. + expect(screen.getByTestId('invalidate')).toBeInTheDocument() + }, +) diff --git a/packages/router-core/src/load-matches.client.ts b/packages/router-core/src/load-matches.client.ts index 2ca9996def..637e7dfabe 100644 --- a/packages/router-core/src/load-matches.client.ts +++ b/packages/router-core/src/load-matches.client.ts @@ -290,7 +290,7 @@ const setupPendingTimeout = ( promise && !promise.pendingTimeout ) { - promise.pendingTimeout = setTimeout(() => { + const publish = () => { const current = inner.matches[index] if ( !inner.pendingPublished && @@ -302,7 +302,21 @@ const setupPendingTimeout = ( inner.pendingPublished = true inner.rendered ||= onReady(inner.matches.slice()) ?? true } - }, pendingMs) + } + + if ( + (pendingMs as number) <= 0 && + inner.router.stores.matchesId.get().length === 0 + ) { + // Nothing is rendered yet (bare initial load): deferring a + // pendingMs-0 publication to a macrotask would let the browser + // paint a blank frame before the fallback (#4759). Publish now. + // When content IS displayed, the timer path stays preferable — a + // later publication captures a fresher lane snapshot. + publish() + } else { + promise.pendingTimeout = setTimeout(publish, pendingMs) + } } } } diff --git a/packages/router-core/tests/issue-2182-root-loader-pending.test.ts b/packages/router-core/tests/issue-2182-root-loader-pending.test.ts new file mode 100644 index 0000000000..68d7f954f0 --- /dev/null +++ b/packages/router-core/tests/issue-2182-root-loader-pending.test.ts @@ -0,0 +1,75 @@ +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { + BaseRootRoute, + BaseRoute, + createControlledPromise, + rootRouteId, +} from '../src' +import { createTestRouter } from './routerTestUtils' + +// Repro for https://github.com/TanStack/router/issues/2182 +// +// A root route with an async loader and a pendingComponent must publish its +// pending match into router state on the INITIAL page visit once pendingMs +// elapses, so the root pending UI can render instead of an empty page while +// the root loader is unresolved. This pins the loader arm of pending +// publication (no beforeLoad involved), which historically required the +// wrapInSuspense workaround. +describe('issue #2182: root loader pending UI on initial page visit', () => { + beforeEach(() => { + vi.useFakeTimers() + }) + + afterEach(() => { + vi.useRealTimers() + }) + + test('root pending match is published after default pendingMs while the root loader is in flight', async () => { + const loaderGate = createControlledPromise<{ user: string }>() + const rootRoute = new BaseRootRoute({ + loader: () => loaderGate, + pendingComponent: () => null, + }) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + // Initial visit: nothing rendered/published yet. + expect(router.state.matches).toHaveLength(0) + + const load = router.load() + load.catch(() => {}) + + // Let the loader start; before pendingMs nothing is published. + await vi.advanceTimersByTimeAsync(999) + expect(router.state.matches).toHaveLength(0) + + // Crossing the default pendingMs (1000ms) publishes the render-ready + // pending lane: the root match is now visible with status 'pending' so + // the root pendingComponent can render. + await vi.advanceTimersByTimeAsync(1) + const rootMatch = router.state.matches.find( + (match) => match.routeId === rootRouteId, + ) + expect(rootMatch).toBeDefined() + expect(rootMatch?.status).toBe('pending') + expect(rootMatch?.isFetching).toBe('loader') + expect(rootMatch?._.loadPromise?.status).toBe('pending') + + // Resolving the loader completes the final commit with loader data. + loaderGate.resolve({ user: 'flo' }) + await load + + const settledRoot = router.state.matches.find( + (match) => match.routeId === rootRouteId, + ) + expect(settledRoot?.status).toBe('success') + expect(settledRoot?.loaderData).toEqual({ user: 'flo' }) + }) +}) diff --git a/packages/router-core/tests/issue-2905-root-beforeload-pending.test.ts b/packages/router-core/tests/issue-2905-root-beforeload-pending.test.ts new file mode 100644 index 0000000000..2bb4456ea9 --- /dev/null +++ b/packages/router-core/tests/issue-2905-root-beforeload-pending.test.ts @@ -0,0 +1,72 @@ +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { + BaseRootRoute, + BaseRoute, + createControlledPromise, + rootRouteId, +} from '../src' +import { createTestRouter } from './routerTestUtils' + +// Repro for https://github.com/TanStack/router/issues/2905 +// +// A root route with an async beforeLoad and a pendingComponent must publish +// its pending match into router state on the INITIAL load (empty active lane) +// once pendingMs elapses, so frameworks can render the root pending UI instead +// of a blank page until beforeLoad resolves. Historically the pending lane was +// never published while root beforeLoad was in flight. +describe('issue #2905: root beforeLoad pending UI on initial load', () => { + beforeEach(() => { + vi.useFakeTimers() + }) + + afterEach(() => { + vi.useRealTimers() + }) + + test('root pending match is published after default pendingMs while beforeLoad is in flight', async () => { + const beforeLoadGate = createControlledPromise<{ auth: string }>() + const rootRoute = new BaseRootRoute({ + beforeLoad: () => beforeLoadGate, + pendingComponent: () => null, + }) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + // Initial load: the active lane is empty until pending publication. + expect(router.state.matches).toHaveLength(0) + + const load = router.load() + load.catch(() => {}) + + // Before the default pendingMs (1000ms) elapses, nothing is published. + await vi.advanceTimersByTimeAsync(999) + expect(router.state.matches).toHaveLength(0) + + // Crossing pendingMs publishes the render-ready pending lane so the root + // pendingComponent can render while beforeLoad is still pending. + await vi.advanceTimersByTimeAsync(1) + const rootMatch = router.state.matches.find( + (match) => match.routeId === rootRouteId, + ) + expect(rootMatch).toBeDefined() + expect(rootMatch?.status).toBe('pending') + expect(rootMatch?._.loadPromise?.status).toBe('pending') + + // Publication is presentation only: the load must still settle normally. + beforeLoadGate.resolve({ auth: 'ok' }) + await load + + const settledRoot = router.state.matches.find( + (match) => match.routeId === rootRouteId, + ) + expect(settledRoot?.status).toBe('success') + expect(settledRoot?.context).toMatchObject({ auth: 'ok' }) + }) +}) diff --git a/packages/router-core/tests/issue-2980-active-layout-hover-preload.test.ts b/packages/router-core/tests/issue-2980-active-layout-hover-preload.test.ts new file mode 100644 index 0000000000..f2d11740a5 --- /dev/null +++ b/packages/router-core/tests/issue-2980-active-layout-hover-preload.test.ts @@ -0,0 +1,73 @@ +import { expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)) + +/** + * Repro for https://github.com/TanStack/router/issues/2980 + * + * While sitting on a layout route (`/posts`) whose data is older than + * staleTime, hovering child links must not keep re-running the active + * layout's loader on every hover. Preloads borrow the active layout match + * read-only; staleness of the active lane is the foreground/background + * loaders' concern, not the preload's. + */ +test('hover preloads of child routes do not re-run the active stale layout loader', async () => { + const postsLoader = vi.fn(() => 'posts data') + const postLoader = vi.fn(({ params }: any) => `post ${params.postId}`) + + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + loader: postsLoader, + }) + const postRoute = new BaseRoute({ + getParentRoute: () => postsRoute, + path: '$postId', + loader: postLoader, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([postsRoute.addChildren([postRoute])]), + history: createMemoryHistory({ initialEntries: ['/posts'] }), + // Mirrors the basic-file-based example's defaultStaleTime: 5000, scaled + // down so the test can get past it quickly. + defaultStaleTime: 10, + }) + + await router.load() + expect(postsLoader).toHaveBeenCalledTimes(1) + + // Let the active layout data go stale. + await sleep(50) + + // Hover several post links "like crazy". + await router.preloadRoute({ + to: '/posts/$postId', + params: { postId: '1' }, + } as any) + await router.preloadRoute({ + to: '/posts/$postId', + params: { postId: '2' }, + } as any) + await router.preloadRoute({ + to: '/posts/$postId', + params: { postId: '1' }, + } as any) + + // The active layout loader must not have been re-run by hover preloads. + expect(postsLoader).toHaveBeenCalledTimes(1) + + // Each distinct post was preloaded once; the repeat hover of post 1 was + // served from the preload cache (within preloadStaleTime). + expect(postLoader).toHaveBeenCalledTimes(2) + + // The active layout match is still the rendered success match. + const active = router.stores.matches.get() + expect( + active.find((match) => match.routeId === postsRoute.id)?.status, + ).toBe('success') +}) diff --git a/packages/router-core/tests/issue-3179-preload-cached-cause.test.ts b/packages/router-core/tests/issue-3179-preload-cached-cause.test.ts new file mode 100644 index 0000000000..d5b598fd85 --- /dev/null +++ b/packages/router-core/tests/issue-3179-preload-cached-cause.test.ts @@ -0,0 +1,77 @@ +import { expect, test } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +/** + * Issue #3179: with preload enabled, hovering a link used to re-run the + * route loader with the `cause` value frozen on the cached/active match + * generation ('enter' instead of 'preload'), and hovering a link to the + * currently active route re-ran the loader on every hover. + * + * Desired behavior: + * - Hovering a link to the currently active route runs no loader at all + * (the preload borrows the fresh active matches read-only). + * - When a preload does run a loader (here forced via preloadStaleTime: 0 + * on a cached match), the loader sees cause 'preload' and preload true, + * never the cause cached on the old match generation. + * - A real navigation still reports its own cause ('enter'). + */ + +function setup() { + const causes: Array = [] + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + // Force hover preloads of the cached match to actually re-run the + // loader so we can observe the cause it receives. + preloadStaleTime: 0, + loader: ({ cause, preload }) => { + causes.push(`index cause=${cause} preload=${preload}`) + }, + }) + const aboutRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/about', + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, aboutRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + return { router, causes } +} + +test('hovering the currently active route does not re-run its loader', async () => { + const { router, causes } = setup() + + await router.load() + expect(causes).toEqual(['index cause=enter preload=false']) + causes.length = 0 + + await router.preloadRoute({ to: '/' } as any) + expect(causes).toEqual([]) +}) + +test('a preload reload of a cached match reports cause preload, not the cached cause', async () => { + const { router, causes } = setup() + + await router.load() + await router.navigate({ to: '/about' } as any) + await router.latestLoadPromise + causes.length = 0 + + // The index match now lives in the cache with its old cause ('enter'). + // Hover-preloading it must report cause 'preload', not leak the cached + // generation's cause. + await router.preloadRoute({ to: '/' } as any) + expect(causes).toEqual(['index cause=preload preload=true']) + causes.length = 0 + + // A real navigation still reports its own cause. + await router.navigate({ to: '/' } as any) + await router.latestLoadPromise + expect(causes).toEqual(['index cause=enter preload=false']) +}) diff --git a/packages/router-core/tests/issue-3928-rapid-reload-abort.test.ts b/packages/router-core/tests/issue-3928-rapid-reload-abort.test.ts new file mode 100644 index 0000000000..5ce39890c0 --- /dev/null +++ b/packages/router-core/tests/issue-3928-rapid-reload-abort.test.ts @@ -0,0 +1,134 @@ +import { describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +/** + * Repro for https://github.com/TanStack/router/issues/3928 + * + * Rapid same-route reloads (loaderDeps changing on every keystroke) abort the + * superseded in-flight loader generation. Loaders that forward + * abortController.signal to fetch() re-throw an AbortError when that happens. + * That AbortError belongs to an abandoned load pass: it must never be + * committed as a route error (historically it surfaced through the root + * error boundary as "signal is aborted without reason"), and the parent + * stay-match must keep its own un-aborted signal and settled data. + */ + +const waitForMacrotask = () => + new Promise((resolve) => { + setTimeout(resolve, 0) + }) + +describe('issue #3928: rapid reloads abort superseded loaders silently', () => { + test('superseded loader AbortErrors never surface as route errors', async () => { + let rootLoaderCalls = 0 + let rootSignal: AbortSignal | undefined + + const indexInvocations = new Map< + string, + { resolve: () => void; signal: AbortSignal } + >() + + const rootRoute = new BaseRootRoute({ + loader: ({ abortController }: { abortController: AbortController }) => { + rootLoaderCalls++ + rootSignal = abortController.signal + return 'root data' + }, + }) + + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + validateSearch: (search: Record) => ({ + filter: typeof search.filter === 'string' ? search.filter : '', + }), + loaderDeps: ({ search }: { search: { filter: string } }) => ({ + filter: search.filter, + }), + loader: ({ + deps, + abortController, + }: { + deps: { filter: string } + abortController: AbortController + }) => + new Promise((resolve, reject) => { + indexInvocations.set(deps.filter, { + resolve: () => resolve(`data:${deps.filter}`), + signal: abortController.signal, + }) + abortController.signal.addEventListener('abort', () => { + const abortError = new Error('signal is aborted without reason') + abortError.name = 'AbortError' + reject(abortError) + }) + }), + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + const initialLoad = router.load() + await vi.waitFor(() => expect(indexInvocations.has('')).toBe(true)) + indexInvocations.get('')!.resolve() + await initialLoad + + expect(rootLoaderCalls).toBe(1) + expect(rootSignal?.aborted).toBe(false) + + // Rapid "keystroke" navigations: each one changes loaderDeps, so each + // starts a new index loader generation and supersedes the previous one. + const nav1 = router.navigate({ to: '/', search: { filter: 'a' } }) + await vi.waitFor(() => expect(indexInvocations.has('a')).toBe(true)) + + const nav2 = router.navigate({ to: '/', search: { filter: 'ab' } }) + await vi.waitFor(() => expect(indexInvocations.has('ab')).toBe(true)) + // The superseded generation's signal is aborted (its fetch is canceled). + await vi.waitFor(() => + expect(indexInvocations.get('a')!.signal.aborted).toBe(true), + ) + + const nav3 = router.navigate({ to: '/', search: { filter: 'abc' } }) + await vi.waitFor(() => expect(indexInvocations.has('abc')).toBe(true)) + await vi.waitFor(() => + expect(indexInvocations.get('ab')!.signal.aborted).toBe(true), + ) + + // Give the aborted generations' rejections time to (incorrectly) commit. + await waitForMacrotask() + await waitForMacrotask() + + for (const match of [ + ...router.state.matches, + ...router.stores.pendingMatches.get(), + ]) { + expect(match.status).not.toBe('error') + expect((match.error as Error | undefined)?.name).not.toBe('AbortError') + } + + indexInvocations.get('abc')!.resolve() + await Promise.all([nav1, nav2, nav3]) + + expect(router.state.location.search).toEqual({ filter: 'abc' }) + + const indexMatch = router.state.matches.find( + (match) => match.routeId === indexRoute.id, + )! + expect(indexMatch.status).toBe('success') + expect(indexMatch.error).toBeUndefined() + expect(indexMatch.loaderData).toBe('data:abc') + + const rootMatch = router.state.matches[0]! + expect(rootMatch.status).toBe('success') + expect(rootMatch.error).toBeUndefined() + expect(rootMatch.loaderData).toBe('root data') + + // The parent stay-match was never re-fetched or aborted by the churn. + expect(rootLoaderCalls).toBe(1) + expect(rootSignal?.aborted).toBe(false) + }) +}) diff --git a/packages/router-core/tests/issue-4112-preload-layout-cache.test.ts b/packages/router-core/tests/issue-4112-preload-layout-cache.test.ts new file mode 100644 index 0000000000..2ef442bf81 --- /dev/null +++ b/packages/router-core/tests/issue-4112-preload-layout-cache.test.ts @@ -0,0 +1,81 @@ +import { expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)) + +/** + * Repro for https://github.com/TanStack/router/issues/4112 + * + * Preloading a route nested under a pathless layout must retain the cached + * layout match between hovers. With a short `defaultStaleTime`, repeated + * hover preloads after staleTime (but within preloadStaleTime) must not + * re-run the layout loader: preload freshness is governed by + * preloadStaleTime, and the cached owned preload matches (layout included) + * must survive between preload passes. + */ +test('repeated hover preloads reuse the cached layout match within preloadStaleTime', async () => { + const layoutLoader = vi.fn(() => 'layout data') + const aboutLoader = vi.fn(() => 'about data') + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const layoutRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + id: '/_layout', + loader: layoutLoader, + }) + const aboutRoute = new BaseRoute({ + getParentRoute: () => layoutRoute, + path: '/about', + loader: aboutLoader, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + layoutRoute.addChildren([aboutRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + // Mirrors the issue's setup: staleTime much shorter than the (default + // 30s) preloadStaleTime. + defaultStaleTime: 10, + }) + + await router.load() + + // First hover + await router.preloadRoute({ to: '/about' } as any) + + expect(layoutLoader).toHaveBeenCalledTimes(1) + expect(aboutLoader).toHaveBeenCalledTimes(1) + + const cachedAfterFirst = router.stores.cachedMatches.get() + expect( + cachedAfterFirst.some((match) => match.routeId === layoutRoute.id), + ).toBe(true) + expect( + cachedAfterFirst.some((match) => match.routeId === aboutRoute.id), + ).toBe(true) + + // Wait past staleTime but well within preloadStaleTime. + await sleep(50) + + // Repeated hovers + await router.preloadRoute({ to: '/about' } as any) + await router.preloadRoute({ to: '/about' } as any) + + // The layout loader must be cached exactly like the leaf loader. + expect(layoutLoader).toHaveBeenCalledTimes(1) + expect(aboutLoader).toHaveBeenCalledTimes(1) + + // The cached layout match is retained across preload passes. + const cachedAfterRepeat = router.stores.cachedMatches.get() + expect( + cachedAfterRepeat.some((match) => match.routeId === layoutRoute.id), + ).toBe(true) +}) diff --git a/packages/router-core/tests/issue-4444-param-parse-error-lazy-child.test.ts b/packages/router-core/tests/issue-4444-param-parse-error-lazy-child.test.ts new file mode 100644 index 0000000000..c4b7db5c1f --- /dev/null +++ b/packages/router-core/tests/issue-4444-param-parse-error-lazy-child.test.ts @@ -0,0 +1,70 @@ +import { describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, PathParamError } from '../src' +import { createTestRouter } from './routerTestUtils' + +/** + * Issue #4444: when a route's params.parse throws and one of its children is + * lazily loaded, the router used to stay "pending" forever: the lazy child's + * chunk was never requested, its match never settled, and framework + * transitioners could never reach idle. + * + * Desired behavior: the param parse error is a serial failure — the failing + * route commits status 'error' for its error boundary, descendants below the + * boundary are trimmed out of the lane with their load promises settled, and + * router.load() resolves with no match left pending. + */ +describe('issue #4444: param parse error on a route with a lazy child', () => { + test('load settles, commits the error boundary, and leaves no match stuck pending', async () => { + const lazyFn = vi.fn(() => + Promise.resolve({ options: { component: () => null } } as any), + ) + + const rootRoute = new BaseRootRoute({}) + const langRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/lang/$lang', + params: { + parse: ({ lang }: { lang: string }) => { + if (lang !== 'en') { + throw new Error(`Unsupported language: ${lang}`) + } + return { lang } + }, + stringify: ({ lang }: { lang: string }) => ({ lang }), + }, + errorComponent: () => null, + }) + const lazyChildRoute = new BaseRoute({ + getParentRoute: () => langRoute, + path: '/lazy', + }).lazy(lazyFn) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + langRoute.addChildren([lazyChildRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/lang/es/lazy'] }), + }) + + // The reported bug: this load never reached a settled render state. + await router.load() + + // The failing route commits the parse error for its error boundary… + const langMatch = router.state.matches.find( + (match) => match.routeId === langRoute.id, + ) + expect(langMatch?.status).toBe('error') + expect(langMatch?.error).toBeInstanceOf(PathParamError) + + // …and the lazy child below the boundary is trimmed out of the lane, so + // nothing is left pending on a chunk that will never load. + expect( + router.state.matches.find((match) => match.routeId === lazyChildRoute.id), + ).toBeUndefined() + expect( + router.state.matches.find((match) => match.status === 'pending'), + ).toBeUndefined() + expect(router.state.isLoading).toBe(false) + }) +}) diff --git a/packages/router-core/tests/issue-4572-preload-root-beforeload-flags.test.ts b/packages/router-core/tests/issue-4572-preload-root-beforeload-flags.test.ts new file mode 100644 index 0000000000..02c4ffd8aa --- /dev/null +++ b/packages/router-core/tests/issue-4572-preload-root-beforeload-flags.test.ts @@ -0,0 +1,59 @@ +import { expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +/** + * Issue #4572: with defaultPreload 'intent', hovering a Link used to + * re-trigger the root's beforeLoad with cause 'enter' and preload false + * (and nested hovers reported 'enter'/false on already-active ancestors). + * + * Desired behavior: + * - Hover-preloading a sibling route does not re-run beforeLoad of + * already-active ancestors: the preload borrows them read-only. + * - The preloaded route's own beforeLoad sees cause 'preload' and + * preload true. + * - Hover-preloading the currently active route runs no beforeLoad at all. + */ + +test('hover preload does not re-run active ancestors and passes correct flags to new matches', async () => { + const rootBeforeLoad = vi.fn() + const aboutBeforeLoad = vi.fn() + + const rootRoute = new BaseRootRoute({ beforeLoad: rootBeforeLoad }) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const aboutRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/about', + beforeLoad: aboutBeforeLoad, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, aboutRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + expect(rootBeforeLoad).toHaveBeenCalledTimes(1) + expect(rootBeforeLoad).toHaveBeenCalledWith( + expect.objectContaining({ cause: 'enter', preload: false }), + ) + + // Hover a sibling route: the active root match is borrowed, its + // beforeLoad must NOT be re-invoked (previously it re-ran with + // cause 'enter' and preload false). + await router.preloadRoute({ to: '/about' } as any) + expect(rootBeforeLoad).toHaveBeenCalledTimes(1) + expect(aboutBeforeLoad).toHaveBeenCalledTimes(1) + expect(aboutBeforeLoad).toHaveBeenCalledWith( + expect.objectContaining({ cause: 'preload', preload: true }), + ) + + // Hover the currently active route: everything is borrowed, nothing runs. + await router.preloadRoute({ to: '/' } as any) + expect(rootBeforeLoad).toHaveBeenCalledTimes(1) + expect(aboutBeforeLoad).toHaveBeenCalledTimes(1) +}) diff --git a/packages/router-core/tests/issue-4614-preload-borrowed-parent-context.test.ts b/packages/router-core/tests/issue-4614-preload-borrowed-parent-context.test.ts new file mode 100644 index 0000000000..9579805844 --- /dev/null +++ b/packages/router-core/tests/issue-4614-preload-borrowed-parent-context.test.ts @@ -0,0 +1,66 @@ +import { expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +/** + * Issue #4614 (selective SSR + intent preload) — unit-level analogue. + * + * After hydration the root match's committed beforeLoad context comes from + * the server run. A hover preload borrows that active root match, so a + * preloaded child's beforeLoad receives the root's committed context and + * the root beforeLoad is NOT re-run by the preload. Only a real navigation + * re-runs the root beforeLoad and refreshes the derived context. + * + * This pins the borrowing semantics: the inconsistency reported in #4614 + * (root re-running with fresh context on hover while the child still saw + * the stale one) cannot happen because borrowed ancestors do not re-run at + * all during preloads. Whether dehydrated beforeLoad context should be + * recomputed client-side for selective-SSR trees is a separate Start + * design question tracked on the issue. + */ + +test('preload borrows the active parent: no beforeLoad re-run, committed context flows to the child', async () => { + let env = 'server' + const seen: Array<{ env: unknown; preload: boolean }> = [] + + const rootBeforeLoad = vi.fn(() => ({ env })) + const rootRoute = new BaseRootRoute({ beforeLoad: rootBeforeLoad }) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const testRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/test', + beforeLoad: ({ context, preload }) => { + seen.push({ env: (context as any).env, preload }) + }, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, testRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + expect(rootBeforeLoad).toHaveBeenCalledTimes(1) + + // The environment feeding the root's beforeLoad changes after the first + // load (in #4614: server -> client across the hydration boundary). + env = 'client' + + // Hover preload: the active root match is borrowed read-only. Its + // beforeLoad must not re-run, and the child consistently receives the + // root's committed context. + await router.preloadRoute({ to: '/test' } as any) + expect(rootBeforeLoad).toHaveBeenCalledTimes(1) + expect(seen).toEqual([{ env: 'server', preload: true }]) + + // A real navigation re-runs the root beforeLoad and refreshes the + // context seen by the child. + await router.navigate({ to: '/test' } as any) + await router.latestLoadPromise + expect(rootBeforeLoad).toHaveBeenCalledTimes(2) + expect(seen[seen.length - 1]).toEqual({ env: 'client', preload: false }) +}) diff --git a/packages/router-core/tests/issue-4684-head-on-beforeload-error.test.ts b/packages/router-core/tests/issue-4684-head-on-beforeload-error.test.ts new file mode 100644 index 0000000000..24d96e5004 --- /dev/null +++ b/packages/router-core/tests/issue-4684-head-on-beforeload-error.test.ts @@ -0,0 +1,86 @@ +import { createMemoryHistory } from '@tanstack/history' +import { describe, expect, test, vi } from 'vitest' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +// https://github.com/TanStack/router/issues/4684 +// +// When beforeLoad throws, head() must still execute for the retained lane — +// the root head owns global stylesheets/title that the errorComponent page +// depends on, and the failing route's own head can provide error-specific +// head content. +describe('issue #4684: head executes when beforeLoad throws', () => { + const setup = (isServer: boolean) => { + const beforeLoadError = new Error('beforeLoad failed') + const rootHead = vi.fn(() => ({ + meta: [{ title: 'Root title' }], + links: [{ rel: 'stylesheet', href: '/global.css' }], + })) + const failingHead = vi.fn(({ match }: any) => ({ + meta: [{ title: match.error ? 'Error title' : 'Success title' }], + })) + + const rootRoute = new BaseRootRoute({ head: rootHead }) + const failingRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/fail', + beforeLoad: () => { + throw beforeLoadError + }, + head: failingHead, + errorComponent: () => 'error', + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([failingRoute]), + history: createMemoryHistory({ initialEntries: ['/fail'] }), + isServer, + }) + + return { router, rootRoute, failingRoute, rootHead, failingHead } + } + + test('server load projects root and failing-route heads for the error lane', async () => { + const { router, rootRoute, failingRoute, rootHead, failingHead } = + setup(true) + + await router.load() + + expect(router.statusCode).toBe(500) + expect(rootHead).toHaveBeenCalledTimes(1) + expect(failingHead).toHaveBeenCalledTimes(1) + + const rootMatch = router.state.matches.find( + (match) => match.routeId === rootRoute.id, + ) + const failingMatch = router.state.matches.find( + (match) => match.routeId === failingRoute.id, + ) + expect(rootMatch?.meta).toEqual([{ title: 'Root title' }]) + expect(rootMatch?.links).toEqual([ + { rel: 'stylesheet', href: '/global.css' }, + ]) + expect(failingMatch?.status).toBe('error') + expect(failingMatch?.meta).toEqual([{ title: 'Error title' }]) + }) + + test('client load projects root and failing-route heads for the error lane', async () => { + const { router, rootRoute, failingRoute, rootHead, failingHead } = + setup(false) + + await router.load() + + expect(rootHead).toHaveBeenCalledTimes(1) + expect(failingHead).toHaveBeenCalledTimes(1) + + const rootMatch = router.state.matches.find( + (match) => match.routeId === rootRoute.id, + ) + const failingMatch = router.state.matches.find( + (match) => match.routeId === failingRoute.id, + ) + expect(rootMatch?.meta).toEqual([{ title: 'Root title' }]) + expect(failingMatch?.status).toBe('error') + expect(failingMatch?.meta).toEqual([{ title: 'Error title' }]) + }) +}) diff --git a/packages/router-core/tests/issue-4696-parent-context-child-search-error.test.ts b/packages/router-core/tests/issue-4696-parent-context-child-search-error.test.ts new file mode 100644 index 0000000000..578aea4e18 --- /dev/null +++ b/packages/router-core/tests/issue-4696-parent-context-child-search-error.test.ts @@ -0,0 +1,113 @@ +import { describe, expect, test } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +/** + * Repro for https://github.com/TanStack/router/issues/4696 + * + * A parent (root) route has `beforeLoad` returning context that its own + * loader depends on. A child route's `validateSearch` throws when required + * search params are missing. Navigating directly to the child without the + * required search params must not prevent the parent's loader from seeing the + * parent's beforeLoad context. + * + * The bug was that the child's search validation error short-circuited the + * serial beforeLoad phase in a way that left ancestor loaders running with a + * context that was missing the ancestors' beforeLoad contributions. + */ + +describe("parent context when child validateSearch fails (issue #4696)", () => { + const setup = () => { + const rootLoaderContexts: Array> = [] + + const rootRoute = new BaseRootRoute({ + beforeLoad: async () => { + await new Promise((resolve) => setTimeout(resolve, 1)) + return { auth: 'authenticated' as const } + }, + loader: ({ context }: { context: Record }) => { + rootLoaderContexts.push(context) + return { navbar: true } + }, + }) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const dashboardRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/dashboard', + validateSearch: (search: Record) => { + if (typeof search.page !== 'number') { + throw new Error('page search param is required') + } + return { page: search.page } + }, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, dashboardRoute]), + history: createMemoryHistory({ initialEntries: ['/dashboard'] }), + }) + + return { router, rootRoute, dashboardRoute, rootLoaderContexts } + } + + test('root loader receives root beforeLoad context when child validateSearch throws on initial load', async () => { + const { router, rootRoute, dashboardRoute, rootLoaderContexts } = setup() + + await router.load() + + // The root loader ran and observed its own beforeLoad context. + expect(rootLoaderContexts).toHaveLength(1) + expect(rootLoaderContexts[0]).toMatchObject({ auth: 'authenticated' }) + + const rootMatch = router.state.matches.find( + (match) => match.routeId === rootRoute.id, + ) + const dashboardMatch = router.state.matches.find( + (match) => match.routeId === dashboardRoute.id, + ) + + // The root still rendered successfully with its loader data (the navbar + // in the original issue) and a fully merged context. + expect(rootMatch?.status).toBe('success') + expect(rootMatch?.loaderData).toEqual({ navbar: true }) + expect(rootMatch?.context).toMatchObject({ auth: 'authenticated' }) + + // The search validation failure is owned by the child match. + expect(dashboardMatch?.status).toBe('error') + expect(dashboardMatch?.error).toBeInstanceOf(Error) + expect((dashboardMatch?.error as Error).message).toBe( + 'page search param is required', + ) + }) + + test('root loader keeps beforeLoad context when navigating from a valid route to the failing child', async () => { + const { router, rootRoute, rootLoaderContexts } = setup() + + await router.load() + rootLoaderContexts.length = 0 + + await router.navigate({ to: '/' }) + await router.navigate({ to: '/dashboard' }) + + // Force the lane to reload while the child sits in its search-error + // state: the root loader must re-run and still see the full beforeLoad + // context. (Stay-match navigations alone do not re-run the root loader, + // which would leave this scenario unexercised.) + await router.invalidate() + + const rootMatch = router.state.matches.find( + (match) => match.routeId === rootRoute.id, + ) + expect(rootMatch?.status).toBe('success') + expect(rootMatch?.context).toMatchObject({ auth: 'authenticated' }) + + expect(rootLoaderContexts.length).toBeGreaterThan(0) + for (const context of rootLoaderContexts) { + expect(context).toMatchObject({ auth: 'authenticated' }) + } + }) +}) diff --git a/packages/router-core/tests/issue-5106-hydrated-notfound-boundary.test.ts b/packages/router-core/tests/issue-5106-hydrated-notfound-boundary.test.ts new file mode 100644 index 0000000000..99cf49c3ab --- /dev/null +++ b/packages/router-core/tests/issue-5106-hydrated-notfound-boundary.test.ts @@ -0,0 +1,220 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, isNotFound } from '../src' +import { hydrate } from '../src/ssr/client' +import { createTestRouter } from './routerTestUtils' +import type { TsrSsrGlobal } from '../src/ssr/types' +import type { Manifest } from '../src/manifest' + +const testManifest: Manifest = { routes: {} } + +// https://github.com/TanStack/router/issues/5106 +// SSR: a child loader throws notFound(). The server commits a notFound-capped +// lane and the client hydrates it. The parent route must not "freeze": every +// hydrated match has to settle (a still-pending loadPromise suspends the +// parent subtree forever in React) and no server loader may re-run client-side. +describe('issue #5106 - hydrating a server-committed notFound boundary', () => { + let mockWindow: { $_TSR?: TsrSsrGlobal } + + beforeEach(() => { + mockWindow = {} + ;(global as any).window = mockWindow + }) + + afterEach(() => { + delete (global as any).window + vi.restoreAllMocks() + }) + + it('child-owned boundary settles all matches without re-running loaders', async () => { + const postsLoader = vi.fn(() => 'posts-data') + const postLoader = vi.fn(() => 'post-data') + const history = createMemoryHistory({ + initialEntries: ['/posts/i-do-not-exist'], + }) + + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + loader: postsLoader, + component: () => 'Posts', + }) + const postRoute = new BaseRoute({ + getParentRoute: () => postsRoute, + path: '/$postId', + loader: postLoader, + component: () => 'Post', + notFoundComponent: () => 'Post not found', + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([postsRoute.addChildren([postRoute])]), + history, + isServer: false, + }) + + const matches = router.matchRoutes(router.stores.location.get()) + expect(matches).toHaveLength(3) + + mockWindow.$_TSR = { + router: { + manifest: testManifest, + dehydratedData: {}, + // The child is its own notFound boundary, so the server lane still + // ends at the child match. + lastMatchId: matches[2]!.id, + matches: [ + { + i: matches[0]!.id, + s: 'success' as const, + ssr: true, + u: Date.now(), + }, + { + i: matches[1]!.id, + s: 'success' as const, + l: 'posts-data', + ssr: true, + u: Date.now(), + }, + { + i: matches[2]!.id, + s: 'notFound' as const, + e: { isNotFound: true }, + ssr: true, + u: Date.now(), + }, + ], + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + initialized: false, + } + + await hydrate(router) + + const stateMatches = router.stores.matches.get() + expect(stateMatches).toHaveLength(3) + + // Parent keeps its server data and status. + expect(stateMatches[1]!.status).toBe('success') + expect(stateMatches[1]!.loaderData).toBe('posts-data') + + // Child hydrated as the notFound boundary. + expect(stateMatches[2]!.status).toBe('notFound') + expect(isNotFound(stateMatches[2]!.error)).toBe(true) + + // No server loader re-ran on the client. + expect(postsLoader).not.toHaveBeenCalled() + expect(postLoader).not.toHaveBeenCalled() + + // Every match settled: an unsettled loadPromise here is the #5106 freeze - + // the framework Match suspends on it and the parent never hydrates. + for (const match of stateMatches) { + expect(match._.dehydrated).toBeUndefined() + expect(match._.loadPromise).toBeUndefined() + } + + // Hydration finished without needing a follow-up router.load(). + expect(router.stores.resolvedLocation.get()).toBeDefined() + expect(router.stores.isLoading.get()).toBe(false) + }) + + it('ancestor boundary replays the dehydrated notFound in the follow-up load instead of loading the omitted child', async () => { + const postsLoader = vi.fn(() => 'posts-data') + const postLoader = vi.fn(() => 'post-data') + const history = createMemoryHistory({ + initialEntries: ['/posts/i-do-not-exist'], + }) + + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + loader: postsLoader, + component: () => 'Posts', + notFoundComponent: () => 'Posts not found', + }) + // The child has no notFoundComponent, so the server selected the parent + // as the boundary and omitted the child match from the dehydrated lane. + const postRoute = new BaseRoute({ + getParentRoute: () => postsRoute, + path: '/$postId', + loader: postLoader, + component: () => 'Post', + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([postsRoute.addChildren([postRoute])]), + history, + isServer: false, + }) + + const matches = router.matchRoutes(router.stores.location.get()) + expect(matches).toHaveLength(3) + + mockWindow.$_TSR = { + router: { + manifest: testManifest, + dehydratedData: {}, + // Server lane was capped at the parent boundary. + lastMatchId: matches[1]!.id, + matches: [ + { + i: matches[0]!.id, + s: 'success' as const, + ssr: true, + u: Date.now(), + }, + { + i: matches[1]!.id, + s: 'notFound' as const, + l: 'posts-data', + e: { isNotFound: true }, + ssr: true, + u: Date.now(), + }, + ], + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + initialized: false, + } + + await hydrate(router) + + // hydrate() schedules a follow-up router.load() for the ssr:false hole + // left by the omitted child. The dehydrated parent boundary must replay + // and cap the lane exactly like the server did. + await vi.waitFor(() => { + expect(router.stores.isLoading.get()).toBe(false) + expect(router.state.matches).toHaveLength(2) + }) + + const stateMatches = router.stores.matches.get() + expect(stateMatches[1]!.routeId).toBe(postsRoute.id) + expect(stateMatches[1]!.status).toBe('notFound') + expect(isNotFound(stateMatches[1]!.error)).toBe(true) + // The boundary keeps the parent's server loader data (the e2e + // parent-boundary spec renders it). + expect(stateMatches[1]!.loaderData).toBe('posts-data') + + // Neither the omitted child nor the dehydrated parent re-ran client-side. + expect(postLoader).not.toHaveBeenCalled() + expect(postsLoader).not.toHaveBeenCalled() + + // The committed lane is fully settled - nothing left for React to + // suspend on (the #5106 freeze). + for (const match of stateMatches) { + expect(match._.dehydrated).toBeUndefined() + expect(match._.loadPromise).toBeUndefined() + } + }) +}) diff --git a/packages/router-core/tests/issue-5778-preload-live-router-context.test.ts b/packages/router-core/tests/issue-5778-preload-live-router-context.test.ts new file mode 100644 index 0000000000..c6be08ce5a --- /dev/null +++ b/packages/router-core/tests/issue-5778-preload-live-router-context.test.ts @@ -0,0 +1,92 @@ +import { expect, test } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +/** + * Issue #5778: updating router.options.context (what RouterProvider's + * `context` prop does via router.update()) is picked up by the next + * navigation's beforeLoad, but an intent preload that borrows the active + * root match still derives descendant context from the root's previously + * committed context — so the preloaded route's beforeLoad sees the + * expired value until the first real navigation. + * + * Desired behavior: a preload derives ancestor context the same way a + * navigation would — live router.options.context merged under the + * ancestors' committed route/beforeLoad contexts. + */ + +function setup() { + const seen: Array = [] + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const authRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + id: '_authenticated', + beforeLoad: ({ context }) => { + seen.push((context as any).foo) + }, + }) + const fooRoute = new BaseRoute({ + getParentRoute: () => authRoute, + path: '/foo', + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + authRoute.addChildren([fooRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + context: { foo: 'old' }, + } as any) + + const updateContext = (foo: string) => { + router.update({ + ...router.options, + context: { ...router.options.context, foo }, + } as any) + } + + return { router, seen, updateContext } +} + +// KNOWN GAP (kept as an expected failure): a preload that borrows the active +// root match derives descendant context from the root's committed context +// snapshot, not live router.options.context. Fixing this means recomputing +// borrowed ancestors' contexts from their stored __routeContext / +// __beforeLoadContext layers — a change to the read-only borrow protocol +// that belongs in a dedicated follow-up, not this PR. The documented +// workaround (router.invalidate() after context changes) is pinned below. +test.fails('preload sees updated router context without an explicit invalidate', async () => { + const { router, seen, updateContext } = setup() + + await router.load() + updateContext('new') + + // Hover intent: the preload borrows the active root match. Its + // committed context must not shadow the live router context that a + // navigation would see. + await router.preloadRoute({ to: '/foo' } as any) + expect(seen).toEqual(['new']) + + // Sanity: a real navigation sees the same value. + await router.navigate({ to: '/foo' } as any) + await router.latestLoadPromise + expect(seen).toEqual(['new', 'new']) +}) + +test('preload sees updated router context after the documented invalidate() pattern', async () => { + const { router, seen, updateContext } = setup() + + await router.load() + updateContext('new') + await router.invalidate() + await router.latestLoadPromise + + await router.preloadRoute({ to: '/foo' } as any) + expect(seen).toEqual(['new']) +}) diff --git a/packages/router-core/tests/issue-6107-preload-chunk-failure.test.ts b/packages/router-core/tests/issue-6107-preload-chunk-failure.test.ts new file mode 100644 index 0000000000..a38b0cbcea --- /dev/null +++ b/packages/router-core/tests/issue-6107-preload-chunk-failure.test.ts @@ -0,0 +1,73 @@ +import { describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +/** + * Issue #6107: going offline and hovering a link (preload intent) made the + * failed dynamic import surface as an unhandled rejection in the console, and + * the error never reached the route's error component. + * + * Desired behavior: + * - a hover preload whose lazy chunk rejects resolves non-fatally and leaves + * no unhandled rejection (only a deliberate dev-only console.error), and + * - the failed chunk is evicted, so the subsequent real navigation retries + * the import and commits the chunk error onto the match (status 'error'), + * which is what framework error components render. + */ +describe('issue #6107: failed dynamic import of a lazy route chunk', () => { + test('hover preload failure is non-fatal and navigation surfaces the chunk error to the error boundary', async () => { + const unhandledRejection = vi.fn() + process.on('unhandledRejection', unhandledRejection) + const consoleError = vi + .spyOn(console, 'error') + .mockImplementation(() => undefined) + try { + const chunkError = new TypeError( + 'Failed to fetch dynamically imported module: /assets/posts.lazy-abc123.js', + ) + let lazyCalls = 0 + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + }).lazy(() => { + lazyCalls++ + return Promise.reject(chunkError) + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([postsRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + await router.load() + + // Hovering a while offline: the preload must resolve without + // throwing and without leaking an unhandled rejection. + await router.preloadRoute({ to: '/posts' }) + await new Promise((resolve) => setTimeout(resolve, 20)) + expect(unhandledRejection).not.toHaveBeenCalled() + // The preload attempted the import at least once (the error path may + // legitimately retry once more for the errorComponent chunk). + expect(lazyCalls).toBeGreaterThanOrEqual(1) + const lazyCallsAfterPreload = lazyCalls + + // Clicking the link: the rejected chunk was evicted (not cached), so + // navigation retries the import; when it fails again the error is + // committed on the match for the error component to render. + await router.navigate({ to: '/posts' }) + const postsMatch = router.state.matches.find( + (match) => match.routeId === postsRoute.id, + ) + // The rejected chunk was not replayed from cache: navigation retried + // the import. + expect(lazyCalls).toBeGreaterThan(lazyCallsAfterPreload) + expect(postsMatch?.status).toBe('error') + expect(postsMatch?.error).toBe(chunkError) + expect(unhandledRejection).not.toHaveBeenCalled() + } finally { + consoleError.mockRestore() + process.off('unhandledRejection', unhandledRejection) + } + }) +}) diff --git a/packages/router-core/tests/issue-6221-head-waits-for-loader.test.ts b/packages/router-core/tests/issue-6221-head-waits-for-loader.test.ts new file mode 100644 index 0000000000..ad9c94e921 --- /dev/null +++ b/packages/router-core/tests/issue-6221-head-waits-for-loader.test.ts @@ -0,0 +1,132 @@ +import { createMemoryHistory } from '@tanstack/history' +import { describe, expect, test, vi } from 'vitest' +import { BaseRootRoute, BaseRoute, notFound } from '../src' +import { createTestRouter } from './routerTestUtils' + +const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)) + +// https://github.com/TanStack/router/issues/6221 +// +// head() must never compute from loaderData older than the data the lane +// commits. Two reported shapes: +// 1. Revisiting a route whose previous visit ended in notFound — the head +// must see the fresh successful loaderData, not run before the loader. +// 2. Revisiting a cached success match that gets a stale reload — the head +// title must not lag one loaderData run behind. +describe('issue #6221: head does not run before loader data is ready', () => { + test('head sees fresh loaderData when a previously-notFound route loads successfully', async () => { + let authed = false + const headLoaderData: Array = [] + + const articleLoader = vi.fn(async () => { + await sleep(5) + if (!authed) throw notFound() + return { title: 'Article 123' } + }) + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const articleRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/article', + loader: articleLoader, + notFoundComponent: () => 'Not found', + head: ({ loaderData }) => { + headLoaderData.push(loaderData) + return { + meta: [{ title: (loaderData as any)?.title ?? 'Generic title' }], + } + }, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, articleRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + + // Logged out: the article loader throws notFound. + await router.navigate({ to: '/article' }) + const notFoundMatch = router.state.matches.find( + (match) => match.routeId === articleRoute.id, + ) + expect(notFoundMatch?.status).toBe('notFound') + + // Log in, go elsewhere, then come back (the issue's back-button step). + authed = true + await router.navigate({ to: '/' }) + await router.navigate({ to: '/article' }) + + await vi.waitFor(() => { + const articleMatch = router.state.matches.find( + (match) => match.routeId === articleRoute.id, + ) + expect(articleMatch?.status).toBe('success') + expect(articleMatch?.meta).toEqual([{ title: 'Article 123' }]) + }) + + // The head executed for the successful lane saw the fresh loaderData. + expect(headLoaderData[headLoaderData.length - 1]).toEqual({ + title: 'Article 123', + }) + }) + + test('head title does not lag one loaderData run behind on revisits', async () => { + let version = 0 + const quoteLoader = vi.fn(async () => { + await sleep(5) + version += 1 + return { author: `author-${version}` } + }) + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const quoteRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/quote', + loader: quoteLoader, + head: ({ loaderData }) => ({ + meta: [ + { title: `Quote by ${(loaderData as any)?.author ?? '...'}` }, + ], + }), + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, quoteRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + + await router.navigate({ to: '/quote' }) + await vi.waitFor(() => { + const quoteMatch = router.state.matches.find( + (match) => match.routeId === quoteRoute.id, + ) + expect(quoteMatch?.meta).toEqual([{ title: 'Quote by author-1' }]) + }) + + await router.navigate({ to: '/' }) + await router.navigate({ to: '/quote' }) + + // The revisit reloads the stale match. Whether that reload is foreground + // or background, the committed head must reflect the loaderData it was + // committed with — never the previous run's data. + await vi.waitFor(() => { + expect(quoteLoader).toHaveBeenCalledTimes(2) + const quoteMatch = router.state.matches.find( + (match) => match.routeId === quoteRoute.id, + ) + expect(quoteMatch?.loaderData).toEqual({ author: 'author-2' }) + expect(quoteMatch?.meta).toEqual([{ title: 'Quote by author-2' }]) + }) + }) +}) diff --git a/packages/router-core/tests/issue-6371-search-default-normalization-abort.test.ts b/packages/router-core/tests/issue-6371-search-default-normalization-abort.test.ts new file mode 100644 index 0000000000..4513c2d912 --- /dev/null +++ b/packages/router-core/tests/issue-6371-search-default-normalization-abort.test.ts @@ -0,0 +1,112 @@ +import { describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, trimPathRight } from '../src' +import { createTestRouter } from './routerTestUtils' + +/** + * Repro for https://github.com/TanStack/router/issues/6371 + * + * Entering a route directly via URL without search params, while + * validateSearch supplies defaults, makes the framework Transitioner commit a + * canonical replace-navigation (URL with the defaulted search) right after + * the mount load already started. That replace supersedes the first load + * pass and aborts its match's abortController. A loader that forwarded that + * signal to fetch() re-throws an AbortError ("signal is aborted without + * reason"): it belongs to the abandoned pass and must not surface as a route + * error; the follow-up canonical load must complete normally. + */ + +const waitForMacrotask = () => + new Promise((resolve) => { + setTimeout(resolve, 0) + }) + +describe('issue #6371: search default normalization aborts the mount load silently', () => { + test('canonical replace after validateSearch defaults does not surface AbortError', async () => { + const invocations: Array<{ resolve: () => void; signal: AbortSignal }> = [] + + const rootRoute = new BaseRootRoute({}) + const aboutRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/about', + validateSearch: (search: Record) => ({ + page: typeof search.page === 'number' ? search.page : 1, + }), + loader: ({ abortController }: { abortController: AbortController }) => + new Promise((resolve, reject) => { + invocations.push({ + resolve: () => resolve('about data'), + signal: abortController.signal, + }) + abortController.signal.addEventListener('abort', () => { + const abortError = new Error('signal is aborted without reason') + abortError.name = 'AbortError' + reject(abortError) + }) + }), + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([aboutRoute]), + history: createMemoryHistory({ initialEntries: ['/about'] }), + }) + + // Mount load for the raw URL (no search params in the href yet). + const initialLoad = router.load() + await vi.waitFor(() => expect(invocations.length).toBe(1)) + + // What the framework Transitioner does on mount: rebuild the canonical + // location with validated search and replace if the public href differs. + const nextLocation = router.buildLocation({ + to: router.latestLocation.pathname, + search: true, + params: true, + hash: true, + state: true, + _includeValidateSearch: true, + } as any) + + expect(nextLocation.publicHref).toContain('page=1') + expect(trimPathRight(router.latestLocation.publicHref)).not.toBe( + trimPathRight(nextLocation.publicHref), + ) + + // In core (no history subscribers) commitLocation starts the second load. + void router.commitLocation({ ...nextLocation, replace: true } as any) + + await vi.waitFor(() => expect(invocations.length).toBe(2)) + + // The superseded mount-load generation was aborted (its fetch canceled). + expect(invocations[0]!.signal.aborted).toBe(true) + + // Give the aborted rejection time to (incorrectly) commit as an error. + await waitForMacrotask() + await waitForMacrotask() + + for (const match of [ + ...router.state.matches, + ...router.stores.pendingMatches.get(), + ]) { + expect(match.status).not.toBe('error') + expect((match.error as Error | undefined)?.name).not.toBe('AbortError') + } + + invocations[1]!.resolve() + // Awaiting the superseded mount load also awaits the superseding chain. + await initialLoad + + // No runaway normalization loop: exactly one aborted + one canonical run. + expect(invocations.length).toBe(2) + + const aboutMatch = router.state.matches.find( + (match) => match.routeId === aboutRoute.id, + )! + expect(aboutMatch.status).toBe('success') + expect(aboutMatch.error).toBeUndefined() + expect(aboutMatch.loaderData).toBe('about data') + expect(aboutMatch.search).toEqual({ page: 1 }) + + expect(router.state.location.search).toEqual({ page: 1 }) + expect(router.latestLocation.publicHref).toContain('page=1') + }) +}) diff --git a/packages/router-core/tests/issue-6645-load-route-chunk-rejection.test.ts b/packages/router-core/tests/issue-6645-load-route-chunk-rejection.test.ts new file mode 100644 index 0000000000..a93b4763a9 --- /dev/null +++ b/packages/router-core/tests/issue-6645-load-route-chunk-rejection.test.ts @@ -0,0 +1,71 @@ +import { describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +/** + * Port of the essential test from PR #6645: a rejected route lazy chunk + * (e.g. network error or stale chunk after a deploy) must not leak an + * unhandled promise rejection from loadRouteChunk's internal promise + * bookkeeping (Sentry noise), and must be evicted so a later pass can retry + * the import. + * + * Adapted to this branch's semantics: loadRouteChunk propagates the + * rejection to its awaiting caller (who normalizes it through the route + * failure lifecycle) instead of swallowing it. + */ +describe('loadRouteChunk lazy chunk rejection (PR #6645 port)', () => { + test('rejected lazyFn is observed internally, evicted, and retryable', async () => { + const unhandledRejection = vi.fn() + process.on('unhandledRejection', unhandledRejection) + try { + const chunkError = new TypeError( + 'Failed to fetch dynamically imported module: /assets/foo.lazy-abc123.js', + ) + let lazyCalls = 0 + const fooComponent = () => null + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + }).lazy(() => { + lazyCalls++ + if (lazyCalls === 1) { + return Promise.reject(chunkError) + } + return Promise.resolve({ options: { component: fooComponent } } as any) + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + // The rejection reaches the awaiting caller (route failure lifecycle + // territory during real navigations)… + await expect(router.loadRouteChunk(fooRoute as any)).rejects.toBe( + chunkError, + ) + + // …while the internal cached promise chain observes it, so nothing + // escapes to the global unhandledrejection channel. + await new Promise((resolve) => setTimeout(resolve, 20)) + expect(unhandledRejection).not.toHaveBeenCalled() + + // The failed chunk is evicted, not poisoned forever. + expect((fooRoute as any)._lazyPromise).toBeUndefined() + expect((fooRoute as any)._lazyLoaded).toBeFalsy() + expect((fooRoute as any)._componentsLoaded).toBeFalsy() + + // A later pass retries the import and succeeds. + await router.loadRouteChunk(fooRoute as any) + expect(lazyCalls).toBe(2) + expect((fooRoute as any)._lazyLoaded).toBe(true) + expect((fooRoute as any)._componentsLoaded).toBe(true) + expect(fooRoute.options.component).toBe(fooComponent) + expect(unhandledRejection).not.toHaveBeenCalled() + } finally { + process.off('unhandledRejection', unhandledRejection) + } + }) +}) diff --git a/packages/router-core/tests/issue-7003-cache-eviction-during-preload.test.ts b/packages/router-core/tests/issue-7003-cache-eviction-during-preload.test.ts new file mode 100644 index 0000000000..44b1a7b96d --- /dev/null +++ b/packages/router-core/tests/issue-7003-cache-eviction-during-preload.test.ts @@ -0,0 +1,147 @@ +import { expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +/** + * Adapted from the regression tests donated by + * https://github.com/TanStack/router/pull/7003 (and its alternative + * https://github.com/TanStack/router/pull/7006). + * + * On the old architecture, an in-flight preload lived inside + * `cachedMatches`, so cache eviction (`clearExpiredCache`) or + * `router.invalidate()` while the preload was still loading could rip the + * match out from under `loadRouteMatch`, producing `_nonReactive` crashes + * and console errors. + * + * On this branch, pending preload work is private to the preload lane and + * must never appear in `cachedMatches` until it has succeeded. Cache + * clearing and invalidation while a preload is in flight must not crash, + * must not log errors, and the preload must still complete and cache its + * successful result. + */ + +function setup() { + let resolveFooLoader: ((value: string) => void) | undefined + const fooLoader = vi.fn( + () => + new Promise((resolve) => { + resolveFooLoader = resolve + }), + ) + const barLoader = vi.fn(() => 'bar data') + + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader: fooLoader, + }) + const barRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/bar', + loader: barLoader, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute, barRoute]), + history: createMemoryHistory({ initialEntries: ['/bar'] }), + }) + + return { + router, + fooRoute, + barRoute, + fooLoader, + barLoader, + getResolveFooLoader: () => resolveFooLoader, + } +} + +test('clearCache during an in-flight preload does not crash and the preload still completes', async () => { + const consoleErrorSpy = vi + .spyOn(console, 'error') + .mockImplementation(() => {}) + + try { + const { router, fooRoute, getResolveFooLoader } = setup() + + await router.load() + + const preloadPromise = router.preloadRoute({ to: '/foo' } as any) + await Promise.resolve() + + // New invariant: pending preload work is private and must not be + // observable in the public cache while the loader is in flight. + expect( + router.stores.cachedMatches + .get() + .some((match) => match.routeId === fooRoute.id), + ).toBe(false) + + // Explicit cache cleanup while the preload is still loading. + router.clearCache() + + getResolveFooLoader()?.('foo data') + + const preloaded = await preloadPromise + + // The preload completed and cached its owned successful match. + expect(preloaded?.some((match) => match.routeId === fooRoute.id)).toBe( + true, + ) + expect( + router.stores.cachedMatches + .get() + .some( + (match) => + match.routeId === fooRoute.id && match.status === 'success', + ), + ).toBe(true) + expect(consoleErrorSpy).not.toHaveBeenCalled() + } finally { + consoleErrorSpy.mockRestore() + } +}) + +test('invalidate during an in-flight preload does not crash and both loads settle', async () => { + const consoleErrorSpy = vi + .spyOn(console, 'error') + .mockImplementation(() => {}) + + try { + const { router, fooRoute, barLoader, getResolveFooLoader } = setup() + + await router.load() + expect(barLoader).toHaveBeenCalledTimes(1) + + const preloadPromise = router.preloadRoute({ to: '/foo' } as any) + await Promise.resolve() + + const invalidatePromise = router.invalidate() + await Promise.resolve() + + getResolveFooLoader()?.('foo data') + + const [preloaded] = await Promise.all([preloadPromise, invalidatePromise]) + + // The active route reloaded due to invalidation. + expect(barLoader).toHaveBeenCalledTimes(2) + + // The preload still settled cleanly and cached its result. + expect(preloaded?.some((match) => match.routeId === fooRoute.id)).toBe( + true, + ) + expect( + router.stores.cachedMatches + .get() + .some( + (match) => + match.routeId === fooRoute.id && match.status === 'success', + ), + ).toBe(true) + expect(consoleErrorSpy).not.toHaveBeenCalled() + } finally { + consoleErrorSpy.mockRestore() + } +}) diff --git a/packages/router-core/tests/issue-7110-beforeload-null-context.test.ts b/packages/router-core/tests/issue-7110-beforeload-null-context.test.ts new file mode 100644 index 0000000000..7d8ceede2f --- /dev/null +++ b/packages/router-core/tests/issue-7110-beforeload-null-context.test.ts @@ -0,0 +1,123 @@ +import { describe, expect, test } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +/** + * Pins the behavior discussed in + * https://github.com/TanStack/router/issues/7110 and + * https://github.com/TanStack/router/pull/7114 + * + * `beforeLoad` returning `null` (e.g. a server function that resolves to + * null) must behave like returning `undefined` for context purposes: the + * merged route context keeps all parent/router-provided values and no `null` + * leaks into or clobbers the merged context object. + */ + +describe('beforeLoad returning null keeps merged context intact (issue #7110 / PR #7114)', () => { + const setup = (beforeLoad: () => any) => { + const loaderContexts: Array> = [] + + const rootRoute = new BaseRootRoute({ + beforeLoad, + }) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + loader: ({ context }: { context: Record }) => { + loaderContexts.push(context) + return null + }, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + context: { foo: 'bar' }, + }) + + return { router, rootRoute, indexRoute, loaderContexts } + } + + test('sync beforeLoad returning null preserves router-provided context', async () => { + const { router, rootRoute, indexRoute, loaderContexts } = setup(() => null) + + await router.load() + + const rootMatch = router.state.matches.find( + (match) => match.routeId === rootRoute.id, + ) + const indexMatch = router.state.matches.find( + (match) => match.routeId === indexRoute.id, + ) + + expect(rootMatch?.status).toBe('success') + expect(rootMatch?.context).toEqual({ foo: 'bar' }) + expect(indexMatch?.context).toEqual({ foo: 'bar' }) + + // The child loader saw the merged context, not `{}` or `null`. + expect(loaderContexts).toHaveLength(1) + expect(loaderContexts[0]).toEqual({ foo: 'bar' }) + }) + + test('async beforeLoad returning null preserves router-provided context', async () => { + const { router, rootRoute, indexRoute, loaderContexts } = setup( + async () => { + await new Promise((resolve) => setTimeout(resolve, 1)) + return null + }, + ) + + await router.load() + + const rootMatch = router.state.matches.find( + (match) => match.routeId === rootRoute.id, + ) + const indexMatch = router.state.matches.find( + (match) => match.routeId === indexRoute.id, + ) + + expect(rootMatch?.status).toBe('success') + expect(rootMatch?.context).toEqual({ foo: 'bar' }) + expect(indexMatch?.context).toEqual({ foo: 'bar' }) + expect(loaderContexts).toHaveLength(1) + expect(loaderContexts[0]).toEqual({ foo: 'bar' }) + }) + + test('beforeLoad returning null does not clobber route context() contributions', async () => { + const loaderContexts: Array> = [] + + const rootRoute = new BaseRootRoute({ + context: () => ({ fromRouteContext: 'yes' }), + beforeLoad: () => null, + }) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + loader: ({ context }: { context: Record }) => { + loaderContexts.push(context) + return null + }, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + context: { foo: 'bar' }, + }) + + await router.load() + + const rootMatch = router.state.matches.find( + (match) => match.routeId === rootRoute.id, + ) + expect(rootMatch?.context).toEqual({ + foo: 'bar', + fromRouteContext: 'yes', + }) + expect(loaderContexts[0]).toEqual({ + foo: 'bar', + fromRouteContext: 'yes', + }) + }) +}) diff --git a/packages/router-core/tests/issue-7379-head-matches-direct-load.test.ts b/packages/router-core/tests/issue-7379-head-matches-direct-load.test.ts new file mode 100644 index 0000000000..9eafcea725 --- /dev/null +++ b/packages/router-core/tests/issue-7379-head-matches-direct-load.test.ts @@ -0,0 +1,83 @@ +import { createMemoryHistory } from '@tanstack/history' +import { describe, expect, test } from 'vitest' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)) + +// https://github.com/TanStack/router/issues/7379 +// +// On a direct (initial) load, head({ matches }) must observe loaderData and +// context on every ancestor match so a breadcrumb-style title can be built. +describe('issue #7379: head({ matches }) has loaderData and context on direct load', () => { + test('initial load executes head after loaders with populated matches', async () => { + const seenMatches: Array< + Array<{ routeId: string; loaderData: unknown; context: unknown }> + > = [] + + const rootRoute = new BaseRootRoute({}) + const nestedRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/nested', + beforeLoad: async () => { + await sleep(5) + return { section: 'nested-section' } + }, + loader: async () => { + await sleep(5) + return { crumb: 'Nested' } + }, + }) + const evenRoute = new BaseRoute({ + getParentRoute: () => nestedRoute, + path: 'even', + loader: async () => { + await sleep(5) + return { crumb: 'Even' } + }, + head: ({ matches }) => { + seenMatches.push( + matches.map((match: any) => ({ + routeId: match.routeId, + loaderData: match.loaderData, + context: match.context, + })), + ) + const crumbs = matches + .map((match: any) => match.loaderData?.crumb) + .filter(Boolean) + return { + meta: [{ title: [...crumbs, 'Company Inc.'].join(' - ') }], + } + }, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([nestedRoute.addChildren([evenRoute])]), + history: createMemoryHistory({ initialEntries: ['/nested/even'] }), + }) + + // Direct load: this is the first and only load of the router. + await router.load() + + expect(seenMatches).toHaveLength(1) + const seen = seenMatches[0]! + + const seenNested = seen.find((entry) => entry.routeId === nestedRoute.id) + const seenEven = seen.find((entry) => entry.routeId === evenRoute.id) + + // loaderData is present on every match handed to head(). + expect(seenNested?.loaderData).toEqual({ crumb: 'Nested' }) + expect(seenEven?.loaderData).toEqual({ crumb: 'Even' }) + + // context (incl. beforeLoad context) is present as well. + expect(seenNested?.context).toMatchObject({ section: 'nested-section' }) + expect(seenEven?.context).toMatchObject({ section: 'nested-section' }) + + // The breadcrumb title is complete on the committed match. + const evenMatch = router.state.matches.find( + (match) => match.routeId === evenRoute.id, + ) + expect(evenMatch?.meta).toEqual([{ title: 'Nested - Even - Company Inc.' }]) + }) +}) diff --git a/packages/router-core/tests/issue-7602-parent-beforeload-context-child-loader.test.ts b/packages/router-core/tests/issue-7602-parent-beforeload-context-child-loader.test.ts new file mode 100644 index 0000000000..a82f1e3aed --- /dev/null +++ b/packages/router-core/tests/issue-7602-parent-beforeload-context-child-loader.test.ts @@ -0,0 +1,123 @@ +import { describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, createControlledPromise } from '../src' +import { createTestRouter } from './routerTestUtils' + +/** + * Repro for https://github.com/TanStack/router/issues/7602 + * + * A parent route's async `beforeLoad` returns context that a child route's + * loader (and the child's published match) depend on. On a return navigation + * the child match is reused from cache with `status: 'success'` and its stale + * loader reload runs in the background. The bug was that the reused child was + * published with a context that did not yet include the parent's fresh + * beforeLoad contribution, so readers observed `context.number === undefined` + * while the child loader was still executing. + * + * Desired behavior: whenever the child match is published, its `context` + * already carries the parent's beforeLoad context, and every child loader + * invocation observes that context too. + */ + +describe('parent beforeLoad context propagation to child (issue #7602)', () => { + const setup = () => { + const loaderContextNumbers: Array = [] + let loaderRuns = 0 + const secondLoaderGate = createControlledPromise() + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const reproRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/repro', + beforeLoad: async () => { + // Async so there is a real window between match creation and the + // beforeLoad context becoming available. + await new Promise((resolve) => setTimeout(resolve, 1)) + return { number: 42 } + }, + }) + const reproIndexRoute = new BaseRoute({ + getParentRoute: () => reproRoute, + path: '/', + loader: async ({ context }: { context: { number?: number } }) => { + loaderRuns += 1 + loaderContextNumbers.push(context.number) + if (loaderRuns > 1) { + // Keep the return-navigation reload in flight so the test can + // observe the published child match while its loader is executing. + await secondLoaderGate + } + return { visit: loaderRuns } + }, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + reproRoute.addChildren([reproIndexRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/repro'] }), + }) + + return { + router, + reproIndexRoute, + loaderContextNumbers, + secondLoaderGate, + getChildMatch: () => + router.state.matches.find( + (match) => match.routeId === reproIndexRoute.id, + ), + } + } + + test('child loader sees parent beforeLoad context on first visit', async () => { + const { router, loaderContextNumbers, getChildMatch } = setup() + + await router.load() + + expect(loaderContextNumbers).toEqual([42]) + expect(getChildMatch()?.context).toMatchObject({ number: 42 }) + }) + + test('reused child match is republished with fresh parent beforeLoad context while its reload is still running', async () => { + const { + router, + loaderContextNumbers, + secondLoaderGate, + getChildMatch, + } = setup() + + await router.load() + expect(loaderContextNumbers).toEqual([42]) + + // Leave /repro (child match with a loader is cached), then come back. + await router.navigate({ to: '/' }) + expect(getChildMatch()).toBeUndefined() + + await router.navigate({ to: '/repro' }) + + // The child match was reused from cache as a success match and its stale + // reload is non-blocking, so the navigation commits while the second + // loader invocation is still pending behind the gate. + const childAfterCommit = getChildMatch() + expect(childAfterCommit?.status).toBe('success') + + // Desired behavior from the issue: the republished child must immediately + // carry the parent's beforeLoad context — never `undefined`. + expect(childAfterCommit?.context).toMatchObject({ number: 42 }) + + // The in-flight reload also observed the fresh parent context. + await vi.waitFor(() => expect(loaderContextNumbers).toHaveLength(2)) + expect(loaderContextNumbers).toEqual([42, 42]) + + secondLoaderGate.resolve() + await vi.waitFor(() => expect(getChildMatch()?.isFetching).toBe(false)) + + expect(getChildMatch()?.context).toMatchObject({ number: 42 }) + }) +}) diff --git a/packages/router-core/tests/issue-7635-dehydrated-error-child-head.test.ts b/packages/router-core/tests/issue-7635-dehydrated-error-child-head.test.ts new file mode 100644 index 0000000000..25b7644123 --- /dev/null +++ b/packages/router-core/tests/issue-7635-dehydrated-error-child-head.test.ts @@ -0,0 +1,124 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { hydrate } from '../src/ssr/client' +import { createTestRouter } from './routerTestUtils' +import type { TsrSsrGlobal } from '../src/ssr/types' +import type { Manifest } from '../src/manifest' + +const testManifest: Manifest = { routes: {} } + +// https://github.com/TanStack/router/issues/7635 +// +// Server: `_app.beforeLoad` throws, so the server lane is capped at +// [__root, _app(error)] and the SSR document title is the error title. +// Client: hydration matches the full branch [__root, _app, child]. The +// follow-up client load must replay the dehydrated error boundary instead of +// loading the child and executing its head — otherwise the child head +// overwrites the error document title on the client. +describe('issue #7635: dehydrated parent beforeLoad error caps child head', () => { + let mockWindow: { $_TSR?: TsrSsrGlobal } + + beforeEach(() => { + mockWindow = {} + ;(global as any).window = mockWindow + }) + + afterEach(() => { + vi.restoreAllMocks() + delete (global as any).window + }) + + it('does not run child loader/head after hydrating a server error boundary', async () => { + const serverError = new Error('App beforeLoad failed') + const appHead = vi.fn(({ match }: any) => ({ + meta: [ + { title: match.error ? 'App error title' : 'App success title' }, + ], + })) + const childHead = vi.fn(() => ({ + meta: [{ title: 'Child success title' }], + })) + const childLoader = vi.fn(() => ({ child: 'data' })) + + const rootRoute = new BaseRootRoute({}) + const appRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/app', + head: appHead, + errorComponent: () => 'App error', + }) + const childRoute = new BaseRoute({ + getParentRoute: () => appRoute, + path: '/child', + loader: childLoader, + head: childHead, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([appRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/app/child'] }), + isServer: false, + }) + + // The dehydrated payload only contains what the server rendered: + // the root and the _app error boundary. The child match is absent. + const matches = router.matchRoutes(router.stores.location.get()) + const rootMatch = matches[0]! + const appMatch = matches[1]! + + mockWindow.$_TSR = { + router: { + manifest: testManifest, + dehydratedData: {}, + lastMatchId: appMatch.id, + matches: [ + { + i: rootMatch.id, + s: 'success' as const, + ssr: true, + u: Date.now(), + }, + { + i: appMatch.id, + s: 'error' as const, + e: serverError, + ssr: true, + u: Date.now(), + }, + ], + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + initialized: false, + } + + await hydrate(router) + + // The follow-up client load must cap the lane at the server error + // boundary exactly like the server did. + await vi.waitFor(() => { + expect(router.state.matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + appRoute.id, + ]) + }) + + const committedApp = router.state.matches.find( + (match) => match.routeId === appRoute.id, + ) + expect(committedApp?.status).toBe('error') + + // The child was never rendered by the server; its loader and head must + // not run on the client either. + expect(childLoader).not.toHaveBeenCalled() + expect(childHead).not.toHaveBeenCalled() + + // The error boundary head owns the document title. + expect(appHead).toHaveBeenCalled() + expect(committedApp?.meta).toEqual([{ title: 'App error title' }]) + }) +}) From 39e8fe573b645e135542b1da1583a7797d142121 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Sat, 4 Jul 2026 11:20:13 +0200 Subject: [PATCH 25/54] fix(solid-router): render hydration display pending through the shared ClientOnly slot MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The outer _displayPending branch made the hydrating client render the pending fallback at a different structural depth than the server (which renders it through ClientOnly's fallback), so Solid's dev runtime threw 'Hydration Mismatch' and cascaded into 'template is not a function' via the root CatchBoundary — dev-mode-only because prod silently falls back to client rendering. This regressed data-only+pendingComponent routes vs main and was also the mechanism behind the pre-existing #7283 (ssr:false+pendingComponent, broken on main too). _displayPending now renders inside MatchInner, which only mounts after ClientOnly hydrates — outside the hydration key sequence — fixing both cases. Adds a dev-server e2e spec covering both. Fixes #7283 Co-Authored-By: Claude Fable 5 --- .../tests/issue-7283-dev-hydration.spec.ts | 122 ++++++++++++++++++ packages/solid-router/src/Match.tsx | 16 ++- 2 files changed, 135 insertions(+), 3 deletions(-) create mode 100644 e2e/solid-start/selective-ssr/tests/issue-7283-dev-hydration.spec.ts diff --git a/e2e/solid-start/selective-ssr/tests/issue-7283-dev-hydration.spec.ts b/e2e/solid-start/selective-ssr/tests/issue-7283-dev-hydration.spec.ts new file mode 100644 index 0000000000..817467a0e2 --- /dev/null +++ b/e2e/solid-start/selective-ssr/tests/issue-7283-dev-hydration.spec.ts @@ -0,0 +1,122 @@ +import { spawn } from 'node:child_process' +import path from 'node:path' +import { expect, test } from '@playwright/test' +import type { ChildProcess } from 'node:child_process' +import type { Page } from '@playwright/test' + +// Regression test for https://github.com/TanStack/router/issues/7283 +// +// Selective SSR routes (`ssr: false` / `ssr: 'data-only'`) that declare a +// `pendingComponent` must hydrate cleanly in DEV mode. Solid only validates +// hydration markers in dev, so the production webServer configured in +// playwright.config.ts masks the mismatch ("template is not a function", +// route never reaches its loaded component). This spec therefore boots its +// own `vite dev` server on a dedicated port and drives the app against it. + +const DEV_PORT = 58283 +const devBaseURL = `http://localhost:${DEV_PORT}` + +let devServer: ChildProcess | undefined + +async function waitForServer(url: string, timeoutMs: number) { + const deadline = Date.now() + timeoutMs + let lastError: unknown + while (Date.now() < deadline) { + try { + const res = await fetch(url) + if (res.ok) return + } catch (err) { + lastError = err + } + await new Promise((resolve) => setTimeout(resolve, 1000)) + } + throw new Error(`dev server did not start on ${url}: ${lastError}`) +} + +test.beforeAll(async () => { + const appDir = path.resolve(import.meta.dirname, '..') + devServer = spawn( + 'pnpm', + [ + 'dev:e2e', + '--host', + 'localhost', + '--port', + String(DEV_PORT), + '--strictPort', + ], + { + cwd: appDir, + env: { + ...process.env, + VITE_SERVER_PORT: String(DEV_PORT), + NODE_ENV: 'development', + }, + stdio: 'ignore', + detached: true, + }, + ) + await waitForServer(`${devBaseURL}/`, 90_000) +}) + +test.afterAll(() => { + if (devServer?.pid) { + try { + process.kill(-devServer.pid, 'SIGTERM') + } catch { + // already gone + } + } +}) + +function collectHydrationFailures(page: Page) { + const failures: Array = [] + const isHydrationFailure = (text: string) => + text.includes('template is not a function') || + text.includes("wasn't caught by any route") || + text.includes('Hydration Mismatch') + page.on('pageerror', (err) => { + if (isHydrationFailure(err.message)) failures.push(err.message) + }) + page.on('console', (msg) => { + if (msg.type() === 'error' || msg.type() === 'warning') { + const text = msg.text() + if (isHydrationFailure(text)) failures.push(text) + } + }) + return failures +} + +test.describe('dev-mode hydration of selective SSR routes with pendingComponent', () => { + test.setTimeout(120_000) + + test('ssr:false route with pendingComponent hydrates cleanly and reaches its loaded component (issue #7283)', async ({ + page, + }) => { + const failures = collectHydrationFailures(page) + + await page.goto(`${devBaseURL}/ssr-false-pending-min`) + + // The loaded component must eventually replace the pending UI. + await expect(page.getByTestId('ssr-false-target')).toBeVisible({ + timeout: 15_000, + }) + + // No dev hydration mismatch may occur along the way. + expect(failures).toEqual([]) + }) + + test('data-only route with pendingComponent hydrates cleanly and reaches its loaded component (regression vs main)', async ({ + page, + }) => { + const failures = collectHydrationFailures(page) + + await page.goto(`${devBaseURL}/data-only-pending-component`) + + await expect( + page.getByTestId('data-only-pending-component-ready-label'), + ).toHaveText('OK - loader finished', { timeout: 15_000 }) + + expect(failures).toEqual([]) + }) +}) diff --git a/packages/solid-router/src/Match.tsx b/packages/solid-router/src/Match.tsx index 4350a6fcc2..e256f9cf57 100644 --- a/packages/solid-router/src/Match.tsx +++ b/packages/solid-router/src/Match.tsx @@ -164,9 +164,6 @@ export const Match = (props: { matchId: string }) => { }} > - - - { id: currentMatch.id, status: currentMatch.status, error: currentMatch.error, + _displayPending: currentMatch._displayPending, _: currentMatch._, }, } @@ -319,6 +317,18 @@ export const MatchInner = (): any => { return ( + + {(_) => { + // Hydration display match: its loadPromise was settled by + // hydrate(), so the normal pending branch must not run. + // MatchInner only mounts after ClientOnly hydrated, so this + // renders outside the hydration key sequence. + const FallbackComponent = PendingComponent() + return FallbackComponent ? ( + + ) : null + }} + {(_) => { const loadPromise = currentMatch()._.loadPromise From 3ebb72e254f657667f70a464fb41ac677ffa4aa2 Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Sat, 4 Jul 2026 09:24:36 +0000 Subject: [PATCH 26/54] ci: apply automated fixes --- ...-7638-invalidate-transition-error.test.tsx | 12 +++---- ...e-2980-active-layout-hover-preload.test.ts | 6 ++-- ...-parent-context-child-search-error.test.ts | 2 +- ...e-5778-preload-live-router-context.test.ts | 31 ++++++++++--------- .../issue-6221-head-waits-for-loader.test.ts | 4 +-- ...7003-cache-eviction-during-preload.test.ts | 8 ++--- ...nt-beforeload-context-child-loader.test.ts | 8 ++--- ...e-7635-dehydrated-error-child-head.test.ts | 4 +-- 8 files changed, 32 insertions(+), 43 deletions(-) diff --git a/packages/react-router/tests/issue-7638-invalidate-transition-error.test.tsx b/packages/react-router/tests/issue-7638-invalidate-transition-error.test.tsx index 6b07664ad3..d27492e81b 100644 --- a/packages/react-router/tests/issue-7638-invalidate-transition-error.test.tsx +++ b/packages/react-router/tests/issue-7638-invalidate-transition-error.test.tsx @@ -77,14 +77,14 @@ function setup({ failVia }: { failVia: 'render' | 'loader' }) { let errorRenders = 0 const router = createRouter({ - routeTree: rootRoute.addChildren([ - testRoute.addChildren([testIndexRoute]), - ]), + routeTree: rootRoute.addChildren([testRoute.addChildren([testIndexRoute])]), history: createMemoryHistory({ initialEntries: ['/test'] }), defaultErrorComponent: (props: ErrorComponentProps) => { errorRenders++ return ( -
error: {(props.error as Error).message}
+
+ error: {(props.error as Error).message} +
) }, }) @@ -98,9 +98,7 @@ test.each(['render', 'loader'] as const)( // Error boundaries log caught errors through console.error, and so does a // hooks-order crash. Capture instead of polluting the test output, then // inspect the captured calls for the crash signature. - const consoleError = vi - .spyOn(console, 'error') - .mockImplementation(() => {}) + const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}) const { router, childLoader, getErrorRenders } = setup({ failVia }) render() diff --git a/packages/router-core/tests/issue-2980-active-layout-hover-preload.test.ts b/packages/router-core/tests/issue-2980-active-layout-hover-preload.test.ts index f2d11740a5..667c3b9fd6 100644 --- a/packages/router-core/tests/issue-2980-active-layout-hover-preload.test.ts +++ b/packages/router-core/tests/issue-2980-active-layout-hover-preload.test.ts @@ -67,7 +67,7 @@ test('hover preloads of child routes do not re-run the active stale layout loade // The active layout match is still the rendered success match. const active = router.stores.matches.get() - expect( - active.find((match) => match.routeId === postsRoute.id)?.status, - ).toBe('success') + expect(active.find((match) => match.routeId === postsRoute.id)?.status).toBe( + 'success', + ) }) diff --git a/packages/router-core/tests/issue-4696-parent-context-child-search-error.test.ts b/packages/router-core/tests/issue-4696-parent-context-child-search-error.test.ts index 578aea4e18..608e836bbe 100644 --- a/packages/router-core/tests/issue-4696-parent-context-child-search-error.test.ts +++ b/packages/router-core/tests/issue-4696-parent-context-child-search-error.test.ts @@ -17,7 +17,7 @@ import { createTestRouter } from './routerTestUtils' * context that was missing the ancestors' beforeLoad contributions. */ -describe("parent context when child validateSearch fails (issue #4696)", () => { +describe('parent context when child validateSearch fails (issue #4696)', () => { const setup = () => { const rootLoaderContexts: Array> = [] diff --git a/packages/router-core/tests/issue-5778-preload-live-router-context.test.ts b/packages/router-core/tests/issue-5778-preload-live-router-context.test.ts index c6be08ce5a..129f2dcefa 100644 --- a/packages/router-core/tests/issue-5778-preload-live-router-context.test.ts +++ b/packages/router-core/tests/issue-5778-preload-live-router-context.test.ts @@ -61,23 +61,26 @@ function setup() { // __beforeLoadContext layers — a change to the read-only borrow protocol // that belongs in a dedicated follow-up, not this PR. The documented // workaround (router.invalidate() after context changes) is pinned below. -test.fails('preload sees updated router context without an explicit invalidate', async () => { - const { router, seen, updateContext } = setup() +test.fails( + 'preload sees updated router context without an explicit invalidate', + async () => { + const { router, seen, updateContext } = setup() - await router.load() - updateContext('new') + await router.load() + updateContext('new') - // Hover intent: the preload borrows the active root match. Its - // committed context must not shadow the live router context that a - // navigation would see. - await router.preloadRoute({ to: '/foo' } as any) - expect(seen).toEqual(['new']) + // Hover intent: the preload borrows the active root match. Its + // committed context must not shadow the live router context that a + // navigation would see. + await router.preloadRoute({ to: '/foo' } as any) + expect(seen).toEqual(['new']) - // Sanity: a real navigation sees the same value. - await router.navigate({ to: '/foo' } as any) - await router.latestLoadPromise - expect(seen).toEqual(['new', 'new']) -}) + // Sanity: a real navigation sees the same value. + await router.navigate({ to: '/foo' } as any) + await router.latestLoadPromise + expect(seen).toEqual(['new', 'new']) + }, +) test('preload sees updated router context after the documented invalidate() pattern', async () => { const { router, seen, updateContext } = setup() diff --git a/packages/router-core/tests/issue-6221-head-waits-for-loader.test.ts b/packages/router-core/tests/issue-6221-head-waits-for-loader.test.ts index ad9c94e921..279411ef39 100644 --- a/packages/router-core/tests/issue-6221-head-waits-for-loader.test.ts +++ b/packages/router-core/tests/issue-6221-head-waits-for-loader.test.ts @@ -93,9 +93,7 @@ describe('issue #6221: head does not run before loader data is ready', () => { path: '/quote', loader: quoteLoader, head: ({ loaderData }) => ({ - meta: [ - { title: `Quote by ${(loaderData as any)?.author ?? '...'}` }, - ], + meta: [{ title: `Quote by ${(loaderData as any)?.author ?? '...'}` }], }), }) diff --git a/packages/router-core/tests/issue-7003-cache-eviction-during-preload.test.ts b/packages/router-core/tests/issue-7003-cache-eviction-during-preload.test.ts index 44b1a7b96d..4fc5208f0b 100644 --- a/packages/router-core/tests/issue-7003-cache-eviction-during-preload.test.ts +++ b/packages/router-core/tests/issue-7003-cache-eviction-during-preload.test.ts @@ -87,9 +87,7 @@ test('clearCache during an in-flight preload does not crash and the preload stil const preloaded = await preloadPromise // The preload completed and cached its owned successful match. - expect(preloaded?.some((match) => match.routeId === fooRoute.id)).toBe( - true, - ) + expect(preloaded?.some((match) => match.routeId === fooRoute.id)).toBe(true) expect( router.stores.cachedMatches .get() @@ -129,9 +127,7 @@ test('invalidate during an in-flight preload does not crash and both loads settl expect(barLoader).toHaveBeenCalledTimes(2) // The preload still settled cleanly and cached its result. - expect(preloaded?.some((match) => match.routeId === fooRoute.id)).toBe( - true, - ) + expect(preloaded?.some((match) => match.routeId === fooRoute.id)).toBe(true) expect( router.stores.cachedMatches .get() diff --git a/packages/router-core/tests/issue-7602-parent-beforeload-context-child-loader.test.ts b/packages/router-core/tests/issue-7602-parent-beforeload-context-child-loader.test.ts index a82f1e3aed..a0b4b7e09b 100644 --- a/packages/router-core/tests/issue-7602-parent-beforeload-context-child-loader.test.ts +++ b/packages/router-core/tests/issue-7602-parent-beforeload-context-child-loader.test.ts @@ -85,12 +85,8 @@ describe('parent beforeLoad context propagation to child (issue #7602)', () => { }) test('reused child match is republished with fresh parent beforeLoad context while its reload is still running', async () => { - const { - router, - loaderContextNumbers, - secondLoaderGate, - getChildMatch, - } = setup() + const { router, loaderContextNumbers, secondLoaderGate, getChildMatch } = + setup() await router.load() expect(loaderContextNumbers).toEqual([42]) diff --git a/packages/router-core/tests/issue-7635-dehydrated-error-child-head.test.ts b/packages/router-core/tests/issue-7635-dehydrated-error-child-head.test.ts index 25b7644123..51c40a0de0 100644 --- a/packages/router-core/tests/issue-7635-dehydrated-error-child-head.test.ts +++ b/packages/router-core/tests/issue-7635-dehydrated-error-child-head.test.ts @@ -32,9 +32,7 @@ describe('issue #7635: dehydrated parent beforeLoad error caps child head', () = it('does not run child loader/head after hydrating a server error boundary', async () => { const serverError = new Error('App beforeLoad failed') const appHead = vi.fn(({ match }: any) => ({ - meta: [ - { title: match.error ? 'App error title' : 'App success title' }, - ], + meta: [{ title: match.error ? 'App error title' : 'App success title' }], })) const childHead = vi.fn(() => ({ meta: [{ title: 'Child success title' }], From 3867af174025281b3b174932464150a7138b9d4e Mon Sep 17 00:00:00 2001 From: Sheraff Date: Sat, 4 Jul 2026 11:55:44 +0200 Subject: [PATCH 27/54] fix: drop unnecessary type assertions in issue-7638 regression test Co-Authored-By: Claude Fable 5 --- .../tests/issue-7638-invalidate-transition-error.test.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/react-router/tests/issue-7638-invalidate-transition-error.test.tsx b/packages/react-router/tests/issue-7638-invalidate-transition-error.test.tsx index d27492e81b..c990cfd869 100644 --- a/packages/react-router/tests/issue-7638-invalidate-transition-error.test.tsx +++ b/packages/react-router/tests/issue-7638-invalidate-transition-error.test.tsx @@ -83,7 +83,7 @@ function setup({ failVia }: { failVia: 'render' | 'loader' }) { errorRenders++ return (
- error: {(props.error as Error).message} + error: {(props.error).message}
) }, @@ -128,7 +128,7 @@ test.each(['render', 'loader'] as const)( // React must not have torn the tree down with a hooks-order violation. const hooksCrash = consoleError.mock.calls.find((call) => call.some((arg) => - String((arg as any)?.message ?? arg).includes('Rendered more hooks'), + String((arg)?.message ?? arg).includes('Rendered more hooks'), ), ) expect(hooksCrash).toBeUndefined() From 69cf2fbcacc959b8ede1faa923173328e07f6c90 Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Sat, 4 Jul 2026 09:57:47 +0000 Subject: [PATCH 28/54] ci: apply automated fixes --- .../tests/issue-7638-invalidate-transition-error.test.tsx | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/packages/react-router/tests/issue-7638-invalidate-transition-error.test.tsx b/packages/react-router/tests/issue-7638-invalidate-transition-error.test.tsx index c990cfd869..b5333b9bc4 100644 --- a/packages/react-router/tests/issue-7638-invalidate-transition-error.test.tsx +++ b/packages/react-router/tests/issue-7638-invalidate-transition-error.test.tsx @@ -81,11 +81,7 @@ function setup({ failVia }: { failVia: 'render' | 'loader' }) { history: createMemoryHistory({ initialEntries: ['/test'] }), defaultErrorComponent: (props: ErrorComponentProps) => { errorRenders++ - return ( -
- error: {(props.error).message} -
- ) + return
error: {props.error.message}
}, }) @@ -128,7 +124,7 @@ test.each(['render', 'loader'] as const)( // React must not have torn the tree down with a hooks-order violation. const hooksCrash = consoleError.mock.calls.find((call) => call.some((arg) => - String((arg)?.message ?? arg).includes('Rendered more hooks'), + String(arg?.message ?? arg).includes('Rendered more hooks'), ), ) expect(hooksCrash).toBeUndefined() From e1f2a7ce2cb81bd0f94a5fe3319a3df6cb11d719 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Sat, 4 Jul 2026 12:53:11 +0200 Subject: [PATCH 29/54] docs: reconcile INTERNALS.md with the final ready-branch semantics Nine corrections from a full consistency pass: pendingMs-0 synchronous publication, the preload borrow wait/re-read loop and failure-path prefix caching, load-chain settlement for superseded loads, per-type chunk cache with settled-preload eviction (incl. lazyFn rejections), narrowed cancelMatches, per-kind server asset commit with async headers always awaited, hydration's ssr:false asset skip, loadPromise AND dehydrated marker both surviving rematch, and the previously undocumented dehydrated-boundary replay. Co-Authored-By: Claude Fable 5 --- packages/router-core/INTERNALS.md | 113 +++++++++++++++++++++++------- 1 file changed, 89 insertions(+), 24 deletions(-) diff --git a/packages/router-core/INTERNALS.md b/packages/router-core/INTERNALS.md index 5a4d5a3a6f..2c5e11b0dd 100644 --- a/packages/router-core/INTERNALS.md +++ b/packages/router-core/INTERNALS.md @@ -150,7 +150,9 @@ There are several kinds of commit. Keep them separate: transition. It also clears the pending match pool for that load pass. It does preserve exiting success matches in `cachedMatches` — publication removes them from the active pool, and if the load is later superseded the final - commit that would have cached them never runs. + commit that would have cached them never runs. The cache push shares the + `pushExitingMatch` helper with the final commit so the dedup and + isFetching-reset shape stays identical in both paths. - **Final client commit**: `commitFinalMatches()` publishes the final active lane, reconciles cache, clears pending state, updates `loadedAt`, and runs `onLeave`, `onStay`, and `onEnter`. @@ -271,10 +273,11 @@ Server-created matches do not use client pending status for this decision. Existing matches are shallow-copied into the new lane with fresh params/search/preload/cause/controller. The private `_` bucket preserves an -existing `_.loadPromise` first, because hydration and pending owners can keep -readiness ownership across rematching. If there is no load promise, the copy -preserves only the dehydrated marker. That copy is a new generation. The old -match may still exist in an active, pending, or cached pool. +existing `_.loadPromise` and the dehydrated marker together: hydration and +pending owners keep readiness ownership across rematching, a dehydrated match +can legitimately hold a pending load promise, and dropping the marker would +make the follow-up load re-run its server work. That copy is a new generation. +The old match may still exist in an active, pending, or cached pool. ## Client Top-Level Navigation Load @@ -327,6 +330,13 @@ pending and start a replacement navigation, whose load later clears `isLoading`. Framework transitioners are responsible for later marking the router status idle and updating `resolvedLocation`. +A superseded or redirected load does not settle its public `router.load()` +promise as soon as its own pass ends. After resolving its private +`loadPromise`, the pass awaits `router.latestLoadPromise` in a loop until the +navigation chain drains. Callers of `router.load()`/`router.invalidate()` rely +on observing post-settlement state, and the preload borrow protocol uses the +foreground load promise as its "committed or gone" signal. + ### Background-only foreground pass When a same-href load finds only non-blocking stale reloads, the foreground pass @@ -452,6 +462,14 @@ Core owns `pendingMs`. Framework match components own `pendingMinMs` by writing still-pending local load promise. Core later observes `pendingUntil` before committing success/error/notFound/redirect. +`pendingMs` publication normally goes through a timer on the load promise. One +exception: when the effective `pendingMs` is `<= 0` and nothing is rendered yet +(the active match store is empty, as on a bare initial load), +`setupPendingTimeout` publishes synchronously instead of deferring to a +macrotask, so the browser cannot paint a blank frame before the pending +fallback (#4759). When content is already displayed, the timer path is kept +because a later publication captures a fresher lane snapshot. + ```mermaid sequenceDiagram participant Load as loadClientMatches @@ -525,10 +543,15 @@ component failure replace the original route failure and commit directly as an error — it must not recursively try to load another boundary component. Boundary chunk requests are per-component-type: `loadRouteChunk(route, -'errorComponent')` joins that component's own in-flight chunk but never -waits on the whole-route `_componentsPromise`, so an unrelated slow or failed -component chunk cannot block or poison boundary UI. Rejected preloads are -evicted (not cached), so a later load generation can retry. +'errorComponent')` joins that component's own in-flight chunk in the per-type +cache (`route._componentPromises`) but never waits on the whole-route +`_componentsPromise`, so an unrelated slow or failed component chunk cannot +block or poison boundary UI. Settled chunk preloads — success or failure — +leave the per-type cache: repeats are the component's own concern (lazy +components memoize their import), and a rejection is never replayed forever. A +rejected `lazyFn` chunk is evicted from `route._lazyPromise` the same way, so +the next load generation retries the import; awaiters of the evicted promise +still own the rejection. ```mermaid flowchart TD @@ -601,10 +624,10 @@ sequenceDiagram alt borrowed loadPromise pending J->>F: await borrowed loadPromise end - alt borrowed match still in pending store + loop owner still pending-status or in pending store, and a foreground load exists J->>F: await router.latestLoadPromise + J->>R: re-read owner match end - J->>R: re-read owner match alt owner missing/aborted J-->>L: throw inner sentinel else owner renderable @@ -631,7 +654,14 @@ Why wait for both `loadPromise` and sometimes `latestLoadPromise`? - `loadPromise` says the borrowed match's local work has reached a terminal render state. - `latestLoadPromise` says the foreground owner has actually committed or - disappeared from the pending store. + disappeared. The owner may still sit in the pending store, or be a + render-ready pending publication — `onReady()` moved it into the active + store and cleared the pending pool while the final commit is still in + flight, so its snapshot is stuck at `status: 'pending'` even though its + local work settled. Both shapes wait for the foreground load. +- The wait is a re-read loop, not a single await: a newer foreground load can + re-publish a pending lane for the same match, so the join re-reads the owner + after each foreground settlement until it reaches a committed state. Without the foreground wait, a preload can observe a transient pending-store owner and start descendant work before the navigation that owns the parent has @@ -646,7 +676,10 @@ Preload route-control behavior: - A private preload redirect recursively preloads the redirect target. It does not navigate the active app, and it stops if `reloadDocument` is required. -- A preload notFound or regular error is not fatal to the app. +- A preload notFound or regular error is not fatal to the app. The leading run + of successful ancestor matches is still projected and cached from the failure + path, so repeated hovers do not re-run expensive ancestor loaders; only the + failed/pending tail stays out of the cache. - Borrowed active redirect/notFound/error stops descendant preload work because the active foreground owner already owns that outcome. - Borrowed matches must re-read as present, un-aborted, and `status: 'success'` @@ -734,8 +767,13 @@ Outcome priority for background batches: 3. If there is no regular error, the first selected notFound wins. Background asset projection waits until all selected loader work has settled. -That keeps data and head coherent. A parent-only background reload can still -republish child head because the child head may derive from parent loader data. +That keeps data and head coherent. The background commit is atomic for data +and asset success: if asset projection for the fresh data fails or loses +currentness, the lane is not published at all — publishing would expose new +`loaderData` under head output that still describes the previous data. The old +lane stays and the finalizer clears the fetching markers. A parent-only +background reload can still republish child head because the child head may +derive from parent loader data. Selected background loaders own their `loaderData` field just like foreground loaders: an `undefined` result is written into the copied background lane and asset projection sees that cleared value before the atomic `setMatches()`. @@ -788,10 +826,19 @@ Server projection: current lane before being rethrown; they may not have a committed error match. - Handles `head()`, `scripts()`, and `headers()`. - Does not need currentness checks. -- If `scripts()` or `headers()` throws synchronously after an earlier async asset - hook started, server projection observes the abandoned earlier promises. Async - server projection uses `Promise.allSettled()` so one rejected asset hook does - not leave another hook unobserved. +- Each asset kind commits independently: route `headers()` are response + behavior and are never dropped because a decorative `head()`/`scripts()` + failed, and vice versa. +- If any asset hook throws synchronously, projection commits the + sync-available values for the other kinds and abandons still-pending + decorative promises, observing them with `Promise.allSettled()` so they + cannot become unhandled — except a pending `headers()` promise, which is + always awaited (and committed on success) even after a sync decorative + throw, because headers are response behavior. +- Async server projection uses `Promise.allSettled()` over `head()`, + `scripts()`, and `headers()`; a rejected hook logs and commits `undefined` + for that kind only, so one rejected asset hook does not leave another hook + unobserved or uncommitted. Hydration projection: @@ -799,7 +846,12 @@ Hydration projection: - `ssr-client.ts` waits for route chunks first because lazy chunks can install route context, head, and scripts. - It reconstructs route context from dehydrated data where available, then - executes head and scripts for each match in the initial hydration lane. + executes head and scripts for each match in the initial hydration lane — + except `ssr: false` matches. The server rendered no assets for those + (including matches it omitted below a server error/notFound boundary, which + the dehydrated payload also marks `ssr: false`), and their hooks could only + run with missing or stale loader data; the follow-up client load projects + assets for the lane it actually commits. - A `notFound()` thrown by hydration head/scripts records a notFound-shaped match error and continues. Other hydration asset/context errors reject, settle matches, and clear display pending. @@ -824,10 +876,15 @@ stateDiagram-v2 Current --> Published: pending publication / final commit / background setMatches ``` -`cancelMatches()` aborts and settles pending and active matches. It skips active -matches that are also in the pending pool so the same match is not canceled -twice. Settling clears `loadPromise`, clears pending timeout, and resolves the -promise if it is still pending. +`cancelMatches()` aborts and settles pending matches, and active matches that +still have in-flight route work (`status: 'pending'` or any fetching marker, +beforeLoad and loader alike). A settled idle active success match keeps its +controller un-aborted: loaders may have handed that signal to still-streaming +deferred data, and the public contract only cancels it when the route unloads +or its loader call becomes outdated. It skips active matches that are also in +the pending pool so the same match is not canceled twice. Settling clears +`loadPromise`, clears pending timeout, and resolves the promise if it is still +pending. After foreground/background work detects ownership loss, it must not: @@ -967,6 +1024,14 @@ Hydration flow: dehydrated markers, settle load promises, set `resolvedLocation`, and stop. 12. Otherwise call normal `router.load()` to fill SPA or `ssr: false` holes. +That follow-up load replays dehydrated boundaries: when the serial pass in +`loadClientMatches()` reaches a dehydrated match whose status is `notFound` +(with a notFound error) or `error`, it treats that server-committed boundary +as the pass's serial failure. The server intentionally omitted every match +below the boundary, so replaying it caps the client lane the same way instead +of loading, committing, and projecting assets for descendants the server never +rendered. + ```mermaid flowchart TD H["hydrate(router)"] --> Data["read TSR bootstrap data"] From 77ec643b312a1de5ef6208871a80fcb642579360 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Sat, 4 Jul 2026 12:53:35 +0200 Subject: [PATCH 30/54] docs: cover the remaining behavior changes in the changeset pendingMs-0 synchronous publication, narrowed cancelMatches, exiting- match cache preservation at pending publication, dehydrated boundary replay, and async headers() always awaited. Co-Authored-By: Claude Fable 5 --- .changeset/violet-poets-wait.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.changeset/violet-poets-wait.md b/.changeset/violet-poets-wait.md index 0608526748..3747103a72 100644 --- a/.changeset/violet-poets-wait.md +++ b/.changeset/violet-poets-wait.md @@ -19,4 +19,7 @@ Fix match loading consistency across client navigation, preloading, background r - Behavior change: a navigation that starts while a hover/intent preload for the same route is in flight no longer adopts the preload's loader run — the navigation runs its own loader with `preload: false` semantics, so loaders may execute twice in that window. Use your data layer (e.g. an external cache) to dedupe fetches. - Preloads now cache the successful ancestor prefix even when a descendant throws an error or `notFound`, so repeated hovers do not re-run expensive ancestor loaders. - Route chunk (lazy import) failures now run the normal route failure lifecycle: `onError` fires and thrown redirects/notFounds are honored. Error/notFound boundary chunks load independently of the route's other component chunks, and failed chunk preloads are retried on the next load instead of being cached forever. -- Server rendering keeps route `headers()` when a decorative `head()`/`scripts()` hook fails, background reloads never publish fresh `loaderData` whose asset projection failed, and hydration no longer executes `head()`/`scripts()` for matches the server omitted (`ssr: false` or a server-side error/notFound boundary). +- Server rendering keeps route `headers()` when a decorative `head()`/`scripts()` hook fails (async `headers()` are always awaited), background reloads never publish fresh `loaderData` whose asset projection failed, and hydration no longer executes `head()`/`scripts()` for matches the server omitted (`ssr: false` or a server-side error/notFound boundary). The follow-up client load after hydration replays a server-committed notFound/error boundary, so routes the server omitted are not loaded or asset-projected client-side. +- With `pendingMs: 0`, the pending fallback is published synchronously on bare initial loads (nothing rendered yet) instead of after a macrotask, eliminating the blank first frame. +- Starting a navigation no longer aborts the `abortController` of settled success matches that stay mounted — deferred/streamed data tied to a stay-match's loader signal survives child navigations and `invalidate()`. Matches with in-flight `beforeLoad`/loader work are still cancelled. +- Fresh data for routes you navigate away from survives pending publication: if a navigation is superseded (e.g. back button) after its pending UI was published, the exited matches are served from cache instead of re-running their loaders. From 354d65931044052ef45ee573074591eda362c406 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Sat, 4 Jul 2026 13:42:34 +0200 Subject: [PATCH 31/54] fix: address delta-review findings MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - joinPreloadedActiveMatch's foreground wait is now bounded: a speculative preload drops its pass (ownership sentinel) instead of outwaiting sustained navigation churn, where every iteration picked up the replacement latestLoadPromise and awaiters never settled. Covered by a churn regression test with signal-aware loaders. - The react Transitioner stuck-pending repair now also emits onLoad/onBeforeRouteMount/onResolved — deferred one macrotask so the normal effect pipeline (which sets status idle) always wins arbitration and events cannot double-fire; only genuinely unobserved loads repair. - Server asset projection no longer abandons a pending async head()/ scripts() when a sync throw coincides with an async headers(): the response waits on headers regardless, so that case now flows through the generic per-kind branch and commits everything that settles. This also removes the duplicated commit+recurse continuation. - Restores solid-router's server-mode test suite ('vitest --mode server'), accidentally dropped from test:unit by a concurrent agent edit swept into an earlier commit; the suite passes. Co-Authored-By: Claude Fable 5 --- packages/react-router/src/Transitioner.tsx | 25 +++-- .../tests/preloaded-mount-resolution.test.tsx | 11 ++- .../router-core/src/load-matches.client.ts | 22 ++--- .../router-core/src/route-assets.server.ts | 49 +++------- .../tests/preload-join-churn.test.ts | 93 +++++++++++++++++++ .../server-headers-asset-failure.test.ts | 28 ++++++ packages/solid-router/package.json | 2 +- 7 files changed, 176 insertions(+), 54 deletions(-) create mode 100644 packages/router-core/tests/preload-join-churn.test.ts diff --git a/packages/react-router/src/Transitioner.tsx b/packages/react-router/src/Transitioner.tsx index 03a96a82dd..3892ea32c6 100644 --- a/packages/react-router/src/Transitioner.tsx +++ b/packages/react-router/src/Transitioner.tsx @@ -87,18 +87,31 @@ export function Transitioner() { // A mount load can settle before this component observes the // isLoading flip (loads started before mount, or loads completing // within this effect's batch), leaving the router status stuck at - // 'pending' so onResolved/onRendered never fire. Repair it the same - // way ssr-client does after its follow-up load. - batch(() => { + // 'pending' so the load lifecycle events and onRendered never fire. + // Repair is deferred one macrotask: when the flips WERE observed, + // React's already-scheduled render/effects run first, emit the + // events, and set status 'idle' via the onResolved effect — making + // this a no-op. Only a genuinely unobserved load still reads + // 'pending' here, and then this emits what the pipeline would have. + setTimeout(() => { if ( router.stores.status.get() === 'pending' && !router.stores.isLoading.get() && !router.stores.hasPending.get() ) { - router.stores.status.set('idle') - router.stores.resolvedLocation.set(router.stores.location.get()) + const changeInfo = getLocationChangeInfo( + router.stores.location.get(), + router.stores.resolvedLocation.get(), + ) + router.emit({ type: 'onLoad', ...changeInfo }) + router.emit({ type: 'onBeforeRouteMount', ...changeInfo }) + router.emit({ type: 'onResolved', ...changeInfo }) + batch(() => { + router.stores.status.set('idle') + router.stores.resolvedLocation.set(router.stores.location.get()) + }) } - }) + }, 0) } tryLoad() diff --git a/packages/react-router/tests/preloaded-mount-resolution.test.tsx b/packages/react-router/tests/preloaded-mount-resolution.test.tsx index e0a2962c35..31c7af36e8 100644 --- a/packages/react-router/tests/preloaded-mount-resolution.test.tsx +++ b/packages/react-router/tests/preloaded-mount-resolution.test.tsx @@ -63,7 +63,14 @@ test('mounting after a settled load still resolves status and fires onRendered', }) const onRendered = vi.fn() - const unsubscribe = router.subscribe('onRendered', onRendered) + const onResolved = vi.fn() + const onLoad = vi.fn() + const unsubscribers = [ + router.subscribe('onRendered', onRendered), + router.subscribe('onResolved', onResolved), + router.subscribe('onLoad', onLoad), + ] + const unsubscribe = () => unsubscribers.forEach((fn) => fn()) const container = document.createElement('div') document.body.appendChild(container) const reactRoot = createRoot(container) @@ -88,6 +95,8 @@ test('mounting after a settled load still resolves status and fires onRendered', router.stores.location.get().href, ) await until(() => onRendered.mock.calls.length > 0, 'onRendered to fire') + await until(() => onResolved.mock.calls.length > 0, 'onResolved to fire') + await until(() => onLoad.mock.calls.length > 0, 'onLoad to fire') } finally { unsubscribe() reactRoot.unmount() diff --git a/packages/router-core/src/load-matches.client.ts b/packages/router-core/src/load-matches.client.ts index 637e7dfabe..13dc796fb9 100644 --- a/packages/router-core/src/load-matches.client.ts +++ b/packages/router-core/src/load-matches.client.ts @@ -94,9 +94,13 @@ const joinPreloadedActiveMatch = async ( // be a render-ready pending publication (onReady() moved it into the // active store, clearing the pending pool, while the final commit is // still in flight — the snapshot is stuck at status 'pending' even though - // its local work settled). Wait for the foreground load and re-read until - // the owner reaches a committed state; each iteration re-reads because a - // newer load can re-publish a pending lane for the same match. + // its local work settled). Wait for the foreground load and re-read; + // each iteration re-reads because a newer load can re-publish a pending + // lane for the same match. The wait is BOUNDED: a speculative preload + // must not outwait sustained navigation churn, and dropping the pass + // (throwing the ownership sentinel) is the correct outcome when the + // owner never reaches a committed state. + let foregroundWaits = 0 while (true) { match = inner.router.getMatch(matchId, false) if (!match || match.abortController.signal.aborted) { @@ -112,16 +116,10 @@ const joinPreloadedActiveMatch = async ( break } - await foreground - if (inner.router.latestLoadPromise === foreground) { - // The chain settled without being replaced; a final re-read below - // decides the outcome instead of spinning on the same promise. - match = inner.router.getMatch(matchId, false) - if (!match || match.abortController.signal.aborted) { - throw inner - } - break + if (foregroundWaits++ >= 3) { + throw inner } + await foreground } // From here the preload lane uses the owner match read-only. It must not clone diff --git a/packages/router-core/src/route-assets.server.ts b/packages/router-core/src/route-assets.server.ts index 7b38ea1ffa..a04021f2a6 100644 --- a/packages/router-core/src/route-assets.server.ts +++ b/packages/router-core/src/route-assets.server.ts @@ -69,12 +69,15 @@ export const projectServerRouteAssets = ( logAssetError(match, error) } - if (syncFailed) { - // A sync throw must not hold the response hostage waiting on the other - // DECORATIVE hooks' async work: commit sync-available head/scripts and - // abandon pending ones, owning their rejections so they cannot become - // unhandled. A pending headers() promise is different — headers are - // response behavior, so it is always awaited. + if (syncFailed && !isPromise(headers)) { + // A sync throw must not hold the response hostage waiting on the + // other DECORATIVE hooks' async work: commit sync-available + // head/scripts and abandon pending ones, owning their rejections so + // they cannot become unhandled. When headers() is async the response + // waits for it regardless (headers are response behavior), so that + // case falls through to the generic per-kind branch below, which + // awaits ALL kinds — nothing extra is blocked and a pending head() + // is committed instead of dropped. const settle = (value: any) => { if (isPromise(value)) { void Promise.allSettled([value]) @@ -82,34 +85,12 @@ export const projectServerRouteAssets = ( } return value } - const syncHead = settle(head) - const syncScripts = settle(scripts) - - if (isPromise(headers)) { - return headers.then( - (headerValue) => { - matches[i] = withServerAssets( - match, - syncHead, - syncScripts, - headerValue, - ) - return projectServerRouteAssets(router, matches, i + 1) - }, - (error) => { - logAssetError(match, error) - matches[i] = withServerAssets( - match, - syncHead, - syncScripts, - undefined, - ) - return projectServerRouteAssets(router, matches, i + 1) - }, - ) - } - - matches[i] = withServerAssets(match, syncHead, syncScripts, headers) + matches[i] = withServerAssets( + match, + settle(head), + settle(scripts), + headers, + ) continue } diff --git a/packages/router-core/tests/preload-join-churn.test.ts b/packages/router-core/tests/preload-join-churn.test.ts new file mode 100644 index 0000000000..c2215322e4 --- /dev/null +++ b/packages/router-core/tests/preload-join-churn.test.ts @@ -0,0 +1,93 @@ +import { describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, createControlledPromise } from '../src' +import { createTestRouter } from './routerTestUtils' + +/** + * A preload that borrows an active match waits for the foreground load to + * commit — but that wait must be bounded. Under sustained navigation churn + * (every foreground load replaced by a newer one before the borrowed owner + * commits), the preload must settle by dropping the speculative pass + * instead of hanging its awaiter indefinitely. + */ + +describe('preload join under navigation churn', () => { + test('a borrowing preload settles instead of outwaiting endless foreground loads', async () => { + vi.useFakeTimers() + try { + const gates: Array>> = [] + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + pendingMs: 0, + pendingComponent: {}, + loader: async ({ + abortController, + }: { + abortController: AbortController + }) => { + const gate = createControlledPromise() + gates.push(gate) + // Signal-aware like a real fetch: an aborted (superseded) load + // settles instead of hanging on abandoned work. + abortController.signal.addEventListener('abort', () => gate.resolve()) + await gate + return 'parent' + }, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: () => 'child', + }) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + + // Foreground navigation to /parent; pendingMs 0 publishes the pending + // lane so the parent match becomes a borrowable pending-published + // owner in the active store. + const navigations: Array> = [ + router.navigate({ to: '/parent' }), + ] + await vi.waitFor(() => expect(gates.length).toBe(1)) + + let preloadSettled = false + const preload = router + .preloadRoute({ to: '/parent/child' } as any) + .then(() => { + preloadSettled = true + }) + + // Churn: keep superseding the foreground load before the parent ever + // commits. Each cycle replaces router.latestLoadPromise. + for (let i = 0; i < 6; i++) { + navigations.push(router.navigate({ to: '/parent', replace: true })) + await vi.advanceTimersByTimeAsync(1) + } + + // The preload must have given up by now (bounded wait), even though + // the foreground owner still has not committed. + await vi.waitFor(() => expect(preloadSettled).toBe(true)) + + for (const gate of gates) { + gate.resolve() + } + await Promise.allSettled([...navigations, preload]) + } finally { + vi.useRealTimers() + } + }) +}) diff --git a/packages/router-core/tests/server-headers-asset-failure.test.ts b/packages/router-core/tests/server-headers-asset-failure.test.ts index 2afb198c66..3a954a9fe8 100644 --- a/packages/router-core/tests/server-headers-asset-failure.test.ts +++ b/packages/router-core/tests/server-headers-asset-failure.test.ts @@ -61,6 +61,34 @@ describe('server asset projection route headers', () => { expect(targetMatch!.headers).toEqual(expectedHeaders) }) + test('commits async head alongside async headers when scripts throws synchronously', async () => { + const rootRoute = new BaseRootRoute({}) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + head: async () => ({ meta: [{ title: 'kept title' }] }), + scripts: () => { + throw new Error('scripts failed') + }, + headers: async () => expectedHeaders, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([targetRoute]), + history: createMemoryHistory({ initialEntries: ['/target'] }), + isServer: true, + }) + + await router.load() + + const targetMatch = router.state.matches.find( + (match) => match.routeId === targetRoute.id, + ) + // The response waits on async headers regardless, so the pending head + // must be committed rather than abandoned. + expect(targetMatch!.headers).toEqual(expectedHeaders) + expect(targetMatch!.meta).toEqual([{ title: 'kept title' }]) + }) + test('awaits async route headers when head throws synchronously', async () => { const rootRoute = new BaseRootRoute({}) const targetRoute = new BaseRoute({ diff --git a/packages/solid-router/package.json b/packages/solid-router/package.json index ef431a9924..6b8e7a2949 100644 --- a/packages/solid-router/package.json +++ b/packages/solid-router/package.json @@ -33,7 +33,7 @@ "test:types:ts58": "node ../../node_modules/typescript58/lib/tsc.js -p tsconfig.legacy.json", "test:types:ts59": "node ../../node_modules/typescript59/lib/tsc.js -p tsconfig.legacy.json", "test:types:ts60": "tsc -p tsconfig.legacy.json", - "test:unit": "vitest", + "test:unit": "vitest && vitest --mode server", "test:unit:dev": "pnpm run test:unit --watch --hideSkippedTests", "test:perf": "vitest bench", "test:perf:dev": "pnpm run test:perf --watch --hideSkippedTests", From c9efc46097b9b9936292ebe76fd17fe2a86bc982 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Sat, 4 Jul 2026 14:20:47 +0200 Subject: [PATCH 32/54] refactor: single-shot foreground wait in the preload borrow protocol MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replace the counter-capped wait loop with the deterministic contract the protocol originally had: if the borrowed owner is mid-navigation, await the current foreground load exactly once and re-read. An owner that still has not committed after that belongs to a newer navigation, and the speculative pass yields via the ownership sentinel. Zero or one await by construction — no arbitrary iteration bound. INTERNALS and the churn regression test updated to match. Co-Authored-By: Claude Fable 5 --- packages/router-core/INTERNALS.md | 11 +++--- .../router-core/src/load-matches.client.ts | 37 ++++++++----------- .../tests/preload-join-churn.test.ts | 14 +++---- 3 files changed, 28 insertions(+), 34 deletions(-) diff --git a/packages/router-core/INTERNALS.md b/packages/router-core/INTERNALS.md index 2c5e11b0dd..83f3743912 100644 --- a/packages/router-core/INTERNALS.md +++ b/packages/router-core/INTERNALS.md @@ -624,8 +624,8 @@ sequenceDiagram alt borrowed loadPromise pending J->>F: await borrowed loadPromise end - loop owner still pending-status or in pending store, and a foreground load exists - J->>F: await router.latestLoadPromise + opt owner still pending-status or in pending store, and a foreground load exists + J->>F: await router.latestLoadPromise once J->>R: re-read owner match end alt owner missing/aborted @@ -659,9 +659,10 @@ Why wait for both `loadPromise` and sometimes `latestLoadPromise`? store and cleared the pending pool while the final commit is still in flight, so its snapshot is stuck at `status: 'pending'` even though its local work settled. Both shapes wait for the foreground load. -- The wait is a re-read loop, not a single await: a newer foreground load can - re-publish a pending lane for the same match, so the join re-reads the owner - after each foreground settlement until it reaches a committed state. +- The foreground wait is single-shot by design: the join awaits the current + `latestLoadPromise` exactly once and re-reads the owner. If the owner still + has not committed (a newer navigation re-published it), the speculative + pass yields via the ownership sentinel instead of chasing navigation churn. Without the foreground wait, a preload can observe a transient pending-store owner and start descendant work before the navigation that owns the parent has diff --git a/packages/router-core/src/load-matches.client.ts b/packages/router-core/src/load-matches.client.ts index 13dc796fb9..f5a4dfa8c6 100644 --- a/packages/router-core/src/load-matches.client.ts +++ b/packages/router-core/src/load-matches.client.ts @@ -94,32 +94,25 @@ const joinPreloadedActiveMatch = async ( // be a render-ready pending publication (onReady() moved it into the // active store, clearing the pending pool, while the final commit is // still in flight — the snapshot is stuck at status 'pending' even though - // its local work settled). Wait for the foreground load and re-read; - // each iteration re-reads because a newer load can re-publish a pending - // lane for the same match. The wait is BOUNDED: a speculative preload - // must not outwait sustained navigation churn, and dropping the pass - // (throwing the ownership sentinel) is the correct outcome when the - // owner never reaches a committed state. - let foregroundWaits = 0 - while (true) { + // its local work settled). Wait for the current foreground load exactly + // once: if the owner still has not committed after that, a newer + // navigation owns it, and this speculative pass yields (the final status + // check below throws the ownership sentinel) instead of chasing churn. + match = inner.router.getMatch(matchId, false) + if (!match || match.abortController.signal.aborted) { + throw inner + } + if ( + inner.router.latestLoadPromise && + (match.status === 'pending' || + inner.router.stores.pendingMatchStores.has(matchId)) + ) { + await inner.router.latestLoadPromise + match = inner.router.getMatch(matchId, false) if (!match || match.abortController.signal.aborted) { throw inner } - - const foreground = inner.router.latestLoadPromise - if ( - !foreground || - (match.status !== 'pending' && - !inner.router.stores.pendingMatchStores.has(matchId)) - ) { - break - } - - if (foregroundWaits++ >= 3) { - throw inner - } - await foreground } // From here the preload lane uses the owner match read-only. It must not clone diff --git a/packages/router-core/tests/preload-join-churn.test.ts b/packages/router-core/tests/preload-join-churn.test.ts index c2215322e4..f4a74b72aa 100644 --- a/packages/router-core/tests/preload-join-churn.test.ts +++ b/packages/router-core/tests/preload-join-churn.test.ts @@ -4,11 +4,11 @@ import { BaseRootRoute, BaseRoute, createControlledPromise } from '../src' import { createTestRouter } from './routerTestUtils' /** - * A preload that borrows an active match waits for the foreground load to - * commit — but that wait must be bounded. Under sustained navigation churn - * (every foreground load replaced by a newer one before the borrowed owner - * commits), the preload must settle by dropping the speculative pass - * instead of hanging its awaiter indefinitely. + * A preload that borrows an active match waits for the current foreground + * load exactly once. Under sustained navigation churn (every foreground + * load replaced by a newer one before the borrowed owner commits), the + * preload must settle by yielding the speculative pass instead of hanging + * its awaiter indefinitely. */ describe('preload join under navigation churn', () => { @@ -78,8 +78,8 @@ describe('preload join under navigation churn', () => { await vi.advanceTimersByTimeAsync(1) } - // The preload must have given up by now (bounded wait), even though - // the foreground owner still has not committed. + // The preload must have given up by now (single-shot foreground + // wait), even though the foreground owner still has not committed. await vi.waitFor(() => expect(preloadSettled).toBe(true)) for (const gate of gates) { From 4d9e0e760d38e08c6a4c0c7aa8ec3b925415da1e Mon Sep 17 00:00:00 2001 From: Sheraff Date: Sat, 4 Jul 2026 15:33:30 +0200 Subject: [PATCH 33/54] refactor: remove unnecessary mechanism across the match-loading pipeline MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Complexity sweep over the combined #7637+#7744 diff (23 verified simplifications; every candidate adversarially checked for behavior preservation against INTERNALS and the test suite): - One flag instead of two for pending publication (pendingPublished folded into rendered); serial failures live on inner.serialFailure instead of a local mirrored by a temporary background-null bracket (retained ancestors now gate background selection explicitly). - Provably-dead code deleted: finalizeRouteFailure's never-passed componentFailure parameter, an unreachable lane-shortening guard, the join's pre-wait aborted check, three sync-gap currentness re-checks in the background path, the server-side latestLoadPromise clear, two unreachable isServer branches in react Match, and the supersession drain loop's impossible-state guards (with a new multi-supersession pinning test). - One owner per rule: the serial-failure loader-prefix cap is a shared helper used by both client and server (new foreground-lane pinning test); matchRoutesInternal derives context through getMatchContext; invalidate() uses one parameterized updater; cancelMatches reads its known pool directly; the server reduction uses Promise.allSettled. - Vestigial indirection dropped: hydrate()'s follow-up load microtask deferral, solid's createResource microtask yield and armPending wrapper, ssr-client's duplicate route.options.ssr write, the loadedMatches/matches aliases, and stores.ts's initial-state object for five compile-time constants. Bundle: −95 to −150 B gzip (−300 to −494 B raw) on every measured target across react/solid/vue and vite/rsbuild. All suites green (router-core 1492, react 941, solid 821+server-mode, vue 791) plus react/solid selective-ssr e2e. Co-Authored-By: Claude Fable 5 --- packages/react-router/src/Match.tsx | 21 +-- packages/router-core/INTERNALS.md | 10 +- .../router-core/src/load-matches.client.ts | 137 ++++++++---------- .../router-core/src/load-matches.server.ts | 37 ++--- packages/router-core/src/load-matches.ts | 25 +++- .../router-core/src/route-assets.client.ts | 18 ++- .../router-core/src/router-load.client.ts | 30 ++-- .../router-core/src/router-load.server.ts | 1 - .../router-core/src/router-preload.client.ts | 5 +- packages/router-core/src/router.ts | 79 ++++------ packages/router-core/src/ssr/ssr-client.ts | 6 +- packages/router-core/src/stores.ts | 16 +- .../serial-failure-foreground-prefix.test.ts | 76 ++++++++++ .../tests/superseded-load-await.test.ts | 84 +++++++++++ packages/solid-router/src/Match.tsx | 47 ++---- 15 files changed, 340 insertions(+), 252 deletions(-) create mode 100644 packages/router-core/tests/serial-failure-foreground-prefix.test.ts diff --git a/packages/react-router/src/Match.tsx b/packages/react-router/src/Match.tsx index c6f0e7a2e4..eac6767f11 100644 --- a/packages/react-router/src/Match.tsx +++ b/packages/react-router/src/Match.tsx @@ -406,11 +406,7 @@ export const MatchInner = React.memo(function MatchInnerImpl({ ? (routeOptions.pendingMinMs ?? router.options.defaultPendingMinMs) : undefined const localPromise = match._.loadPromise - if ( - !(isServer ?? router.isServer) && - localPromise?.status === 'pending' && - pendingMinMs - ) { + if (localPromise?.status === 'pending' && pendingMinMs) { localPromise.pendingUntil ??= Date.now() + pendingMinMs } @@ -429,21 +425,6 @@ export const MatchInner = React.memo(function MatchInnerImpl({ } if (match.status === 'error') { - if (isServer ?? router.isServer) { - const RouteErrorComponent = - (routeOptions.errorComponent ?? router.options.defaultErrorComponent) || - ErrorComponent - return ( - - ) - } - throw match.error } diff --git a/packages/router-core/INTERNALS.md b/packages/router-core/INTERNALS.md index 83f3743912..58938977c9 100644 --- a/packages/router-core/INTERNALS.md +++ b/packages/router-core/INTERNALS.md @@ -416,10 +416,10 @@ flowchart TD - Converts thrown/returned redirects and notFounds into a serial failure record. This is why a child loader never sees a half-finished parent beforeLoad context. -When the serial phase records a beforeLoad failure, retained ancestor prefix -loaders run with `inner.background` temporarily disabled. Those reloads belong -to the foreground failure lane and must not be deferred into a background batch -that may be discarded by the boundary trim. +When the serial phase records a beforeLoad failure (`inner.serialFailure`), +retained ancestor prefix loaders skip background selection. Those reloads +belong to the foreground failure lane and must not be deferred into a +background batch that may be discarded by the boundary trim. ### loader and chunk work on the client @@ -1048,7 +1048,7 @@ flowchart TD Chunks --> Rebuild["restore ssr, rebuild route context and head/scripts"] Rebuild --> Full{"no ssr:false and not SPA mode?"} Full -->|"yes"| Done["settle, clear dehydrated, set resolvedLocation"] - Full -->|"no"| Load["Promise.resolve().then(router.load) for SPA/ssr:false matches"] + Full -->|"no"| Load["router.load() for SPA/ssr:false matches"] ``` Hydration display pending uses `_displayPending`, not the normal client pending diff --git a/packages/router-core/src/load-matches.client.ts b/packages/router-core/src/load-matches.client.ts index f5a4dfa8c6..c66290cdfd 100644 --- a/packages/router-core/src/load-matches.client.ts +++ b/packages/router-core/src/load-matches.client.ts @@ -11,6 +11,7 @@ import { getNotFoundBoundaryPatch, markError, normalizeRouteFailure, + serialFailurePrefixCap, settleMatchLoad, } from './load-matches' import type { NotFoundError } from './not-found' @@ -73,15 +74,13 @@ const joinPreloadedActiveMatch = async ( const matchId = inner.matches[index]!.id // A preload can reuse an active/pending match by ID, but it does not own that - // match. If the foreground owner is already gone or aborted, this speculative - // preload pass has nothing safe to borrow. + // match. If the foreground owner is already gone, this speculative preload + // pass has nothing safe to borrow. (An aborted owner is caught by the + // re-read and check below.) let match = inner.router.getMatch(matchId, false) if (!match) { throw inner } - if (match.abortController.signal.aborted) { - throw inner - } // Wait for the borrowed match's own beforeLoad/loader/component work to reach // a terminal render state before copying it into the private preload lane. @@ -147,48 +146,46 @@ const finalizeRouteFailure = async ( index: number, error: unknown, abortController: AbortController, - componentFailure?: boolean, ): Promise => { let errorIndex = index + let componentFailure = false let currentMatch = requireCurrentMatch(inner, index, abortController) - if (!componentFailure) { - try { - if (isNotFound(error)) { - errorIndex = getNotFoundBoundaryIndex(inner, error) - const boundaryMatch = inner.matches[errorIndex]! + try { + if (isNotFound(error)) { + errorIndex = getNotFoundBoundaryIndex(inner, error) + const boundaryMatch = inner.matches[errorIndex]! - if (inner.preload?.includes(boundaryMatch.id)) { - // The selected boundary is owned by an active/pending route match. - // A speculative preload must not load its boundary component or mutate it. - throw inner - } - await loadRouteChunk( - inner.router.routesById[boundaryMatch.routeId], - 'notFoundComponent', - ) - } else if (!isRedirect(error)) { - await loadRouteChunk( - inner.router.routesById[currentMatch.routeId], - 'errorComponent', - ) - } - } catch (chunkError) { - if (chunkError === inner) { - // Preserve the stale-pass sentinel from the borrowed-boundary branch; - // it is not a component preload failure. + if (inner.preload?.includes(boundaryMatch.id)) { + // The selected boundary is owned by an active/pending route match. + // A speculative preload must not load its boundary component or mutate it. throw inner } - // This error already came from component/chunk loading, so commit it - // directly instead of trying to load another boundary component. - error = chunkError - componentFailure = true + await loadRouteChunk( + inner.router.routesById[boundaryMatch.routeId], + 'notFoundComponent', + ) + } else if (!isRedirect(error)) { + await loadRouteChunk( + inner.router.routesById[currentMatch.routeId], + 'errorComponent', + ) } - - currentMatch = requireCurrentMatch(inner, index, abortController) + } catch (chunkError) { + if (chunkError === inner) { + // Preserve the stale-pass sentinel from the borrowed-boundary branch; + // it is not a component preload failure. + throw inner + } + // This error already came from component/chunk loading, so commit it + // directly instead of trying to load another boundary component. + error = chunkError + componentFailure = true } + currentMatch = requireCurrentMatch(inner, index, abortController) + const pendingWait = waitPendingMin(currentMatch) if (pendingWait) { await pendingWait @@ -221,13 +218,6 @@ const finalizeRouteFailure = async ( } } - const matchToCommit = inner.matches[errorIndex] - if (!matchToCommit) { - // The lane was shortened by a newer outcome before this finalizer could - // commit. Cancel this stale finalizer. - throw inner - } - inner.requiresCommit = true markError(inner, errorIndex) @@ -238,7 +228,7 @@ const finalizeRouteFailure = async ( context: getMatchContext( inner, errorIndex, - matchToCommit.__beforeLoadContext, + inner.matches[errorIndex]!.__beforeLoadContext, ), updatedAt: Date.now(), }) @@ -269,7 +259,7 @@ const setupPendingTimeout = ( if ( match.status === 'pending' && onReady && - !inner.pendingPublished && + !inner.rendered && (routeOptions.pendingComponent ?? (inner.router.options as any).defaultPendingComponent) ) { @@ -284,14 +274,13 @@ const setupPendingTimeout = ( const publish = () => { const current = inner.matches[index] if ( - !inner.pendingPublished && + !inner.rendered && current?._.loadPromise === promise && current.status === 'pending' ) { // Publish the current render-ready lane so pending UI can render while // beforeLoad/loader work continues. - inner.pendingPublished = true - inner.rendered ||= onReady(inner.matches.slice()) ?? true + inner.rendered = onReady(inner.matches.slice()) ?? true } } @@ -546,9 +535,13 @@ const loadClientRouteMatch = async ( return finishMatchLoad(inner, index) } + // A serial failure is part of the foreground render lane. Retained + // ancestors must honor shouldReload/staleTime in that lane instead of + // being deferred into background work that may be discarded by the boundary. if ( loader && inner.background && + !inner.serialFailure && (loaderOption?.staleReloadMode ?? router.options.defaultStaleReloadMode) !== 'blocking' ) { @@ -836,13 +829,11 @@ export function startBackgroundLoad( } if (redirectError) { - if (isCurrent()) { - void router.navigate({ - ...(redirectError as any).options, - replace: true, - ignoreBlocker: true, - }) - } + void router.navigate({ + ...(redirectError as any).options, + replace: true, + ignoreBlocker: true, + }) return } @@ -850,7 +841,6 @@ export function startBackgroundLoad( // eslint-disable-next-line prefer-const let [index, error] = failure try { - requireCurrent() await loadRouteChunk( router.routesById[matches[index]!.routeId], 'errorComponent', @@ -879,7 +869,6 @@ export function startBackgroundLoad( const index = getNotFoundBoundaryIndex(inner, notFoundError) const match = matches[index]! try { - requireCurrent() await loadRouteChunk( router.routesById[match.routeId], 'notFoundComponent', @@ -941,11 +930,12 @@ export async function loadClientMatches( const matchPromises: Array> = [] let firstNotFound: NotFoundError | undefined - let failure: SerialFailure | undefined for ( let i = 0; - i < inner.matches.length && !failure && inner.badIndex === undefined; + i < inner.matches.length && + !inner.serialFailure && + inner.badIndex === undefined; i++ ) { try { @@ -966,7 +956,7 @@ export async function loadClientMatches( isNotFound(dehydratedMatch.error)) || dehydratedMatch.status === 'error' ) { - failure = [i, dehydratedMatch.error] + inner.serialFailure = [i, dehydratedMatch.error] break } matchPromises[i] = loadClientRouteMatch(inner, matchPromises, i) @@ -975,9 +965,11 @@ export async function loadClientMatches( const beforeLoadResult = handleClientBeforeLoad(inner, i) if (isPromise(beforeLoadResult)) { - failure = (await beforeLoadResult) as SerialFailure | undefined + inner.serialFailure = (await beforeLoadResult) as + | SerialFailure + | undefined } else { - failure = beforeLoadResult as SerialFailure | undefined + inner.serialFailure = beforeLoadResult as SerialFailure | undefined } } catch (err) { if (err === inner) { @@ -994,32 +986,19 @@ export async function loadClientMatches( } let maxIndexExclusive = inner.badIndex ?? inner.matches.length - if (failure) { - const [index, error] = failure + if (inner.serialFailure) { maxIndexExclusive = Math.min( maxIndexExclusive, - isRedirect(error) - ? 0 - : isNotFound(error) - ? Math.min(getNotFoundBoundaryIndex(inner, error) + 1, index) - : index, + serialFailurePrefixCap(inner, inner.serialFailure), ) } - const background = inner.background - if (failure) { - // A serial failure is part of the foreground render lane. Retained - // ancestors must honor shouldReload/staleTime in that lane instead of - // being deferred into background work that may be discarded by the boundary. - inner.background = undefined - } for (let i = 0; i < maxIndexExclusive; i++) { matchPromises[i] ||= loadClientRouteMatch(inner, matchPromises, i) } - inner.background = background - if (failure) { - const [index, error] = failure + if (inner.serialFailure) { + const [index, error] = inner.serialFailure matchPromises.push( finalizeRouteFailure( inner, diff --git a/packages/router-core/src/load-matches.server.ts b/packages/router-core/src/load-matches.server.ts index 0176a1f5e0..ede7c9565d 100644 --- a/packages/router-core/src/load-matches.server.ts +++ b/packages/router-core/src/load-matches.server.ts @@ -11,6 +11,7 @@ import { getNotFoundBoundaryIndex, markError, normalizeRouteFailure, + serialFailurePrefixCap, } from './load-matches' import type { NotFoundError } from './not-found' import type { @@ -434,15 +435,9 @@ export const loadServerMatches = async ( } const failure = inner.serialFailure - let maxIndexExclusive = inner.matches.length - if (failure) { - const [index, error] = failure - maxIndexExclusive = isRedirect(error) - ? 0 - : isNotFound(error) - ? Math.min(getNotFoundBoundaryIndex(inner, error) + 1, index) - : index - } + const maxIndexExclusive = failure + ? serialFailurePrefixCap(inner, failure) + : inner.matches.length for (let i = 0; i < maxIndexExclusive; i++) { matchPromises[i] ||= loadServerRouteMatch(inner, matchPromises, i) @@ -457,26 +452,14 @@ export const loadServerMatches = async ( let fatalError: unknown let hasFatalError = false - const results = await Promise.all( - matchPromises.map((promise) => - promise.then( - () => ({ ok: true as const }), - (reason) => ({ - ok: false as const, - error: - process.env.NODE_ENV !== 'production' && reason === undefined - ? new Error('Route load failed with undefined') - : reason, - }), - ), - ), - ) - - for (const result of results) { - if (result.ok) { + for (const result of await Promise.allSettled(matchPromises)) { + if (result.status === 'fulfilled') { continue } - const reason = result.error + const reason = + process.env.NODE_ENV !== 'production' && result.reason === undefined + ? new Error('Route load failed with undefined') + : result.reason if (isRedirect(reason)) { firstRedirect ||= reason } else if (isNotFound(reason)) { diff --git a/packages/router-core/src/load-matches.ts b/packages/router-core/src/load-matches.ts index 3bdccc7c6b..f966c6c2cd 100644 --- a/packages/router-core/src/load-matches.ts +++ b/packages/router-core/src/load-matches.ts @@ -12,10 +12,11 @@ export type InnerLoadContext = { router: AnyRouter /** Target location for this private load lane. */ location: ParsedLocation - /** Framework render promise returned by pending publication. */ + /** + * Pending lane was published for presentation (truthy = published; a Promise + * is the framework render promise to await). Final commit still owns effects. + */ rendered?: true | Promise - /** Pending lane was published for presentation; final commit still owns effects. */ - pendingPublished?: true /** Private match lane being loaded. */ matches: Array /** @@ -29,7 +30,7 @@ export type InnerLoadContext = { forceStaleReload?: boolean /** Callback that publishes pending UI when the lane becomes renderable. */ onReady?: (matches: Array) => void | Promise - /** Server beforeLoad failure captured during the serial phase. */ + /** beforeLoad failure captured during the serial phase. */ serialFailure?: SerialFailure /** Client background reload indices selected during foreground matching. */ background?: Array @@ -127,6 +128,22 @@ export const getNotFoundBoundaryIndex = ( return requestedRouteId ? startIndex : 0 } +/** + * Exclusive loader-prefix bound for a serial beforeLoad failure: redirects + * run no loaders, notFounds run up to the selected boundary (never past the + * throwing route), regular errors run everything before the failing route. + * Single owner of this rule for the client and server pipelines. + */ +export const serialFailurePrefixCap = ( + inner: InnerLoadContext, + [index, error]: SerialFailure, +): number => + isRedirect(error) + ? 0 + : isNotFound(error) + ? Math.min(getNotFoundBoundaryIndex(inner, error) + 1, index) + : index + export const normalizeRouteFailure = ( inner: InnerLoadContext, index: number, diff --git a/packages/router-core/src/route-assets.client.ts b/packages/router-core/src/route-assets.client.ts index 26180b5dc3..4c9b53f7b8 100644 --- a/packages/router-core/src/route-assets.client.ts +++ b/packages/router-core/src/route-assets.client.ts @@ -33,8 +33,6 @@ export function projectClientRouteAssets( isCurrent?: () => boolean, startIndex = 0, ): boolean | Promise { - let ok = true - for (let i = startIndex; i < matches.length; i++) { if (isCurrent && !isCurrent()) { return false @@ -97,7 +95,7 @@ export function projectClientRouteAssets( isCurrent, i + 1, ) - return isPromise(rest) ? rest.then((r) => r && ok) : rest && ok + return rest }, (error) => { if (isCurrent && !isCurrent()) { @@ -129,12 +127,22 @@ export function projectClientRouteAssets( return false } - ok = false if (process.env.NODE_ENV !== 'production') { console.error(`Error executing head for route ${match.routeId}:`, error) } + + // Keep projecting the rest of the lane, but force the overall result + // to false — same shape as the async rejection handler above. + const rest = projectClientRouteAssets( + router, + matches, + preload, + isCurrent, + i + 1, + ) + return isPromise(rest) ? rest.then(() => false) : false } } - return ok + return true } diff --git a/packages/router-core/src/router-load.client.ts b/packages/router-core/src/router-load.client.ts index 46ce9bbe43..d8c67416f8 100644 --- a/packages/router-core/src/router-load.client.ts +++ b/packages/router-core/src/router-load.client.ts @@ -175,7 +175,6 @@ export const loadClientRouter = async ( }) } - let loadedMatches: Array = pendingMatches const background = opts?.sync ? undefined : ([] as Array) const commitReady = (matches: Array) => { if (!isCurrentLoad()) { @@ -218,9 +217,9 @@ export const loadClientRouter = async ( onReady: commitReady, } try { - loadedMatches = (await loadClientMatches( - loadContext, - )) as Array + // loadClientMatches mutates the pendingMatches lane in place; its + // return value is that same array. + await loadClientMatches(loadContext) } catch (err) { if (err === loadContext) { // This foreground lane was superseded before reaching a route outcome. @@ -234,7 +233,7 @@ export const loadClientRouter = async ( } const backgroundIndices = background?.filter((index) => { - const match = loadedMatches[index] + const match = pendingMatches[index] return match && match.status === 'success' && !match.globalNotFound }) const backgroundLength = backgroundIndices?.length @@ -242,7 +241,7 @@ export const loadClientRouter = async ( sameHref && backgroundLength && !loadContext.requiresCommit && - !loadContext.pendingPublished + !loadContext.rendered if (isCurrentLoad()) { if (backgroundOnly) { @@ -255,7 +254,7 @@ export const loadClientRouter = async ( } else { const assets = projectClientRouteAssets( router, - loadedMatches, + pendingMatches, undefined, isCurrentLoad, ) @@ -266,7 +265,7 @@ export const loadClientRouter = async ( await router.startViewTransition(async () => { if (isCurrentLoad()) { router.startTransition(() => { - commitFinalMatches(router, baseMatches, loadedMatches) + commitFinalMatches(router, baseMatches, pendingMatches) }) } }) @@ -275,7 +274,7 @@ export const loadClientRouter = async ( } if (isCurrentLoad() && backgroundLength) { startedBackgroundLoad = true - startBackgroundLoad(router, next, loadedMatches, backgroundIndices) + startBackgroundLoad(router, next, pendingMatches, backgroundIndices) } } catch (err) { if (isCurrentLoad() && isRedirect(err)) { @@ -307,12 +306,17 @@ export const loadClientRouter = async ( // the navigation chain does: callers of router.load()/invalidate() rely on // observing post-settlement state, and the preload borrow protocol uses the // foreground load promise as its "committed or gone" signal. + // + // Termination invariant: latestLoadPromise is only ever installed as a fresh + // promise by a newer pass (top of this function) or cleared to undefined by + // the owning pass in the same sync block that resolves it (above). So after + // `await latest`, latestLoadPromise is either undefined or a strictly newer + // pass's promise — never `latest` (or this pass's loadPromise) again. Any + // future writer that resolves latestLoadPromise without replacing/clearing + // it would turn this loop into an infinite microtask spin. let latest = router.latestLoadPromise - while (latest && latest !== loadPromise) { + while (latest) { await latest - if (router.latestLoadPromise === latest) { - break - } latest = router.latestLoadPromise } diff --git a/packages/router-core/src/router-load.server.ts b/packages/router-core/src/router-load.server.ts index c31acb8e64..c4c331ddce 100644 --- a/packages/router-core/src/router-load.server.ts +++ b/packages/router-core/src/router-load.server.ts @@ -79,7 +79,6 @@ export const loadServerRouter = async ( router.redirect = resolvedRedirect } finally { const commitLocationPromise = router.commitLocationPromise - router.latestLoadPromise = undefined router.commitLocationPromise = undefined commitLocationPromise?.resolve() } diff --git a/packages/router-core/src/router-preload.client.ts b/packages/router-core/src/router-preload.client.ts index 38aed22561..98ce4eca10 100644 --- a/packages/router-core/src/router-preload.client.ts +++ b/packages/router-core/src/router-preload.client.ts @@ -14,7 +14,7 @@ export const preloadClientRoute = async ( ): Promise | undefined> => { const next = opts._builtLocation ?? router.buildLocation(opts) - let matches = router.matchRoutes(next, { + const matches = router.matchRoutes(next, { throwOnError: true, preload: true, }) @@ -72,7 +72,8 @@ export const preloadClientRoute = async ( } try { - matches = await loadClientMatches(loadContext) + // loadClientMatches mutates the lane in place and returns it. + await loadClientMatches(loadContext) await cacheSuccessfulPrefix() diff --git a/packages/router-core/src/router.ts b/packages/router-core/src/router.ts index 6586250b60..f2394f2119 100644 --- a/packages/router-core/src/router.ts +++ b/packages/router-core/src/router.ts @@ -37,7 +37,7 @@ import { defaultParseSearch, defaultStringifySearch } from './searchParams' import { rootRouteId } from './root' import { isRedirect } from './redirect' import { getLocationChangeInfo } from './location-change' -import { settleMatchLoad } from './load-matches' +import { getMatchContext, settleMatchLoad } from './load-matches' import { preloadClientRoute } from './router-preload.client' import { loadClientRouter } from './router-load.client' import { loadServerRouter } from './router-load.server' @@ -1184,17 +1184,7 @@ export class RouterCore< if (!this.stores && this.latestLocation) { const config = this.getStoreConfig(this) this.batch = config.batch - this.stores = createRouterStores( - { - loadedAt: 0, - isLoading: false, - status: 'idle', - resolvedLocation: undefined, - location: this.latestLocation, - matches: [], - }, - config, - ) + this.stores = createRouterStores(this.latestLocation, config) if (!(isServer ?? this.isServer)) { setupScrollRestoration(this) @@ -1612,13 +1602,10 @@ export class RouterCore< // dehydrated match can legitimately hold a pending loadPromise // (hydration keeps readiness across rematching), and dropping the // marker would make the follow-up load re-run its server work. - _: - loadPromise || existingMatch._.dehydrated - ? { - loadPromise, - dehydrated: existingMatch._.dehydrated, - } - : {}, + _: { + loadPromise, + dehydrated: existingMatch._.dehydrated, + }, search, _strictSearch: strictMatchSearch, searchError, @@ -1686,15 +1673,11 @@ export class RouterCore< } as RouteContextOptions) } - if (match.__routeContext || match.__beforeLoadContext) { - match.context = { - ...parentContext, - ...match.__routeContext, - ...match.__beforeLoadContext, - } - } else { - match.context = parentContext - } + match.context = getMatchContext( + { router: this, matches }, + index, + match.__beforeLoadContext, + ) } for (let i = 0; i < matches.length; i++) { @@ -1801,7 +1784,7 @@ export class RouterCore< } for (const matchId of this.stores.pendingIds.get()) { - const match = this.getMatch(matchId) + const match = this.stores.pendingMatchStores.get(matchId)?.get() if (match) { cancelMatch(match) } @@ -1818,7 +1801,7 @@ export class RouterCore< // handed that signal to still-streaming deferred data, and the public // contract only cancels it when the route unloads or its loader call // becomes outdated. - const match = this.getMatch(matchId) + const match = this.stores.matchStores.get(matchId)?.get() if (match && (match.status === 'pending' || match.isFetching !== false)) { cancelMatch(match) } @@ -2481,37 +2464,35 @@ export class RouterCore< TDehydrated > > = (opts) => { - const invalidateLive = (d: MakeRouteMatch) => { - if (opts?.filter?.(d as MakeRouteMatchUnion) ?? true) { + // `live` gates the only policy difference between the pools: cached + // entries stay `status: 'success'` until they are reused, expired, or + // explicitly cleared, so only live/pending matches may flip to pending. + const makeInvalidate = + (live: boolean) => (d: MakeRouteMatch) => { + if (!(opts?.filter?.(d as MakeRouteMatchUnion) ?? true)) { + return d + } return { ...d, invalid: true, - ...(opts?.forcePending || - d.status === 'error' || - d.status === 'notFound' + ...(live && + (opts?.forcePending || + d.status === 'error' || + d.status === 'notFound') ? ({ status: 'pending', error: undefined } as const) : undefined), } } - return d - } - const invalidateCached = (d: MakeRouteMatch) => { - if (opts?.filter?.(d as MakeRouteMatchUnion) ?? true) { - return { - ...d, - invalid: true, - } - } - return d - } this.batch(() => { - this.stores.setMatches(this.stores.matches.get().map(invalidateLive)) + this.stores.setMatches( + this.stores.matches.get().map(makeInvalidate(true)), + ) this.stores.setCached( - this.stores.cachedMatches.get().map(invalidateCached), + this.stores.cachedMatches.get().map(makeInvalidate(false)), ) this.stores.setPending( - this.stores.pendingMatches.get().map(invalidateLive), + this.stores.pendingMatches.get().map(makeInvalidate(true)), ) }) diff --git a/packages/router-core/src/ssr/ssr-client.ts b/packages/router-core/src/ssr/ssr-client.ts index 5f3449f155..a2a2889cf8 100644 --- a/packages/router-core/src/ssr/ssr-client.ts +++ b/packages/router-core/src/ssr/ssr-client.ts @@ -110,8 +110,6 @@ export async function hydrate(router: AnyRouter): Promise { } } - route.options.ssr = match.ssr - match._.dehydrated = match.ssr !== false if (match.ssr === false) { @@ -334,8 +332,8 @@ export async function hydrate(router: AnyRouter): Promise { return } - void Promise.resolve() - .then(() => router.load()) + void router + .load() .catch((err) => { if (process.env.NODE_ENV !== 'production') { console.error('Error during router hydration:', err) diff --git a/packages/router-core/src/stores.ts b/packages/router-core/src/stores.ts index 910d681e97..45e08ac3b1 100644 --- a/packages/router-core/src/stores.ts +++ b/packages/router-core/src/stores.ts @@ -111,7 +111,7 @@ export interface RouterStores { } export function createRouterStores( - initialState: RouterState & { loadedAt: number }, + initialLocation: ParsedLocation>, config: StoreConfig, ): RouterStores { const { createMutableStore, createReadonlyStore, batch, init } = config @@ -122,11 +122,13 @@ export function createRouterStores( const cachedMatchStores = new Map() // atoms - const status = createMutableStore(initialState.status) - const loadedAt = createMutableStore(initialState.loadedAt) - const isLoading = createMutableStore(initialState.isLoading) - const location = createMutableStore(initialState.location) - const resolvedLocation = createMutableStore(initialState.resolvedLocation) + const status = createMutableStore['status']>('idle') + const loadedAt = createMutableStore(0) + const isLoading = createMutableStore(false) + const location = createMutableStore(initialLocation) + const resolvedLocation = createMutableStore< + ParsedLocation> | undefined + >(undefined) const matchesId = createMutableStore>([]) const pendingIds = createMutableStore>([]) const cachedIds = createMutableStore>([]) @@ -236,8 +238,6 @@ export function createRouterStores( setCached, } as RouterStores - // initialize the active matches - setMatches(initialState.matches as Array) init?.(store as unknown as RouterStores) // setters to update non-reactive utilities in sync with the reactive stores diff --git a/packages/router-core/tests/serial-failure-foreground-prefix.test.ts b/packages/router-core/tests/serial-failure-foreground-prefix.test.ts new file mode 100644 index 0000000000..6a5a5e2108 --- /dev/null +++ b/packages/router-core/tests/serial-failure-foreground-prefix.test.ts @@ -0,0 +1,76 @@ +import { describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +/** + * When the serial beforeLoad phase records a failure, retained ancestor + * prefix loaders belong to the foreground failure lane: a stale ancestor + * must reload in the foreground commit rather than being deferred into a + * background batch that the boundary trim would discard. + */ + +describe('serial failure keeps ancestor reloads in the foreground lane', () => { + test('a stale ancestor reloads with fresh data when a child beforeLoad fails', async () => { + let parentRuns = 0 + let shouldFail = false + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + staleTime: 0, + loader: () => `parent run ${++parentRuns}`, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + errorComponent: {}, + beforeLoad: () => { + if (shouldFail) { + throw new Error('child beforeLoad failed') + } + }, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + }) + + await router.load() + expect(parentRuns).toBe(1) + + await router.navigate({ to: '/' }) + shouldFail = true + await router.navigate({ to: '/parent/child' }) + + const parentMatch = router.state.matches.find( + (match) => match.routeId === parentRoute.id, + ) + const childMatch = router.state.matches.find( + (match) => match.routeId === childRoute.id, + ) + + // The child committed its serial failure... + expect(childMatch?.status).toBe('error') + // ...and the stale parent reloaded in the SAME foreground lane: fresh + // loaderData is committed with the failure, not deferred to a discarded + // background batch. + await vi.waitFor(() => { + expect(parentRuns).toBe(2) + expect( + router.state.matches.find((match) => match.routeId === parentRoute.id) + ?.loaderData, + ).toBe('parent run 2') + }) + expect(parentMatch?.status).toBe('success') + }) +}) diff --git a/packages/router-core/tests/superseded-load-await.test.ts b/packages/router-core/tests/superseded-load-await.test.ts index 471fb9b189..e8284edc89 100644 --- a/packages/router-core/tests/superseded-load-await.test.ts +++ b/packages/router-core/tests/superseded-load-await.test.ts @@ -82,4 +82,88 @@ describe('superseded load await', () => { expect(secondLoaderSettled).toBe(true) expect(supersededLoadSettled).toBe(true) }) + + // Multi-supersession drain: L1 superseded by L2 superseded by L3, and a + // fourth navigation (L4) started while L1 is already parked in its drain + // loop. Gates resolve out of order. L1's public await must not settle until + // the entire navigation chain drains (L4 commits), which forces the drain + // loop to re-read latestLoadPromise across multiple iterations. + test('superseded load drains a multi-supersession chain (out-of-order gates)', async () => { + const gates = { + one: createControlledPromise(), + two: createControlledPromise(), + three: createControlledPromise(), + four: createControlledPromise(), + } + const calls: Array = [] + let load1Settled = false + let lastSettled: string | undefined + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const mkRoute = (name: keyof typeof gates) => + new BaseRoute({ + getParentRoute: () => rootRoute, + path: `/${name}`, + loader: async () => { + calls.push(name) + await gates[name] + lastSettled = name + return name + }, + }) + const one = mkRoute('one') + const two = mkRoute('two') + const three = mkRoute('three') + const four = mkRoute('four') + + const history = createMemoryHistory({ initialEntries: ['/'] }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, one, two, three, four]), + history, + }) + await router.load() + + history.push('/one') + const load1 = router.load().then(() => { + load1Settled = true + }) + await vi.waitFor(() => expect(calls).toContain('one')) + + const nav2 = router.navigate({ to: '/two' }) + await vi.waitFor(() => expect(calls).toContain('two')) + const nav3 = router.navigate({ to: '/three' }) + await vi.waitFor(() => expect(calls).toContain('three')) + + // Finish L1's own pass first: it must park in the drain loop. + gates.one.resolve() + await waitForMacrotask() + expect(load1Settled).toBe(false) + + // Now start a 4th navigation while L1 is already awaiting the chain. + const nav4 = router.navigate({ to: '/four' }) + await vi.waitFor(() => expect(calls).toContain('four')) + + // Resolve remaining gates out of order: L3, then L2, then L4. + gates.three.resolve() + await waitForMacrotask() + expect(load1Settled).toBe(false) + + gates.two.resolve() + await waitForMacrotask() + expect(load1Settled).toBe(false) + + gates.four.resolve() + await Promise.all([load1, nav2, nav3, nav4]) + + expect(load1Settled).toBe(true) + expect(lastSettled).toBe('four') + expect(router.latestLoadPromise).toBeUndefined() + expect( + router.stores.matches.get().some((m) => m.routeId === '/four'), + ).toBe(true) + }) }) diff --git a/packages/solid-router/src/Match.tsx b/packages/solid-router/src/Match.tsx index e256f9cf57..be032bf440 100644 --- a/packages/solid-router/src/Match.tsx +++ b/packages/solid-router/src/Match.tsx @@ -272,34 +272,6 @@ export const MatchInner = (): any => { route().options.pendingComponent ?? router.options.defaultPendingComponent - const armPending = (pendingMatch: any) => { - const FallbackComponent = PendingComponent() - const pendingMinMs = - route().options.pendingMinMs ?? router.options.defaultPendingMinMs - const loadPromise = pendingMatch._.loadPromise - const promise = - loadPromise?.status === 'pending' - ? loadPromise - : router.latestLoadPromise - - if (process.env.NODE_ENV !== 'production' && !promise) { - throw new Error( - `Invariant failed: pending match "${pendingMatch.id}" has no loadPromise`, - ) - } - - if ( - !(isServer ?? router.isServer) && - FallbackComponent && - pendingMinMs && - loadPromise?.status === 'pending' - ) { - loadPromise.pendingUntil ??= Date.now() + pendingMinMs - } - - return FallbackComponent - } - const out = () => { const Comp = route().options.component ?? router.options.defaultComponent @@ -343,15 +315,20 @@ export const MatchInner = (): any => { ) } - const FallbackComponent = + const FallbackComponent = PendingComponent() + const pendingMinMs = + route().options.pendingMinMs ?? + router.options.defaultPendingMinMs + if ( + !(isServer ?? router.isServer) && + FallbackComponent && + pendingMinMs && loadPromise?.status === 'pending' - ? armPending(currentMatch()) - : PendingComponent() + ) { + loadPromise.pendingUntil ??= Date.now() + pendingMinMs + } - const [loaderResult] = Solid.createResource(async () => { - await Promise.resolve() - return promise - }) + const [loaderResult] = Solid.createResource(() => promise) return ( <> From d5a59102f75e4702037ef1432ab97f44d5cb478f Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Sat, 4 Jul 2026 13:35:31 +0000 Subject: [PATCH 34/54] ci: apply automated fixes --- packages/router-core/tests/superseded-load-await.test.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/router-core/tests/superseded-load-await.test.ts b/packages/router-core/tests/superseded-load-await.test.ts index e8284edc89..1e01e0617d 100644 --- a/packages/router-core/tests/superseded-load-await.test.ts +++ b/packages/router-core/tests/superseded-load-await.test.ts @@ -162,8 +162,8 @@ describe('superseded load await', () => { expect(load1Settled).toBe(true) expect(lastSettled).toBe('four') expect(router.latestLoadPromise).toBeUndefined() - expect( - router.stores.matches.get().some((m) => m.routeId === '/four'), - ).toBe(true) + expect(router.stores.matches.get().some((m) => m.routeId === '/four')).toBe( + true, + ) }) }) From 022395e1991314f537299cd243aa60080156fa3e Mon Sep 17 00:00:00 2001 From: Sheraff Date: Sat, 4 Jul 2026 16:11:57 +0200 Subject: [PATCH 35/54] refactor(react-router): one deterministic emitter for the load lifecycle MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Transitioner carried two emission pipelines: render-observed usePrevious edges (lossy by design — React batching can hide a flip inside one commit) and the mount-load repair, with a setTimeout(0) arbitrating between them. Both are replaced by a single emitter driven by synchronous store subscriptions (isLoading/hasPending), which cannot miss an edge, plus one render-coupled signal for onResolved: a commit tick bumped inside the transition and observed by a layout effect, so resolution still lands after React committed the transition render. A counter rather than a boolean so nested transitions (invalidate inside a user startTransition) can never coalesce into an unobservable no-change. No timer, no arbitration, no repair block, and the mount load reduces to a bare router.load() — its own isLoading toggle through the armed subscriptions is the deterministic signal even for loads that settled before mount (the memory-benchmark case, re-verified: no hang). Net smaller than the file it replaces. Co-Authored-By: Claude Fable 5 --- packages/react-router/src/Transitioner.tsx | 182 ++++++++++----------- 1 file changed, 85 insertions(+), 97 deletions(-) diff --git a/packages/react-router/src/Transitioner.tsx b/packages/react-router/src/Transitioner.tsx index 3892ea32c6..3aee4a1f8d 100644 --- a/packages/react-router/src/Transitioner.tsx +++ b/packages/react-router/src/Transitioner.tsx @@ -1,41 +1,108 @@ 'use client' import * as React from 'react' -import { batch, useStore } from '@tanstack/react-store' +import { batch } from '@tanstack/react-store' import { getLocationChangeInfo, trimPathRight } from '@tanstack/router-core' -import { useLayoutEffect, usePrevious } from './utils' +import { useLayoutEffect } from './utils' import { useRouter } from './useRouter' export function Transitioner() { const router = useRouter() const mountLoadForRouter = React.useRef({ router, mounted: false }) - const [isTransitioning, setIsTransitioning] = React.useState(false) - // Track pending state changes - const isLoading = useStore(router.stores.isLoading, (value) => value) - const hasPending = useStore(router.stores.hasPending, (value) => value) + // `transitioning` bridges router time and React time: raised before the + // commit's startTransition, lowered by the tick effect below — which + // React runs only after committing the transition render, keeping the + // onResolved edge render-coupled. A counter (not a boolean) so nested + // transitions can never coalesce into an unobservable no-change. + const transitioning = React.useRef(false) + const [transitionTick, setTransitionTick] = React.useState(0) - const previousIsLoading = usePrevious(isLoading) + const previous = React.useRef({ + isLoading: false, + isPagePending: false, + isAnyPending: false, + }) - const isAnyPending = isLoading || isTransitioning || hasPending - const previousIsAnyPending = usePrevious(isAnyPending) + // Single emitter for the load lifecycle. Level changes arrive through + // synchronous store subscriptions — which, unlike render-observed edges, + // cannot lose a flip to React batching — plus the render-coupled + // transition edge. One emitter means nothing to arbitrate. + const emitEdges = React.useCallback(() => { + const isLoading = router.stores.isLoading.get() + const isPagePending = isLoading || router.stores.hasPending.get() + const isAnyPending = isPagePending || transitioning.current + const prev = previous.current + previous.current = { isLoading, isPagePending, isAnyPending } - const isPagePending = isLoading || hasPending - const previousIsPagePending = usePrevious(isPagePending) + const changeInfo = () => + getLocationChangeInfo( + router.stores.location.get(), + router.stores.resolvedLocation.get(), + ) + + if (prev.isLoading && !isLoading) { + // The new URL has committed and the new matches are in state.matches. + router.emit({ type: 'onLoad', ...changeInfo() }) + } + if (prev.isPagePending && !isPagePending) { + router.emit({ type: 'onBeforeRouteMount', ...changeInfo() }) + } + if (prev.isAnyPending && !isAnyPending) { + router.emit({ type: 'onResolved', ...changeInfo() }) + batch(() => { + router.stores.status.set('idle') + router.stores.resolvedLocation.set(router.stores.location.get()) + }) + } + }, [router]) router.startTransition = (fn: () => void) => { - setIsTransitioning(true) + transitioning.current = true + // Register the rising transition level so the falling edge resolves + // even when the load's own levels already settled. + emitEdges() React.startTransition(() => { try { fn() } finally { - // A throwing commit must not strand isTransitioning, which would - // permanently block onResolved and the idle status transition. - setIsTransitioning(false) + // A throwing commit must not strand the transition level, which + // would permanently block onResolved and the idle transition. + setTransitionTick((tick) => tick + 1) } }) } + // Render-coupled falling edge: this effect runs only after React + // committed the render that included the transition's tick bump. + useLayoutEffect(() => { + if (transitioning.current) { + transitioning.current = false + emitEdges() + } + }, [transitionTick, emitEdges]) + + // Armed before the mount load below, so every load — including one that + // settled before mount (the mount load below still toggles isLoading) — + // produces an observable edge. + useLayoutEffect(() => { + previous.current.isLoading = router.stores.isLoading.get() + previous.current.isPagePending = + previous.current.isLoading || router.stores.hasPending.get() + previous.current.isAnyPending = + previous.current.isPagePending || transitioning.current + + const subscriptions = [ + router.stores.isLoading.subscribe(emitEdges), + router.stores.hasPending.subscribe(emitEdges), + ] + return () => { + for (const subscription of subscriptions) { + subscription.unsubscribe() + } + } + }, [router, emitEdges]) + // Subscribe to location changes // and try to load the new location React.useEffect(() => { @@ -77,89 +144,10 @@ export function Transitioner() { } mountLoadForRouter.current = { router, mounted: true } - const tryLoad = async () => { - try { - await router.load() - } catch (err) { - console.error(err) - } - - // A mount load can settle before this component observes the - // isLoading flip (loads started before mount, or loads completing - // within this effect's batch), leaving the router status stuck at - // 'pending' so the load lifecycle events and onRendered never fire. - // Repair is deferred one macrotask: when the flips WERE observed, - // React's already-scheduled render/effects run first, emit the - // events, and set status 'idle' via the onResolved effect — making - // this a no-op. Only a genuinely unobserved load still reads - // 'pending' here, and then this emits what the pipeline would have. - setTimeout(() => { - if ( - router.stores.status.get() === 'pending' && - !router.stores.isLoading.get() && - !router.stores.hasPending.get() - ) { - const changeInfo = getLocationChangeInfo( - router.stores.location.get(), - router.stores.resolvedLocation.get(), - ) - router.emit({ type: 'onLoad', ...changeInfo }) - router.emit({ type: 'onBeforeRouteMount', ...changeInfo }) - router.emit({ type: 'onResolved', ...changeInfo }) - batch(() => { - router.stores.status.set('idle') - router.stores.resolvedLocation.set(router.stores.location.get()) - }) - } - }, 0) - } - - tryLoad() + router.load().catch((err) => { + console.error(err) + }) }, [router]) - useLayoutEffect(() => { - // The router was loading and now it's not - if (previousIsLoading && !isLoading) { - router.emit({ - type: 'onLoad', // When the new URL has committed, when the new matches have been loaded into state.matches - ...getLocationChangeInfo( - router.stores.location.get(), - router.stores.resolvedLocation.get(), - ), - }) - } - }, [previousIsLoading, router, isLoading]) - - useLayoutEffect(() => { - // emit onBeforeRouteMount - if (previousIsPagePending && !isPagePending) { - router.emit({ - type: 'onBeforeRouteMount', - ...getLocationChangeInfo( - router.stores.location.get(), - router.stores.resolvedLocation.get(), - ), - }) - } - }, [isPagePending, previousIsPagePending, router]) - - useLayoutEffect(() => { - if (previousIsAnyPending && !isAnyPending) { - const changeInfo = getLocationChangeInfo( - router.stores.location.get(), - router.stores.resolvedLocation.get(), - ) - router.emit({ - type: 'onResolved', - ...changeInfo, - }) - - batch(() => { - router.stores.status.set('idle') - router.stores.resolvedLocation.set(router.stores.location.get()) - }) - } - }, [isAnyPending, previousIsAnyPending, router]) - return null } From e9deed2277fc418a1318ec0eccf1e2b646a42c60 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Sat, 4 Jul 2026 17:30:54 +0200 Subject: [PATCH 36/54] refactor: delete hedges against invariants the model already guarantees (core) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Trust-the-model sweep over the combined diff, core half — every deletion adversarially verified against INTERNALS and the suites: - Dead mechanism: the server redirect path's write-only match._.error (vestige of main's removed 'redirected' status; its only reader is the client-only preload borrow protocol), the reloadDocument carve-out in the server redirect short-circuit (client-navigation concept), and the rendered field's never-used promise arm — onReady is now a void callback and publication is synchronous by contract. - Duplicate signal writers: finalizeRouteFailure's notFound branch no longer sets requiresCommit (this branch always throws; the loadClientRouter catch owns the flag for thrown outcomes), and backgroundOnly drops its !rendered condition (pending publication implies requiresCommit). - Unreachable defenses: the serial loop's badIndex condition (badIndex is loader-phase-only by construction), the server finalizer's missing-match guard (the linear server lane cannot shorten mid- finalizer), redundant ownership re-checks with no async gap, and the background chunk catches' sentinel classification that duplicated the following isCurrentOrCancel. - One owner per rule: recordBeforeLoadFailure takes the pass controller instead of re-deriving it, and commitServerNotFoundBoundary now uses the shared getNotFoundBoundaryPatch. Each deleted hedge leaves a one-line invariant comment where a future reader might be tempted to re-add it. Full router-core suite green. Co-Authored-By: Claude Fable 5 --- packages/router-core/INTERNALS.md | 7 +-- .../router-core/src/load-matches.client.ts | 54 ++++++++----------- .../router-core/src/load-matches.server.ts | 36 ++----------- packages/router-core/src/load-matches.ts | 15 +++--- .../router-core/src/router-load.client.ts | 11 ++-- packages/router-core/tests/load.test.ts | 35 ++++++------ 6 files changed, 62 insertions(+), 96 deletions(-) diff --git a/packages/router-core/INTERNALS.md b/packages/router-core/INTERNALS.md index 58938977c9..1f1cffcff4 100644 --- a/packages/router-core/INTERNALS.md +++ b/packages/router-core/INTERNALS.md @@ -347,8 +347,9 @@ is the `backgroundOnly` case: - The target href equals the resolved/current href. - The filtered background list is non-empty. -- No route work set `requiresCommit`. -- No pending UI was published. +- No route work set `requiresCommit`. (Pending-UI publication implies + `requiresCommit`: pending UI can only be published for a pending-status + match, and every pending-status match forces `requiresCommit`.) The foreground pass clears pending/isLoading and then starts the background reload. If a background load was started, `loadClientRouter()` yields one @@ -375,7 +376,7 @@ flowchart TD BF -->|"redirect"| Prefix0["loader prefix length = 0"] BF -->|"notFound"| NFPrefix["prefix = min(boundary + 1, failing index)"] BF -->|"regular error"| ErrPrefix["prefix ends before failing route"] - BF -->|"none"| FullPrefix["prefix = full lane or first bad index"] + BF -->|"none"| FullPrefix["prefix = full lane"] Prefix0 --> Loaders["start loader/chunk promises for prefix"] NFPrefix --> Loaders diff --git a/packages/router-core/src/load-matches.client.ts b/packages/router-core/src/load-matches.client.ts index c66290cdfd..57d39eb0b7 100644 --- a/packages/router-core/src/load-matches.client.ts +++ b/packages/router-core/src/load-matches.client.ts @@ -204,8 +204,8 @@ const finalizeRouteFailure = async ( } if (isNotFound(error)) { - inner.requiresCommit = true - + // No requiresCommit write here: this branch always throws, and + // loadClientRouter's catch owns the flag for thrown outcomes. commitMatch(inner, index, { status: 'notFound', error, @@ -238,9 +238,9 @@ const finalizeRouteFailure = async ( const recordBeforeLoadFailure = ( inner: InnerLoadContext, index: number, + abortController: AbortController, error: unknown, ): SerialFailure => { - const abortController = inner.matches[index]!.abortController requireCurrentMatch(inner, index, abortController) error = normalizeRouteFailure(inner, index, error) requireCurrentMatch(inner, index, abortController).__beforeLoadContext = @@ -280,7 +280,8 @@ const setupPendingTimeout = ( ) { // Publish the current render-ready lane so pending UI can render while // beforeLoad/loader work continues. - inner.rendered = onReady(inner.matches.slice()) ?? true + onReady(inner.matches.slice()) + inner.rendered = true } } @@ -330,7 +331,7 @@ const handleClientBeforeLoad = ( if (serialError !== undefined) { pending() - return recordBeforeLoadFailure(inner, index, serialError) + return recordBeforeLoadFailure(inner, index, abortController, serialError) } setupPendingTimeout(inner, routeOptions, index, existingMatch) @@ -355,7 +356,12 @@ const handleClientBeforeLoad = ( requireCurrentMatch(inner, index, abortController) if (isRouteControl(beforeLoadContext)) { - return recordBeforeLoadFailure(inner, index, beforeLoadContext) + return recordBeforeLoadFailure( + inner, + index, + abortController, + beforeLoadContext, + ) } commitBeforeLoad(beforeLoadContext) @@ -396,10 +402,9 @@ const handleClientBeforeLoad = ( if (isPromise(beforeLoadContext)) { requireCurrentMatch(inner, index, abortController) pending() - return beforeLoadContext.then(updateContext, (err) => { - requireCurrentMatch(inner, index, abortController) - return recordBeforeLoadFailure(inner, index, err) - }) + return beforeLoadContext.then(updateContext, (err) => + recordBeforeLoadFailure(inner, index, abortController, err), + ) } } catch (err) { if (err === inner) { @@ -407,7 +412,7 @@ const handleClientBeforeLoad = ( } pending() - return recordBeforeLoadFailure(inner, index, err) + return recordBeforeLoadFailure(inner, index, abortController, err) } return updateContext(beforeLoadContext) @@ -550,6 +555,10 @@ const loadClientRouteMatch = async ( } } + // Must stay before the first await and keep the status === 'pending' + // disjunct: the backgroundOnly decision in loadClientRouter relies on every + // pending-status lane match setting requiresCommit, since pending UI can + // only be published for a pending match. if (loader || match.status === 'pending' || match.invalid) { inner.requiresCommit = true } @@ -787,7 +796,6 @@ export function startBackgroundLoad( throw error } - requireCurrent() return (matches[index] = { ...match, isFetching: false, @@ -847,10 +855,6 @@ export function startBackgroundLoad( ) requireCurrent() } catch (componentError) { - if (componentError === token) { - cancelBatch() - return - } if (!isCurrentOrCancel()) { return } @@ -880,10 +884,6 @@ export function startBackgroundLoad( invalid: false, } } catch (componentError) { - if (componentError === token) { - cancelBatch() - return - } if (!isCurrentOrCancel()) { return } @@ -931,13 +931,7 @@ export async function loadClientMatches( let firstNotFound: NotFoundError | undefined - for ( - let i = 0; - i < inner.matches.length && - !inner.serialFailure && - inner.badIndex === undefined; - i++ - ) { + for (let i = 0; i < inner.matches.length && !inner.serialFailure; i++) { try { if (inner.preload?.includes(inner.matches[i]!.id)) { await (matchPromises[i] = joinPreloadedActiveMatch(inner, i)) @@ -985,7 +979,7 @@ export async function loadClientMatches( } } - let maxIndexExclusive = inner.badIndex ?? inner.matches.length + let maxIndexExclusive = inner.matches.length if (inner.serialFailure) { maxIndexExclusive = Math.min( maxIndexExclusive, @@ -1066,10 +1060,6 @@ export async function loadClientMatches( } } - if (inner.rendered && inner.rendered !== true) { - await inner.rendered - } - if (firstNotFound) { throw firstNotFound } diff --git a/packages/router-core/src/load-matches.server.ts b/packages/router-core/src/load-matches.server.ts index ede7c9565d..ed6dd1c3e7 100644 --- a/packages/router-core/src/load-matches.server.ts +++ b/packages/router-core/src/load-matches.server.ts @@ -9,6 +9,7 @@ import { getLoader, getMatchContext, getNotFoundBoundaryIndex, + getNotFoundBoundaryPatch, markError, normalizeRouteFailure, serialFailurePrefixCap, @@ -27,16 +28,13 @@ import type { InnerLoadContext, LoadMatchesArg } from './load-matches' const handleServerRedirectOrNotFound = ( inner: InnerLoadContext, index: number, - match: AnyRouteMatch, err: unknown, ): void => { if (isRedirect(err)) { - if (err.redirectHandled && !err.options.reloadDocument) { + if (err.redirectHandled) { throw err } - match._.error = err - err.options._fromLocation = inner.location err.redirectHandled = true throw inner.router.resolveRedirect(err) @@ -92,12 +90,7 @@ const finalizeServerRouteFailure = async ( } if (!componentError) { - handleServerRedirectOrNotFound(inner, index, inner.matches[index]!, error) - } - - const matchToCommit = inner.matches[errorIndex] - if (!matchToCommit) { - return + handleServerRedirectOrNotFound(inner, index, error) } markError(inner, errorIndex) @@ -107,7 +100,7 @@ const finalizeServerRouteFailure = async ( context: getMatchContext( inner, errorIndex, - matchToCommit.__beforeLoadContext, + inner.matches[errorIndex]!.__beforeLoadContext, ), updatedAt: Date.now(), }) @@ -307,26 +300,7 @@ const commitServerNotFoundBoundary = ( err: NotFoundError, ): number => { const index = getNotFoundBoundaryIndex(inner, err) - const match = inner.matches[index]! - const routeId = match.routeId - - err.routeId = routeId - commitMatch( - inner, - index, - routeId === rootRouteId - ? { - status: 'success', - error: undefined, - globalNotFound: true, - context: getMatchContext(inner, index, match.__beforeLoadContext), - } - : { - status: 'notFound', - error: err, - context: getMatchContext(inner, index, match.__beforeLoadContext), - }, - ) + commitMatch(inner, index, getNotFoundBoundaryPatch(inner, index, err)) return index } diff --git a/packages/router-core/src/load-matches.ts b/packages/router-core/src/load-matches.ts index f966c6c2cd..401bc6a9dc 100644 --- a/packages/router-core/src/load-matches.ts +++ b/packages/router-core/src/load-matches.ts @@ -13,10 +13,10 @@ export type InnerLoadContext = { /** Target location for this private load lane. */ location: ParsedLocation /** - * Pending lane was published for presentation (truthy = published; a Promise - * is the framework render promise to await). Final commit still owns effects. + * Pending lane was published for presentation (publication is synchronous). + * Final commit still owns effects. */ - rendered?: true | Promise + rendered?: true /** Private match lane being loaded. */ matches: Array /** @@ -24,12 +24,15 @@ export type InnerLoadContext = { * this pass borrows read-only instead of owning in the cache. */ preload?: Array - /** Earliest route index with a committed route error. */ + /** + * Earliest route index with a committed route error (loader/chunk phase + * only; never set during the serial beforeLoad phase). + */ badIndex?: number /** Same-href client load should revalidate stale matches. */ forceStaleReload?: boolean /** Callback that publishes pending UI when the lane becomes renderable. */ - onReady?: (matches: Array) => void | Promise + onReady?: (matches: Array) => void /** beforeLoad failure captured during the serial phase. */ serialFailure?: SerialFailure /** Client background reload indices selected during foreground matching. */ @@ -47,7 +50,7 @@ export type LoadMatchesArg = { preload?: Array forceReload?: boolean background?: Array - onReady?: (matches: Array) => void | Promise + onReady?: (matches: Array) => void } export type BackgroundLoad = { diff --git a/packages/router-core/src/router-load.client.ts b/packages/router-core/src/router-load.client.ts index d8c67416f8..fb5cb59991 100644 --- a/packages/router-core/src/router-load.client.ts +++ b/packages/router-core/src/router-load.client.ts @@ -237,11 +237,14 @@ export const loadClientRouter = async ( return match && match.status === 'success' && !match.globalNotFound }) const backgroundLength = backgroundIndices?.length + // Pending-UI publication implies requiresCommit: publish() only fires for + // a lane match still at status 'pending' (setupPendingTimeout guards in + // load-matches.client.ts), and every pending-status match forces + // requiresCommit before this line (loadClientRouteMatch's pre-await write, + // finalizeRouteFailure, or the catch above) or aborts this evaluation + // entirely. const backgroundOnly = - sameHref && - backgroundLength && - !loadContext.requiresCommit && - !loadContext.rendered + sameHref && backgroundLength && !loadContext.requiresCommit if (isCurrentLoad()) { if (backgroundOnly) { diff --git a/packages/router-core/tests/load.test.ts b/packages/router-core/tests/load.test.ts index e9f179f4fa..7cc501c220 100644 --- a/packages/router-core/tests/load.test.ts +++ b/packages/router-core/tests/load.test.ts @@ -7512,7 +7512,7 @@ test('loader AbortError respects pendingMinMs before committing error', async () router, location, matches, - onReady: async (readyMatches) => { + onReady: (readyMatches) => { const readyMatch = readyMatches.find( (match) => match.routeId === targetRoute.id, )! @@ -8131,7 +8131,7 @@ describe('head execution', () => { router, location, matches, - onReady: async () => { + onReady: () => { oldOnReady() }, }) @@ -9182,7 +9182,7 @@ describe('match loadPromise lifecycle', () => { router, location, matches, - onReady: async (readyMatches) => { + onReady: (readyMatches) => { const readyMatch = readyMatches.find( (match) => match.routeId === targetRoute.id, )! @@ -9483,7 +9483,7 @@ describe('match loadPromise lifecycle', () => { router, location: fooLocation, matches: firstMatches, - onReady: async (readyMatches) => { + onReady: (readyMatches) => { staleOnReady(readyMatches) }, }) @@ -9608,7 +9608,7 @@ describe('match loadPromise lifecycle', () => { router, location: staleLocation, matches: staleMatches, - onReady: async (readyMatches) => { + onReady: (readyMatches) => { staleOnReady(readyMatches) }, }) @@ -9743,7 +9743,7 @@ describe('match loadPromise lifecycle', () => { router, location, matches, - onReady: async (readyMatches) => { + onReady: (readyMatches) => { oldOnReady(readyMatches) }, }) @@ -9801,7 +9801,7 @@ describe('match loadPromise lifecycle', () => { router, location, matches, - onReady: async (readyMatches) => { + onReady: (readyMatches) => { staleOnReady(readyMatches) }, }) @@ -10039,7 +10039,7 @@ describe('match loadPromise lifecycle', () => { router, location: staleLocation, matches: staleMatches, - onReady: async (readyMatches) => { + onReady: (readyMatches) => { staleOnReady(readyMatches) }, }) @@ -10064,7 +10064,7 @@ describe('match loadPromise lifecycle', () => { router, location: freshLocation, matches: freshMatches, - onReady: async (readyMatches) => { + onReady: (readyMatches) => { freshOnReady(readyMatches) }, }) @@ -10151,7 +10151,7 @@ describe('match loadPromise lifecycle', () => { router, location: staleLocation, matches: staleMatches, - onReady: async (readyMatches) => { + onReady: (readyMatches) => { staleOnReady(readyMatches) }, }) @@ -10176,7 +10176,7 @@ describe('match loadPromise lifecycle', () => { router, location: freshLocation, matches: freshMatches, - onReady: async (readyMatches) => { + onReady: (readyMatches) => { freshOnReady(readyMatches) }, }) @@ -10528,7 +10528,7 @@ describe('match loadPromise lifecycle', () => { router, location, matches, - onReady: async (readyMatches) => { + onReady: (readyMatches) => { const readyMatch = readyMatches.find( (match) => match.routeId === targetRoute.id, )! @@ -10591,7 +10591,7 @@ describe('match loadPromise lifecycle', () => { router, location, matches, - onReady: async (readyMatches) => { + onReady: (readyMatches) => { const readyMatch = readyMatches.find( (match) => match.routeId === errorRoute.id, )! @@ -10652,7 +10652,7 @@ describe('match loadPromise lifecycle', () => { router, location, matches, - onReady: async (readyMatches) => { + onReady: (readyMatches) => { const readyMatch = readyMatches.find( (match) => match.routeId === missingRoute.id, )! @@ -11531,7 +11531,6 @@ describe('match loadPromise lifecycle', () => { vi.useFakeTimers() try { const beforeLoadGate = createControlledPromise() - const onReadyGate = createControlledPromise() const rootRoute = new BaseRootRoute({}) const parentRoute = new BaseRoute({ getParentRoute: () => rootRoute, @@ -11564,12 +11563,10 @@ describe('match loadPromise lifecycle', () => { router, location, matches, - onReady: async (readyMatches) => { + onReady: (readyMatches) => { calls.push({ ids: readyMatches.map((match) => match.id), }) - - await onReadyGate }, }) @@ -11577,8 +11574,6 @@ describe('match loadPromise lifecycle', () => { await vi.waitFor(() => expect(calls).toHaveLength(1)) beforeLoadGate.resolve() - await Promise.resolve() - onReadyGate.resolve() const loadedMatches = await loadPromise expect(calls).toEqual([{ ids: initialIds }]) From a70abdd5655d022277470d92685915c576966717 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Sat, 4 Jul 2026 17:46:22 +0200 Subject: [PATCH 37/54] refactor: delete hedges against invariants the model already guarantees (frameworks) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Framework half of the trust-the-model sweep: - Vue's Transitioner adopts the single-emitter shape react uses: synchronous store subscriptions drive one emitEdges instead of three watch pipelines over usePrevious edges; the transition edge stays flush-coupled via nextTick for the onResolved event, while the idle/resolvedLocation commit happens on the first falling edge — joining the same reactive flush as the matches commit, so matchRoute/status consumers can never render one flush behind the committed lane. Navigations now produce one fewer store flush across the board (pinned counts updated downward). - Vue and Solid useMatch drop the hasPendingMatch throw-suppression guards and the pendingMatchContext/pendingRouteIds plumbing that fed them: atomic pending publication means a match the store publishes is always judgeable, matching react's semantics (changeset documents the Vue behavior change). Full suites green (router-core 1492, react 938, solid 818+server-mode, vue 789 incl. the conditional-Link regression this rework surfaced and fixed), react selective-ssr e2e green. Bundle: −30 to −218 B gzip on every measured target. Co-Authored-By: Claude Fable 5 --- .changeset/violet-poets-wait.md | 1 + packages/solid-router/src/Match.tsx | 7 - packages/solid-router/src/Matches.tsx | 5 - packages/solid-router/src/matchContext.tsx | 2 - packages/solid-router/src/useMatch.tsx | 4 +- packages/vue-router/src/Match.tsx | 13 +- packages/vue-router/src/Transitioner.tsx | 200 ++++++++---------- packages/vue-router/src/matchContext.tsx | 27 +-- packages/vue-router/src/routerStores.ts | 14 -- packages/vue-router/src/useMatch.tsx | 18 +- packages/vue-router/src/utils.ts | 20 -- .../store-updates-during-navigation.test.tsx | 18 +- 12 files changed, 110 insertions(+), 219 deletions(-) diff --git a/.changeset/violet-poets-wait.md b/.changeset/violet-poets-wait.md index 3747103a72..0b367037b6 100644 --- a/.changeset/violet-poets-wait.md +++ b/.changeset/violet-poets-wait.md @@ -23,3 +23,4 @@ Fix match loading consistency across client navigation, preloading, background r - With `pendingMs: 0`, the pending fallback is published synchronously on bare initial loads (nothing rendered yet) instead of after a macrotask, eliminating the blank first frame. - Starting a navigation no longer aborts the `abortController` of settled success matches that stay mounted — deferred/streamed data tied to a stay-match's loader signal survives child navigations and `invalidate()`. Matches with in-flight `beforeLoad`/loader work are still cancelled. - Fresh data for routes you navigate away from survives pending publication: if a navigation is superseded (e.g. back button) after its pending UI was published, the exited matches are served from cache instead of re-running their loaders. +- Behavior change (Vue): `useMatch({ from })` no longer suppresses its missing-match invariant during a navigation whose destination includes `from` before that navigation's first commit — it throws (or returns `undefined` when `shouldThrow: false`) exactly as it does at idle, matching React. diff --git a/packages/solid-router/src/Match.tsx b/packages/solid-router/src/Match.tsx index be032bf440..d109104394 100644 --- a/packages/solid-router/src/Match.tsx +++ b/packages/solid-router/src/Match.tsx @@ -45,17 +45,10 @@ export const Match = (props: { matchId: string }) => { } }) - const hasPendingMatch = Solid.createMemo(() => { - const currentRouteId = rawMatchState()?.routeId - return currentRouteId - ? Boolean(router.stores.pendingRouteIds.get()[currentRouteId]) - : false - }) const nearestMatch = { matchId: () => rawMatchState()?.matchId, routeId: () => rawMatchState()?.routeId, match, - hasPending: hasPendingMatch, } return ( diff --git a/packages/solid-router/src/Matches.tsx b/packages/solid-router/src/Matches.tsx index 75586f862d..654f2051ec 100644 --- a/packages/solid-router/src/Matches.tsx +++ b/packages/solid-router/src/Matches.tsx @@ -66,16 +66,11 @@ function MatchesInner() { const routeId = () => (matchId() ? rootRouteId : undefined) const match = () => routeId() ? router.stores.getRouteMatchStore(rootRouteId).get() : undefined - const hasPendingMatch = () => - routeId() - ? Boolean(router.stores.pendingRouteIds.get()[rootRouteId]) - : false const resetKey = () => router.stores.loadedAt.get() const nearestMatch = { matchId, routeId, match, - hasPending: hasPendingMatch, } const matchComponent = () => { diff --git a/packages/solid-router/src/matchContext.tsx b/packages/solid-router/src/matchContext.tsx index f6efc37c6b..3eeb2440cc 100644 --- a/packages/solid-router/src/matchContext.tsx +++ b/packages/solid-router/src/matchContext.tsx @@ -5,14 +5,12 @@ export type NearestMatchContextValue = { matchId: Solid.Accessor routeId: Solid.Accessor match: Solid.Accessor - hasPending: Solid.Accessor } const defaultNearestMatchContext: NearestMatchContextValue = { matchId: () => undefined, routeId: () => undefined, match: () => undefined, - hasPending: () => false, } export const nearestMatchContext = diff --git a/packages/solid-router/src/useMatch.tsx b/packages/solid-router/src/useMatch.tsx index cd2b50a237..bfc9427be7 100644 --- a/packages/solid-router/src/useMatch.tsx +++ b/packages/solid-router/src/useMatch.tsx @@ -89,7 +89,7 @@ export function useMatch< const hasPendingMatch = opts.from ? Boolean(router.stores.pendingRouteIds.get()[opts.from!]) - : (nearestMatch?.hasPending() ?? false) + : false if (!hasPendingMatch && (opts.shouldThrow ?? true)) { if (process.env.NODE_ENV !== 'production') { @@ -108,7 +108,7 @@ export function useMatch< if (selectedMatch === undefined) { const hasPendingMatch = opts.from ? Boolean(router.stores.pendingRouteIds.get()[opts.from!]) - : (nearestMatch?.hasPending() ?? false) + : false if (prev !== undefined && hasPendingMatch) { return prev diff --git a/packages/vue-router/src/Match.tsx b/packages/vue-router/src/Match.tsx index 2b2179901b..3d65628062 100644 --- a/packages/vue-router/src/Match.tsx +++ b/packages/vue-router/src/Match.tsx @@ -11,11 +11,7 @@ import { CatchBoundary, ErrorComponent } from './CatchBoundary' import { ClientOnly } from './ClientOnly' import { useRouter } from './useRouter' import { CatchNotFound } from './not-found' -import { - matchContext, - pendingMatchContext, - routeIdContext, -} from './matchContext' +import { matchContext, routeIdContext } from './matchContext' import { renderRouteNotFound } from './renderRouteNotFound' import { ScrollRestoration } from './scroll-restoration' import type { VNode } from 'vue' @@ -59,11 +55,6 @@ export const Match = Vue.defineComponent({ router.stores.getRouteMatchStore(routeId), (value) => value, ) - const isPendingMatchRef = useStore( - router.stores.pendingRouteIds, - (pendingRouteIds) => Boolean(pendingRouteIds[routeId]), - { equal: Object.is }, - ) const loadedAt = useStore(router.stores.loadedAt, (value) => value) const matchData = Vue.computed(() => { @@ -134,8 +125,6 @@ export const Match = Vue.defineComponent({ ) Vue.provide(matchContext, matchIdRef) - Vue.provide(pendingMatchContext, isPendingMatchRef) - return (): VNode => { const actualMatchId = matchData.value?.matchId ?? props.matchId diff --git a/packages/vue-router/src/Transitioner.tsx b/packages/vue-router/src/Transitioner.tsx index b3869f0e70..4122c3527f 100644 --- a/packages/vue-router/src/Transitioner.tsx +++ b/packages/vue-router/src/Transitioner.tsx @@ -1,9 +1,8 @@ import * as Vue from 'vue' import { getLocationChangeInfo, trimPathRight } from '@tanstack/router-core' import { isServer } from '@tanstack/router-core/isServer' -import { batch, useStore } from '@tanstack/vue-store' +import { batch } from '@tanstack/vue-store' import { useRouter } from './useRouter' -import { usePrevious } from './utils' // Track mount state per router to avoid double-loading let mountLoadForRouter = { router: null as any, mounted: false } @@ -14,7 +13,7 @@ let mountLoadForRouter = { router: null as any, mounted: false } * - router.startTransition * - router.startViewTransition * - History subscription - * - Router event watchers + * - Router lifecycle event emission * * Must be called during component setup phase. */ @@ -26,42 +25,96 @@ export function useTransitionerSetup() { return } - const isLoading = useStore(router.stores.isLoading, (value) => value) + // `transitioning` bridges router time and Vue time: raised before the + // simulated transition runs, lowered by a single nextTick callback — + // which runs only after Vue has flushed the reactive updates, keeping + // the onResolved edge flush-coupled. + let transitioning = false - // Track if we're in a transition - using a ref to track async transitions - const isTransitioning = Vue.ref(false) + const previous = { + isLoading: false, + isPagePending: false, + isAnyPending: false, + } - // Track pending state changes - const hasPending = useStore(router.stores.hasPending, (value) => value) + // Single emitter for the load lifecycle. Level changes arrive through + // synchronous store subscriptions — which, unlike watcher-observed edges, + // cannot lose a flip to Vue's flush batching — plus the flush-coupled + // transition edge. One emitter means nothing to arbitrate. + const emitEdges = () => { + const isLoading = router.stores.isLoading.get() + const isPagePending = isLoading || router.stores.hasPending.get() + const isAnyPending = isPagePending || transitioning + const prev = { ...previous } + previous.isLoading = isLoading + previous.isPagePending = isPagePending + previous.isAnyPending = isAnyPending - const previousIsLoading = usePrevious(() => isLoading.value) + const changeInfo = () => + getLocationChangeInfo( + router.stores.location.get(), + router.stores.resolvedLocation.get(), + ) - const isAnyPending = Vue.computed( - () => isLoading.value || isTransitioning.value || hasPending.value, - ) - const previousIsAnyPending = usePrevious(() => isAnyPending.value) - - const isPagePending = Vue.computed(() => isLoading.value || hasPending.value) - const previousIsPagePending = usePrevious(() => isPagePending.value) + if (prev.isLoading && !isLoading) { + // The new URL has committed and the new matches are in state.matches. + router.emit({ type: 'onLoad', ...changeInfo() }) + } + // Commit idle/resolvedLocation on the FIRST falling edge (guarded for + // idempotence): these store updates join the same reactive flush as the + // new matches, so matchRoute/status consumers can never render one + // flush behind the committed lane. Only the onResolved EVENT is + // flush-coupled to the deferred transition edge. + const commitIdle = () => { + if (router.stores.status.get() === 'pending') { + batch(() => { + router.stores.status.set('idle') + router.stores.resolvedLocation.set(router.stores.location.get()) + }) + } + } + if (prev.isPagePending && !isPagePending) { + router.emit({ type: 'onBeforeRouteMount', ...changeInfo() }) + commitIdle() + } + if (prev.isAnyPending && !isAnyPending) { + router.emit({ type: 'onResolved', ...changeInfo() }) + commitIdle() + } + } // Implement startTransition similar to React/Solid // Vue doesn't have a native useTransition like React 18, so we simulate it router.startTransition = (fn: () => void) => { - isTransitioning.value = true + transitioning = true + // Register the rising transition level so the falling edge resolves + // even when the load's own levels already settled. + emitEdges() try { fn() } finally { - // Use nextTick to ensure Vue has processed all reactive updates + // Flush-coupled falling edge: use nextTick so the transition level + // only lowers after Vue has processed all reactive updates. void Vue.nextTick(() => { - try { - isTransitioning.value = false - } catch { - // Ignore errors if component is unmounted - } + transitioning = false + emitEdges() }) } } + // Armed before the mount load below, so every load — including one that + // settled before mount (the mount load below still toggles isLoading) — + // produces an observable edge. + previous.isLoading = router.stores.isLoading.get() + previous.isPagePending = + previous.isLoading || router.stores.hasPending.get() + previous.isAnyPending = previous.isPagePending || transitioning + + const subscriptions = [ + router.stores.isLoading.subscribe(emitEdges), + router.stores.hasPending.subscribe(emitEdges), + ] + // Vue updates DOM asynchronously (next tick). The View Transitions API expects the // update callback promise to resolve only after the DOM has been updated. // Wrap the router-core implementation to await a Vue flush before resolving. @@ -108,23 +161,28 @@ export function useTransitionerSetup() { } }) - // Track if component is mounted to prevent updates after unmount - const isMounted = Vue.ref(false) - + // One-shot idle repair at arm time: Vue's mount-load guard is + // module-global, so a remount with the same router skips the mount load, + // and a load that settled while unmounted produces no future edge. + // Repair the stranded 'pending' status here. Vue.onMounted(() => { - isMounted.value = true - if (!isAnyPending.value) { - if (router.stores.status.get() === 'pending') { - batch(() => { - router.stores.status.set('idle') - router.stores.resolvedLocation.set(router.stores.location.get()) - }) - } + if ( + !router.stores.isLoading.get() && + !router.stores.hasPending.get() && + !transitioning && + router.stores.status.get() === 'pending' + ) { + batch(() => { + router.stores.status.set('idle') + router.stores.resolvedLocation.set(router.stores.location.get()) + }) } }) Vue.onUnmounted(() => { - isMounted.value = false + for (const subscription of subscriptions) { + subscription.unsubscribe() + } if (unsubscribe) { unsubscribe() } @@ -148,78 +206,6 @@ export function useTransitionerSetup() { } tryLoad() }) - - // Setup watchers for emitting events - // All watchers check isMounted to prevent updates after unmount - Vue.watch( - () => isLoading.value, - (newValue) => { - if (!isMounted.value) return - try { - if (previousIsLoading.value.previous && !newValue) { - router.emit({ - type: 'onLoad', - ...getLocationChangeInfo( - router.stores.location.get(), - router.stores.resolvedLocation.get(), - ), - }) - } - } catch { - // Ignore errors if component is unmounted - } - }, - ) - - Vue.watch(isPagePending, (newValue) => { - if (!isMounted.value) return - try { - // emit onBeforeRouteMount - if (previousIsPagePending.value.previous && !newValue) { - router.emit({ - type: 'onBeforeRouteMount', - ...getLocationChangeInfo( - router.stores.location.get(), - router.stores.resolvedLocation.get(), - ), - }) - if (router.stores.status.get() === 'pending') { - batch(() => { - router.stores.status.set('idle') - router.stores.resolvedLocation.set(router.stores.location.get()) - }) - } - } - } catch { - // Ignore errors if component is unmounted - } - }) - - Vue.watch(isAnyPending, (newValue) => { - if (!isMounted.value) return - try { - if (!newValue && router.stores.status.get() === 'pending') { - batch(() => { - router.stores.status.set('idle') - router.stores.resolvedLocation.set(router.stores.location.get()) - }) - } - - // The router was pending and now it's not - if (previousIsAnyPending.value.previous && !newValue) { - const changeInfo = getLocationChangeInfo( - router.stores.location.get(), - router.stores.resolvedLocation.get(), - ) - router.emit({ - type: 'onResolved', - ...changeInfo, - }) - } - } catch { - // Ignore errors if component is unmounted - } - }) } /** diff --git a/packages/vue-router/src/matchContext.tsx b/packages/vue-router/src/matchContext.tsx index 1a8b7fb167..1bf5d42d0e 100644 --- a/packages/vue-router/src/matchContext.tsx +++ b/packages/vue-router/src/matchContext.tsx @@ -1,4 +1,4 @@ -import * as Vue from 'vue' +import type * as Vue from 'vue' // Reactive nearest-match context used by hooks that work relative to the // current match in the tree. @@ -6,34 +6,9 @@ export const matchContext = Symbol('TanStackRouterMatch') as Vue.InjectionKey< Vue.Ref > -// Pending match context for nearest-match lookups -export const pendingMatchContext = Symbol( - 'TanStackRouterPendingMatch', -) as Vue.InjectionKey> - -// Dummy pending context when nearest pending state is not needed -export const dummyPendingMatchContext = Symbol( - 'TanStackRouterDummyPendingMatch', -) as Vue.InjectionKey> - // Stable routeId context — a plain string (not reactive) that identifies // which route this component belongs to. Provided by Match, consumed by // MatchInner, Outlet, and useMatch for routeId-based store lookups. export const routeIdContext = Symbol( 'TanStackRouterRouteId', ) as Vue.InjectionKey - -/** - * Retrieves nearest pending-match state from the component tree - */ -export function injectPendingMatch(): Vue.Ref { - return Vue.inject(pendingMatchContext, Vue.ref(false)) -} - -/** - * Retrieves dummy pending-match state from the component tree - * This only exists so we can conditionally inject a value when we are not interested in the nearest pending match - */ -export function injectDummyPendingMatch(): Vue.Ref { - return Vue.inject(dummyPendingMatchContext, Vue.ref(false)) -} diff --git a/packages/vue-router/src/routerStores.ts b/packages/vue-router/src/routerStores.ts index da943fe990..dec689c47c 100644 --- a/packages/vue-router/src/routerStores.ts +++ b/packages/vue-router/src/routerStores.ts @@ -11,8 +11,6 @@ declare module '@tanstack/router-core' { export interface RouterStores { /** Maps each active routeId to the matchId of its child in the match tree. */ childMatchIdByRouteId: RouterReadableStore> - /** Maps each pending routeId to true for quick lookup. */ - pendingRouteIds: RouterReadableStore> } } @@ -37,18 +35,6 @@ export const getStoreFactory: GetStoreConfig = (_opts) => { } return obj }) - - stores.pendingRouteIds = createAtom(() => { - const ids = stores.pendingIds.get() - const obj: Record = {} - for (const id of ids) { - const store = stores.pendingMatchStores.get(id) - if (store?.routeId) { - obj[store.routeId] = true - } - } - return obj - }) }, } } diff --git a/packages/vue-router/src/useMatch.tsx b/packages/vue-router/src/useMatch.tsx index f039eff944..969d7ce788 100644 --- a/packages/vue-router/src/useMatch.tsx +++ b/packages/vue-router/src/useMatch.tsx @@ -2,11 +2,7 @@ import * as Vue from 'vue' import { invariant } from '@tanstack/router-core' import { useStore } from '@tanstack/vue-store' import { isServer } from '@tanstack/router-core/isServer' -import { - injectDummyPendingMatch, - injectPendingMatch, - routeIdContext, -} from './matchContext' +import { routeIdContext } from './matchContext' import { useRouter } from './useRouter' import type { AnyRouter, @@ -114,9 +110,6 @@ export function useMatch< > } - const hasPendingNearestMatch = opts.from - ? injectDummyPendingMatch() - : injectPendingMatch() // Set up reactive match value based on lookup strategy. let match: Readonly> @@ -141,17 +134,10 @@ export function useMatch< } } - const hasPendingRouteMatch = opts.from - ? useStore(router.stores.pendingRouteIds, (ids) => ids) - : undefined - const result = Vue.computed(() => { const selectedMatch = match.value if (selectedMatch === undefined) { - const hasPendingMatch = opts.from - ? Boolean(hasPendingRouteMatch?.value[opts.from!]) - : hasPendingNearestMatch.value - if (!hasPendingMatch && (opts.shouldThrow ?? true)) { + if (opts.shouldThrow ?? true) { if (process.env.NODE_ENV !== 'production') { throw new Error( `Invariant failed: Could not find ${opts.from ? `an active match from "${opts.from}"` : 'a nearest match!'}`, diff --git a/packages/vue-router/src/utils.ts b/packages/vue-router/src/utils.ts index 609c4558a8..ffc3848d77 100644 --- a/packages/vue-router/src/utils.ts +++ b/packages/vue-router/src/utils.ts @@ -3,26 +3,6 @@ import * as Vue from 'vue' export const useLayoutEffect = typeof window !== 'undefined' ? Vue.effect : Vue.effect -export const usePrevious = (fn: () => boolean) => { - return Vue.computed( - ( - prev: { current: boolean | null; previous: boolean | null } = { - current: null, - previous: null, - }, - ) => { - const current = fn() - - if (prev.current !== current) { - prev.previous = prev.current - prev.current = current - } - - return prev - }, - ) -} - /** * React hook to wrap `IntersectionObserver`. * diff --git a/packages/vue-router/tests/store-updates-during-navigation.test.tsx b/packages/vue-router/tests/store-updates-during-navigation.test.tsx index 42a93972c2..388e76c5fa 100644 --- a/packages/vue-router/tests/store-updates-during-navigation.test.tsx +++ b/packages/vue-router/tests/store-updates-during-navigation.test.tsx @@ -137,8 +137,10 @@ describe("Store doesn't update *too many* times during navigation", () => { // This number should be as small as possible to minimize the amount of work // that needs to be done during a navigation. // Any change that increases this number should be investigated. + // (Reduced by one across the board when the transitioner began committing + // idle/resolvedLocation in the same flush as the matches commit.) // Note: Vue has different update counts than React/Solid due to different reactivity - expect(updates).toBe(4) + expect(updates).toBe(3) }) test('redirection in preload', async () => { @@ -180,7 +182,7 @@ describe("Store doesn't update *too many* times during navigation", () => { // that needs to be done during a navigation. // Any change that increases this number should be investigated. // Note: Vue has different update counts than React/Solid due to different reactivity - expect(updates).toBe(4) + expect(updates).toBe(3) }) test('nothing', async () => { @@ -192,7 +194,7 @@ describe("Store doesn't update *too many* times during navigation", () => { // that needs to be done during a navigation. // Any change that increases this number should be investigated. // Note: Vue has different update counts than React/Solid due to different reactivity - expect(updates).toBe(3) + expect(updates).toBe(2) }) test('not found in beforeLoad', async () => { @@ -208,7 +210,7 @@ describe("Store doesn't update *too many* times during navigation", () => { // that needs to be done during a navigation. // Any change that increases this number should be investigated. // Note: Vue has different update counts than React/Solid due to different reactivity - expect(updates).toBe(3) + expect(updates).toBe(2) }) test('hover preload, then navigate, w/ async loaders', async () => { @@ -235,7 +237,7 @@ describe("Store doesn't update *too many* times during navigation", () => { // that needs to be done during a navigation. // Any change that increases this number should be investigated. // Note: Vue has different update counts than React/Solid due to different reactivity - expect(updates).toBe(3) + expect(updates).toBe(2) }) test('navigate, w/ preloaded & async loaders', async () => { @@ -252,7 +254,7 @@ describe("Store doesn't update *too many* times during navigation", () => { // that needs to be done during a navigation. // Any change that increases this number should be investigated. // Note: Vue has different update counts than React/Solid due to different reactivity - expect(updates).toBe(3) + expect(updates).toBe(2) }) test('navigate, w/ preloaded & sync loaders', async () => { @@ -269,7 +271,7 @@ describe("Store doesn't update *too many* times during navigation", () => { // that needs to be done during a navigation. // Any change that increases this number should be investigated. // Note: Vue has different update counts than React/Solid due to different reactivity - expect(updates).toBe(3) + expect(updates).toBe(2) }) test('navigate, w/ previous navigation & async loader', async () => { @@ -286,7 +288,7 @@ describe("Store doesn't update *too many* times during navigation", () => { // that needs to be done during a navigation. // Any change that increases this number should be investigated. // Note: Vue has different update counts than React/Solid due to different reactivity - expect(updates).toBe(3) + expect(updates).toBe(2) }) test('preload a preloaded route w/ async loader', async () => { From ccf92bcb8b7facb1fdf6eb1d1a7f8045c845c77a Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Sat, 4 Jul 2026 15:48:26 +0000 Subject: [PATCH 38/54] ci: apply automated fixes --- packages/vue-router/src/Transitioner.tsx | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/packages/vue-router/src/Transitioner.tsx b/packages/vue-router/src/Transitioner.tsx index 4122c3527f..642647c9ed 100644 --- a/packages/vue-router/src/Transitioner.tsx +++ b/packages/vue-router/src/Transitioner.tsx @@ -106,8 +106,7 @@ export function useTransitionerSetup() { // settled before mount (the mount load below still toggles isLoading) — // produces an observable edge. previous.isLoading = router.stores.isLoading.get() - previous.isPagePending = - previous.isLoading || router.stores.hasPending.get() + previous.isPagePending = previous.isLoading || router.stores.hasPending.get() previous.isAnyPending = previous.isPagePending || transitioning const subscriptions = [ From bcc23d84df9b79ad34b82524d1da6a657f5e1a67 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Sat, 4 Jul 2026 18:45:54 +0200 Subject: [PATCH 39/54] feat: navigations adopt in-flight preload loader runs (data-only) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Restores the essential hover-preload contract — click during an in-flight preload executes the loader ONCE — without resurrecting the old join's bug classes: - Data only, never control flow: a donor preload that ends in redirect/ notFound/error is ignored and the navigation runs its own loader, so preload-computed redirects can no longer hijack navigations (the redirect regression test now pins non-leakage AND the retry). - The navigation always runs its own beforeLoad with preload:false semantics (the old join's context-mismatch class stays dead). - Private preload lanes register in router._preloadLanes; matchRoutes attaches a join handle; the loader phase adopts via the shared loadPromise. Joining is gated on the donor's loader being in flight — before that, the preload's serial phase may itself be waiting on this navigation through the borrow protocol, and joining would deadlock the pair (pinned by a serial-phase test). Concurrent sibling preloads of the same route also dedupe to one loader run. - No cache pollution: lanes stay private until success, unchanged. The adoption await is gated on the join handle so the synchronous loader-start contract is untouched for the no-preload case. Co-Authored-By: Claude Fable 5 --- .changeset/violet-poets-wait.md | 2 +- packages/router-core/INTERNALS.md | 26 +++++ packages/router-core/src/Matches.ts | 6 + .../router-core/src/load-matches.client.ts | 106 ++++++++++++++---- .../router-core/src/router-preload.client.ts | 5 + packages/router-core/src/router.ts | 20 +++- packages/router-core/tests/load.test.ts | 26 ++++- .../tests/preload-adoption.test.ts | 100 +++++++++++++++++ 8 files changed, 263 insertions(+), 28 deletions(-) create mode 100644 packages/router-core/tests/preload-adoption.test.ts diff --git a/.changeset/violet-poets-wait.md b/.changeset/violet-poets-wait.md index 0b367037b6..553e8b3f0b 100644 --- a/.changeset/violet-poets-wait.md +++ b/.changeset/violet-poets-wait.md @@ -16,7 +16,7 @@ Fix match loading consistency across client navigation, preloading, background r - Server loading now has a dedicated path for status codes, redirects, notFound and error responses. - React, Solid, and Vue match rendering now consume the simplified match readiness model, including aborted loader errors, SSR/data-only pending fallbacks, and stale render snapshots. - Awaiting `router.load()` or `router.invalidate()` now settles only when the whole navigation chain settles, including superseded and redirected loads; preloads that borrow a pending-published foreground match wait for its commit instead of being dropped. -- Behavior change: a navigation that starts while a hover/intent preload for the same route is in flight no longer adopts the preload's loader run — the navigation runs its own loader with `preload: false` semantics, so loaders may execute twice in that window. Use your data layer (e.g. an external cache) to dedupe fetches. +- A navigation that starts while a hover/intent preload for the same route is in flight adopts the preload's loader run once it succeeds — the loader executes once, like before. Adoption is data-only: the navigation always runs its own `beforeLoad` (with `preload: false` semantics), and a preload that ends in a redirect, notFound, or error is never adopted — the navigation runs its own loader instead, so preload-flavored control flow can no longer leak into navigations (the old implementation could land you on a preload-computed redirect). Concurrent preloads of the same route also share one loader run. - Preloads now cache the successful ancestor prefix even when a descendant throws an error or `notFound`, so repeated hovers do not re-run expensive ancestor loaders. - Route chunk (lazy import) failures now run the normal route failure lifecycle: `onError` fires and thrown redirects/notFounds are honored. Error/notFound boundary chunks load independently of the route's other component chunks, and failed chunk preloads are retried on the next load instead of being cached forever. - Server rendering keeps route `headers()` when a decorative `head()`/`scripts()` hook fails (async `headers()` are always awaited), background reloads never publish fresh `loaderData` whose asset projection failed, and hydration no longer executes `head()`/`scripts()` for matches the server omitted (`ssr: false` or a server-side error/notFound boundary). The follow-up client load after hydration replays a server-committed notFound/error boundary, so routes the server omitted are not loaded or asset-projected client-side. diff --git a/packages/router-core/INTERNALS.md b/packages/router-core/INTERNALS.md index 1f1cffcff4..7c17e70121 100644 --- a/packages/router-core/INTERNALS.md +++ b/packages/router-core/INTERNALS.md @@ -674,6 +674,32 @@ finished. Tests anchor this with: - `joined preload waits for borrowed notFound to commit` - `preload canceled by borrowed owner disappearance projects no assets and caches nothing` +### Navigation adoption of in-flight preloads + +Borrowing has a mirror. While a preload pass is loading, its lane is +registered in `router._preloadLanes`. A navigation (or sibling preload) that +matches the same match id attaches a join handle (`match._.preloadLane`) and, +in its loader phase, adopts the donor's SUCCESSFUL loader result instead of +executing the loader a second time. + +Adoption is deliberately narrow: + +- Data only, never control flow. A donor that ends in redirect, notFound, or + error is ignored and the pass runs its own loader — preload-flavored + outcomes cannot leak into navigations. +- The pass always runs its own `beforeLoad` (navigation semantics); only the + loader run is shared. +- Joining is gated on the donor's loader being IN FLIGHT + (`isFetching === 'loader'`). Before that, the preload's serial phase may + itself be waiting on this navigation through the borrow protocol, and + joining would deadlock the pair. Once the donor's loader started, its + serial phase is over by construction and the preload settles + independently — the preload's finalizer settles every owned load promise, + so the adoption wait cannot hang. +- Private lanes stay private: nothing enters `cachedMatches` before the + preload finishes, and the preload's own cache write already skips ids that + became active in the meantime. + Preload route-control behavior: - A private preload redirect recursively preloads the redirect target. It does diff --git a/packages/router-core/src/Matches.ts b/packages/router-core/src/Matches.ts index eac88656a2..6cce767cd7 100644 --- a/packages/router-core/src/Matches.ts +++ b/packages/router-core/src/Matches.ts @@ -149,6 +149,12 @@ export interface RouteMatch< dehydrated?: boolean /** Internal loader error used by match loading. */ error?: unknown + /** + * Internal: a private in-flight preload lane already loading this + * match. The loader phase adopts its successful result instead of + * running the loader twice. + */ + preloadLane?: { matches: Array } } loaderData?: TLoaderData /** Internal route context scratch value. */ diff --git a/packages/router-core/src/load-matches.client.ts b/packages/router-core/src/load-matches.client.ts index 57d39eb0b7..ec69fa6732 100644 --- a/packages/router-core/src/load-matches.client.ts +++ b/packages/router-core/src/load-matches.client.ts @@ -133,6 +133,56 @@ const joinPreloadedActiveMatch = async ( return match } +/** + * The mirror of joinPreloadedActiveMatch: a navigation adopts an in-flight + * private preload's SUCCESSFUL loader result instead of executing the loader + * a second time. Only data is adopted — never control flow: a preload that + * ended in redirect/notFound/error is ignored and the navigation runs its + * own loader, so preload-flavored outcomes cannot leak into navigations. + * + * Joining is gated on the donor's loader actually being IN FLIGHT + * (isFetching === 'loader'): before that, the preload's serial phase may + * itself be waiting on this navigation through the borrow protocol, and + * joining would deadlock the pair. Once the donor's loader started, its + * serial phase is over by construction and the pass settles independently. + */ +const adoptInFlightPreload = async ( + inner: InnerLoadContext, + index: number, + passController: AbortController, +): Promise<{ loaderData: unknown } | undefined> => { + const match = inner.matches[index]! + const lane = match._.preloadLane + if (!lane) { + return undefined + } + match._.preloadLane = undefined + + const readDonor = () => + lane.matches.find((m) => m.id === match.id && m.preload) + let donor = readDonor() + + if (donor && donor.status !== 'success') { + if ( + donor.isFetching !== 'loader' || + donor._.loadPromise?.status !== 'pending' + ) { + return undefined + } + commitMatch(inner, index, { isFetching: 'loader' }) + // The preload pass settles every owned match's loadPromise in its + // finally, so this wait cannot hang even for aborted preloads. + await donor._.loadPromise + requireCurrentMatch(inner, index, passController) + donor = readDonor() + } + + if (donor?.status !== 'success') { + return undefined + } + return { loaderData: donor.loaderData } +} + function waitPendingMin(match: AnyRouteMatch): Promise | undefined { const remaining = (match._.loadPromise?.pendingUntil ?? 0) - Date.now() if (remaining > 0) { @@ -569,31 +619,45 @@ const loadClientRouteMatch = async ( // Actually run the loader and handle the result try { - // Kick off the loader! - const loaderResult = loader?.( - getLoaderContext(inner, matchPromises, index, route), - ) - const loaderResultIsPromise = isPromise(loaderResult) - if (loaderResultIsPromise || routeChunkPromise) { + // Gate on the lane handle before awaiting: adoption is async, and an + // unconditional await would break the synchronous loader-start + // contract for the (overwhelmingly common) no-preload case. + const adopted = + loader && inner.matches[index]!._.preloadLane + ? await adoptInFlightPreload(inner, index, passController) + : undefined + + if (adopted) { commitMatch(inner, index, { - isFetching: 'loader', + loaderData: adopted.loaderData, }) - } - - if (loader) { - const loaderData = loaderResultIsPromise - ? await loaderResult - : loaderResult - - requireCurrentMatch(inner, index, passController) - - if (isRouteControl(loaderData)) { - throw loaderData + } else { + // Kick off the loader! + const loaderResult = loader?.( + getLoaderContext(inner, matchPromises, index, route), + ) + const loaderResultIsPromise = isPromise(loaderResult) + if (loaderResultIsPromise || routeChunkPromise) { + commitMatch(inner, index, { + isFetching: 'loader', + }) } - commitMatch(inner, index, { - loaderData, - }) + if (loader) { + const loaderData = loaderResultIsPromise + ? await loaderResult + : loaderResult + + requireCurrentMatch(inner, index, passController) + + if (isRouteControl(loaderData)) { + throw loaderData + } + + commitMatch(inner, index, { + loaderData, + }) + } } } catch (error) { if (error === inner) { diff --git a/packages/router-core/src/router-preload.client.ts b/packages/router-core/src/router-preload.client.ts index 98ce4eca10..729af87d46 100644 --- a/packages/router-core/src/router-preload.client.ts +++ b/packages/router-core/src/router-preload.client.ts @@ -71,6 +71,10 @@ export const preloadClientRoute = async ( } } + // Register the lane so concurrent navigations (and sibling preloads) can + // adopt this pass's in-flight loader results instead of re-running them. + ;(router._preloadLanes ??= new Set()).add(loadContext) + try { // loadClientMatches mutates the lane in place and returns it. await loadClientMatches(loadContext) @@ -105,6 +109,7 @@ export const preloadClientRoute = async ( } return } finally { + router._preloadLanes.delete(loadContext) for (const match of matches) { if (match.preload) { settleMatchLoad(match) diff --git a/packages/router-core/src/router.ts b/packages/router-core/src/router.ts index f2394f2119..b37fdfc82c 100644 --- a/packages/router-core/src/router.ts +++ b/packages/router-core/src/router.ts @@ -1550,6 +1550,20 @@ export class RouterCore< loaderDepsHash const existingMatch = this.getMatch(matchId) + // A private in-flight preload lane may already be loading this exact + // match. Attach a join handle so the loader phase can adopt its + // successful result instead of executing the loader twice. (A preload + // pass registers its lane only after matching, so it never finds + // itself here — but it may join a concurrent sibling preload.) + let preloadLane: { matches: Array } | undefined + if (this._preloadLanes) { + for (const lane of this._preloadLanes) { + if (lane.matches.some((m) => m.id === matchId && m.preload)) { + preloadLane = lane + break + } + } + } const previousMatch = previousActiveMatches[index]?.routeId === route.id ? previousActiveMatches[index] @@ -1605,6 +1619,7 @@ export class RouterCore< _: { loadPromise, dehydrated: existingMatch._.dehydrated, + preloadLane, }, search, _strictSearch: strictMatchSearch, @@ -1637,8 +1652,9 @@ export class RouterCore< _: pending ? { loadPromise: createControlledPromise(), + preloadLane, } - : {}, + : { preloadLane }, abortController, cause, loaderDeps, @@ -2380,6 +2396,8 @@ export class RouterCore< } declare latestLoadPromise: undefined | ControlledPromise + /** Private in-flight preload lanes, joinable by navigations (client only). */ + declare _preloadLanes: Set<{ matches: Array }> | undefined declare _backgroundLoad: BackgroundLoad | undefined load: LoadFn = async (opts) => { diff --git a/packages/router-core/tests/load.test.ts b/packages/router-core/tests/load.test.ts index 7cc501c220..7d1efe95d7 100644 --- a/packages/router-core/tests/load.test.ts +++ b/packages/router-core/tests/load.test.ts @@ -3628,15 +3628,26 @@ describe('loader skip or exec', () => { expect(loader).toHaveBeenCalledTimes(1) }) - test('exec if pending preload (success)', async () => { - const loader = vi.fn(() => sleep(100)) + test('adopt if pending preload (success)', async () => { + const loader = vi.fn(async () => { + await sleep(100) + return 'preloaded' + }) const router = setup({ loader }) router.preloadRoute({ to: '/foo' }) - await Promise.resolve() + // Wait until the preload's loader is actually in flight — adoption is + // deliberately gated on that (a preload still in its serial phase may + // itself be waiting on the navigation through the borrow protocol). + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(1)) expect(router.stores.cachedMatches.get()).toEqual([]) await router.navigate({ to: '/foo' }) - expect(loader).toHaveBeenCalledTimes(2) + // The navigation adopted the in-flight preload's loader run. + expect(loader).toHaveBeenCalledTimes(1) + expect( + router.state.matches.find((match) => match.id === '/foo/foo') + ?.loaderData, + ).toBe('preloaded') }) test('exec if rejected preload (notFound)', async () => { @@ -3747,7 +3758,6 @@ describe('loader skip or exec', () => { await vi.waitFor(() => expect(rejectFoo).toHaveLength(1)) const navigation = router.navigate({ to: '/foo' }) - await vi.waitFor(() => expect(rejectFoo).toHaveLength(2)) await vi.advanceTimersByTimeAsync(1) await vi.waitFor(() => expect( @@ -3756,10 +3766,16 @@ describe('loader skip or exec', () => { ), ).toBe(true), ) + // The navigation adopted the in-flight preload loader: no second run. + expect(rejectFoo).toHaveLength(1) rejectFoo[0]!(redirect({ to: '/bar' })) await preload + // The preload's redirect is control flow the navigation must not + // adopt: instead of leaking to /bar, the navigation runs its OWN + // loader once the failed donor settles. + await vi.waitFor(() => expect(rejectFoo).toHaveLength(2)) expect( router.state.matches.find((match) => match.id === '/foo/foo')?.status, ).toBe('pending') diff --git a/packages/router-core/tests/preload-adoption.test.ts b/packages/router-core/tests/preload-adoption.test.ts new file mode 100644 index 0000000000..d6d0b10822 --- /dev/null +++ b/packages/router-core/tests/preload-adoption.test.ts @@ -0,0 +1,100 @@ +import { describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, createControlledPromise } from '../src' +import { createTestRouter } from './routerTestUtils' + +/** + * Preload adoption edge cases. The happy path (navigation adopts an + * in-flight preload's successful loader run) and the control-flow + * non-leakage path are pinned in load.test.ts; this file pins the + * deadlock guard: adoption is gated on the donor's loader being in + * flight, because a preload still in its serial phase can itself be + * waiting on the navigation through the borrow protocol. + */ + +describe('preload adoption', () => { + test('navigating during the preload serial phase does not deadlock (adoption declined)', async () => { + const beforeLoadGate = createControlledPromise() + let beforeLoadCalls = 0 + const loader = vi.fn(() => 'data') + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + beforeLoad: async () => { + beforeLoadCalls++ + if (beforeLoadCalls === 1) { + // Keep the PRELOAD's serial phase in flight; the navigation's + // own beforeLoad (call 2) proceeds immediately. + await beforeLoadGate + } + }, + loader, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, fooRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + + // Preload is stuck in its serial phase — its loader has NOT started. + const preload = router.preloadRoute({ to: '/foo' } as any) + await vi.waitFor(() => expect(beforeLoadCalls).toBe(1)) + + // The navigation must not join a donor whose loader is not in flight; + // it runs its own loader and completes without waiting on the preload. + await router.navigate({ to: '/foo' }) + expect(loader).toHaveBeenCalledTimes(1) + expect( + router.state.matches.find((match) => match.routeId === fooRoute.id) + ?.status, + ).toBe('success') + + beforeLoadGate.resolve() + await preload + }) + + test('a sibling preload adopts another preload lane\'s in-flight loader', async () => { + const loaderGate = createControlledPromise() + const loader = vi.fn(() => loaderGate) + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, fooRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + + const first = router.preloadRoute({ to: '/foo' } as any) + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(1)) + + const second = router.preloadRoute({ to: '/foo' } as any) + loaderGate.resolve('once') + await Promise.all([first, second]) + + expect(loader).toHaveBeenCalledTimes(1) + expect( + router.stores.cachedMatches + .get() + .find((match) => match.routeId === fooRoute.id)?.loaderData, + ).toBe('once') + }) +}) From 6dcb32cfbc559d45d4dc3b2e1183b9697c4c81f7 Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Sat, 4 Jul 2026 16:47:53 +0000 Subject: [PATCH 40/54] ci: apply automated fixes --- packages/router-core/tests/load.test.ts | 3 +-- packages/router-core/tests/preload-adoption.test.ts | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/packages/router-core/tests/load.test.ts b/packages/router-core/tests/load.test.ts index 7d1efe95d7..d7b7bbdbf0 100644 --- a/packages/router-core/tests/load.test.ts +++ b/packages/router-core/tests/load.test.ts @@ -3645,8 +3645,7 @@ describe('loader skip or exec', () => { // The navigation adopted the in-flight preload's loader run. expect(loader).toHaveBeenCalledTimes(1) expect( - router.state.matches.find((match) => match.id === '/foo/foo') - ?.loaderData, + router.state.matches.find((match) => match.id === '/foo/foo')?.loaderData, ).toBe('preloaded') }) diff --git a/packages/router-core/tests/preload-adoption.test.ts b/packages/router-core/tests/preload-adoption.test.ts index d6d0b10822..6705a892cc 100644 --- a/packages/router-core/tests/preload-adoption.test.ts +++ b/packages/router-core/tests/preload-adoption.test.ts @@ -61,7 +61,7 @@ describe('preload adoption', () => { await preload }) - test('a sibling preload adopts another preload lane\'s in-flight loader', async () => { + test("a sibling preload adopts another preload lane's in-flight loader", async () => { const loaderGate = createControlledPromise() const loader = vi.fn(() => loaderGate) From f89dc959ffc840d5c9783159da3c173cd1cc9d39 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Sat, 4 Jul 2026 18:58:28 +0200 Subject: [PATCH 41/54] refactor: discover preload donors at loader time instead of threading a join handle MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Inspired by main's original adoption shape (the join point was the match's own discoverable state, not plumbing): the loader phase now looks the donor up directly in router._preloadLanes, deleting the _.preloadLane private field, the Matches type addition, and the per-match lane scan in matchRoutesInternal's hot path. The adoption gate excludes a preload pass's own registered lane so the synchronous loader-start contract holds for solo preloads too. A preload completing in the microtask window between matchRoutes and the loader phase is deliberately NOT adopted — the navigation runs its own loader, which is correct, just not deduplicated; guarding that window was a hedge whose failure mode is a duplicate fetch, not a defect. Net vs the handle version: two files instead of four, no hot-path work, and marginally smaller bundles. Co-Authored-By: Claude Fable 5 --- packages/router-core/src/Matches.ts | 6 -- .../router-core/src/load-matches.client.ts | 69 ++++++++++++------- packages/router-core/src/router.ts | 18 +---- 3 files changed, 44 insertions(+), 49 deletions(-) diff --git a/packages/router-core/src/Matches.ts b/packages/router-core/src/Matches.ts index 6cce767cd7..eac88656a2 100644 --- a/packages/router-core/src/Matches.ts +++ b/packages/router-core/src/Matches.ts @@ -149,12 +149,6 @@ export interface RouteMatch< dehydrated?: boolean /** Internal loader error used by match loading. */ error?: unknown - /** - * Internal: a private in-flight preload lane already loading this - * match. The loader phase adopts its successful result instead of - * running the loader twice. - */ - preloadLane?: { matches: Array } } loaderData?: TLoaderData /** Internal route context scratch value. */ diff --git a/packages/router-core/src/load-matches.client.ts b/packages/router-core/src/load-matches.client.ts index ec69fa6732..f54f6ec5b4 100644 --- a/packages/router-core/src/load-matches.client.ts +++ b/packages/router-core/src/load-matches.client.ts @@ -140,6 +140,11 @@ const joinPreloadedActiveMatch = async ( * ended in redirect/notFound/error is ignored and the navigation runs its * own loader, so preload-flavored outcomes cannot leak into navigations. * + * The donor is discovered here, at loader time, from the registered preload + * lanes (or, for a preload that finished in the meantime, from its cache + * entry) — the join point is discoverable state, not plumbing threaded + * through match creation. + * * Joining is gated on the donor's loader actually being IN FLIGHT * (isFetching === 'loader'): before that, the preload's serial phase may * itself be waiting on this navigation through the borrow protocol, and @@ -152,35 +157,43 @@ const adoptInFlightPreload = async ( passController: AbortController, ): Promise<{ loaderData: unknown } | undefined> => { const match = inner.matches[index]! - const lane = match._.preloadLane - if (!lane) { - return undefined - } - match._.preloadLane = undefined - const readDonor = () => - lane.matches.find((m) => m.id === match.id && m.preload) - let donor = readDonor() + for (const lane of inner.router._preloadLanes!) { + if (lane === inner) { + continue + } + const readDonor = () => + lane.matches.find((m) => m.id === match.id && m.preload) + let donor = readDonor() + if (!donor) { + continue + } - if (donor && donor.status !== 'success') { - if ( - donor.isFetching !== 'loader' || - donor._.loadPromise?.status !== 'pending' - ) { + if (donor.status !== 'success') { + if ( + donor.isFetching !== 'loader' || + donor._.loadPromise?.status !== 'pending' + ) { + return undefined + } + commitMatch(inner, index, { isFetching: 'loader' }) + // The preload pass settles every owned match's loadPromise in its + // finally, so this wait cannot hang even for aborted preloads. + await donor._.loadPromise + requireCurrentMatch(inner, index, passController) + donor = readDonor() + } + + if (donor?.status !== 'success') { return undefined } - commitMatch(inner, index, { isFetching: 'loader' }) - // The preload pass settles every owned match's loadPromise in its - // finally, so this wait cannot hang even for aborted preloads. - await donor._.loadPromise - requireCurrentMatch(inner, index, passController) - donor = readDonor() + return { loaderData: donor.loaderData } } - if (donor?.status !== 'success') { - return undefined - } - return { loaderData: donor.loaderData } + // A preload that completes in the microtask window between matchRoutes + // and this loader phase is simply not adopted — the navigation runs its + // own loader, which is correct, just not deduplicated. Not worth a hedge. + return undefined } function waitPendingMin(match: AnyRouteMatch): Promise | undefined { @@ -619,11 +632,15 @@ const loadClientRouteMatch = async ( // Actually run the loader and handle the result try { - // Gate on the lane handle before awaiting: adoption is async, and an + // Gate on live DONOR lanes before awaiting: adoption is async, and an // unconditional await would break the synchronous loader-start - // contract for the (overwhelmingly common) no-preload case. + // contract — both for the (overwhelmingly common) no-preload case and + // for a preload pass seeing only its own registered lane. + const preloadLanes = inner.router._preloadLanes const adopted = - loader && inner.matches[index]!._.preloadLane + loader && + preloadLanes?.size && + !(preloadLanes.size === 1 && preloadLanes.has(inner)) ? await adoptInFlightPreload(inner, index, passController) : undefined diff --git a/packages/router-core/src/router.ts b/packages/router-core/src/router.ts index b37fdfc82c..61b1409b44 100644 --- a/packages/router-core/src/router.ts +++ b/packages/router-core/src/router.ts @@ -1550,20 +1550,6 @@ export class RouterCore< loaderDepsHash const existingMatch = this.getMatch(matchId) - // A private in-flight preload lane may already be loading this exact - // match. Attach a join handle so the loader phase can adopt its - // successful result instead of executing the loader twice. (A preload - // pass registers its lane only after matching, so it never finds - // itself here — but it may join a concurrent sibling preload.) - let preloadLane: { matches: Array } | undefined - if (this._preloadLanes) { - for (const lane of this._preloadLanes) { - if (lane.matches.some((m) => m.id === matchId && m.preload)) { - preloadLane = lane - break - } - } - } const previousMatch = previousActiveMatches[index]?.routeId === route.id ? previousActiveMatches[index] @@ -1619,7 +1605,6 @@ export class RouterCore< _: { loadPromise, dehydrated: existingMatch._.dehydrated, - preloadLane, }, search, _strictSearch: strictMatchSearch, @@ -1652,9 +1637,8 @@ export class RouterCore< _: pending ? { loadPromise: createControlledPromise(), - preloadLane, } - : { preloadLane }, + : {}, abortController, cause, loaderDeps, From 98c8c27841f6f134b78dee730f6061a880c95cac Mon Sep 17 00:00:00 2001 From: Sheraff Date: Tue, 7 Jul 2026 14:34:40 +0200 Subject: [PATCH 42/54] fix: scope built-location currentness to preload passes and surface fatal load rejections Co-Authored-By: Claude Fable 5 --- packages/router-core/INTERNALS.md | 10 ++- .../router-core/src/load-matches.client.ts | 22 +++++-- packages/router-core/src/redirect.ts | 3 - .../router-core/src/router-load.client.ts | 18 +++++ .../blocked-navigation-current-load.test.ts | 65 +++++++++++++++++++ .../tests/fatal-load-rejection.test.ts | 64 ++++++++++++++++++ .../tests/preload-adoption.test.ts | 57 ++++++++++++++++ 7 files changed, 226 insertions(+), 13 deletions(-) create mode 100644 packages/router-core/tests/blocked-navigation-current-load.test.ts create mode 100644 packages/router-core/tests/fatal-load-rejection.test.ts diff --git a/packages/router-core/INTERNALS.md b/packages/router-core/INTERNALS.md index 7c17e70121..4aa0a86b61 100644 --- a/packages/router-core/INTERNALS.md +++ b/packages/router-core/INTERNALS.md @@ -172,8 +172,12 @@ Client match work is current when all of these hold: - `inner.matches[index].abortController` is the controller captured by this async pass. - The controller signal has not been aborted. -- If `router.pendingBuiltLocation` exists, its public browser href still equals - the load context public href. +- For speculative (preload) passes only: if `router.pendingBuiltLocation` + exists, its public browser href still equals the load context public href. + Foreground navigation passes ignore a merely-built pending location — a + history blocker can still discard that commit, in which case no replacement + load ever starts. Their supersession is observed through the abort + controller once the newer load actually runs `cancelMatches()`. The helper `requireCurrentMatch(inner, index, controller)` checks those conditions. It throws `inner` as a private sentinel when ownership is lost. @@ -896,7 +900,7 @@ stateDiagram-v2 Current --> Stale: controller identity changed Current --> Stale: controller aborted Current --> Stale: match removed from private lane - Current --> Stale: pendingBuiltLocation publicHref changed + Current --> Stale: pendingBuiltLocation publicHref changed (preload pass only) Current --> Stale: background token replaced Current --> Stale: latestLoadPromise replaced Stale --> [*]: throw private sentinel or return without publishing diff --git a/packages/router-core/src/load-matches.client.ts b/packages/router-core/src/load-matches.client.ts index f54f6ec5b4..bd718aaf2f 100644 --- a/packages/router-core/src/load-matches.client.ts +++ b/packages/router-core/src/load-matches.client.ts @@ -29,11 +29,15 @@ const isRouteControl = (error: unknown) => // Route work may only commit while it still owns the lane entry it is about to // mutate. Each client load pass stamps its matches with an AbortController: -// starting a newer load replaces the controller, cancellation aborts its signal, -// and a different pending public location means this pass no longer represents -// the browser target. Compare publicHref, not href, because href may be the -// router-internal path while publicHref includes basepath/rewrite output. Any -// of those cases makes continuing unsafe because stale beforeLoad/loader/chunk +// starting a newer load replaces the controller, and cancellation aborts its +// signal. Speculative (preload) passes additionally yield when a different +// public location is being built — compare publicHref, not href, because href +// may be the router-internal path while publicHref includes basepath/rewrite +// output. Foreground navigation passes must NOT treat a merely-built pending +// location as ownership loss: a history blocker can still discard that commit +// (so no replacement load would ever start), and true supersession is +// observed via the controller once the newer load runs cancelMatches. Any of +// those cases makes continuing unsafe because stale beforeLoad/loader/chunk // work could write into the current lane. // // Throwing `inner` is intentional. `loadClientMatches` catches that exact object @@ -45,7 +49,9 @@ const requireCurrentMatch = ( abortController: AbortController, ): AnyRouteMatch => { const match = inner.matches[index] - const pendingLocation = inner.router.pendingBuiltLocation + const pendingLocation = inner.preload + ? inner.router.pendingBuiltLocation + : undefined if ( !match || match.abortController !== abortController || @@ -174,7 +180,9 @@ const adoptInFlightPreload = async ( donor.isFetching !== 'loader' || donor._.loadPromise?.status !== 'pending' ) { - return undefined + // Not joinable (e.g. still in its serial phase) — a later registered + // lane may hold the same match with its loader already in flight. + continue } commitMatch(inner, index, { isFetching: 'loader' }) // The preload pass settles every owned match's loadPromise in its diff --git a/packages/router-core/src/redirect.ts b/packages/router-core/src/redirect.ts index 312343b7a1..c18b457240 100644 --- a/packages/router-core/src/redirect.ts +++ b/packages/router-core/src/redirect.ts @@ -165,13 +165,11 @@ function getRedirectHeaders(opts: { href?: string; headers?: HeadersInit }) { return headers } -/** Check whether a value is a TanStack Router redirect Response. */ /** Check whether a value is a TanStack Router redirect Response. */ export function isRedirect(obj: any): obj is AnyRedirect { return obj instanceof Response && !!(obj as any).options } -/** True if value is a redirect with a resolved `href` location. */ /** True if value is a redirect with a resolved `href` location. */ export function isResolvedRedirect( obj: any, @@ -179,7 +177,6 @@ export function isResolvedRedirect( return isRedirect(obj) && !!obj.options.href } -/** Parse a serialized redirect object back into a redirect Response. */ /** Parse a serialized redirect object back into a redirect Response. */ export function parseRedirect(obj: any) { if (obj !== null && typeof obj === 'object' && obj.isSerializedRedirect) { diff --git a/packages/router-core/src/router-load.client.ts b/packages/router-core/src/router-load.client.ts index fb5cb59991..61d95e3012 100644 --- a/packages/router-core/src/router-load.client.ts +++ b/packages/router-core/src/router-load.client.ts @@ -1,4 +1,5 @@ import { createControlledPromise, isPromise } from './utils' +import { isNotFound } from './not-found' import { isRedirect } from './redirect' import { getLocationChangeInfo, @@ -229,6 +230,18 @@ export const loadClientRouter = async ( if (isRedirect(err)) { throw err } + if (!isNotFound(err)) { + // Anything else thrown here is a fatal machinery failure (e.g. + // resolveRedirect threw); a notFound lane was already committed and + // trimmed with settled promises. Keep the failure observable, and + // settle the lane's load promises — the loader phase may never have + // run for some matches (a serial redirect caps the prefix at 0), and + // committing them unsettled would hang Suspense forever. + Promise.reject(err) + for (const match of pendingMatches) { + settleMatchLoad(match) + } + } loadContext.requiresCommit = true } @@ -303,6 +316,11 @@ export const loadClientRouter = async ( commitLocationPromise?.resolve() } + // Ordering invariant: the success lane must already be published + // (setMatches in commitFinalMatches above) before this resolve. Framework + // Match components throw router.latestLoadPromise for stale pending + // snapshots and rely on that ordering to avoid a suspense busy-loop on an + // already-resolved load. loadPromise.resolve() // A superseded or redirected load must not settle its public await before diff --git a/packages/router-core/tests/blocked-navigation-current-load.test.ts b/packages/router-core/tests/blocked-navigation-current-load.test.ts new file mode 100644 index 0000000000..bda8133662 --- /dev/null +++ b/packages/router-core/tests/blocked-navigation-current-load.test.ts @@ -0,0 +1,65 @@ +import { describe, expect, test } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, createControlledPromise } from '../src' +import { createTestRouter } from './routerTestUtils' + +/** + * A history blocker can discard a navigation commit AFTER + * buildAndCommitLocation set router.pendingBuiltLocation (it is cleared a + * microtask later). A continuation of the still-current in-flight load that + * resumes inside that window must not treat the merely-built location as + * ownership loss: a blocked commit never starts a replacement load, so + * abandoning the pass would leave the router with status 'pending', + * isLoading true, and a populated pending pool forever. + */ + +describe('blocked navigation does not cancel the current load', () => { + test('loader continuation resuming while a blocked navigation is built still commits', async () => { + const loaderGate = createControlledPromise() + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const slowRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/slow', + loader: () => loaderGate, + }) + const otherRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/other', + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, slowRoute, otherRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + + const navigation = router.navigate({ to: '/slow' }) + + // Discard every later navigation commit. The blocker is async, so the + // discarded commit still sets pendingBuiltLocation for one microtask. + const unblock = router.history.block({ blockerFn: async () => true }) + + // Same tick: settle the loader, then issue a navigation the blocker + // discards. The loader continuation resumes inside the window where + // pendingBuiltLocation still points at /other. + loaderGate.resolve('slow data') + void router.navigate({ to: '/other' }) + + await navigation + + expect(router.stores.isLoading.get()).toBe(false) + expect(router.state.location.pathname).toBe('/slow') + expect( + router.state.matches.find((m) => m.routeId === slowRoute.id)?.status, + ).toBe('success') + expect(router.stores.pendingIds.get()).toHaveLength(0) + + unblock() + }) +}) diff --git a/packages/router-core/tests/fatal-load-rejection.test.ts b/packages/router-core/tests/fatal-load-rejection.test.ts new file mode 100644 index 0000000000..d665396624 --- /dev/null +++ b/packages/router-core/tests/fatal-load-rejection.test.ts @@ -0,0 +1,64 @@ +import { describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, redirect } from '../src' +import { createTestRouter } from './routerTestUtils' + +/** + * A genuinely fatal rejection inside loadClientMatches (not a route outcome — + * e.g. resolveRedirect throwing while finalizing a serial beforeLoad + * redirect) must stay observable instead of being silently swallowed, and + * the defensive commit that follows must not publish matches whose load + * promises never settled: the serial redirect capped the loader prefix at 0, + * so the loader phase never ran for ancestor matches and their pending + * loadPromise would hang Suspense forever. + */ + +describe('fatal load rejection', () => { + test('fatal rejection during a serial-redirect-capped pass surfaces and settles the lane', async () => { + const unhandledRejection = vi.fn() + process.on('unhandledRejection', unhandledRejection) + + try { + const boom = new Error('resolveRedirect failed') + + const rootRoute = new BaseRootRoute({ + // Never runs: the serial redirect caps the loader prefix at 0. Its + // loadPromise (created for the beforeLoad phase) must still settle. + loader: () => 'root data', + }) + const badRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/bad', + beforeLoad: () => { + // resolveRedirect builds the target location; the throwing search + // updater turns redirect finalization into a fatal rejection. + throw redirect({ + to: '/bad', + search: () => { + throw boom + }, + }) + }, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([badRoute]), + history: createMemoryHistory({ initialEntries: ['/bad'] }), + }) + + await router.load() + + // The failure stayed observable. + await new Promise((resolve) => setTimeout(resolve, 0)) + expect(unhandledRejection).toHaveBeenCalledWith(boom, expect.anything()) + + // No committed match may keep a pending loadPromise (hung Suspense). + expect(router.state.matches.length).toBeGreaterThan(0) + for (const match of router.state.matches) { + expect(match._.loadPromise?.status ?? 'settled').not.toBe('pending') + } + } finally { + process.off('unhandledRejection', unhandledRejection) + } + }) +}) diff --git a/packages/router-core/tests/preload-adoption.test.ts b/packages/router-core/tests/preload-adoption.test.ts index 6705a892cc..b3e7bb2126 100644 --- a/packages/router-core/tests/preload-adoption.test.ts +++ b/packages/router-core/tests/preload-adoption.test.ts @@ -97,4 +97,61 @@ describe('preload adoption', () => { .find((match) => match.routeId === fooRoute.id)?.loaderData, ).toBe('once') }) + + test('a non-joinable earlier lane does not hide a later lane with its loader in flight', async () => { + const beforeLoadGate = createControlledPromise() + let beforeLoadCalls = 0 + const loaderGate = createControlledPromise() + const loader = vi.fn(() => loaderGate) + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + beforeLoad: async () => { + beforeLoadCalls++ + if (beforeLoadCalls === 1) { + // Keep the FIRST preload's serial phase in flight so its lane + // holds a non-joinable donor; later calls proceed immediately. + await beforeLoadGate + } + }, + loader, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, fooRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + + // First lane: registered first, stuck in its serial phase. + const first = router.preloadRoute({ to: '/foo' } as any) + await vi.waitFor(() => expect(beforeLoadCalls).toBe(1)) + + // Second lane: its loader is in flight and therefore joinable. + const second = router.preloadRoute({ to: '/foo' } as any) + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(1)) + + // The navigation must scan PAST the first (serial-phase) lane and adopt + // the second lane's in-flight loader run instead of re-running it. + const navigation = router.navigate({ to: '/foo' }) + await vi.waitFor(() => expect(beforeLoadCalls).toBe(3)) + loaderGate.resolve('once') + await Promise.all([navigation, second]) + + expect(loader).toHaveBeenCalledTimes(1) + expect( + router.state.matches.find((match) => match.routeId === fooRoute.id) + ?.loaderData, + ).toBe('once') + + beforeLoadGate.resolve() + await first + }) }) From 886050c36cfdf22a23a06ec951566f8e831ca5ca Mon Sep 17 00:00:00 2001 From: Sheraff Date: Tue, 7 Jul 2026 14:34:45 +0200 Subject: [PATCH 43/54] fix: run server chunk failures through the route failure lifecycle and cap ssr() notFound prefixes Co-Authored-By: Claude Fable 5 --- .../router-core/src/load-matches.server.ts | 78 ++++++++++---- .../router-core/src/route-assets.server.ts | 9 +- packages/router-core/src/ssr/ssr-client.ts | 9 +- .../server-chunk-failure-lifecycle.test.ts | 101 ++++++++++++++++++ .../server-headers-asset-failure.test.ts | 29 +++++ .../tests/server-loader-abort-error.test.ts | 38 +++++++ .../tests/server-serial-ssr-notfound.test.ts | 78 ++++++++++++++ 7 files changed, 312 insertions(+), 30 deletions(-) create mode 100644 packages/router-core/tests/server-chunk-failure-lifecycle.test.ts create mode 100644 packages/router-core/tests/server-loader-abort-error.test.ts create mode 100644 packages/router-core/tests/server-serial-ssr-notfound.test.ts diff --git a/packages/router-core/src/load-matches.server.ts b/packages/router-core/src/load-matches.server.ts index ed6dd1c3e7..179cb6effa 100644 --- a/packages/router-core/src/load-matches.server.ts +++ b/packages/router-core/src/load-matches.server.ts @@ -64,29 +64,30 @@ const finalizeServerRouteFailure = async ( inner: InnerLoadContext, index: number, error: unknown, - componentError?: boolean, ): Promise => { const routesById = inner.router.routesById let errorIndex = index + // Set when loading a boundary component (errorComponent/notFoundComponent) + // chunk fails: that failure replaces the original one and commits directly + // as an error — it must not recurse into another boundary chunk. + let componentError = false - if (!componentError) { - try { - if (isNotFound(error)) { - errorIndex = getNotFoundBoundaryIndex(inner, error) - await loadRouteChunk( - routesById[inner.matches[errorIndex]!.routeId], - 'notFoundComponent', - ) - } else if (!isRedirect(error)) { - await loadRouteChunk( - routesById[inner.matches[index]!.routeId], - 'errorComponent', - ) - } - } catch (chunkError) { - error = chunkError - componentError = true + try { + if (isNotFound(error)) { + errorIndex = getNotFoundBoundaryIndex(inner, error) + await loadRouteChunk( + routesById[inner.matches[errorIndex]!.routeId], + 'notFoundComponent', + ) + } else if (!isRedirect(error)) { + await loadRouteChunk( + routesById[inner.matches[index]!.routeId], + 'errorComponent', + ) } + } catch (chunkError) { + error = chunkError + componentError = true } if (!componentError) { @@ -342,6 +343,27 @@ const loadServerRouteMatch = async ( throw loaderError } + if ((loaderError as any)?.name === 'AbortError') { + // A loader's own AbortError (e.g. an internal fetch timeout) is not a + // route failure: settle the match without committing an error instead + // of turning the abort into a 500. If the match's own signal was + // aborted, leave the match as-is. + if (!inner.matches[index]!.abortController.signal.aborted) { + commitMatch(inner, index, { + status: + inner.matches[index]!.status === 'pending' + ? 'success' + : inner.matches[index]!.status, + context: getMatchContext( + inner, + index, + inner.matches[index]!.__beforeLoadContext, + ), + }) + } + return inner.matches[index]! + } + await finalizeServerRouteFailure( inner, index, @@ -355,7 +377,16 @@ const loadServerRouteMatch = async ( await routeChunkPromise } } catch (chunkError) { - await finalizeServerRouteFailure(inner, index, chunkError, true) + // A primary route chunk failure goes through the normal route failure + // lifecycle (onError, redirect/notFound conversion) like loader + // failures. Only a subsequent boundary component chunk failure commits + // directly inside finalizeServerRouteFailure instead of recursing into + // another boundary chunk. + await finalizeServerRouteFailure( + inner, + index, + normalizeRouteFailure(inner, index, chunkError), + ) return inner.matches[index]! } @@ -399,11 +430,14 @@ export const loadServerMatches = async ( matchPromises[i] = Promise.resolve(finishServerSkippedMatch(inner, i)) } } catch (err) { - if (isNotFound(err)) { - firstNotFound ||= err - } else { + if (!isNotFound(err)) { throw err } + // An `ssr()` option can throw notFound(). Record it as the pass's + // serial failure so the loader prefix is capped at the selected + // boundary — the throwing route and descendants whose beforeLoad + // never ran must not load. + recordServerBeforeLoadFailure(inner, i, err) break } } diff --git a/packages/router-core/src/route-assets.server.ts b/packages/router-core/src/route-assets.server.ts index a04021f2a6..3bb607b988 100644 --- a/packages/router-core/src/route-assets.server.ts +++ b/packages/router-core/src/route-assets.server.ts @@ -108,11 +108,10 @@ export const projectServerRouteAssets = ( : undefined, ) - const failed = [headResult, scriptResult, headerResult].find( - (result) => result.status === 'rejected', - ) - if (failed) { - logAssetError(match, failed.reason) + for (const result of [headResult, scriptResult, headerResult]) { + if (result.status === 'rejected') { + logAssetError(match, result.reason) + } } return projectServerRouteAssets(router, matches, i + 1) diff --git a/packages/router-core/src/ssr/ssr-client.ts b/packages/router-core/src/ssr/ssr-client.ts index a2a2889cf8..296b1c69f9 100644 --- a/packages/router-core/src/ssr/ssr-client.ts +++ b/packages/router-core/src/ssr/ssr-client.ts @@ -85,13 +85,16 @@ export async function hydrate(router: AnyRouter): Promise { // First step is to rehydrate loaderData and beforeLoad context. let firstNonSsrMatch: AnyRouteMatch | undefined = undefined let hasSsrFalseMatches = false + const dehydratedMatchesById = new Map( + dehydratedRouter.matches.map( + (dehydrated) => [hydrateSsrMatchId(dehydrated.i), dehydrated] as const, + ), + ) const routeChunkPromise = Promise.all( matches.map((match) => { const route = routesById[match.routeId]! - const dehydratedMatch = dehydratedRouter.matches.find( - (dehydrated) => hydrateSsrMatchId(dehydrated.i) === match.id, - ) + const dehydratedMatch = dehydratedMatchesById.get(match.id) if (!dehydratedMatch) { match.ssr = false } else { diff --git a/packages/router-core/tests/server-chunk-failure-lifecycle.test.ts b/packages/router-core/tests/server-chunk-failure-lifecycle.test.ts new file mode 100644 index 0000000000..aa7b4a5916 --- /dev/null +++ b/packages/router-core/tests/server-chunk-failure-lifecycle.test.ts @@ -0,0 +1,101 @@ +import { describe, expect, test } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, notFound } from '../src' +import { createTestRouter } from './routerTestUtils' + +/** + * A primary route chunk failure observed by the server loader phase (a route + * component preload or lazyFn rejection) must go through the same route + * failure lifecycle as loader failures: the route's onError runs, + * redirect/notFound conversion applies, and the errorComponent boundary + * chunk is loaded. Only boundary component chunk failures commit directly + * without recursing into another boundary chunk. + * + * These tests use a real server router load with a route component whose + * preload rejects. + */ + +describe('server route chunk failure lifecycle', () => { + test('calls route onError once and loads the errorComponent chunk when the route component chunk rejects', async () => { + const chunkError = new Error('component chunk failed') + const capturedErrors: Array = [] + const events: Array = [] + + const FailingComponent = Object.assign(() => null, { + preload: () => Promise.reject(chunkError), + }) + const ErrorBoundary = Object.assign(() => null, { + preload: () => { + events.push('errorComponent-preload') + return Promise.resolve() + }, + }) + + const rootRoute = new BaseRootRoute({}) + const chunkedRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/chunked', + onError: (error: unknown) => { + capturedErrors.push(error) + events.push('onError') + }, + component: FailingComponent as any, + errorComponent: ErrorBoundary as any, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([chunkedRoute]), + history: createMemoryHistory({ initialEntries: ['/chunked'] }), + isServer: true, + }) + + await router.load() + + const match = router.state.matches.find( + (item) => item.routeId === chunkedRoute.id, + ) + expect(capturedErrors).toEqual([chunkError]) + expect(match?.status).toBe('error') + expect(match?.error).toBe(chunkError) + // Failure finalization loads the errorComponent boundary chunk after + // onError ran. (The initial whole-route preload also requests it before + // the failure, hence lastIndexOf.) + expect(events.lastIndexOf('errorComponent-preload')).toBeGreaterThan( + events.indexOf('onError'), + ) + expect(router.statusCode).toBe(500) + }) + + test('a notFound thrown from onError for a route chunk failure sets 404 instead of 500', async () => { + const chunkError = new Error('component chunk failed') + + const FailingComponent = Object.assign(() => null, { + preload: () => Promise.reject(chunkError), + }) + + const rootRoute = new BaseRootRoute({}) + const chunkedRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/chunked', + onError: () => { + throw notFound() + }, + component: FailingComponent as any, + notFoundComponent: () => null, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([chunkedRoute]), + history: createMemoryHistory({ initialEntries: ['/chunked'] }), + isServer: true, + }) + + await router.load() + + const match = router.state.matches.find( + (item) => item.routeId === chunkedRoute.id, + ) + expect(router.statusCode).toBe(404) + expect(router.redirect).toBeUndefined() + expect(match?.status).toBe('notFound') + expect(match?.error).toEqual(expect.objectContaining({ isNotFound: true })) + }) +}) diff --git a/packages/router-core/tests/server-headers-asset-failure.test.ts b/packages/router-core/tests/server-headers-asset-failure.test.ts index 3a954a9fe8..56af4894fe 100644 --- a/packages/router-core/tests/server-headers-asset-failure.test.ts +++ b/packages/router-core/tests/server-headers-asset-failure.test.ts @@ -89,6 +89,35 @@ describe('server asset projection route headers', () => { expect(targetMatch!.meta).toEqual([{ title: 'kept title' }]) }) + test('logs every rejected asset hook when several reject asynchronously', async () => { + const headError = new Error('head failed') + const headersError = new Error('headers failed') + const rootRoute = new BaseRootRoute({}) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + head: async () => { + throw headError + }, + headers: async () => { + throw headersError + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([targetRoute]), + history: createMemoryHistory({ initialEntries: ['/target'] }), + isServer: true, + }) + + await router.load() + + const loggedErrors = vi + .mocked(console.error) + .mock.calls.map((call) => call.at(-1)) + expect(loggedErrors).toContain(headError) + expect(loggedErrors).toContain(headersError) + }) + test('awaits async route headers when head throws synchronously', async () => { const rootRoute = new BaseRootRoute({}) const targetRoute = new BaseRoute({ diff --git a/packages/router-core/tests/server-loader-abort-error.test.ts b/packages/router-core/tests/server-loader-abort-error.test.ts new file mode 100644 index 0000000000..b74fa56c42 --- /dev/null +++ b/packages/router-core/tests/server-loader-abort-error.test.ts @@ -0,0 +1,38 @@ +import { describe, expect, test } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +/** + * A server loader that throws an AbortError while the match's own signal is + * NOT aborted (e.g. the loader's own fetch timed out) is not a route + * failure. It settles the match as a non-error instead of committing a 500. + */ + +describe('server loader AbortError', () => { + test('settles as non-error with a 200 status when the match signal is not aborted', async () => { + const rootRoute = new BaseRootRoute({}) + const abortingRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/aborting', + loader: () => { + throw new DOMException('The operation was aborted.', 'AbortError') + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([abortingRoute]), + history: createMemoryHistory({ initialEntries: ['/aborting'] }), + isServer: true, + }) + + await router.load() + + const match = router.state.matches.find( + (item) => item.routeId === abortingRoute.id, + ) + expect(router.statusCode).toBe(200) + expect(router.redirect).toBeUndefined() + expect(match?.status).toBe('success') + expect(match?.error).toBeUndefined() + }) +}) diff --git a/packages/router-core/tests/server-serial-ssr-notfound.test.ts b/packages/router-core/tests/server-serial-ssr-notfound.test.ts new file mode 100644 index 0000000000..290bd9a8a2 --- /dev/null +++ b/packages/router-core/tests/server-serial-ssr-notfound.test.ts @@ -0,0 +1,78 @@ +import { describe, expect, test } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, notFound } from '../src' +import { createTestRouter } from './routerTestUtils' + +/** + * A notFound thrown from a route's ssr() option happens during the serial + * phase, before beforeLoad has run for that route and its descendants. It + * must cap the loader prefix like a beforeLoad notFound: the throwing route + * and its descendants must not run their loaders (their context is + * incomplete and their ssr status unresolved), and the response must be a + * 404 — a descendant loader failure must not be able to turn the outcome + * into a 200/500. + */ + +function setupRouter(childLoader: () => unknown) { + const loaderCalls: Array = [] + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + notFoundComponent: () => null, + ssr: () => { + throw notFound() + }, + loader: () => { + loaderCalls.push('parent') + }, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: () => { + loaderCalls.push('child') + return childLoader() + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + isServer: true, + }) + + return { router, parentRoute, loaderCalls } +} + +describe('server serial ssr() notFound', () => { + test('caps the loader prefix at the boundary and sets 404', async () => { + const { router, parentRoute, loaderCalls } = setupRouter(() => 'child') + + await router.load() + + const parentMatch = router.state.matches.find( + (item) => item.routeId === parentRoute.id, + ) + expect(loaderCalls).toEqual([]) + expect(router.statusCode).toBe(404) + expect(router.redirect).toBeUndefined() + expect(parentMatch?.status).toBe('notFound') + expect(parentMatch?.error).toEqual( + expect.objectContaining({ isNotFound: true }), + ) + // The lane is trimmed to the notFound boundary. + expect(router.state.matches.at(-1)?.routeId).toBe(parentRoute.id) + }) + + test('a descendant loader that would reject fatally cannot displace the 404', async () => { + const { router, loaderCalls } = setupRouter(() => { + throw new Error('child loader failed') + }) + + await router.load() + + expect(loaderCalls).toEqual([]) + expect(router.statusCode).toBe(404) + }) +}) From 85b9079e89c319cecddf0e6ffd69c981816e99a3 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Tue, 7 Jul 2026 14:34:45 +0200 Subject: [PATCH 44/54] fix: vue onResolved/onRendered emit real location change info Co-Authored-By: Claude Fable 5 --- packages/vue-router/src/Match.tsx | 75 +++++++++++++---------- packages/vue-router/src/Transitioner.tsx | 17 ++++- packages/vue-router/tests/router.test.tsx | 47 ++++++++++++++ 3 files changed, 104 insertions(+), 35 deletions(-) diff --git a/packages/vue-router/src/Match.tsx b/packages/vue-router/src/Match.tsx index 3d65628062..bc0bc44749 100644 --- a/packages/vue-router/src/Match.tsx +++ b/packages/vue-router/src/Match.tsx @@ -15,7 +15,11 @@ import { matchContext, routeIdContext } from './matchContext' import { renderRouteNotFound } from './renderRouteNotFound' import { ScrollRestoration } from './scroll-restoration' import type { VNode } from 'vue' -import type { AnyRoute, RootRouteOptions } from '@tanstack/router-core' +import type { + AnyRoute, + ParsedLocation, + RootRouteOptions, +} from '@tanstack/router-core' export const Match = Vue.defineComponent({ name: 'Match', @@ -241,24 +245,32 @@ const OnRendered = Vue.defineComponent({ (resolvedLocation) => resolvedLocation?.state.__TSR_key, ) - let prevHref: string | undefined - + // Track the resolvedLocation as of the last emission so onRendered can + // report the correct fromLocation. By the time this watcher fires, + // Transitioner has already advanced resolvedLocation to the new location, + // so router.stores.resolvedLocation.get() cannot be used as fromLocation. + // Stored on the router (not a closure) because a cross-route navigation + // remounts this keyed component, which would otherwise reset the tracker. Vue.watch( location, () => { - if (location.value) { - const currentHref = router.latestLocation.href - if (prevHref === undefined || prevHref !== currentHref) { - router.emit({ - type: 'onRendered', - ...getLocationChangeInfo( - router.stores.location.get(), - router.stores.resolvedLocation.get(), - ), - }) - prevHref = currentHref - } + const currentResolvedLocation = router.stores.resolvedLocation.get() + const previousResolvedLocation = (router as any) + .__tsrOnRenderedLocation as ParsedLocation | undefined + if ( + currentResolvedLocation && + (!previousResolvedLocation || + previousResolvedLocation.href !== currentResolvedLocation.href) + ) { + router.emit({ + type: 'onRendered', + ...getLocationChangeInfo( + router.stores.location.get(), + previousResolvedLocation ?? currentResolvedLocation, + ), + }) } + ;(router as any).__tsrOnRenderedLocation = currentResolvedLocation }, { immediate: true }, ) @@ -336,41 +348,41 @@ export const MatchInner = Vue.defineComponent({ return (): VNode | null => { // If match doesn't exist, return null (component is being unmounted or not ready) - if (!combinedState.value || !match.value || !route.value) return null + if (!combinedState.value) return null // A hydration display match keeps rendering pending UI until the // follow-up client load clears the marker, even though its local // loadPromise was already settled by hydrate(). - if (match.value._displayPending) { + if (match.value!._displayPending) { const PendingComponent = - route.value.options.pendingComponent ?? + route.value!.options.pendingComponent ?? router.options.defaultPendingComponent return PendingComponent ? Vue.h(PendingComponent) : null } - if (match.value.status === 'notFound') { - if (!isNotFound(match.value.error)) { + if (match.value!.status === 'notFound') { + if (!isNotFound(match.value!.error)) { if (process.env.NODE_ENV !== 'production') { throw new Error('Invariant failed: Expected a notFound error') } invariant() } - return renderRouteNotFound(router, route.value, match.value.error) + return renderRouteNotFound(router, route.value!, match.value!.error) } - if (match.value.status === 'error') { + if (match.value!.status === 'error') { // Check if this route or any parent has an error component const RouteErrorComponent = - route.value.options.errorComponent ?? + route.value!.options.errorComponent ?? router.options.defaultErrorComponent // If this route has an error component, render it directly // This is more reliable than relying on Vue's error boundary if (RouteErrorComponent) { return Vue.h(RouteErrorComponent, { - error: match.value.error, + error: match.value!.error, reset: () => { router.invalidate() }, @@ -382,10 +394,10 @@ export const MatchInner = Vue.defineComponent({ // If there's no error component for this route, throw the error // so it can bubble up to the nearest parent with an error component - throw match.value.error + throw match.value!.error } - if (match.value.status === 'pending') { + if (match.value!.status === 'pending') { // In Vue, we render the pending component directly instead of throwing a promise // because Vue's Suspense doesn't catch thrown promises like React does const PendingComponent = @@ -398,9 +410,9 @@ export const MatchInner = Vue.defineComponent({ // cancelMatches) but before the newer lane commits, so a missing // local promise is a legitimate state here. Only a still-pending // local promise owns pendingMinMs timing. - const localPromise = Vue.toRaw(match.value._).loadPromise + const localPromise = Vue.toRaw(match.value!._).loadPromise const pendingMinMs = - route.value.options.pendingMinMs ?? + route.value!.options.pendingMinMs ?? router.options.defaultPendingMinMs if ( @@ -420,7 +432,7 @@ export const MatchInner = Vue.defineComponent({ // Success status - render the component with remount key const Comp = - route.value.options.component ?? router.options.defaultComponent + route.value!.options.component ?? router.options.defaultComponent const key = remountKey.value if (Comp) { @@ -484,10 +496,7 @@ export const Outlet = Vue.defineComponent({ return (): VNode | null => { if (parentGlobalNotFound.value) { - if (!route.value) { - return null - } - return renderRouteNotFound(router, route.value, undefined) + return renderRouteNotFound(router, route.value!, undefined) } if (!childMatchData.value) { diff --git a/packages/vue-router/src/Transitioner.tsx b/packages/vue-router/src/Transitioner.tsx index 642647c9ed..09a2a0c4cd 100644 --- a/packages/vue-router/src/Transitioner.tsx +++ b/packages/vue-router/src/Transitioner.tsx @@ -37,6 +37,14 @@ export function useTransitionerSetup() { isAnyPending: false, } + // Change info captured at the pagePending falling edge, before commitIdle() + // advances resolvedLocation to the new location. Reused for the (possibly + // nextTick-deferred) onResolved emission so it reports the navigation that + // actually resolved instead of a from===to no-op. Reset once consumed. + let resolvedChangeInfo: + | ReturnType + | undefined + // Single emitter for the load lifecycle. Level changes arrive through // synchronous store subscriptions — which, unlike watcher-observed edges, // cannot lose a flip to Vue's flush batching — plus the flush-coupled @@ -74,11 +82,16 @@ export function useTransitionerSetup() { } } if (prev.isPagePending && !isPagePending) { - router.emit({ type: 'onBeforeRouteMount', ...changeInfo() }) + resolvedChangeInfo = changeInfo() + router.emit({ type: 'onBeforeRouteMount', ...resolvedChangeInfo }) commitIdle() } if (prev.isAnyPending && !isAnyPending) { - router.emit({ type: 'onResolved', ...changeInfo() }) + router.emit({ + type: 'onResolved', + ...(resolvedChangeInfo ?? changeInfo()), + }) + resolvedChangeInfo = undefined commitIdle() } } diff --git a/packages/vue-router/tests/router.test.tsx b/packages/vue-router/tests/router.test.tsx index 6521d9fa13..edc6e206cc 100644 --- a/packages/vue-router/tests/router.test.tsx +++ b/packages/vue-router/tests/router.test.tsx @@ -839,6 +839,53 @@ describe('router emits events during rendering', () => { unsub() }) + it('should emit "onResolved" with change info describing the navigation', async () => { + const { router } = createTestRouter({ + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + render() + await sleep(0) + + const mockOnResolved = vi.fn() + const unsub = router.subscribe('onResolved', mockOnResolved) + + await router.navigate({ to: '/posts/$slug', params: { slug: 'first' } }) + await waitFor(() => expect(mockOnResolved).toBeCalledTimes(1)) + + const payload = mockOnResolved.mock.calls[0]?.[0] + expect(payload?.fromLocation?.pathname).toBe('/') + expect(payload?.toLocation.pathname).toBe('/posts/first') + expect(payload?.pathChanged).toBe(true) + expect(payload?.hrefChanged).toBe(true) + + unsub() + }) + + it('should emit "onRendered" with the previous location as fromLocation', async () => { + const { router } = createTestRouter({ + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + render() + await sleep(0) + + const mockOnRendered = vi.fn() + const unsub = router.subscribe('onRendered', mockOnRendered) + + await router.navigate({ to: '/posts/$slug', params: { slug: 'first' } }) + await waitFor(() => expect(mockOnRendered).toBeCalledTimes(1)) + + const payload = mockOnRendered.mock.calls[0]?.[0] + expect(payload?.fromLocation?.pathname).toBe('/') + expect(payload?.toLocation.pathname).toBe('/posts/first') + expect(payload?.fromLocation?.href).not.toBe(payload?.toLocation.href) + + unsub() + }) + it('should emit the "onRendered" event when a route renders, after navigation, and after param/search updates', async () => { const { router } = createTestRouter({ history: createMemoryHistory({ initialEntries: ['/'] }), From 4588e4515e82b4e24f04be841a6f7df4b4c3c340 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Tue, 7 Jul 2026 14:34:45 +0200 Subject: [PATCH 45/54] fix: fuzzy 404s honor layout notFoundComponents; preloads keep borrowed cache entries on gcTime Co-Authored-By: Claude Fable 5 --- .../router-core/src/router-preload.client.ts | 14 +- packages/router-core/src/router.ts | 12 +- .../issue-6351-fuzzy-notfound-layout.test.ts | 99 ++++++++++++++ .../preload-borrowed-cache-gctime.test.ts | 129 ++++++++++++++++++ 4 files changed, 250 insertions(+), 4 deletions(-) create mode 100644 packages/router-core/tests/issue-6351-fuzzy-notfound-layout.test.ts create mode 100644 packages/router-core/tests/preload-borrowed-cache-gctime.test.ts diff --git a/packages/router-core/src/router-preload.client.ts b/packages/router-core/src/router-preload.client.ts index 729af87d46..722649e37b 100644 --- a/packages/router-core/src/router-preload.client.ts +++ b/packages/router-core/src/router-preload.client.ts @@ -54,9 +54,19 @@ export const preloadClientRoute = async ( let ownedMatches: Array | undefined for (const match of prefix) { - if (match.preload && !router.getMatch(match.id, false)) { - ;(ownedMatches ||= []).push(match) + if (!match.preload || router.getMatch(match.id, false)) { + continue } + // A cache entry this pass borrowed without reloading is not owned + // work: re-caching it would restamp `preload: true` — silently + // demoting a navigation entry from gcTime to preloadGcTime — while + // keeping its old `updatedAt`. Only snapshots whose loader ran under + // this pass (fresh `updatedAt`) may replace an existing cache entry. + const cachedMatch = router.getMatch(match.id) + if (cachedMatch && cachedMatch.updatedAt === match.updatedAt) { + continue + } + ;(ownedMatches ||= []).push(match) } if (ownedMatches) { router.stores.setCached([ diff --git a/packages/router-core/src/router.ts b/packages/router-core/src/router.ts index 61b1409b44..62b5cdbac4 100644 --- a/packages/router-core/src/router.ts +++ b/packages/router-core/src/router.ts @@ -1452,8 +1452,16 @@ export class RouterCore< for (let i = matchedRoutes.length - 1; i >= 0; i--) { const route = matchedRoutes[i]! if (route.children) { - globalNotFoundRouteId = route.id - break + // Prefer the deepest matched route that can actually render + // the notFound. Without a notFoundComponent anywhere, fall + // back to the deepest matched route with children. + if (route.options.notFoundComponent) { + globalNotFoundRouteId = route.id + break + } + if (globalNotFoundRouteId === rootRouteId) { + globalNotFoundRouteId = route.id + } } } } diff --git a/packages/router-core/tests/issue-6351-fuzzy-notfound-layout.test.ts b/packages/router-core/tests/issue-6351-fuzzy-notfound-layout.test.ts new file mode 100644 index 0000000000..25e212b8f5 --- /dev/null +++ b/packages/router-core/tests/issue-6351-fuzzy-notfound-layout.test.ts @@ -0,0 +1,99 @@ +import { expect, test } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +/** + * https://github.com/TanStack/router/issues/6351 + * + * A fuzzy (unmatched-URL) 404 must be attributed to the nearest matched + * ancestor that can actually render it: the deepest matched route with + * children that defines a `notFoundComponent`. Attributing it to the + * deepest matched route with children regardless of whether it has a + * `notFoundComponent` skips pathless-layout/ancestor `notFoundComponent`s + * and makes the framework fall back to `defaultNotFoundComponent`. + * + * When no matched route defines a `notFoundComponent`, the previous + * behavior (deepest matched route with children) is preserved, and + * `notFoundMode: 'root'` still attributes the 404 to the root route. + */ + +function setup(opts: { + layoutNotFoundComponent?: () => unknown + agentsNotFoundComponent?: () => unknown + notFoundMode?: 'fuzzy' | 'root' +}) { + const rootRoute = new BaseRootRoute({}) + const layoutRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + id: '_authenticated', + notFoundComponent: opts.layoutNotFoundComponent, + }) + const agentsRoute = new BaseRoute({ + getParentRoute: () => layoutRoute, + path: '/agents', + notFoundComponent: opts.agentsNotFoundComponent, + }) + const skillAgentRoute = new BaseRoute({ + getParentRoute: () => agentsRoute, + path: '/skill-agent', + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + layoutRoute.addChildren([agentsRoute.addChildren([skillAgentRoute])]), + ]), + history: createMemoryHistory({ initialEntries: ['/agents/skill-agen'] }), + notFoundMode: opts.notFoundMode, + }) + + return { router, rootRoute, layoutRoute, agentsRoute } +} + +function globalNotFoundRouteIds(router: { + state: { matches: Array<{ routeId: string; globalNotFound?: boolean }> } +}) { + return router.state.matches + .filter((match) => match.globalNotFound) + .map((match) => match.routeId) +} + +test('fuzzy notFound lands on the pathless layout that defines a notFoundComponent', async () => { + const { router, layoutRoute } = setup({ + layoutNotFoundComponent: () => 'layout not found', + }) + + await router.load() + + expect(globalNotFoundRouteIds(router)).toEqual([layoutRoute.id]) +}) + +test('fuzzy notFound prefers the deepest matched route with a notFoundComponent', async () => { + const { router, agentsRoute } = setup({ + layoutNotFoundComponent: () => 'layout not found', + agentsNotFoundComponent: () => 'agents not found', + }) + + await router.load() + + expect(globalNotFoundRouteIds(router)).toEqual([agentsRoute.id]) +}) + +test('fuzzy notFound falls back to the deepest matched route with children when no notFoundComponent exists', async () => { + const { router, agentsRoute } = setup({}) + + await router.load() + + expect(globalNotFoundRouteIds(router)).toEqual([agentsRoute.id]) +}) + +test("notFoundMode 'root' attributes the notFound to the root route even when a layout has a notFoundComponent", async () => { + const { router, rootRoute } = setup({ + layoutNotFoundComponent: () => 'layout not found', + notFoundMode: 'root', + }) + + await router.load() + + expect(globalNotFoundRouteIds(router)).toEqual([rootRoute.id]) +}) diff --git a/packages/router-core/tests/preload-borrowed-cache-gctime.test.ts b/packages/router-core/tests/preload-borrowed-cache-gctime.test.ts new file mode 100644 index 0000000000..3118376217 --- /dev/null +++ b/packages/router-core/tests/preload-borrowed-cache-gctime.test.ts @@ -0,0 +1,129 @@ +import { expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +/** + * A preload pass that borrows a navigation-cached entry without re-running + * its loader (fresh within preloadStaleTime) does not own that snapshot and + * must not re-cache it: doing so would restamp `preload: true` and silently + * demote the entry from `gcTime` to `preloadGcTime` while keeping its old + * `updatedAt`, evicting it at the next commit-time GC. + * + * Only snapshots the pass actually produced — new matches, or borrowed + * entries whose loader re-ran under the pass — enter the cache. + */ + +function setup(routeOptions: { + gcTime: number + preloadGcTime: number + preloadStaleTime: number +}) { + let calls = 0 + const postsLoader = vi.fn(() => ({ value: ++calls })) + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + loader: postsLoader, + ...routeOptions, + }) + const otherRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/other', + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, postsRoute, otherRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + const getCachedEntry = () => + router.stores.cachedMatches + .get() + .find((match) => match.routeId === postsRoute.id) + + return { router, postsLoader, getCachedEntry } +} + +test('preloading a fresh navigation-cached entry does not demote it to preloadGcTime', async () => { + vi.useFakeTimers() + vi.setSystemTime(1_000) + + try { + const { router, postsLoader, getCachedEntry } = setup({ + gcTime: 30 * 60_000, + preloadGcTime: 30_000, + preloadStaleTime: 10 * 60_000, + }) + + await router.load() + await router.navigate({ to: '/posts' }) + expect(postsLoader).toHaveBeenCalledTimes(1) + await router.navigate({ to: '/' }) + + const navigationEntry = getCachedEntry()! + expect(navigationEntry.status).toBe('success') + expect(navigationEntry.preload).toBeFalsy() + + // Past preloadGcTime (30s), well within gcTime (30min). + vi.setSystemTime(61_000) + + // Fresh within preloadStaleTime: the preload borrows the cached entry + // and its loader does not re-run. + await router.preloadRoute({ to: '/posts' } as any) + expect(postsLoader).toHaveBeenCalledTimes(1) + + // The navigation-owned cache entry is untouched. + const afterPreload = getCachedEntry()! + expect(afterPreload.preload).toBeFalsy() + expect(afterPreload.updatedAt).toBe(navigationEntry.updatedAt) + + // Commit-time GC keeps the entry alive under gcTime. + await router.navigate({ to: '/other' }) + expect(getCachedEntry()).toBeDefined() + + // And the entry still expires under its own gcTime. + vi.setSystemTime(1_000 + 31 * 60_000) + await router.navigate({ to: '/' }) + expect(getCachedEntry()).toBeUndefined() + } finally { + vi.useRealTimers() + } +}) + +test('a preload that reloads a stale cached entry re-caches the fresh snapshot', async () => { + vi.useFakeTimers() + vi.setSystemTime(1_000) + + try { + const { router, postsLoader, getCachedEntry } = setup({ + gcTime: 30 * 60_000, + preloadGcTime: 30_000, + preloadStaleTime: 5_000, + }) + + await router.load() + await router.navigate({ to: '/posts' }) + expect(postsLoader).toHaveBeenCalledTimes(1) + await router.navigate({ to: '/' }) + + // Past preloadStaleTime: the preload re-runs the loader, so the pass + // owns the fresh snapshot and caches it under preload gc semantics. + vi.setSystemTime(61_000) + await router.preloadRoute({ to: '/posts' } as any) + expect(postsLoader).toHaveBeenCalledTimes(2) + + const refreshed = getCachedEntry()! + expect(refreshed.preload).toBe(true) + expect(refreshed.loaderData).toEqual({ value: 2 }) + expect(refreshed.updatedAt).toBe(61_000) + } finally { + vi.useRealTimers() + } +}) From 75c0d25a5291f9e58bcea5894b96dc1e6302005a Mon Sep 17 00:00:00 2001 From: Sheraff Date: Tue, 7 Jul 2026 14:34:45 +0200 Subject: [PATCH 46/54] fix: detect webpack/rspack ChunkLoadError in module-not-found recovery; pin issue regressions Co-Authored-By: Claude Fable 5 --- packages/router-core/src/utils.ts | 2 + .../issue-3293-onenter-after-loader.test.ts | 55 ++++++++++++++ ...4078-loader-notfound-root-boundary.test.ts | 69 ++++++++++++++++++ .../issue-4476-preload-navigate-abort.test.ts | 72 +++++++++++++++++++ .../tests/issue-7633-chunk-load-error.test.ts | 45 ++++++++++++ 5 files changed, 243 insertions(+) create mode 100644 packages/router-core/tests/issue-3293-onenter-after-loader.test.ts create mode 100644 packages/router-core/tests/issue-4078-loader-notfound-root-boundary.test.ts create mode 100644 packages/router-core/tests/issue-4476-preload-navigate-abort.test.ts create mode 100644 packages/router-core/tests/issue-7633-chunk-load-error.test.ts diff --git a/packages/router-core/src/utils.ts b/packages/router-core/src/utils.ts index 0e48cbe2b4..538bed672d 100644 --- a/packages/router-core/src/utils.ts +++ b/packages/router-core/src/utils.ts @@ -497,6 +497,8 @@ export function isModuleNotFoundError(error: any): boolean { // chrome: "Failed to fetch dynamically imported module: http://localhost:5173/src/routes/posts.index.tsx?tsr-split" // firefox: "error loading dynamically imported module: http://localhost:5173/src/routes/posts.index.tsx?tsr-split" // safari: "Importing a module script failed." + // webpack/rspack: error.name === "ChunkLoadError", message like "Loading chunk 42 failed." + if (error?.name === 'ChunkLoadError') return true if (typeof error?.message !== 'string') return false return ( error.message.startsWith('Failed to fetch dynamically imported module') || diff --git a/packages/router-core/tests/issue-3293-onenter-after-loader.test.ts b/packages/router-core/tests/issue-3293-onenter-after-loader.test.ts new file mode 100644 index 0000000000..d74f20f11d --- /dev/null +++ b/packages/router-core/tests/issue-3293-onenter-after-loader.test.ts @@ -0,0 +1,55 @@ +import { describe, expect, it } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +// https://github.com/TanStack/router/issues/3293 +// onEnter used to fire before / in parallel with the route's loader, so the +// documented "onEnter runs once the route is loaded" contract was violated. +// The lane model runs onLeave/onStay/onEnter in the final commit, strictly +// after loadClientMatches, so onEnter always observes a settled loader. +describe('issue #3293 - onEnter runs after the loader settles', () => { + const setup = (order: Array, initialEntries: Array) => { + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const aboutRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/about', + loader: async () => { + order.push('loader:start') + await new Promise((resolve) => setTimeout(resolve, 10)) + order.push('loader:end') + }, + onEnter: () => { + order.push('onEnter') + }, + }) + + return createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, aboutRoute]), + history: createMemoryHistory({ initialEntries }), + }) + } + + it('initial load: onEnter fires after the loader end', async () => { + const order: Array = [] + const router = setup(order, ['/about']) + + await router.load() + + expect(order).toEqual(['loader:start', 'loader:end', 'onEnter']) + }) + + it('navigation: onEnter fires after the loader end', async () => { + const order: Array = [] + const router = setup(order, ['/']) + + await router.load() + await router.navigate({ to: '/about' }) + + expect(order).toEqual(['loader:start', 'loader:end', 'onEnter']) + }) +}) diff --git a/packages/router-core/tests/issue-4078-loader-notfound-root-boundary.test.ts b/packages/router-core/tests/issue-4078-loader-notfound-root-boundary.test.ts new file mode 100644 index 0000000000..3efab8bcb9 --- /dev/null +++ b/packages/router-core/tests/issue-4078-loader-notfound-root-boundary.test.ts @@ -0,0 +1,69 @@ +import { describe, expect, it } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, notFound, rootRouteId } from '../src' +import { createTestRouter } from './routerTestUtils' + +// https://github.com/TanStack/router/issues/4078 +// https://github.com/TanStack/router/issues/2255 +// Throwing an untargeted notFound() in a child loader used to always render the +// defaultNotFoundComponent, even when __root__ defined a notFoundComponent +// (#4078). #2255 is the same asymmetry: a path-mismatch notFound renders the +// root component + notFoundComponent, but a loader-thrown notFound did not. +// +// The lane-model getNotFoundBoundaryIndex walks up from the throwing route to +// the nearest route with a notFoundComponent; for an untargeted notFound with +// no boundary below root that is __root__ itself. When the boundary is the root +// route the root match commits `status: 'success'` with `globalNotFound: true`, +// so the root's own notFoundComponent renders (not the default). +describe('issue #4078 / #2255 - loader notFound resolves to the root boundary', () => { + const setup = (initialEntries: Array) => { + const rootRoute = new BaseRootRoute({ + component: () => 'Root', + notFoundComponent: () => 'Root not found', + }) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const aboutRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/about', + loader: () => { + throw notFound() + }, + component: () => 'About', + }) + + return createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, aboutRoute]), + history: createMemoryHistory({ initialEntries }), + }) + } + + it('navigating to a route whose loader throws notFound() selects the root boundary', async () => { + const router = setup(['/']) + await router.load() + + await router.navigate({ to: '/about' }) + await router.load() + + const rootMatch = router.state.matches.find( + (match) => match.routeId === rootRouteId, + ) + // Root boundary selected: root renders its own notFoundComponent, not the + // default one. + expect(rootMatch?.status).toBe('success') + expect(rootMatch?.globalNotFound).toBe(true) + }) + + it('initial load of that route selects the root boundary too (#2255 asymmetry)', async () => { + const router = setup(['/about']) + await router.load() + + const rootMatch = router.state.matches.find( + (match) => match.routeId === rootRouteId, + ) + expect(rootMatch?.status).toBe('success') + expect(rootMatch?.globalNotFound).toBe(true) + }) +}) diff --git a/packages/router-core/tests/issue-4476-preload-navigate-abort.test.ts b/packages/router-core/tests/issue-4476-preload-navigate-abort.test.ts new file mode 100644 index 0000000000..8821478db8 --- /dev/null +++ b/packages/router-core/tests/issue-4476-preload-navigate-abort.test.ts @@ -0,0 +1,72 @@ +import { describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, createControlledPromise } from '../src' +import { createTestRouter } from './routerTestUtils' + +// https://github.com/TanStack/router/issues/4476 +// A navigation that adopts an in-flight preload's loader run must reuse that +// run: it must NOT abort the preload's loader signal, and it must NOT re-run +// the loader. Aborting mid-flight is what surfaced as a CancelledError from a +// signal-aware queryFn (e.g. queryClient.fetchQuery) when the user clicked +// through during an intent preload. +// +// This shape is not covered by preload-adoption.test.ts (serial-phase decline +// and sibling-preload adoption); the distinguishing assertion here is that the +// adopted loader's captured signal is never aborted. +describe('issue #4476 - navigation adopting an in-flight preload does not abort the loader', () => { + test('adopted preload loader runs once and its signal is not aborted', async () => { + const loaderGate = createControlledPromise() + let capturedSignal: AbortSignal | undefined + const loader = vi.fn( + ({ abortController }: { abortController: AbortController }) => { + capturedSignal = abortController.signal + return loaderGate + }, + ) + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, fooRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + + // Start the preload and wait until its loader is actually in flight. + // (The private preload lane stays out of cachedMatches until it succeeds, + // so the loader-call gate is how we observe the in-flight loader here.) + const preload = router.preloadRoute({ to: '/foo' } as any) + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(1)) + expect(capturedSignal).toBeDefined() + expect(capturedSignal?.aborted).toBe(false) + + // Navigate while the preload's loader is still pending — the navigation + // must adopt the in-flight run rather than aborting and re-issuing it. + const navigation = router.navigate({ to: '/foo' }) + + // Resolve the shared loader and let both settle. + loaderGate.resolve('adopted') + await Promise.all([navigation, preload]) + + // Loader ran exactly once; the adopted run's signal was never aborted. + expect(loader).toHaveBeenCalledTimes(1) + expect(capturedSignal?.aborted).toBe(false) + + // Navigation committed with the adopted loaderData. + const committed = router.state.matches.find( + (match) => match.routeId === fooRoute.id, + ) + expect(committed?.status).toBe('success') + expect(committed?.loaderData).toBe('adopted') + }) +}) diff --git a/packages/router-core/tests/issue-7633-chunk-load-error.test.ts b/packages/router-core/tests/issue-7633-chunk-load-error.test.ts new file mode 100644 index 0000000000..716b6c0c6e --- /dev/null +++ b/packages/router-core/tests/issue-7633-chunk-load-error.test.ts @@ -0,0 +1,45 @@ +import { describe, expect, it } from 'vitest' +import { isModuleNotFoundError } from '../src/utils' + +// https://github.com/TanStack/router/issues/7633 +// isModuleNotFoundError only matched the Vite/native-ESM dynamic-import message +// prefixes, so webpack/rspack chunk failures (error.name === 'ChunkLoadError') +// were missed and lazyRouteComponent's one-shot reload-after-deploy recovery +// never fired on those bundlers. +describe('issue #7633 - isModuleNotFoundError detects webpack/rspack ChunkLoadError', () => { + it('detects a ChunkLoadError by name', () => { + const error = new Error('Loading chunk 42 failed.') + error.name = 'ChunkLoadError' + expect(isModuleNotFoundError(error)).toBe(true) + }) + + it('detects a ChunkLoadError even when message is not a string', () => { + // Defensive about error shape: some bundlers surface a non-Error object. + expect(isModuleNotFoundError({ name: 'ChunkLoadError' })).toBe(true) + }) + + it('still detects the native ESM / Vite message prefixes', () => { + expect( + isModuleNotFoundError( + new Error('Failed to fetch dynamically imported module: /a.js'), + ), + ).toBe(true) + expect( + isModuleNotFoundError( + new Error('error loading dynamically imported module: /a.js'), + ), + ).toBe(true) + expect( + isModuleNotFoundError(new Error('Importing a module script failed.')), + ).toBe(true) + }) + + it('does not detect a generic error', () => { + expect(isModuleNotFoundError(new Error('Loading chunk 42 failed.'))).toBe( + false, + ) + expect(isModuleNotFoundError(new Error('something else'))).toBe(false) + expect(isModuleNotFoundError(undefined)).toBe(false) + expect(isModuleNotFoundError(null)).toBe(false) + }) +}) From f9182086b205f9548a8b40ff8f6e9e3c13cd1221 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Tue, 7 Jul 2026 14:34:45 +0200 Subject: [PATCH 47/54] refactor: remove solid pendingRouteIds suppression and unreachable outlet guards Co-Authored-By: Claude Fable 5 --- packages/react-router/src/Match.tsx | 11 +-- packages/solid-router/src/routerStores.ts | 14 ---- packages/solid-router/src/useMatch.tsx | 14 +--- packages/solid-router/tests/loaders.test.tsx | 14 +++- packages/solid-router/tests/useMatch.test.tsx | 78 ++++++++++++++++++- 5 files changed, 91 insertions(+), 40 deletions(-) diff --git a/packages/react-router/src/Match.tsx b/packages/react-router/src/Match.tsx index eac6767f11..103aba6903 100644 --- a/packages/react-router/src/Match.tsx +++ b/packages/react-router/src/Match.tsx @@ -487,16 +487,7 @@ export const Outlet = React.memo(function OutletImpl() { ) : null if (parentGlobalNotFound) { - if (!route) { - if (process.env.NODE_ENV !== 'production') { - throw new Error( - 'Invariant failed: Could not resolve route for Outlet render', - ) - } - - invariant() - } - return renderRouteNotFound(router, route, undefined) + return renderRouteNotFound(router, route!, undefined) } if (!childMatchId) { diff --git a/packages/solid-router/src/routerStores.ts b/packages/solid-router/src/routerStores.ts index 11c06a35ef..51be801aec 100644 --- a/packages/solid-router/src/routerStores.ts +++ b/packages/solid-router/src/routerStores.ts @@ -16,8 +16,6 @@ declare module '@tanstack/router-core' { export interface RouterStores { /** Maps each active routeId to the matchId of its child in the match tree. */ childMatchIdByRouteId: RouterReadableStore> - /** Maps each pending routeId to true for quick lookup. */ - pendingRouteIds: RouterReadableStore> } } @@ -38,18 +36,6 @@ function initRouterStores( } return obj }) - - stores.pendingRouteIds = createReadonlyStore(() => { - const ids = stores.pendingIds.get() - const obj: Record = {} - for (const id of ids) { - const store = stores.pendingMatchStores.get(id) - if (store?.routeId) { - obj[store.routeId] = true - } - } - return obj - }) } function createSolidMutableStore( diff --git a/packages/solid-router/src/useMatch.tsx b/packages/solid-router/src/useMatch.tsx index bfc9427be7..cee95bc5d9 100644 --- a/packages/solid-router/src/useMatch.tsx +++ b/packages/solid-router/src/useMatch.tsx @@ -87,11 +87,7 @@ export function useMatch< return } - const hasPendingMatch = opts.from - ? Boolean(router.stores.pendingRouteIds.get()[opts.from!]) - : false - - if (!hasPendingMatch && (opts.shouldThrow ?? true)) { + if (opts.shouldThrow ?? true) { if (process.env.NODE_ENV !== 'production') { throw new Error( `Invariant failed: Could not find ${opts.from ? `an active match from "${opts.from}"` : 'a nearest match!'}`, @@ -106,14 +102,6 @@ export function useMatch< const selectedMatch = match() if (selectedMatch === undefined) { - const hasPendingMatch = opts.from - ? Boolean(router.stores.pendingRouteIds.get()[opts.from!]) - : false - - if (prev !== undefined && hasPendingMatch) { - return prev - } - return undefined } diff --git a/packages/solid-router/tests/loaders.test.tsx b/packages/solid-router/tests/loaders.test.tsx index 4ecee0521e..f389dcd5f7 100644 --- a/packages/solid-router/tests/loaders.test.tsx +++ b/packages/solid-router/tests/loaders.test.tsx @@ -769,7 +769,7 @@ test('clears pendingTimeout when match resolves', async () => { expect(fooPendingComponentOnMountMock).not.toHaveBeenCalled() }) -test('useLoaderData retains previous data while route match is pending', async () => { +test('useLoaderData({ from }) surfaces the missing match when the route leaves the active lane', async () => { const history = createMemoryHistory({ initialEntries: ['/app'] }) const rootRoute = createRootRoute({ component: () => { @@ -806,12 +806,22 @@ test('useLoaderData retains previous data while route match is pending', async ( throw new Error('Expected /app match to be active') } + // Synthetically move /app out of the active lane and into the pending pool. + // A real navigation never produces this state — pending publication keeps the + // incoming lane in the active matches, so a `from` match the store publishes + // stays continuously resolvable. useMatch({ from }) no longer suppresses its + // missing-match invariant while a route is only pending (matching React/Vue), + // so the stale loader data is not retained — the invariant is surfaced. router.stores.setPending([{ ...appMatch, id: `${appMatch.id}__pending` }]) router.stores.setMatches( router.state.matches.filter((match) => match.routeId !== '/app'), ) - expect(screen.getByTestId('combined')).toHaveTextContent('6:0') + expect( + await screen.findByText( + 'Invariant failed: Could not find an active match from "/app"', + ), + ).toBeInTheDocument() }) test('cancelMatches after pending timeout', async () => { diff --git a/packages/solid-router/tests/useMatch.test.tsx b/packages/solid-router/tests/useMatch.test.tsx index f9c592601d..54da06d0a7 100644 --- a/packages/solid-router/tests/useMatch.test.tsx +++ b/packages/solid-router/tests/useMatch.test.tsx @@ -1,5 +1,12 @@ import { afterEach, describe, expect, test, vi } from 'vitest' -import { cleanup, render, screen, waitFor } from '@solidjs/testing-library' +import * as Solid from 'solid-js' +import { + cleanup, + fireEvent, + render, + screen, + waitFor, +} from '@solidjs/testing-library' import { Link, Outlet, @@ -116,4 +123,73 @@ describe('useMatch', () => { }) }) }) + + // Pins the Vue/React-matching semantics: a `useMatch({ from })` mounted while + // the target route is only in the pending pool (loader in flight, before + // pending publication) does not observe an active match — it resolves to + // `undefined` (or throws with the default `shouldThrow`) exactly as at idle, + // then resolves once the navigation commits. There is no throw-suppression / + // stale-value window during the navigation. + describe('when the target route is only in the pending pool', () => { + test('({ from }) returns undefined while pending, then resolves after commit', async () => { + let resolveLoader!: () => void + const loaderGate = new Promise((resolve) => { + resolveLoader = resolve + }) + + const seenRouteIds: Array = [] + + const rootRoute = createRootRoute({ + component: () => { + const match = useMatch({ from: '/posts', shouldThrow: false }) + Solid.createEffect(() => { + seenRouteIds.push(match()?.routeId) + }) + return ( + <> + Posts + + + ) + }, + }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>

IndexTitle

, + }) + const postsRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + loader: () => loaderGate, + component: () =>

PostsTitle

, + }) + + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, postsRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render(() => ) + + // Idle at index: /posts has no active match. + await screen.findByText('IndexTitle') + expect(seenRouteIds).toEqual([undefined]) + + // Navigate; the gated loader keeps /posts in the pending pool (default + // pendingMs is 1000ms, so no pending publication within this window). + fireEvent.click(screen.getByRole('link', { name: 'Posts' })) + await new Promise((resolve) => setTimeout(resolve, 50)) + + // The target is only pending — useMatch({ from }) never sees it as active. + expect(seenRouteIds).not.toContain('/posts') + + // Commit the navigation. + resolveLoader() + await screen.findByText('PostsTitle') + await waitFor(() => { + expect(seenRouteIds.at(-1)).toBe('/posts') + }) + }) + }) }) From 38470e34c6d8f54baeccb44e84ed1507a10b1b85 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Tue, 7 Jul 2026 14:34:45 +0200 Subject: [PATCH 48/54] docs: declare removed public API in the changeset and update RouterType docs Co-Authored-By: Claude Fable 5 --- .changeset/devtools-age-ticker-routes.md | 5 +++++ .changeset/violet-poets-wait.md | 14 ++++++++++++++ docs/router/api/router/RouterType.md | 8 ++------ 3 files changed, 21 insertions(+), 6 deletions(-) create mode 100644 .changeset/devtools-age-ticker-routes.md diff --git a/.changeset/devtools-age-ticker-routes.md b/.changeset/devtools-age-ticker-routes.md new file mode 100644 index 0000000000..ec7513a2bd --- /dev/null +++ b/.changeset/devtools-age-ticker-routes.md @@ -0,0 +1,5 @@ +--- +'@tanstack/router-devtools-core': patch +--- + +Internal compat: replace the removed `router.looseRoutesById` with `routesById` in the match age ticker. diff --git a/.changeset/violet-poets-wait.md b/.changeset/violet-poets-wait.md index 553e8b3f0b..02edd64707 100644 --- a/.changeset/violet-poets-wait.md +++ b/.changeset/violet-poets-wait.md @@ -19,8 +19,22 @@ Fix match loading consistency across client navigation, preloading, background r - A navigation that starts while a hover/intent preload for the same route is in flight adopts the preload's loader run once it succeeds — the loader executes once, like before. Adoption is data-only: the navigation always runs its own `beforeLoad` (with `preload: false` semantics), and a preload that ends in a redirect, notFound, or error is never adopted — the navigation runs its own loader instead, so preload-flavored control flow can no longer leak into navigations (the old implementation could land you on a preload-computed redirect). Concurrent preloads of the same route also share one loader run. - Preloads now cache the successful ancestor prefix even when a descendant throws an error or `notFound`, so repeated hovers do not re-run expensive ancestor loaders. - Route chunk (lazy import) failures now run the normal route failure lifecycle: `onError` fires and thrown redirects/notFounds are honored. Error/notFound boundary chunks load independently of the route's other component chunks, and failed chunk preloads are retried on the next load instead of being cached forever. +- `isModuleNotFoundError` now recognizes webpack/rspack `ChunkLoadError`s, so `lazyRouteComponent`'s automatic one-shot reload after a deploy also works on those bundlers, not just Vite/native ESM. +- Fuzzy (unmatched-URL) 404s now attribute the notFound to the deepest matched route with children that defines a `notFoundComponent`, so pathless layout `notFoundComponent`s render instead of `defaultNotFoundComponent` — consistent with how thrown `notFound()`s select their boundary. When no matched route defines one, the previous attribution is unchanged, and `notFoundMode: 'root'` still targets the root. - Server rendering keeps route `headers()` when a decorative `head()`/`scripts()` hook fails (async `headers()` are always awaited), background reloads never publish fresh `loaderData` whose asset projection failed, and hydration no longer executes `head()`/`scripts()` for matches the server omitted (`ssr: false` or a server-side error/notFound boundary). The follow-up client load after hydration replays a server-committed notFound/error boundary, so routes the server omitted are not loaded or asset-projected client-side. - With `pendingMs: 0`, the pending fallback is published synchronously on bare initial loads (nothing rendered yet) instead of after a macrotask, eliminating the blank first frame. - Starting a navigation no longer aborts the `abortController` of settled success matches that stay mounted — deferred/streamed data tied to a stay-match's loader signal survives child navigations and `invalidate()`. Matches with in-flight `beforeLoad`/loader work are still cancelled. - Fresh data for routes you navigate away from survives pending publication: if a navigation is superseded (e.g. back button) after its pending UI was published, the exited matches are served from cache instead of re-running their loaders. +- Vue: `onResolved` and `onRendered` router events now carry real location-change info (`fromLocation` was previously always equal to `toLocation`, so `pathChanged`/`hrefChanged` were always `false` and cross-location scroll restoration never ran). - Behavior change (Vue): `useMatch({ from })` no longer suppresses its missing-match invariant during a navigation whose destination includes `from` before that navigation's first commit — it throws (or returns `undefined` when `shouldThrow: false`) exactly as it does at idle, matching React. +- Behavior change (Solid): `useMatch({ from })` no longer suppresses its missing-match invariant during a navigation whose destination includes `from` before that navigation's first commit — it throws (or returns `undefined` when `shouldThrow: false`) exactly as it does at idle, matching React. + +**Removed / changed public API** + +- `RouterState` no longer includes `loadedAt`, `isTransitioning`, `statusCode`, or `redirect`. `statusCode` and `redirect` are now server-only instance properties (`router.statusCode`, `router.redirect`) and are `undefined` on the client. +- Removed `RouterCore` members: `cancelMatch(id)`, `beforeLoad()`, `hasNotFoundMatch()`, `clearExpiredCache()` (expired cache entries are now dropped during commit-time reconciliation), `looseRoutesById` (use `routesById`), `getParsedLocationHref()`, and `viewTransitionPromise`. +- `getInitialRouterState` is no longer exported from `@tanstack/router-core`. +- `RouteMatch.fetchCount` has been removed. +- Client-side, a caught redirect's `headers` no longer include a `Location` header; response headers are server behavior, and `router.resolveRedirect` only sets `Location` on the server. +- `router.subscribe('onBeforeNavigate')` now also fires for redirect-replacement navigations (previously suppressed while a redirect was being applied). +- `router.startViewTransition(fn)` now returns `Promise` (previously `void`). diff --git a/docs/router/api/router/RouterType.md b/docs/router/api/router/RouterType.md index 757a6098ca..fbee8ab343 100644 --- a/docs/router/api/router/RouterType.md +++ b/docs/router/api/router/RouterType.md @@ -35,15 +35,11 @@ An instance of the `Router` has the following properties and methods: - Matches a pathname and search params against the router's route tree and returns an array of route matches. - If `opts.throwOnError` is `true`, any errors that occur during the matching process will be thrown (in addition to being returned in the route match's `error` property). -### `.cancelMatch` method - -- Type: `(matchId: string) => void` -- Cancels a route match that is currently pending by calling `match.abortController.abort()`. - ### `.cancelMatches` method - Type: `() => void` -- Cancels all route matches that are currently pending by calling `match.abortController.abort()` on each one. +- Aborts and settles route matches that still have in-flight route work — matches in the `pending` status or currently fetching `beforeLoad`/loader — by calling `match.abortController.abort()` on each one. +- Settled `success` matches are no longer aborted, because their abort signals may be held by streamed/deferred data. ### `.buildLocation` method From 3cc89701f218381fb8138169ef743c78fe9e5d8b Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Tue, 7 Jul 2026 12:36:52 +0000 Subject: [PATCH 49/54] ci: apply automated fixes --- packages/vue-router/src/Transitioner.tsx | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/packages/vue-router/src/Transitioner.tsx b/packages/vue-router/src/Transitioner.tsx index 09a2a0c4cd..e042c3b0c1 100644 --- a/packages/vue-router/src/Transitioner.tsx +++ b/packages/vue-router/src/Transitioner.tsx @@ -41,9 +41,7 @@ export function useTransitionerSetup() { // advances resolvedLocation to the new location. Reused for the (possibly // nextTick-deferred) onResolved emission so it reports the navigation that // actually resolved instead of a from===to no-op. Reset once consumed. - let resolvedChangeInfo: - | ReturnType - | undefined + let resolvedChangeInfo: ReturnType | undefined // Single emitter for the load lifecycle. Level changes arrive through // synchronous store subscriptions — which, unlike watcher-observed edges, From f4b56fe3aea7fee0449619757ee161e36d40f1ab Mon Sep 17 00:00:00 2001 From: Sheraff Date: Tue, 7 Jul 2026 15:12:34 +0200 Subject: [PATCH 50/54] perf: recover gzip bytes in lane-model client code and match components Co-Authored-By: Claude Fable 5 --- packages/react-router/src/Match.tsx | 18 ++++---------- packages/react-router/src/Transitioner.tsx | 9 ++++--- .../router-core/src/load-matches.client.ts | 21 ++++++++-------- .../router-core/src/router-load.client.ts | 10 ++++---- .../router-core/src/router-preload.client.ts | 24 +++++++++---------- packages/solid-router/src/Match.tsx | 20 ++++------------ packages/vue-router/src/Match.tsx | 9 ++----- 7 files changed, 41 insertions(+), 70 deletions(-) diff --git a/packages/react-router/src/Match.tsx b/packages/react-router/src/Match.tsx index 103aba6903..1d03204641 100644 --- a/packages/react-router/src/Match.tsx +++ b/packages/react-router/src/Match.tsx @@ -325,13 +325,8 @@ export const MatchInner = React.memo(function MatchInnerImpl({ } if (match.status === 'notFound') { - if (!isNotFound(match.error)) { - if (process.env.NODE_ENV !== 'production') { - throw new Error('Invariant failed: Expected a notFound error') - } - - invariant() - } + // status 'notFound' is only ever committed paired with a NotFoundError + // (getNotFoundBoundaryPatch), so match.error needs no re-check here. return renderRouteNotFound(router, route, match.error) } @@ -414,13 +409,8 @@ export const MatchInner = React.memo(function MatchInnerImpl({ } if (match.status === 'notFound') { - if (!isNotFound(match.error)) { - if (process.env.NODE_ENV !== 'production') { - throw new Error('Invariant failed: Expected a notFound error') - } - - invariant() - } + // status 'notFound' is only ever committed paired with a NotFoundError + // (getNotFoundBoundaryPatch), so match.error needs no re-check here. return renderRouteNotFound(router, route, match.error) } diff --git a/packages/react-router/src/Transitioner.tsx b/packages/react-router/src/Transitioner.tsx index 3aee4a1f8d..539d4c2198 100644 --- a/packages/react-router/src/Transitioner.tsx +++ b/packages/react-router/src/Transitioner.tsx @@ -86,11 +86,10 @@ export function Transitioner() { // settled before mount (the mount load below still toggles isLoading) — // produces an observable edge. useLayoutEffect(() => { - previous.current.isLoading = router.stores.isLoading.get() - previous.current.isPagePending = - previous.current.isLoading || router.stores.hasPending.get() - previous.current.isAnyPending = - previous.current.isPagePending || transitioning.current + const isLoading = router.stores.isLoading.get() + const isPagePending = isLoading || router.stores.hasPending.get() + const isAnyPending = isPagePending || transitioning.current + previous.current = { isLoading, isPagePending, isAnyPending } const subscriptions = [ router.stores.isLoading.subscribe(emitEdges), diff --git a/packages/router-core/src/load-matches.client.ts b/packages/router-core/src/load-matches.client.ts index bd718aaf2f..770eb81e24 100644 --- a/packages/router-core/src/load-matches.client.ts +++ b/packages/router-core/src/load-matches.client.ts @@ -293,14 +293,14 @@ const finalizeRouteFailure = async ( markError(inner, errorIndex) commitMatch(inner, errorIndex, { - error, - status: 'error' as const, - isFetching: false as const, context: getMatchContext( inner, errorIndex, inner.matches[errorIndex]!.__beforeLoadContext, ), + error, + status: 'error' as const, + isFetching: false as const, updatedAt: Date.now(), }) finishMatchLoad(inner, errorIndex) @@ -1021,25 +1021,26 @@ export async function loadClientMatches( let firstNotFound: NotFoundError | undefined for (let i = 0; i < inner.matches.length && !inner.serialFailure; i++) { + // Reads below happen synchronously at iteration start, before any await + // could let a newer pass replace the lane entry. + const match = inner.matches[i]! try { - if (inner.preload?.includes(inner.matches[i]!.id)) { + if (inner.preload?.includes(match.id)) { await (matchPromises[i] = joinPreloadedActiveMatch(inner, i)) continue } - if (inner.matches[i]!._.dehydrated) { - const dehydratedMatch = inner.matches[i]! + if (match._.dehydrated) { // A dehydrated notFound/error is a server-committed boundary: the // server intentionally omitted every match below it. Replay it as // this pass's serial failure so the follow-up client load caps the // lane the same way instead of loading, committing, and projecting // assets for descendants the server never rendered. if ( - (dehydratedMatch.status === 'notFound' && - isNotFound(dehydratedMatch.error)) || - dehydratedMatch.status === 'error' + (match.status === 'notFound' && isNotFound(match.error)) || + match.status === 'error' ) { - inner.serialFailure = [i, dehydratedMatch.error] + inner.serialFailure = [i, match.error] break } matchPromises[i] = loadClientRouteMatch(inner, matchPromises, i) diff --git a/packages/router-core/src/router-load.client.ts b/packages/router-core/src/router-load.client.ts index 61d95e3012..47a9409abf 100644 --- a/packages/router-core/src/router-load.client.ts +++ b/packages/router-core/src/router-load.client.ts @@ -222,12 +222,10 @@ export const loadClientRouter = async ( // return value is that same array. await loadClientMatches(loadContext) } catch (err) { - if (err === loadContext) { - // This foreground lane was superseded before reaching a route outcome. - // Let the outer load cleanup settle it as cancellation, not route error. - throw err - } - if (isRedirect(err)) { + if (err === loadContext || isRedirect(err)) { + // A superseded foreground lane (the loadContext sentinel) settles as + // cancellation, not route error; redirects hand over to navigation. + // Both are handled by the outer catch below. throw err } if (!isNotFound(err)) { diff --git a/packages/router-core/src/router-preload.client.ts b/packages/router-core/src/router-preload.client.ts index 722649e37b..ea8e8bce4a 100644 --- a/packages/router-core/src/router-preload.client.ts +++ b/packages/router-core/src/router-preload.client.ts @@ -54,19 +54,19 @@ export const preloadClientRoute = async ( let ownedMatches: Array | undefined for (const match of prefix) { - if (!match.preload || router.getMatch(match.id, false)) { - continue + // A cache entry this pass borrowed without reloading (same `updatedAt` + // as the cached snapshot) is not owned work: re-caching it would + // restamp `preload: true` — silently demoting a navigation entry from + // gcTime to preloadGcTime — while keeping its old `updatedAt`. Only + // snapshots whose loader ran under this pass (fresh `updatedAt`) may + // replace an existing cache entry. + if ( + match.preload && + !router.getMatch(match.id, false) && + router.getMatch(match.id)?.updatedAt !== match.updatedAt + ) { + ;(ownedMatches ||= []).push(match) } - // A cache entry this pass borrowed without reloading is not owned - // work: re-caching it would restamp `preload: true` — silently - // demoting a navigation entry from gcTime to preloadGcTime — while - // keeping its old `updatedAt`. Only snapshots whose loader ran under - // this pass (fresh `updatedAt`) may replace an existing cache entry. - const cachedMatch = router.getMatch(match.id) - if (cachedMatch && cachedMatch.updatedAt === match.updatedAt) { - continue - } - ;(ownedMatches ||= []).push(match) } if (ownedMatches) { router.stores.setCached([ diff --git a/packages/solid-router/src/Match.tsx b/packages/solid-router/src/Match.tsx index d109104394..62f18821ee 100644 --- a/packages/solid-router/src/Match.tsx +++ b/packages/solid-router/src/Match.tsx @@ -1,10 +1,5 @@ import * as Solid from 'solid-js' -import { - getLocationChangeInfo, - invariant, - isNotFound, - rootRouteId, -} from '@tanstack/router-core' +import { getLocationChangeInfo, rootRouteId } from '@tanstack/router-core' import { isServer } from '@tanstack/router-core/isServer' import { Dynamic } from 'solid-js/web' import { CatchBoundary, ErrorComponent } from './CatchBoundary' @@ -335,16 +330,9 @@ export const MatchInner = (): any => {
{(_) => { - if (!isNotFound(currentMatch().error)) { - if (process.env.NODE_ENV !== 'production') { - throw new Error( - 'Invariant failed: Expected a notFound error', - ) - } - - invariant() - } - + // status 'notFound' is only ever committed paired with a + // NotFoundError (getNotFoundBoundaryPatch), so the error + // needs no re-check here. // Use Show with keyed to ensure re-render when routeId changes return ( diff --git a/packages/vue-router/src/Match.tsx b/packages/vue-router/src/Match.tsx index bc0bc44749..66d8d3b78d 100644 --- a/packages/vue-router/src/Match.tsx +++ b/packages/vue-router/src/Match.tsx @@ -362,13 +362,8 @@ export const MatchInner = Vue.defineComponent({ } if (match.value!.status === 'notFound') { - if (!isNotFound(match.value!.error)) { - if (process.env.NODE_ENV !== 'production') { - throw new Error('Invariant failed: Expected a notFound error') - } - - invariant() - } + // status 'notFound' is only ever committed paired with a NotFoundError + // (getNotFoundBoundaryPatch), so match.error needs no re-check here. return renderRouteNotFound(router, route.value!, match.value!.error) } From 1f917616abb1aecff4f88e22045d272502ef9ac2 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Tue, 7 Jul 2026 19:46:20 +0200 Subject: [PATCH 51/54] perf: gzip shape alignment, dead solid scroll-restoration husk, single-use helper inlines Co-Authored-By: Claude Fable 5 --- .../router-core/src/load-matches.client.ts | 18 +++++++++--------- .../router-core/src/load-matches.server.ts | 4 ++-- packages/router-core/src/load-matches.ts | 4 ---- packages/router-core/src/location-change.ts | 14 ++++++++------ packages/router-core/src/route-chunks.ts | 15 ++++++--------- packages/router-core/src/router.ts | 16 ++++++++-------- packages/solid-router/src/Match.tsx | 14 +++++++++++--- packages/vue-router/src/Match.tsx | 7 +++++-- 8 files changed, 49 insertions(+), 43 deletions(-) diff --git a/packages/router-core/src/load-matches.client.ts b/packages/router-core/src/load-matches.client.ts index 770eb81e24..95ff6db8bf 100644 --- a/packages/router-core/src/load-matches.client.ts +++ b/packages/router-core/src/load-matches.client.ts @@ -9,7 +9,6 @@ import { getMatchContext, getNotFoundBoundaryIndex, getNotFoundBoundaryPatch, - markError, normalizeRouteFailure, serialFailurePrefixCap, settleMatchLoad, @@ -290,18 +289,19 @@ const finalizeRouteFailure = async ( } inner.requiresCommit = true - markError(inner, errorIndex) + // single-call-site inline of the shared badIndex rule (byte-size) + inner.badIndex = Math.min(inner.badIndex ?? errorIndex, errorIndex) commitMatch(inner, errorIndex, { + status: 'error' as const, + error, + isFetching: false as const, + updatedAt: Date.now(), context: getMatchContext( inner, errorIndex, inner.matches[errorIndex]!.__beforeLoadContext, ), - error, - status: 'error' as const, - isFetching: false as const, - updatedAt: Date.now(), }) finishMatchLoad(inner, errorIndex) } @@ -745,8 +745,8 @@ const loadClientRouteMatch = async ( } commitMatch(inner, index, { - error: undefined, status: 'success', + error: undefined, isFetching: false, updatedAt: Date.now(), }) @@ -952,8 +952,8 @@ export function startBackgroundLoad( matches[index] = { ...matches[index]!, - error, status: 'error', + error, isFetching: false, updatedAt: Date.now(), } @@ -978,8 +978,8 @@ export function startBackgroundLoad( } matches[index] = { ...matches[index]!, - error: componentError, status: 'error', + error: componentError, isFetching: false, updatedAt: Date.now(), } diff --git a/packages/router-core/src/load-matches.server.ts b/packages/router-core/src/load-matches.server.ts index 179cb6effa..fc37be640f 100644 --- a/packages/router-core/src/load-matches.server.ts +++ b/packages/router-core/src/load-matches.server.ts @@ -10,7 +10,6 @@ import { getMatchContext, getNotFoundBoundaryIndex, getNotFoundBoundaryPatch, - markError, normalizeRouteFailure, serialFailurePrefixCap, } from './load-matches' @@ -94,7 +93,8 @@ const finalizeServerRouteFailure = async ( handleServerRedirectOrNotFound(inner, index, error) } - markError(inner, errorIndex) + // single-call-site inline of the shared badIndex rule (byte-size) + inner.badIndex = Math.min(inner.badIndex ?? errorIndex, errorIndex) commitMatch(inner, errorIndex, { error, status: 'error' as const, diff --git a/packages/router-core/src/load-matches.ts b/packages/router-core/src/load-matches.ts index 401bc6a9dc..4055a57bae 100644 --- a/packages/router-core/src/load-matches.ts +++ b/packages/router-core/src/load-matches.ts @@ -58,10 +58,6 @@ export type BackgroundLoad = { controller: AbortController } -export const markError = (inner: InnerLoadContext, index: number) => { - inner.badIndex = Math.min(inner.badIndex ?? index, index) -} - export const commitMatch = ( inner: InnerLoadContext, index: number, diff --git a/packages/router-core/src/location-change.ts b/packages/router-core/src/location-change.ts index 57c272113e..37eb838bee 100644 --- a/packages/router-core/src/location-change.ts +++ b/packages/router-core/src/location-change.ts @@ -5,12 +5,14 @@ export function getLocationChangeInfo( location: ParsedLocation, resolvedLocation?: ParsedLocation, ) { - const fromLocation = resolvedLocation - const toLocation = location - const pathChanged = fromLocation?.pathname !== toLocation.pathname - const hrefChanged = fromLocation?.href !== toLocation.href - const hashChanged = fromLocation?.hash !== toLocation.hash - return { fromLocation, toLocation, pathChanged, hrefChanged, hashChanged } + // built directly from the parameters: local aliases survive minification + return { + fromLocation: resolvedLocation, + toLocation: location, + pathChanged: resolvedLocation?.pathname !== location.pathname, + hrefChanged: resolvedLocation?.href !== location.href, + hashChanged: resolvedLocation?.hash !== location.hash, + } } export const locationHistoryActions = new WeakMap< diff --git a/packages/router-core/src/route-chunks.ts b/packages/router-core/src/route-chunks.ts index 5f6e91ea07..c996356c9e 100644 --- a/packages/router-core/src/route-chunks.ts +++ b/packages/router-core/src/route-chunks.ts @@ -6,14 +6,6 @@ type RouteComponentType = | 'pendingComponent' | 'notFoundComponent' -function preloadComponent(component: any): Promise | undefined { - try { - return component?.preload?.() - } catch (error) { - return Promise.reject(error) - } -} - /** * Preloads one component type with per-type in-flight tracking. * @@ -39,7 +31,12 @@ function preloadRouteComponent( } } - const preload = preloadComponent(route.options[componentType]) + let preload: Promise | undefined + try { + preload = (route.options[componentType] as any)?.preload?.() + } catch (error) { + preload = Promise.reject(error) + } if (!preload) { delete cache[componentType] return undefined diff --git a/packages/router-core/src/router.ts b/packages/router-core/src/router.ts index 62b5cdbac4..0beb57e282 100644 --- a/packages/router-core/src/router.ts +++ b/packages/router-core/src/router.ts @@ -1602,9 +1602,13 @@ export class RouterCore< const loadPromise = existingMatch._.loadPromise match = { ...existingMatch, - cause, params: routeParams, _strictParams: strictParams, + search, + _strictSearch: strictMatchSearch, + searchError, + preload, + cause, abortController, // Preserve readiness ownership AND the hydration marker: a // dehydrated match can legitimately hold a pending loadPromise @@ -1614,10 +1618,6 @@ export class RouterCore< loadPromise, dehydrated: existingMatch._.dehydrated, }, - search, - _strictSearch: strictMatchSearch, - searchError, - preload, } } else { const pending = @@ -1634,11 +1634,12 @@ export class RouterCore< routeId: route.id, params: routeParams, _strictParams: strictParams, - pathname: interpolatedPath, - updatedAt: Date.now(), search, _strictSearch: strictMatchSearch, searchError, + preload, + pathname: interpolatedPath, + updatedAt: Date.now(), status: pending ? 'pending' : 'success', isFetching: false, paramsError, @@ -1651,7 +1652,6 @@ export class RouterCore< cause, loaderDeps, invalid: false, - preload, staticData: routeOptions.staticData || {}, fullPath: route.fullPath, } as AnyRouteMatch diff --git a/packages/solid-router/src/Match.tsx b/packages/solid-router/src/Match.tsx index 62f18821ee..0366d4b71d 100644 --- a/packages/solid-router/src/Match.tsx +++ b/packages/solid-router/src/Match.tsx @@ -12,6 +12,14 @@ import { ScrollRestoration } from './scroll-restoration' import { ClientOnly } from './ClientOnly' import type { AnyRoute, RootRouteOptions } from '@tanstack/router-core' +// The scroll restoration script is only ever emitted during SSR. Selecting +// the component through an `isServer === false` constant (same DCE pattern as +// router-core's loadRouter) lets client bundles drop ScrollRestoration and +// its ScriptOnce template entirely; Solid's compiler otherwise hides the +// condition inside a memo where the minifier cannot see it. +const ScrollRestorationScript = + isServer === false ? () => null : ScrollRestoration + export const Match = (props: { matchId: string }) => { const router = useRouter() @@ -173,9 +181,9 @@ export const Match = (props: { matchId: string }) => { {currentMatchState().parentRouteId === rootRouteId ? ( <> - {router.options.scrollRestoration && - (isServer ?? router.isServer) ? ( - + {(isServer ?? router.isServer) && + router.options.scrollRestoration ? ( + ) : null} ) : null} diff --git a/packages/vue-router/src/Match.tsx b/packages/vue-router/src/Match.tsx index 66d8d3b78d..796f4f9a8f 100644 --- a/packages/vue-router/src/Match.tsx +++ b/packages/vue-router/src/Match.tsx @@ -199,8 +199,11 @@ export const Match = Vue.defineComponent({ isChildOfRoot ? Vue.h(Vue.Fragment, null, [ Vue.h(OnRendered), - router.options.scrollRestoration && - (isServer ?? router.isServer) + // isServer first: the minifier folds the whole expression + // to `null` in client bundles (with the options read leading, + // a dead `(options.scrollRestoration, null)` read survives). + (isServer ?? router.isServer) && + router.options.scrollRestoration ? Vue.h(ScrollRestoration) : null, ]) From 4da6ecef2d5a3e0b719d5751be61564b74521199 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Fri, 10 Jul 2026 14:42:18 +0200 Subject: [PATCH 52/54] bundle size improvements --- packages/react-router/src/Transitioner.tsx | 13 +++--- .../router-core/src/load-matches.client.ts | 43 +++++++------------ packages/router-core/src/route-chunks.ts | 35 ++++++--------- .../router-core/src/router-load.client.ts | 9 ++-- .../router-core/src/router-preload.client.ts | 10 ++--- packages/router-core/src/router.ts | 10 ++--- 6 files changed, 47 insertions(+), 73 deletions(-) diff --git a/packages/react-router/src/Transitioner.tsx b/packages/react-router/src/Transitioner.tsx index 539d4c2198..33aecc625e 100644 --- a/packages/react-router/src/Transitioner.tsx +++ b/packages/react-router/src/Transitioner.tsx @@ -91,14 +91,13 @@ export function Transitioner() { const isAnyPending = isPagePending || transitioning.current previous.current = { isLoading, isPagePending, isAnyPending } - const subscriptions = [ - router.stores.isLoading.subscribe(emitEdges), - router.stores.hasPending.subscribe(emitEdges), - ] + const isLoadingSubscription = + router.stores.isLoading.subscribe(emitEdges) + const hasPendingSubscription = + router.stores.hasPending.subscribe(emitEdges) return () => { - for (const subscription of subscriptions) { - subscription.unsubscribe() - } + isLoadingSubscription.unsubscribe() + hasPendingSubscription.unsubscribe() } }, [router, emitEdges]) diff --git a/packages/router-core/src/load-matches.client.ts b/packages/router-core/src/load-matches.client.ts index 95ff6db8bf..ba13de6ccd 100644 --- a/packages/router-core/src/load-matches.client.ts +++ b/packages/router-core/src/load-matches.client.ts @@ -160,7 +160,7 @@ const adoptInFlightPreload = async ( inner: InnerLoadContext, index: number, passController: AbortController, -): Promise<{ loaderData: unknown } | undefined> => { +): Promise => { const match = inner.matches[index]! for (const lane of inner.router._preloadLanes!) { @@ -194,7 +194,8 @@ const adoptInFlightPreload = async ( if (donor?.status !== 'success') { return undefined } - return { loaderData: donor.loaderData } + commitMatch(inner, index, { loaderData: donor.loaderData }) + return true } // A preload that completes in the microtask window between matchRoutes @@ -652,11 +653,7 @@ const loadClientRouteMatch = async ( ? await adoptInFlightPreload(inner, index, passController) : undefined - if (adopted) { - commitMatch(inner, index, { - loaderData: adopted.loaderData, - }) - } else { + if (!adopted) { // Kick off the loader! const loaderResult = loader?.( getLoaderContext(inner, matchPromises, index, route), @@ -1048,13 +1045,9 @@ export async function loadClientMatches( } const beforeLoadResult = handleClientBeforeLoad(inner, i) - if (isPromise(beforeLoadResult)) { - inner.serialFailure = (await beforeLoadResult) as - | SerialFailure - | undefined - } else { - inner.serialFailure = beforeLoadResult as SerialFailure | undefined - } + inner.serialFailure = ( + isPromise(beforeLoadResult) ? await beforeLoadResult : beforeLoadResult + ) as SerialFailure | undefined } catch (err) { if (err === inner) { // This pass lost ownership before serial loading reached a route outcome. @@ -1069,13 +1062,9 @@ export async function loadClientMatches( } } - let maxIndexExclusive = inner.matches.length - if (inner.serialFailure) { - maxIndexExclusive = Math.min( - maxIndexExclusive, - serialFailurePrefixCap(inner, inner.serialFailure), - ) - } + const maxIndexExclusive = inner.serialFailure + ? serialFailurePrefixCap(inner, inner.serialFailure) + : inner.matches.length for (let i = 0; i < maxIndexExclusive; i++) { matchPromises[i] ||= loadClientRouteMatch(inner, matchPromises, i) @@ -1125,7 +1114,7 @@ export async function loadClientMatches( throw fatalError } - const errorIndex = inner.badIndex + let trimIndex = inner.badIndex if (firstNotFound) { // Determine once which matched route will actually render the @@ -1141,11 +1130,11 @@ export async function loadClientMatches( const patch = getNotFoundBoundaryPatch(inner, index, firstNotFound) commitMatch(inner, index, patch) finishMatchLoad(inner, index) - while (inner.matches.length > index + 1) { - settleMatchLoad(inner.matches.pop()!) - } - } else if (errorIndex !== undefined) { - while (inner.matches.length > errorIndex + 1) { + trimIndex = index + } + + if (trimIndex !== undefined) { + while (inner.matches.length > trimIndex + 1) { settleMatchLoad(inner.matches.pop()!) } } diff --git a/packages/router-core/src/route-chunks.ts b/packages/router-core/src/route-chunks.ts index c996356c9e..ea390cefd9 100644 --- a/packages/router-core/src/route-chunks.ts +++ b/packages/router-core/src/route-chunks.ts @@ -55,20 +55,6 @@ function preloadRouteComponent( return preload } -function preloadRouteComponents( - route: AnyRoute, -): Promise> | undefined { - let preloads: Array> | undefined - for (const componentType of componentTypes) { - const preload = preloadRouteComponent(route, componentType, false) - if (preload) { - ;(preloads ||= []).push(preload) - } - } - - return preloads && Promise.all(preloads) -} - export function loadRouteChunk( route: AnyRoute, componentType?: RouteComponentType, @@ -91,13 +77,11 @@ export function loadRouteChunk( // next load generation retries the import, like component chunk // preloads. Awaiters of the evicted promise still own the rejection. const lazyPromise = route._lazyPromise - if (lazyPromise) { - void lazyPromise.then(null, () => { - if (route._lazyPromise === lazyPromise) { - route._lazyPromise = undefined - } - }) - } + void lazyPromise.catch(() => { + if (route._lazyPromise === lazyPromise) { + route._lazyPromise = undefined + } + }) } else { route._lazyLoaded = true } @@ -115,7 +99,14 @@ export function loadRouteChunk( return preloadRouteComponent(route, componentType, true) } if (!route._componentsPromise) { - const componentsPromise = preloadRouteComponents(route) + let preloads: Array> | undefined + for (const type of componentTypes) { + const preload = preloadRouteComponent(route, type, false) + if (preload) { + ;(preloads ||= []).push(preload) + } + } + const componentsPromise = preloads && Promise.all(preloads) if (componentsPromise) { route._componentsPromise = componentsPromise.then( diff --git a/packages/router-core/src/router-load.client.ts b/packages/router-core/src/router-load.client.ts index 47a9409abf..314161d2a5 100644 --- a/packages/router-core/src/router-load.client.ts +++ b/packages/router-core/src/router-load.client.ts @@ -245,7 +245,7 @@ export const loadClientRouter = async ( const backgroundIndices = background?.filter((index) => { const match = pendingMatches[index] - return match && match.status === 'success' && !match.globalNotFound + return match?.status === 'success' && !match.globalNotFound }) const backgroundLength = backgroundIndices?.length // Pending-UI publication implies requiresCommit: publish() only fires for @@ -341,8 +341,9 @@ export const loadClientRouter = async ( if (startedBackgroundLoad) { // Background stale reloads run after the foreground lane is done. If that - // background work is sync, its commit is queued in the next microtask; yield - // once so the caller does not observe the temporary fetching marker. - await Promise.resolve() + // background work is sync, the async loader and its Promise.all reduction + // queue two continuations; yield for both so the caller does not observe + // the temporary fetching marker. + await Promise.resolve().then() } } diff --git a/packages/router-core/src/router-preload.client.ts b/packages/router-core/src/router-preload.client.ts index ea8e8bce4a..c2cf8687aa 100644 --- a/packages/router-core/src/router-preload.client.ts +++ b/packages/router-core/src/router-preload.client.ts @@ -35,10 +35,7 @@ export const preloadClientRoute = async ( // cache; the failed/pending tail never does. const cacheSuccessfulPrefix = async (): Promise => { let prefixEnd = 0 - while ( - prefixEnd < matches.length && - matches[prefixEnd]!.status === 'success' - ) { + while (matches[prefixEnd]?.status === 'success') { prefixEnd++ } if (!prefixEnd) { @@ -83,7 +80,8 @@ export const preloadClientRoute = async ( // Register the lane so concurrent navigations (and sibling preloads) can // adopt this pass's in-flight loader results instead of re-running them. - ;(router._preloadLanes ??= new Set()).add(loadContext) + const preloadLanes = (router._preloadLanes ??= new Set()) + preloadLanes.add(loadContext) try { // loadClientMatches mutates the lane in place and returns it. @@ -119,7 +117,7 @@ export const preloadClientRoute = async ( } return } finally { - router._preloadLanes.delete(loadContext) + preloadLanes.delete(loadContext) for (const match of matches) { if (match.preload) { settleMatchLoad(match) diff --git a/packages/router-core/src/router.ts b/packages/router-core/src/router.ts index 0beb57e282..62d4e4ae28 100644 --- a/packages/router-core/src/router.ts +++ b/packages/router-core/src/router.ts @@ -866,7 +866,7 @@ const preloadRouterRoute = ? async () => undefined : isServer === false ? preloadClientRoute - : (router: AnyRouter, opts: any) => + : async (router: AnyRouter, opts: any) => router.isServer ? undefined : preloadClientRoute(router, opts) export interface ViewTransitionOptions { @@ -2392,9 +2392,7 @@ export class RouterCore< declare _preloadLanes: Set<{ matches: Array }> | undefined declare _backgroundLoad: BackgroundLoad | undefined - load: LoadFn = async (opts) => { - await loadRouter(this, opts) - } + load: LoadFn = (opts) => loadRouter(this, opts) startViewTransition = (fn: () => Promise): Promise => { const shouldViewTransition = @@ -2579,9 +2577,7 @@ export class RouterCore< TTrailingSlashOption, TDefaultStructuralSharingOption, TRouterHistory - > = async (opts) => { - return preloadRouterRoute(this, opts) - } + > = (opts) => preloadRouterRoute(this, opts) matchRoute: MatchRouteFn< TRouteTree, From 89c4321c1e4287c925c570ae851aa525d1f00c90 Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Fri, 10 Jul 2026 12:44:29 +0000 Subject: [PATCH 53/54] ci: apply automated fixes --- packages/react-router/src/Transitioner.tsx | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/packages/react-router/src/Transitioner.tsx b/packages/react-router/src/Transitioner.tsx index 33aecc625e..165a486c37 100644 --- a/packages/react-router/src/Transitioner.tsx +++ b/packages/react-router/src/Transitioner.tsx @@ -91,10 +91,8 @@ export function Transitioner() { const isAnyPending = isPagePending || transitioning.current previous.current = { isLoading, isPagePending, isAnyPending } - const isLoadingSubscription = - router.stores.isLoading.subscribe(emitEdges) - const hasPendingSubscription = - router.stores.hasPending.subscribe(emitEdges) + const isLoadingSubscription = router.stores.isLoading.subscribe(emitEdges) + const hasPendingSubscription = router.stores.hasPending.subscribe(emitEdges) return () => { isLoadingSubscription.unsubscribe() hasPendingSubscription.unsubscribe() From 9e5200d08e7bdcc7d5c84ea8ce494bd5f3e74f69 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Sat, 11 Jul 2026 11:26:10 +0200 Subject: [PATCH 54/54] test: rewrite PR 7744 internals assertions --- .../routes/hydration-capped-assets/child.tsx | 4 +- .../tests/hydration-capped-assets.spec.ts | 8 +- .../tests/fatal-load-rejection.test.ts | 30 +++++-- .../issue-2182-root-loader-pending.test.ts | 7 +- ...issue-2905-root-beforeload-pending.test.ts | 7 +- ...ue-5106-hydrated-notfound-boundary.test.ts | 62 ++++++++++---- ...ue-6645-load-route-chunk-rejection.test.ts | 12 ++- .../pending-match-settled-promise.test.tsx | 81 ++++++++++++++----- 8 files changed, 154 insertions(+), 57 deletions(-) diff --git a/e2e/react-start/basic/src/routes/hydration-capped-assets/child.tsx b/e2e/react-start/basic/src/routes/hydration-capped-assets/child.tsx index 7506747d00..896dc2058d 100644 --- a/e2e/react-start/basic/src/routes/hydration-capped-assets/child.tsx +++ b/e2e/react-start/basic/src/routes/hydration-capped-assets/child.tsx @@ -14,9 +14,7 @@ export const Route = createFileRoute('/hydration-capped-assets/child')({ }), scripts: ({ loaderData }) => [ { - children: `window.__CAPPED_ASSETS_CHILD_SCRIPT = ${JSON.stringify( - loaderData?.title ?? 'missing-loader-data', - )}`, + children: `document.documentElement.setAttribute('data-capped-assets-child-script', ${JSON.stringify(loaderData?.title ?? 'missing-loader-data')})`, }, ], component: () => ( diff --git a/e2e/react-start/basic/tests/hydration-capped-assets.spec.ts b/e2e/react-start/basic/tests/hydration-capped-assets.spec.ts index 25866a57d7..cb7fb15b07 100644 --- a/e2e/react-start/basic/tests/hydration-capped-assets.spec.ts +++ b/e2e/react-start/basic/tests/hydration-capped-assets.spec.ts @@ -42,10 +42,8 @@ test.describe('SSR hydration capped route assets', () => { await expect( page.locator('meta[name="capped-assets-child-head"]'), ).toHaveCount(0) - expect( - await page.evaluate(() => - Boolean((window as any).__CAPPED_ASSETS_CHILD_SCRIPT), - ), - ).toBe(false) + await expect( + page.locator('html[data-capped-assets-child-script]'), + ).toHaveCount(0) }) }) diff --git a/packages/router-core/tests/fatal-load-rejection.test.ts b/packages/router-core/tests/fatal-load-rejection.test.ts index d665396624..aaf8cbb28e 100644 --- a/packages/router-core/tests/fatal-load-rejection.test.ts +++ b/packages/router-core/tests/fatal-load-rejection.test.ts @@ -40,9 +40,15 @@ describe('fatal load rejection', () => { }) }, }) + const safeLoader = vi.fn(() => 'safe data') + const safeRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/safe', + loader: safeLoader, + }) const router = createTestRouter({ - routeTree: rootRoute.addChildren([badRoute]), + routeTree: rootRoute.addChildren([badRoute, safeRoute]), history: createMemoryHistory({ initialEntries: ['/bad'] }), }) @@ -52,11 +58,23 @@ describe('fatal load rejection', () => { await new Promise((resolve) => setTimeout(resolve, 0)) expect(unhandledRejection).toHaveBeenCalledWith(boom, expect.anything()) - // No committed match may keep a pending loadPromise (hung Suspense). - expect(router.state.matches.length).toBeGreaterThan(0) - for (const match of router.state.matches) { - expect(match._.loadPromise?.status ?? 'settled').not.toBe('pending') - } + // A fatal machinery failure is not a route-level error that can be + // rendered by the matched route. Once router.load() has returned, the + // public lane must be settled and the router must remain usable. + expect(router.state.isLoading).toBe(false) + + // A dangling readiness owner would strand framework consumers on the + // failed lane. Prove liveness through a normal follow-up navigation + // instead of inspecting match-owned promise bookkeeping. + await router.navigate({ to: '/safe' }) + expect(router.state.location.pathname).toBe('/safe') + expect(router.state.isLoading).toBe(false) + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: safeRoute.id, + status: 'success', + loaderData: 'safe data', + }) + expect(safeLoader).toHaveBeenCalledTimes(1) } finally { process.off('unhandledRejection', unhandledRejection) } diff --git a/packages/router-core/tests/issue-2182-root-loader-pending.test.ts b/packages/router-core/tests/issue-2182-root-loader-pending.test.ts index 68d7f954f0..967e390a6c 100644 --- a/packages/router-core/tests/issue-2182-root-loader-pending.test.ts +++ b/packages/router-core/tests/issue-2182-root-loader-pending.test.ts @@ -45,6 +45,10 @@ describe('issue #2182: root loader pending UI on initial page visit', () => { const load = router.load() load.catch(() => {}) + let loadSettled = false + void load.finally(() => { + loadSettled = true + }) // Let the loader start; before pendingMs nothing is published. await vi.advanceTimersByTimeAsync(999) @@ -60,11 +64,12 @@ describe('issue #2182: root loader pending UI on initial page visit', () => { expect(rootMatch).toBeDefined() expect(rootMatch?.status).toBe('pending') expect(rootMatch?.isFetching).toBe('loader') - expect(rootMatch?._.loadPromise?.status).toBe('pending') + expect(loadSettled).toBe(false) // Resolving the loader completes the final commit with loader data. loaderGate.resolve({ user: 'flo' }) await load + expect(loadSettled).toBe(true) const settledRoot = router.state.matches.find( (match) => match.routeId === rootRouteId, diff --git a/packages/router-core/tests/issue-2905-root-beforeload-pending.test.ts b/packages/router-core/tests/issue-2905-root-beforeload-pending.test.ts index 2bb4456ea9..ff1275f635 100644 --- a/packages/router-core/tests/issue-2905-root-beforeload-pending.test.ts +++ b/packages/router-core/tests/issue-2905-root-beforeload-pending.test.ts @@ -44,6 +44,10 @@ describe('issue #2905: root beforeLoad pending UI on initial load', () => { const load = router.load() load.catch(() => {}) + let loadSettled = false + void load.finally(() => { + loadSettled = true + }) // Before the default pendingMs (1000ms) elapses, nothing is published. await vi.advanceTimersByTimeAsync(999) @@ -57,11 +61,12 @@ describe('issue #2905: root beforeLoad pending UI on initial load', () => { ) expect(rootMatch).toBeDefined() expect(rootMatch?.status).toBe('pending') - expect(rootMatch?._.loadPromise?.status).toBe('pending') + expect(loadSettled).toBe(false) // Publication is presentation only: the load must still settle normally. beforeLoadGate.resolve({ auth: 'ok' }) await load + expect(loadSettled).toBe(true) const settledRoot = router.state.matches.find( (match) => match.routeId === rootRouteId, diff --git a/packages/router-core/tests/issue-5106-hydrated-notfound-boundary.test.ts b/packages/router-core/tests/issue-5106-hydrated-notfound-boundary.test.ts index 99cf49c3ab..a79ba583f8 100644 --- a/packages/router-core/tests/issue-5106-hydrated-notfound-boundary.test.ts +++ b/packages/router-core/tests/issue-5106-hydrated-notfound-boundary.test.ts @@ -47,9 +47,18 @@ describe('issue #5106 - hydrating a server-committed notFound boundary', () => { component: () => 'Post', notFoundComponent: () => 'Post not found', }) + const safeLoader = vi.fn(() => 'safe-data') + const safeRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/safe', + loader: safeLoader, + }) const router = createTestRouter({ - routeTree: rootRoute.addChildren([postsRoute.addChildren([postRoute])]), + routeTree: rootRoute.addChildren([ + postsRoute.addChildren([postRoute]), + safeRoute, + ]), history, isServer: false, }) @@ -112,16 +121,24 @@ describe('issue #5106 - hydrating a server-committed notFound boundary', () => { expect(postsLoader).not.toHaveBeenCalled() expect(postLoader).not.toHaveBeenCalled() - // Every match settled: an unsettled loadPromise here is the #5106 freeze - - // the framework Match suspends on it and the parent never hydrates. - for (const match of stateMatches) { - expect(match._.dehydrated).toBeUndefined() - expect(match._.loadPromise).toBeUndefined() - } - // Hydration finished without needing a follow-up router.load(). expect(router.stores.resolvedLocation.get()).toBeDefined() expect(router.stores.isLoading.get()).toBe(false) + + // Prove the hydrated lane did not freeze the router by leaving it able to + // complete an ordinary client navigation. This observes the consequence + // that matters without reading hydration/readiness bookkeeping. + await router.navigate({ to: '/safe' }) + expect(router.state.location.pathname).toBe('/safe') + expect(router.state.isLoading).toBe(false) + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: safeRoute.id, + status: 'success', + loaderData: 'safe-data', + }) + expect(safeLoader).toHaveBeenCalledTimes(1) + expect(postsLoader).not.toHaveBeenCalled() + expect(postLoader).not.toHaveBeenCalled() }) it('ancestor boundary replays the dehydrated notFound in the follow-up load instead of loading the omitted child', async () => { @@ -147,9 +164,18 @@ describe('issue #5106 - hydrating a server-committed notFound boundary', () => { loader: postLoader, component: () => 'Post', }) + const safeLoader = vi.fn(() => 'safe-data') + const safeRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/safe', + loader: safeLoader, + }) const router = createTestRouter({ - routeTree: rootRoute.addChildren([postsRoute.addChildren([postRoute])]), + routeTree: rootRoute.addChildren([ + postsRoute.addChildren([postRoute]), + safeRoute, + ]), history, isServer: false, }) @@ -210,11 +236,17 @@ describe('issue #5106 - hydrating a server-committed notFound boundary', () => { expect(postLoader).not.toHaveBeenCalled() expect(postsLoader).not.toHaveBeenCalled() - // The committed lane is fully settled - nothing left for React to - // suspend on (the #5106 freeze). - for (const match of stateMatches) { - expect(match._.dehydrated).toBeUndefined() - expect(match._.loadPromise).toBeUndefined() - } + // The replayed boundary must not strand subsequent client work. + await router.navigate({ to: '/safe' }) + expect(router.state.location.pathname).toBe('/safe') + expect(router.state.isLoading).toBe(false) + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: safeRoute.id, + status: 'success', + loaderData: 'safe-data', + }) + expect(safeLoader).toHaveBeenCalledTimes(1) + expect(postLoader).not.toHaveBeenCalled() + expect(postsLoader).not.toHaveBeenCalled() }) }) diff --git a/packages/router-core/tests/issue-6645-load-route-chunk-rejection.test.ts b/packages/router-core/tests/issue-6645-load-route-chunk-rejection.test.ts index a93b4763a9..3fdd8a9407 100644 --- a/packages/router-core/tests/issue-6645-load-route-chunk-rejection.test.ts +++ b/packages/router-core/tests/issue-6645-load-route-chunk-rejection.test.ts @@ -52,18 +52,16 @@ describe('loadRouteChunk lazy chunk rejection (PR #6645 port)', () => { await new Promise((resolve) => setTimeout(resolve, 20)) expect(unhandledRejection).not.toHaveBeenCalled() - // The failed chunk is evicted, not poisoned forever. - expect((fooRoute as any)._lazyPromise).toBeUndefined() - expect((fooRoute as any)._lazyLoaded).toBeFalsy() - expect((fooRoute as any)._componentsLoaded).toBeFalsy() - // A later pass retries the import and succeeds. await router.loadRouteChunk(fooRoute as any) expect(lazyCalls).toBe(2) - expect((fooRoute as any)._lazyLoaded).toBe(true) - expect((fooRoute as any)._componentsLoaded).toBe(true) expect(fooRoute.options.component).toBe(fooComponent) expect(unhandledRejection).not.toHaveBeenCalled() + + // The successful retry is cached, so an additional consumer does not + // invoke the lazy importer again. + await router.loadRouteChunk(fooRoute as any) + expect(lazyCalls).toBe(2) } finally { process.off('unhandledRejection', unhandledRejection) } diff --git a/packages/vue-router/tests/pending-match-settled-promise.test.tsx b/packages/vue-router/tests/pending-match-settled-promise.test.tsx index d59328ef0b..2524037d99 100644 --- a/packages/vue-router/tests/pending-match-settled-promise.test.tsx +++ b/packages/vue-router/tests/pending-match-settled-promise.test.tsx @@ -1,6 +1,8 @@ -import { afterEach, expect, test } from 'vitest' +import { afterEach, expect, test, vi } from 'vitest' import { cleanup, render, screen } from '@testing-library/vue' import { createMemoryHistory } from '@tanstack/history' +import { createControlledPromise } from '@tanstack/router-core' +import { hydrate as hydrateRouter } from '@tanstack/router-core/ssr/client' import { Outlet, RouterProvider, @@ -19,6 +21,7 @@ import { afterEach(() => { cleanup() + window.$_TSR = undefined }) function setup() { @@ -49,27 +52,67 @@ test('pending match with a settled loadPromise renders the pending component wit .get() .find((m) => m.routeId === slowRoute.id)! expect(match.status).toBe('pending') - // Simulate hydrate()/cancelMatches() settling the match-local promise while - // the match stays pending. - match._.loadPromise = undefined - - render() - - expect(await screen.findByTestId('pending-ui')).toBeTruthy() -}) - -test('hydration display match keeps rendering pending UI after mount', async () => { - const { router, slowRoute } = setup() - router.stores.setMatches(router.matchRoutes(router.latestLocation)) - - const match = router.stores.matches - .get() - .find((m) => m.routeId === slowRoute.id)! - match._displayPending = true - match._.loadPromise = undefined + // Exercise the real path that settles active match readiness while leaving + // this published snapshot pending. + router.cancelMatches() render() expect(await screen.findByTestId('pending-ui')).toBeTruthy() expect(screen.queryByTestId('slow-content')).toBeNull() }) + +test('hydration display match keeps rendering pending UI after mount', async () => { + const loaderGate = createControlledPromise() + const rootRoute = createRootRoute({ + component: () => , + }) + const slowRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/slow', + ssr: false, + loader: () => loaderGate, + pendingComponent: () =>
Pending
, + component: () =>
Slow content
, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([slowRoute]), + history: createMemoryHistory({ initialEntries: ['/slow'] }), + }) + const matches = router.matchRoutes(router.latestLocation) + + window.$_TSR = { + router: { + manifest: { routes: {} }, + dehydratedData: {}, + lastMatchId: matches[0]!.id, + matches: [ + { + i: matches[0]!.id, + s: 'success', + ssr: true, + u: Date.now(), + }, + ], + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + initialized: false, + } + + await hydrateRouter(router) + + render() + + expect(await screen.findByTestId('pending-ui')).toBeTruthy() + expect(screen.queryByTestId('slow-content')).toBeNull() + + loaderGate.resolve() + await router.latestLoadPromise + + expect(await screen.findByTestId('slow-content')).toBeTruthy() + expect(screen.queryByTestId('pending-ui')).toBeNull() +})