From ceaa4d26f29671842f548ead4a7d91715736bd6b Mon Sep 17 00:00:00 2001 From: Sheraff Date: Mon, 13 Jul 2026 09:29:38 +0200 Subject: [PATCH 01/59] fix: lane match loader rewrite --- .../interrupted-navigations/shared.ts | 23 - .../selective-ssr/src/routeTree.gen.ts | 33 +- .../src/routes/ssr-false-pending-min.tsx | 48 + .../tests/issue-7283-dev-hydration.spec.ts | 122 ++ packages/react-router/src/Match.tsx | 192 +-- packages/react-router/src/Matches.tsx | 26 +- packages/react-router/src/Transitioner.tsx | 147 +- .../react-router/src/lazyRouteComponent.tsx | 2 + .../src/ssr/renderRouterToStream.tsx | 10 +- .../src/ssr/renderRouterToString.tsx | 5 +- packages/react-router/tests/Matches.test.tsx | 57 +- ...ancestor-loader-child-pending-min.test.tsx | 95 ++ ...mponent-preload-retry-pending-min.test.tsx | 121 ++ .../tests/component-preload-retry.test.tsx | 62 + .../tests/errorComponent.test.tsx | 5 +- ...hydration-capped-boundary-pending.test.tsx | 176 ++ .../tests/hydration-terminal-lane.test.tsx | 131 ++ .../tests/issue-4759-pending-frame.test.tsx | 71 + ...issue-7051-force-pending-suspense.test.tsx | 92 + .../issue-7367-pending-min-redirect.test.tsx | 78 + ...ue-7457-redirect-chain-first-load.test.tsx | 109 ++ ...-7638-invalidate-transition-error.test.tsx | 130 ++ packages/react-router/tests/loaders.test.tsx | 21 +- .../on-rendered-same-href-state.test.tsx | 50 + ...ding-fallback-promise-replacement.test.tsx | 112 ++ .../tests/preloaded-mount-resolution.test.tsx | 96 ++ packages/react-router/tests/redirect.test.tsx | 197 +-- .../tests/root-pending-min.test.tsx | 375 +++++ packages/react-router/tests/router.test.tsx | 96 +- .../store-updates-during-navigation.test.tsx | 8 +- .../tests/transactional-loading.test.tsx | 210 +++ .../transitioner-listener-errors.test.tsx | 77 + .../tests/transitioner-render-ack.test.tsx | 85 + .../tests/transitioner-router-swap.test.tsx | 100 ++ .../react-router/tests/useNavigate.test.tsx | 50 +- packages/router-core/src/Matches.ts | 18 +- packages/router-core/src/hydrate.ts | 246 +++ packages/router-core/src/isServer/client.ts | 2 + .../router-core/src/isServer/development.ts | 1 + packages/router-core/src/isServer/server.ts | 1 + packages/router-core/src/load-matches.ts | 1278 -------------- packages/router-core/src/load.client.ts | 1496 +++++++++++++++++ packages/router-core/src/load.server.ts | 757 +++++++++ packages/router-core/src/redirect.ts | 1 - packages/router-core/src/route-chunks.ts | 68 + packages/router-core/src/route.ts | 13 +- packages/router-core/src/router.ts | 655 +++----- .../src/ssr/createRequestHandler.ts | 6 +- packages/router-core/src/ssr/ssr-client.ts | 311 +--- packages/router-core/src/ssr/ssr-server.ts | 4 - packages/router-core/src/stores.ts | 59 +- .../tests/background-assets-stale.test.ts | 77 + .../tests/background-trim-abort.test.ts | 120 ++ .../blocked-navigation-current-load.test.ts | 65 + .../tests/boundary-component-chunk.test.ts | 83 + packages/router-core/tests/callbacks.test.ts | 8 - .../tests/chunk-failure-lifecycle.test.ts | 82 + .../tests/client-lane-adversarial.test.ts | 448 +++++ .../tests/fatal-load-rejection.test.ts | 68 + .../router-core/tests/granular-stores.test.ts | 235 +-- packages/router-core/tests/hydrate.test.ts | 37 +- .../tests/hydrated-stay-match-data.test.ts | 94 ++ .../hydration-asset-context-order.test.ts | 62 + .../tests/hydration-boundary-chunks.test.ts | 168 ++ .../tests/hydration-currentness.test.ts | 247 +++ .../invalidate-pre-rematch-failure.test.ts | 52 + .../issue-3928-rapid-reload-abort.test.ts | 131 ++ ...4078-loader-notfound-root-boundary.test.ts | 69 + ...-4444-param-parse-error-lazy-child.test.ts | 70 + .../issue-4476-preload-navigate-abort.test.ts | 75 + ...4572-preload-root-beforeload-flags.test.ts | 59 + ...ssue-4684-head-on-beforeload-error.test.ts | 86 + ...ue-5106-hydrated-notfound-boundary.test.ts | 242 +++ .../issue-6107-preload-chunk-failure.test.ts | 73 + .../issue-6221-head-waits-for-loader.test.ts | 130 ++ .../issue-6351-fuzzy-notfound-layout.test.ts | 99 ++ ...search-default-normalization-abort.test.ts | 109 ++ ...ssue-7379-head-matches-direct-load.test.ts | 83 + ...e-7635-dehydrated-error-child-head.test.ts | 121 ++ .../tests/load-route-chunk.test.ts | 30 + packages/router-core/tests/load.test.ts | 590 ++----- .../tests/preflight-reentrant-context.test.ts | 148 ++ .../tests/preload-adoption.test.ts | 373 ++++ ...reload-background-parent-coherence.test.ts | 87 + .../preload-public-cache-behavior.test.ts | 206 +++ .../preload-public-signal-lifetime.test.ts | 75 + packages/router-core/tests/routerTestUtils.ts | 19 + .../serial-failure-foreground-prefix.test.ts | 76 + ...rver-async-headers-decorative-hang.test.ts | 82 + .../server-beforeload-preload-flag.test.ts | 25 + .../server-chunk-failure-lifecycle.test.ts | 100 ++ .../server-concurrent-error-notfound.test.ts | 168 ++ .../server-headers-asset-failure.test.ts | 107 ++ .../tests/server-loader-abort-error.test.ts | 37 + .../tests/server-serial-ssr-notfound.test.ts | 77 + .../tests/server-ssr-false-assets.test.ts | 91 + .../tests/server-ssr-option-error.test.ts | 44 + .../tests/stay-match-abort.test.ts | 249 +++ .../tests/superseded-load-await.test.ts | 85 + .../router-devtools-core/src/AgeTicker.tsx | 6 +- .../src/BaseTanStackRouterDevtoolsPanel.tsx | 31 +- .../src/core/hmr/handle-route-update.ts | 155 +- packages/router-plugin/tests/add-hmr.test.ts | 1 - .../snapshots/react/arrow-function@true.tsx | 88 +- .../react/arrow-function@webpack-hot.tsx | 88 +- .../createRootRoute-inline-component@true.tsx | 88 +- .../snapshots/react/createRootRoute@true.tsx | 88 +- ...ateRootRouteWithContext-type-args@true.tsx | 88 +- .../explicit-undefined-component@true.tsx | 88 +- .../react/function-declaration@true.tsx | 88 +- .../snapshots/react/multi-component@true.tsx | 88 +- .../react/string-literal-keys@true.tsx | 88 +- .../snapshots/solid/arrow-function@true.tsx | 88 +- .../tests/handle-route-update.test.ts | 268 ++- packages/solid-router/src/ClientOnly.tsx | 4 +- packages/solid-router/src/Match.tsx | 199 +-- packages/solid-router/src/Matches.tsx | 9 +- packages/solid-router/src/Transitioner.tsx | 117 +- .../solid-router/src/lazyRouteComponent.tsx | 2 + packages/solid-router/src/matchContext.tsx | 2 - packages/solid-router/src/routerStores.ts | 14 - .../src/ssr/renderRouterToStream.tsx | 5 +- .../src/ssr/renderRouterToString.tsx | 5 +- packages/solid-router/src/useMatch.tsx | 26 +- .../solid-router/tests/Transitioner.test.tsx | 1 - .../tests/component-preload-retry.test.tsx | 61 + packages/solid-router/tests/link.test.tsx | 10 +- packages/solid-router/tests/loaders.test.tsx | 52 +- .../tests/on-rendered-change-info.test.tsx | 64 + ...ding-fallback-promise-replacement.test.tsx | 179 ++ packages/solid-router/tests/redirect.test.tsx | 114 -- packages/solid-router/tests/router.test.tsx | 38 +- .../tests/same-route-pending-blank.test.tsx | 103 ++ .../tests/server/errorComponent.test.tsx | 1 - .../store-updates-during-navigation.test.tsx | 14 +- .../transitioner-listener-errors.test.tsx | 61 + .../tests/transitioner-remount.test.tsx | 82 + .../tests/transitioner-render-ack.test.tsx | 158 ++ .../use-match-outgoing-transition.test.tsx | 108 ++ .../src/createStartHandler.ts | 4 +- packages/vue-router/src/Match.tsx | 150 +- packages/vue-router/src/Matches.tsx | 8 +- packages/vue-router/src/Transitioner.tsx | 219 +-- .../vue-router/src/lazyRouteComponent.tsx | 1 + packages/vue-router/src/matchContext.tsx | 33 +- packages/vue-router/src/routerStores.ts | 14 - .../src/ssr/renderRouterToStream.tsx | 10 +- .../src/ssr/renderRouterToString.tsx | 5 +- packages/vue-router/src/useMatch.tsx | 31 +- packages/vue-router/tests/Matches.test.tsx | 2 +- .../vue-router/tests/Transitioner.test.tsx | 13 +- .../tests/component-preload-retry.test.tsx | 61 + ...hydration-capped-boundary-pending.test.tsx | 161 ++ packages/vue-router/tests/link.test.tsx | 21 +- packages/vue-router/tests/loaders.test.tsx | 8 +- ...ding-fallback-promise-replacement.test.tsx | 78 + packages/vue-router/tests/redirect.test.tsx | 104 -- packages/vue-router/tests/router.test.tsx | 34 +- .../store-updates-during-navigation.test.tsx | 20 +- .../transitioner-idle-after-render.test.tsx | 46 + .../transitioner-listener-errors.test.tsx | 61 + .../transitioner-remount-rendered.test.tsx | 129 ++ 162 files changed, 12482 insertions(+), 5491 deletions(-) create mode 100644 e2e/solid-start/selective-ssr/src/routes/ssr-false-pending-min.tsx create mode 100644 e2e/solid-start/selective-ssr/tests/issue-7283-dev-hydration.spec.ts create mode 100644 packages/react-router/tests/ancestor-loader-child-pending-min.test.tsx create mode 100644 packages/react-router/tests/component-preload-retry-pending-min.test.tsx create mode 100644 packages/react-router/tests/component-preload-retry.test.tsx create mode 100644 packages/react-router/tests/hydration-capped-boundary-pending.test.tsx create mode 100644 packages/react-router/tests/hydration-terminal-lane.test.tsx 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/react-router/tests/on-rendered-same-href-state.test.tsx create mode 100644 packages/react-router/tests/pending-fallback-promise-replacement.test.tsx create mode 100644 packages/react-router/tests/preloaded-mount-resolution.test.tsx create mode 100644 packages/react-router/tests/root-pending-min.test.tsx create mode 100644 packages/react-router/tests/transactional-loading.test.tsx create mode 100644 packages/react-router/tests/transitioner-listener-errors.test.tsx create mode 100644 packages/react-router/tests/transitioner-render-ack.test.tsx create mode 100644 packages/react-router/tests/transitioner-router-swap.test.tsx create mode 100644 packages/router-core/src/hydrate.ts delete mode 100644 packages/router-core/src/load-matches.ts create mode 100644 packages/router-core/src/load.client.ts create mode 100644 packages/router-core/src/load.server.ts create mode 100644 packages/router-core/src/route-chunks.ts create mode 100644 packages/router-core/tests/background-assets-stale.test.ts create mode 100644 packages/router-core/tests/background-trim-abort.test.ts create mode 100644 packages/router-core/tests/blocked-navigation-current-load.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/client-lane-adversarial.test.ts create mode 100644 packages/router-core/tests/fatal-load-rejection.test.ts create mode 100644 packages/router-core/tests/hydrated-stay-match-data.test.ts create mode 100644 packages/router-core/tests/hydration-asset-context-order.test.ts create mode 100644 packages/router-core/tests/hydration-boundary-chunks.test.ts create mode 100644 packages/router-core/tests/hydration-currentness.test.ts create mode 100644 packages/router-core/tests/invalidate-pre-rematch-failure.test.ts create mode 100644 packages/router-core/tests/issue-3928-rapid-reload-abort.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-4444-param-parse-error-lazy-child.test.ts create mode 100644 packages/router-core/tests/issue-4476-preload-navigate-abort.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-4684-head-on-beforeload-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-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-6351-fuzzy-notfound-layout.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-7379-head-matches-direct-load.test.ts create mode 100644 packages/router-core/tests/issue-7635-dehydrated-error-child-head.test.ts create mode 100644 packages/router-core/tests/load-route-chunk.test.ts create mode 100644 packages/router-core/tests/preflight-reentrant-context.test.ts create mode 100644 packages/router-core/tests/preload-adoption.test.ts create mode 100644 packages/router-core/tests/preload-background-parent-coherence.test.ts create mode 100644 packages/router-core/tests/preload-public-cache-behavior.test.ts create mode 100644 packages/router-core/tests/preload-public-signal-lifetime.test.ts create mode 100644 packages/router-core/tests/serial-failure-foreground-prefix.test.ts create mode 100644 packages/router-core/tests/server-async-headers-decorative-hang.test.ts create mode 100644 packages/router-core/tests/server-beforeload-preload-flag.test.ts create mode 100644 packages/router-core/tests/server-chunk-failure-lifecycle.test.ts create mode 100644 packages/router-core/tests/server-concurrent-error-notfound.test.ts create mode 100644 packages/router-core/tests/server-headers-asset-failure.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 create mode 100644 packages/router-core/tests/server-ssr-false-assets.test.ts create mode 100644 packages/router-core/tests/server-ssr-option-error.test.ts create mode 100644 packages/router-core/tests/stay-match-abort.test.ts create mode 100644 packages/router-core/tests/superseded-load-await.test.ts create mode 100644 packages/solid-router/tests/component-preload-retry.test.tsx create mode 100644 packages/solid-router/tests/on-rendered-change-info.test.tsx create mode 100644 packages/solid-router/tests/pending-fallback-promise-replacement.test.tsx create mode 100644 packages/solid-router/tests/same-route-pending-blank.test.tsx create mode 100644 packages/solid-router/tests/transitioner-listener-errors.test.tsx create mode 100644 packages/solid-router/tests/transitioner-remount.test.tsx create mode 100644 packages/solid-router/tests/transitioner-render-ack.test.tsx create mode 100644 packages/solid-router/tests/use-match-outgoing-transition.test.tsx create mode 100644 packages/vue-router/tests/component-preload-retry.test.tsx create mode 100644 packages/vue-router/tests/hydration-capped-boundary-pending.test.tsx create mode 100644 packages/vue-router/tests/pending-fallback-promise-replacement.test.tsx create mode 100644 packages/vue-router/tests/transitioner-idle-after-render.test.tsx create mode 100644 packages/vue-router/tests/transitioner-listener-errors.test.tsx create mode 100644 packages/vue-router/tests/transitioner-remount-rendered.test.tsx diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/shared.ts b/benchmarks/memory/client/scenarios/interrupted-navigations/shared.ts index f7f3a7cd8b..80f234f0c8 100644 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/shared.ts +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/shared.ts @@ -35,7 +35,6 @@ type RenderedEvent = { } type InterruptedNavigationRouter = { - latestLoadPromise: Promise | undefined load: () => Promise navigate: (options: { to: '/fast/$id' | '/slow/$id' @@ -104,18 +103,6 @@ function assertSlowNavigationSettlement(settlement: NavigationSettlement) { ) } -async function awaitExpectedLoadSettlement(loadPromise: Promise) { - try { - await loadPromise - } catch (reason) { - if (reasonHasAbortShape(reason) || reasonHasCancellationShape(reason)) { - return - } - - throw reason - } -} - function reasonHasAbortShape(reason: unknown) { return reason instanceof DOMException && reason.name === 'AbortError' } @@ -144,7 +131,6 @@ export function createWorkload( let navigateFast: (id: string) => Promise = uninitialized let startSlowNavigation: (id: string) => Promise = uninitializedSettlement - let getLatestLoadPromise: () => Promise | undefined = () => undefined function assertRenderedPage(page: 'shell' | 'fast', id?: string) { const element = container?.querySelector('[data-bench-page]') @@ -203,7 +189,6 @@ export function createWorkload( const mounted = mountTestApp(container) const router = mounted.router as InterruptedNavigationRouter unmount = mounted.unmount - getLatestLoadPromise = () => router.latestLoadPromise unsub = router.subscribe('onRendered', (event) => { if ( @@ -265,7 +250,6 @@ export function createWorkload( expectedRenderedPath = undefined navigateFast = uninitialized startSlowNavigation = uninitializedSettlement - getLatestLoadPromise = () => undefined } async function interrupt( @@ -276,12 +260,6 @@ export function createWorkload( const slowNavigation = startSlowNavigation(slowId) await waitForSlowLoader(slowId) - const slowLoadPromise = getLatestLoadPromise() - - if (!slowLoadPromise) { - throw new Error(`Slow navigation did not start a load for id: ${slowId}`) - } - await navigateFast(fastId) resolveSlowLoader(slowId) @@ -291,7 +269,6 @@ export function createWorkload( assertSlowNavigationSettlement(settlement) } - await awaitExpectedLoadSettlement(slowLoadPromise) await drainMicrotasks() } 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/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/react-router/src/Match.tsx b/packages/react-router/src/Match.tsx index 5de5546aeb..8cce99a276 100644 --- a/packages/react-router/src/Match.tsx +++ b/packages/react-router/src/Match.tsx @@ -2,14 +2,7 @@ import * as React from 'react' import { useStore } from '@tanstack/react-store' -import { - createControlledPromise, - getLocationChangeInfo, - invariant, - isNotFound, - isRedirect, - rootRouteId, -} from '@tanstack/router-core' +import { invariant, isNotFound, rootRouteId } from '@tanstack/router-core' import { isServer } from '@tanstack/router-core/isServer' import { CatchBoundary, ErrorComponent } from './CatchBoundary' import { useRouter } from './useRouter' @@ -19,26 +12,27 @@ import { SafeFragment } from './SafeFragment' import { renderRouteNotFound } from './renderRouteNotFound' import { ScrollRestoration } from './scroll-restoration' import { ClientOnly } from './ClientOnly' -import { useLayoutEffect } from './utils' import type { AnyRoute, AnyRouteMatch, - ParsedLocation, RootRouteOptions, } from '@tanstack/router-core' type OutletMatchSelection = [ routeId: string | undefined, parentGlobalNotFound: boolean, + parentNotFoundError: unknown, ] const matchViewFieldsEqual = (a: AnyRouteMatch, b: AnyRouteMatch) => - a.routeId === b.routeId && a._displayPending === b._displayPending + a.routeId === b.routeId && + a.fetchCount === b.fetchCount && + a.status === b.status const outletMatchSelectionEqual = ( a: OutletMatchSelection, b: OutletMatchSelection, -) => a[0] === b[0] && a[1] === b[1] +) => a[0] === b[0] && a[1] === b[1] && a[2] === b[2] export const Match = React.memo(function MatchImpl({ matchId, @@ -67,11 +61,10 @@ export const Match = React.memo(function MatchImpl({ @@ -93,8 +86,6 @@ 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(() => { @@ -105,16 +96,15 @@ export const Match = React.memo(function MatchImpl({ return { routeId, ssr: match.ssr, - _displayPending: match._displayPending, parentRouteId: parentRouteId as string | undefined, } satisfies MatchViewState - }, [match._displayPending, match.routeId, match.ssr, router.routesById]) + }, [match.routeId, match.ssr, router.routesById]) return ( ) @@ -123,7 +113,6 @@ export const Match = React.memo(function MatchImpl({ type MatchViewState = { routeId: string ssr: boolean | 'data-only' | undefined - _displayPending: boolean | undefined parentRouteId: string | undefined } @@ -159,11 +148,9 @@ function MatchView({ const resolvedNoSsr = matchState.ssr === false || matchState.ssr === 'data-only' const ResolvedSuspenseBoundary = - // If we're on the root route, allow forcefully wrapping in suspense - (!route.isRoot || route.options.wrapInSuspense || resolvedNoSsr) && (route.options.wrapInSuspense ?? - PendingComponent ?? - ((route.options.errorComponent as any)?.preload || resolvedNoSsr)) + PendingComponent ?? + ((route.options.errorComponent as any)?.preload || resolvedNoSsr)) ? React.Suspense : SafeFragment @@ -183,7 +170,7 @@ function MatchView({ resetKey} + getResetKey={() => `${matchId}:${resetKey}`} errorComponent={routeErrorComponent || ErrorComponent} onCatch={(error, errorInfo) => { // Forward not found errors (we don't want to show the error component for these) @@ -213,7 +200,7 @@ function MatchView({ return React.createElement(routeNotFoundComponent, error as any) }} > - {resolvedNoSsr || matchState._displayPending ? ( + {resolvedNoSsr ? ( @@ -225,68 +212,14 @@ function MatchView({ {matchState.parentRouteId === rootRouteId ? ( - <> - - {router.options.scrollRestoration && (isServer ?? router.isServer) ? ( - - ) : null} - + router.options.scrollRestoration && (isServer ?? router.isServer) ? ( + + ) : null ) : null} ) } -// On Rendered can't happen above the root layout because it needs to run after -// the route subtree has committed below the root layout. Keeping it here lets -// us fire onRendered even after a hydration mismatch above the root layout -// (like bad head/link tags, which is common). -function OnRendered() { - const router = useRouter() - - if (isServer ?? router.isServer) { - return null - } - - // Track the resolvedLocation as of the last render so that onRendered can - // report the correct fromLocation. By the time this effect fires, - // resolvedLocation has already been updated to the new location by - // Transitioner, so we cannot use router.stores.resolvedLocation.get() - // directly as the fromLocation. - // @ts-expect-error -- init to `undefined` but don't write `undefined` to shave bytes - // eslint-disable-next-line react-hooks/rules-of-hooks - const prevResolvedLocationRef = React.useRef< - ParsedLocation | undefined - >() - // eslint-disable-next-line react-hooks/rules-of-hooks - const renderedLocationKey = useStore( - router.stores.resolvedLocation, - (resolvedLocation) => resolvedLocation?.state.__TSR_key, - ) - - // eslint-disable-next-line react-hooks/rules-of-hooks - useLayoutEffect(() => { - const currentResolvedLocation = router.stores.resolvedLocation.get() - const previousResolvedLocation = prevResolvedLocationRef.current - - if ( - currentResolvedLocation && - (!previousResolvedLocation || - previousResolvedLocation.href !== currentResolvedLocation.href) - ) { - router.emit({ - type: 'onRendered', - ...getLocationChangeInfo( - router.stores.location.get(), - previousResolvedLocation ?? currentResolvedLocation, - ), - }) - } - prevResolvedLocationRef.current = currentResolvedLocation - }, [renderedLocationKey, router]) - - return null -} - export const MatchInner = React.memo(function MatchInnerImpl({ matchId, }: { @@ -294,22 +227,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) { @@ -337,16 +254,8 @@ export const MatchInner = React.memo(function MatchInnerImpl({ const Comp = route.options.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') + invariant() } if (match.status === 'notFound') { @@ -360,17 +269,6 @@ 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 ?? @@ -434,37 +332,10 @@ export const MatchInner = React.memo(function MatchInnerImpl({ return }, [key, route.options.component, router.options.defaultComponent]) - 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) - } - } - } - throw getMatchPromise(match, 'loadPromise') + const PendingComponent = + route.options.pendingComponent ?? router.options.defaultPendingComponent + return PendingComponent ? : null } if (match.status === 'notFound') { @@ -478,22 +349,6 @@ 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 @@ -534,6 +389,7 @@ export const Outlet = React.memo(function OutletImpl() { let routeId: string | undefined let parentGlobalNotFound = false + let parentNotFoundError: unknown let childMatchId: string | undefined if (isServer ?? router.isServer) { @@ -544,6 +400,7 @@ export const Outlet = React.memo(function OutletImpl() { const parentMatch = parentIndex >= 0 ? matches[parentIndex] : undefined routeId = parentMatch?.routeId as string | undefined parentGlobalNotFound = parentMatch?.globalNotFound ?? false + parentNotFoundError = parentMatch?.error childMatchId = parentIndex >= 0 ? (matches[parentIndex + 1]?.id as string) : undefined } else { @@ -554,11 +411,12 @@ export const Outlet = React.memo(function OutletImpl() { : undefined // eslint-disable-next-line react-hooks/rules-of-hooks - ;[routeId, parentGlobalNotFound] = useStore( + ;[routeId, parentGlobalNotFound, parentNotFoundError] = useStore( parentMatchStore, (match): OutletMatchSelection => [ match?.routeId as string | undefined, match?.globalNotFound ?? false, + match?.error, ], outletMatchSelectionEqual, ) @@ -586,7 +444,7 @@ export const Outlet = React.memo(function OutletImpl() { invariant() } - return renderRouteNotFound(router, route, undefined) + return renderRouteNotFound(router, route, parentNotFoundError) } if (!childMatchId) { diff --git a/packages/react-router/src/Matches.tsx b/packages/react-router/src/Matches.tsx index 62d0fc42ae..bb8b1c962a 100644 --- a/packages/react-router/src/Matches.tsx +++ b/packages/react-router/src/Matches.tsx @@ -7,6 +7,7 @@ import { isServer } from '@tanstack/router-core/isServer' import { CatchBoundary, ErrorComponent } from './CatchBoundary' import { useRouter } from './useRouter' import { useStructuralSharing } from './useMatch' +import { useLayoutEffect } from './utils' import { Transitioner } from './Transitioner' import { matchContext } from './matchContext' import { Match } from './Match' @@ -61,10 +62,12 @@ export function Matches() { : React.Suspense const inner = ( - + <> {!(isServer ?? router.isServer) && } - - + + + + ) return router.options.InnerWrap ? ( @@ -77,14 +80,17 @@ export function Matches() { function MatchesInner() { const router = useRouter() const _isServer = isServer ?? router.isServer - const matchId = _isServer - ? router.stores.firstId.get() + const matches = _isServer + ? router.stores.matches.get() : // eslint-disable-next-line react-hooks/rules-of-hooks - useStore(router.stores.firstId, (id) => id) - const resetKey = _isServer - ? router.stores.loadedAt.get() - : // eslint-disable-next-line react-hooks/rules-of-hooks - useStore(router.stores.loadedAt, (loadedAt) => loadedAt) + useStore(router.stores.matches, (value) => value) + const match = matches[0] + const matchId = match?.id + const resetKey = match ? `${match.id}:${match.fetchCount}` : '' + + useLayoutEffect(() => { + router._rendered?.() + }, [matches, router]) const matchComponent = matchId ? : null diff --git a/packages/react-router/src/Transitioner.tsx b/packages/react-router/src/Transitioner.tsx index bf945571a6..90862c27e4 100644 --- a/packages/react-router/src/Transitioner.tsx +++ b/packages/react-router/src/Transitioner.tsx @@ -1,41 +1,59 @@ 'use client' import * as React from 'react' -import { batch, useStore } 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 mountLoadForRouter = React.useRef< + [typeof router, typeof router.history] | undefined + >(undefined) + const acknowledgements = React.useRef void>>( + [], + ).current - 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) + useLayoutEffect(() => { + const previousTransition = router.startTransition + const previousRendered = router._rendered + const rendered = () => { + for (const resolve of acknowledgements.splice(0)) { + resolve(true) + } + } + const transition = (fn: () => void) => { + return new Promise((resolve) => { + acknowledgements.push(resolve) + React.startTransition(fn) + }) + } + router._rendered = rendered + router.startTransition = transition + return () => { + for (const resolve of acknowledgements.splice(0)) { + resolve(false) + } + if (router._rendered === rendered) { + router._rendered = previousRendered + } + if (router.startTransition === transition) { + router.startTransition = previousTransition + } + } + }, [acknowledgements, router]) - const previousIsLoading = usePrevious(isLoading) - - const isAnyPending = isLoading || isTransitioning || hasPending - const previousIsAnyPending = usePrevious(isAnyPending) - - const isPagePending = isLoading || hasPending - const previousIsPagePending = usePrevious(isPagePending) - - router.startTransition = (fn: () => void) => { - setIsTransitioning(true) - React.startTransition(() => { - fn() - setIsTransitioning(false) - }) - } - - // Subscribe to location changes - // and try to load the new location - React.useEffect(() => { + // Subscribe before canonicalizing so the initial URL has exactly one load. + useLayoutEffect(() => { const unsub = router.history.subscribe(router.load) + const mounted = mountLoadForRouter.current + if (mounted?.[0] === router && mounted[1] === router.history) { + return unsub + } + mountLoadForRouter.current = [router, router.history] + + router.updateLatestLocation() const nextLocation = router.buildLocation({ to: router.latestLocation.pathname, search: true, @@ -53,79 +71,26 @@ export function Transitioner() { trimPathRight(nextLocation.publicHref) ) { router.commitLocation({ ...nextLocation, replace: true }) + return unsub } - return () => { - unsub() - } - }, [router, router.history]) - - // Try to load the initial location - useLayoutEffect(() => { + const resolvedLocation = router.stores.resolvedLocation.get() + const historyLocation = router.history.location if ( - // if we are hydrating from SSR, loading is triggered in ssr-client - (typeof window !== 'undefined' && router.ssr) || - (mountLoadForRouter.current.router === router && - mountLoadForRouter.current.mounted) + resolvedLocation && + resolvedLocation.publicHref === historyLocation.href && + resolvedLocation.state.__TSR_key === historyLocation.state.__TSR_key ) { - return - } - mountLoadForRouter.current = { router, mounted: true } - - const tryLoad = async () => { - try { - await router.load() - } catch (err) { - console.error(err) - } - } - - tryLoad() - }, [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(), - ), + type: 'onRendered', + ...getLocationChangeInfo(resolvedLocation, resolvedLocation), }) + } else { + router.load().catch(console.error) } - }, [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 unsub + }, [router, router.history]) return null } diff --git a/packages/react-router/src/lazyRouteComponent.tsx b/packages/react-router/src/lazyRouteComponent.tsx index b4fe8703c5..f918b55ea4 100644 --- a/packages/react-router/src/lazyRouteComponent.tsx +++ b/packages/react-router/src/lazyRouteComponent.tsx @@ -28,12 +28,14 @@ export function lazyRouteComponent< const load = () => { if (!loadPromise) { + error = undefined loadPromise = importer() .then((res) => { loadPromise = undefined comp = res[exportName ?? 'default'] }) .catch((err) => { + loadPromise = undefined // We don't want an error thrown from preload in this case, because // there's nothing we want to do about module not found during preload. // Record the error, the rest is handled during the render path. diff --git a/packages/react-router/src/ssr/renderRouterToStream.tsx b/packages/react-router/src/ssr/renderRouterToStream.tsx index 46275a5421..ee15b882fd 100644 --- a/packages/react-router/src/ssr/renderRouterToStream.tsx +++ b/packages/react-router/src/ssr/renderRouterToStream.tsx @@ -76,7 +76,10 @@ export const renderRouterToStream = async ({ return createSsrStreamResponse( router, new Response(responseStream as any, { - status: router.stores.statusCode.get(), + status: + router._serverResult?.type === 'render' + ? router._serverResult.status + : 200, headers: responseHeaders, }), ) @@ -199,7 +202,10 @@ export const renderRouterToStream = async ({ return createSsrStreamResponse( router, new Response(responseStream as any, { - status: router.stores.statusCode.get(), + status: + router._serverResult?.type === 'render' + ? router._serverResult.status + : 200, headers: responseHeaders, }), ) diff --git a/packages/react-router/src/ssr/renderRouterToString.tsx b/packages/react-router/src/ssr/renderRouterToString.tsx index e9fe4ec779..5e299cc215 100644 --- a/packages/react-router/src/ssr/renderRouterToString.tsx +++ b/packages/react-router/src/ssr/renderRouterToString.tsx @@ -21,7 +21,10 @@ export const renderRouterToString = async ({ } return new Response(`${html}`, { - status: router.stores.statusCode.get(), + status: + router._serverResult?.type === 'render' + ? router._serverResult.status + : 200, headers: responseHeaders, }) } catch (error) { diff --git a/packages/react-router/tests/Matches.test.tsx b/packages/react-router/tests/Matches.test.tsx index dd3ca3dfa6..94ed262cc4 100644 --- a/packages/react-router/tests/Matches.test.tsx +++ b/packages/react-router/tests/Matches.test.tsx @@ -126,11 +126,11 @@ test('when filtering useMatches by loaderData', async () => { test('should show pendingComponent of root route', async () => { const root = createRootRoute({ - pendingComponent: () =>
, + pendingComponent: () =>
, loader: async () => { await new Promise((r) => setTimeout(r, 50)) }, - component: () =>
, + component: () =>
, }) const router = createRouter({ @@ -145,6 +145,59 @@ test('should show pendingComponent of root route', async () => { expect(await rendered.findByTestId('root-content')).toBeInTheDocument() }) +test('a reused legacy notFoundRoute does not retain the previous parent layout', async () => { + const root = createRootRoute({ component: Outlet }) + const parent = createRoute({ + getParentRoute: () => root, + path: '/parent', + component: () => ( +
+ Parent layout + +
+ ), + }) + const known = createRoute({ + getParentRoute: () => parent, + path: '/known', + }) + const home = createRoute({ + getParentRoute: () => root, + path: '/home', + component: () =>
Home
, + }) + const legacyNotFound = createRoute({ + getParentRoute: () => root, + path: '/404', + loader: () => 'not found', + component: () =>
Legacy not found
, + staleTime: Infinity, + gcTime: Infinity, + }) + const router = createRouter({ + routeTree: root.addChildren([parent.addChildren([known]), home]), + history: createMemoryHistory({ initialEntries: ['/parent/missing'] }), + notFoundRoute: legacyNotFound, + }) + + const rendered = render() + expect(await rendered.findByText('Parent layout')).toBeInTheDocument() + expect(await rendered.findByText('Legacy not found')).toBeInTheDocument() + + await act(async () => { + await router.navigate({ to: '/home' }) + }) + expect(await rendered.findByText('Home')).toBeInTheDocument() + + await act(async () => { + await router.navigate({ to: '/missing' } as any) + }) + + expect(rendered.queryByText('Parent layout')).not.toBeInTheDocument() + expect(await rendered.findByText('Legacy not found')).toBeInTheDocument() + rendered.unmount() +}) + describe('matching on different param types', () => { const testCases = [ { diff --git a/packages/react-router/tests/ancestor-loader-child-pending-min.test.tsx b/packages/react-router/tests/ancestor-loader-child-pending-min.test.tsx new file mode 100644 index 0000000000..a4d587e2f3 --- /dev/null +++ b/packages/react-router/tests/ancestor-loader-child-pending-min.test.tsx @@ -0,0 +1,95 @@ +import * as React from 'react' +import { act, cleanup, render, screen } from '@testing-library/react' +import { afterEach, expect, test, vi } from 'vitest' +import { + Outlet, + RouterProvider, + createControlledPromise, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +afterEach(() => { + cleanup() + vi.useRealTimers() +}) + +test('a child fallback revealed after a fresh ancestor loader keeps its own pendingMinMs', async () => { + vi.useFakeTimers() + + const parentLoader = createControlledPromise() + const childLoader = createControlledPromise() + const rootRoute = createRootRoute({ + component: () => , + }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
Index
, + }) + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: () => parentLoader, + component: () => , + }) + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + pendingMs: 0, + pendingMinMs: 100, + pendingComponent: () =>
Child pending
, + loader: () => childLoader, + component: () =>
Child content
, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + defaultPendingMs: 0, + }) + + await router.load() + render() + expect(screen.getByText('Index')).toBeInTheDocument() + + let navigation!: Promise + await act(async () => { + navigation = router.navigate({ to: '/parent/child' }) + await vi.advanceTimersByTimeAsync(25) + }) + + expect(screen.queryByText('Child pending')).not.toBeInTheDocument() + + await act(async () => { + parentLoader.resolve() + await vi.advanceTimersByTimeAsync(0) + }) + expect(screen.getByText('Child pending')).toBeInTheDocument() + expect(screen.queryByText('Child content')).not.toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(25) + childLoader.resolve() + await Promise.resolve() + }) + + // The minimum is measured from the child's first visible frame, not from + // the navigation start or the ancestor's completion. + await act(async () => { + await vi.advanceTimersByTimeAsync(74) + }) + expect(screen.getByText('Child pending')).toBeInTheDocument() + expect(screen.queryByText('Child content')).not.toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(1) + await navigation + }) + expect(screen.queryByText('Child pending')).not.toBeInTheDocument() + expect(screen.getByText('Child content')).toBeInTheDocument() +}) diff --git a/packages/react-router/tests/component-preload-retry-pending-min.test.tsx b/packages/react-router/tests/component-preload-retry-pending-min.test.tsx new file mode 100644 index 0000000000..25dee12a4e --- /dev/null +++ b/packages/react-router/tests/component-preload-retry-pending-min.test.tsx @@ -0,0 +1,121 @@ +import * as React from 'react' +import { act } from 'react' +import { afterEach, expect, test, vi } from 'vitest' +import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { createControlledPromise } from '@tanstack/router-core' +import { + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, + useRouter, +} from '../src' +import type { ErrorComponentProps } from '../src' + +afterEach(() => { + vi.useRealTimers() + vi.restoreAllMocks() + cleanup() +}) + +/** + * A component-only route can fail while preloading its code, then retry from + * its error UI through invalidate(). The retry is a fresh pending generation: + * it needs a match-local load promise so the rendered pending component can + * attach pendingMinMs to the work that actually owns readiness. + */ +test('component preload retry owns readiness and honors pendingMinMs', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + + const retryChunk = createControlledPromise() + let preloadAttempt = 0 + let retryPromise: Promise | undefined + let retrySettled = false + + const Page = Object.assign( + () =>
Page content
, + { + preload: vi.fn(() => { + preloadAttempt++ + return preloadAttempt === 1 + ? Promise.reject(new Error('initial chunk request failed')) + : retryChunk + }), + }, + ) + + function RetryError({ reset }: ErrorComponentProps) { + const router = useRouter() + return ( + + ) + } + + const rootRoute = createRootRoute({}) + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + component: Page, + errorComponent: RetryError, + pendingMs: 0, + pendingMinMs: 100, + pendingComponent: () => ( +
Loading page...
+ ), + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + render() + + expect( + await screen.findByRole('button', { name: 'Retry chunk' }), + ).toBeInTheDocument() + expect(Page.preload).toHaveBeenCalledTimes(1) + + vi.useFakeTimers() + fireEvent.click(screen.getByRole('button', { name: 'Retry chunk' })) + + // Let pendingMs: 0 publish the retry lane. + await act(async () => { + await vi.advanceTimersByTimeAsync(0) + }) + expect(screen.getByTestId('page-pending')).toBeInTheDocument() + + await act(async () => { + retryChunk.resolve() + await Promise.resolve() + }) + + expect.soft(retrySettled).toBe(false) + expect.soft(screen.queryByTestId('page-pending')).toBeInTheDocument() + expect.soft(screen.queryByTestId('page-content')).not.toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(99) + }) + expect(screen.getByTestId('page-pending')).toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(1) + await retryPromise + }) + + expect(Page.preload).toHaveBeenCalledTimes(2) + expect(screen.getByTestId('page-content')).toBeInTheDocument() + expect(screen.queryByTestId('page-pending')).not.toBeInTheDocument() +}) diff --git a/packages/react-router/tests/component-preload-retry.test.tsx b/packages/react-router/tests/component-preload-retry.test.tsx new file mode 100644 index 0000000000..6111a2dd2e --- /dev/null +++ b/packages/react-router/tests/component-preload-retry.test.tsx @@ -0,0 +1,62 @@ +import * as React from 'react' +import { afterEach, expect, test, vi } from 'vitest' +import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, + lazyRouteComponent, + useRouter, +} from '../src' +import type { ErrorComponentProps } from '../src' + +afterEach(() => { + cleanup() + vi.restoreAllMocks() +}) + +test('a failed component download is retried from the route error UI', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + + const PageContent = () =>
Page content
+ const importer = vi + .fn<() => Promise<{ default: typeof PageContent }>>() + .mockRejectedValueOnce(new Error('component download failed')) + .mockResolvedValue({ default: PageContent }) + const Page = lazyRouteComponent(importer) + + function RouteError({ reset }: ErrorComponentProps) { + const router = useRouter() + return ( + + ) + } + + const rootRoute = createRootRoute() + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + component: Page, + errorComponent: RouteError, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + render() + + fireEvent.click(await screen.findByRole('button', { name: 'Retry' })) + + expect(await screen.findByText('Page content')).toBeInTheDocument() +}) diff --git a/packages/react-router/tests/errorComponent.test.tsx b/packages/react-router/tests/errorComponent.test.tsx index 0779c2e8c4..15dcfbfa8c 100644 --- a/packages/react-router/tests/errorComponent.test.tsx +++ b/packages/react-router/tests/errorComponent.test.tsx @@ -338,7 +338,6 @@ test('SSR errorComponent receives primitive errors thrown from beforeLoad', asyn await router.load() - expect(router.state.statusCode).toBe(500) const html = ReactDOMServer.renderToString() expect(html).toContain('Error:') expect(html).toContain('primitive error thrown') @@ -423,13 +422,11 @@ describe('notFoundComponent is rendered when an error is thrown in params.parse' render() - await act(() => router.latestLoadPromise) - expect(rootLoader).toHaveBeenCalledTimes(1) - const linkToRottenPizza = await screen.findByRole('link', { name: 'link to rotten pizza', }) + expect(rootLoader).toHaveBeenCalledTimes(1) expect(linkToRottenPizza).toBeInTheDocument() await act(() => fireEvent.mouseOver(linkToRottenPizza)) await act(() => fireEvent.click(linkToRottenPizza)) diff --git a/packages/react-router/tests/hydration-capped-boundary-pending.test.tsx b/packages/react-router/tests/hydration-capped-boundary-pending.test.tsx new file mode 100644 index 0000000000..b79a5ce751 --- /dev/null +++ b/packages/react-router/tests/hydration-capped-boundary-pending.test.tsx @@ -0,0 +1,176 @@ +import * as React from 'react' +import { act } from '@testing-library/react' +import { hydrateRoot } from 'react-dom/client' +import { renderToString } from 'react-dom/server' +import { afterEach, describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { hydrate } from '../src/ssr/client' +import { + Outlet, + RouterProvider, + createRootRoute, + createRoute, + createRouter, + notFound, +} from '../src' +import type { TsrSsrGlobal } from '../src/ssr/client' + +declare global { + interface Window { + $_TSR?: TsrSsrGlobal + } +} + +const testCleanups: Array<() => void | Promise> = [] + +afterEach(async () => { + while (testCleanups.length) { + await testCleanups.pop()!() + } + vi.restoreAllMocks() + window.$_TSR = undefined + document.body.innerHTML = '' +}) + +describe('hydrating a server-capped boundary lane', () => { + test.each([ + ['error', 'parent'], + ['notFound', 'parent'], + ['error', 'root'], + ['notFound', 'root'], + ] as const)( + 'keeps the server-rendered %s %s boundary visible', + async (outcome, boundary) => { + const routeFailure = + outcome === 'notFound' ? notFound() : new Error('server route failure') + const childLoader = vi.fn(() => 'child data') + + const makeRouteTree = () => { + const boundaryOptions = { + beforeLoad: () => { + throw routeFailure + }, + pendingComponent: () => ( +
Boundary pending
+ ), + errorComponent: () => ( +
Boundary error
+ ), + notFoundComponent: () => ( +
Boundary not found
+ ), + } + const rootRoute = createRootRoute({ + component: Outlet, + ...(boundary === 'root' ? boundaryOptions : {}), + }) + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + component: Outlet, + ...(boundary === 'parent' ? boundaryOptions : {}), + }) + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: childLoader, + component: () =>
Child
, + }) + return { + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([childRoute]), + ]), + } + } + + const serverRouter = createRouter({ + ...makeRouteTree(), + ...(boundary === 'root' ? { isShell: true } : {}), + history: createMemoryHistory({ + initialEntries: ['/parent/child'], + }), + }) + serverRouter.isServer = true + await serverRouter.load() + + const serverMatches = serverRouter.stores.matches.get() + expect(serverMatches).toHaveLength(boundary === 'root' ? 1 : 2) + const serverBoundary = serverMatches.at(-1)! + if (outcome === 'notFound' && boundary === 'root') { + expect(serverBoundary).toMatchObject({ + status: 'success', + globalNotFound: true, + }) + } else { + expect(serverBoundary.status).toBe(outcome) + } + const serverHtml = renderToString( + , + ) + expect(serverHtml).toContain( + outcome === 'notFound' ? 'Boundary not found' : 'Boundary error', + ) + + const clientRouter = createRouter({ + ...makeRouteTree(), + history: createMemoryHistory({ + initialEntries: ['/parent/child'], + }), + }) + + window.$_TSR = { + router: { + manifest: { routes: {} }, + dehydratedData: {}, + matches: serverMatches.map((match) => ({ + i: match.id, + u: match.updatedAt, + s: match.status, + l: match.loaderData, + e: match.error, + ssr: match.ssr, + ...(match.globalNotFound ? { g: true } : {}), + })), + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + initialized: false, + } + + await hydrate(clientRouter) + + const container = document.createElement('div') + container.innerHTML = serverHtml + document.body.appendChild(container) + const consoleError = vi + .spyOn(console, 'error') + .mockImplementation(() => {}) + const root = hydrateRoot( + container, + , + ) + testCleanups.push(async () => { + await act(() => root.unmount()) + }) + + await act(async () => { + await Promise.resolve() + }) + + // A shorter dehydrated lane means SPA mode only for an actual shell. + // Here it is shorter because the server already rendered a terminal + // boundary, so hydration must not replace that boundary with pending UI. + expect(container).toHaveTextContent( + outcome === 'notFound' ? 'Boundary not found' : 'Boundary error', + ) + expect(container).not.toHaveTextContent('Boundary pending') + expect(consoleError.mock.calls.flat().join(' ')).not.toMatch( + /hydration|did not match/i, + ) + expect(childLoader).not.toHaveBeenCalled() + }, + ) +}) diff --git a/packages/react-router/tests/hydration-terminal-lane.test.tsx b/packages/react-router/tests/hydration-terminal-lane.test.tsx new file mode 100644 index 0000000000..d8e64c5944 --- /dev/null +++ b/packages/react-router/tests/hydration-terminal-lane.test.tsx @@ -0,0 +1,131 @@ +import { cleanup, render, screen } from '@testing-library/react' +import { afterEach, describe, expect, test, vi } from 'vitest' +import { hydrate } from '@tanstack/router-core/ssr/client' +import { + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' +import type { AnyRouteMatch } from '@tanstack/router-core' +import type { TsrSsrGlobal } from '@tanstack/router-core/ssr/client' + +function bootstrap( + matches: Array<{ + match: AnyRouteMatch + status: AnyRouteMatch['status'] + ssr: AnyRouteMatch['ssr'] + data?: unknown + error?: unknown + }>, +): void { + window.$_TSR = { + router: { + manifest: undefined, + matches: matches.map(({ match, status, ssr, data, error }) => ({ + i: match.id, + l: data, + e: error, + s: status, + ssr, + u: Date.now(), + })), + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + } as TsrSsrGlobal +} + +afterEach(() => { + cleanup() + delete window.$_TSR +}) + +describe('hydration terminal lane', () => { + test('keeps server data while loading only the missing client suffix', async () => { + const rootRoute = createRootRoute({ component: Outlet }) + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: () => 'client-parent', + component: () => ( + <> +
{parentRoute.useLoaderData()}
+ + + ), + }) + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + ssr: false, + loader: () => 'client-child', + component: () =>
{childRoute.useLoaderData()}
, + }) + const router = createRouter({ + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + }) + const matches = router.matchRoutes(router.state.location) + bootstrap([ + { match: matches[0]!, status: 'success', ssr: true }, + { + match: matches[1]!, + status: 'success', + ssr: true, + data: 'server-parent', + }, + { match: matches[2]!, status: 'pending', ssr: false }, + ]) + + await hydrate(router) + render() + + expect(await screen.findByText('server-parent')).toBeInTheDocument() + expect(await screen.findByText('client-child')).toBeInTheDocument() + expect(screen.queryByText('client-parent')).not.toBeInTheDocument() + }) + + test('does not render serialized descendants below a server error', async () => { + const rootRoute = createRootRoute({ component: Outlet }) + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + errorComponent: ({ error }) =>
Parent failed: {error.message}
, + component: Outlet, + }) + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + component: () =>
Child must stay omitted
, + }) + const router = createRouter({ + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + }) + const matches = router.matchRoutes(router.state.location) + bootstrap([ + { match: matches[0]!, status: 'success', ssr: true }, + { + match: matches[1]!, + status: 'error', + ssr: true, + error: new Error('server boom'), + }, + { match: matches[2]!, status: 'success', ssr: true }, + ]) + + await hydrate(router) + render() + + expect(await screen.findByText('Parent failed: server boom')).toBeVisible() + expect( + screen.queryByText('Child must stay omitted'), + ).not.toBeInTheDocument() + }) +}) 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..7694b1d57e --- /dev/null +++ b/packages/react-router/tests/issue-7051-force-pending-suspense.test.tsx @@ -0,0 +1,92 @@ +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. A forced-pending reload must keep showing its pending +// fallback until fresh content commits instead of exposing the error boundary. +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 + let invalidation!: Promise + act(() => { + invalidation = 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(() => invalidation) + 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..666f1d3e4b --- /dev/null +++ b/packages/react-router/tests/issue-7367-pending-min-redirect.test.tsx @@ -0,0 +1,78 @@ +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') + 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..3583190d79 --- /dev/null +++ b/packages/react-router/tests/issue-7457-redirect-chain-first-load.test.tsx @@ -0,0 +1,109 @@ +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') + 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..eb31703b0a --- /dev/null +++ b/packages/react-router/tests/issue-7638-invalidate-transition-error.test.tsx @@ -0,0 +1,130 @@ +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.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) + }) + + // 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'), + ), + ) + 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/react-router/tests/loaders.test.tsx b/packages/react-router/tests/loaders.test.tsx index d9b5968d72..14518a66f7 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 UI when loaders finish before their pending delays', async () => { const defaultPendingComponentOnMountMock = vi.fn() const nestedPendingComponentOnMountMock = vi.fn() const fooPendingComponentOnMountMock = vi.fn() @@ -716,7 +716,6 @@ test('clears pendingTimeout when match resolves', async () => { }) render() - await act(() => router.latestLoadPromise) const linkToFoo = await screen.findByTestId('link-to-foo') fireEvent.click(linkToFoo) const fooElement = await screen.findByText('Nested Foo page') @@ -757,7 +756,7 @@ test('throw abortError from loader upon initial load with basepath', async () => expect(window.location.pathname.startsWith('/app')).toBe(true) }) -test('cancelMatches after pending timeout', async () => { +test('navigating away from a pending route aborts its loader', async () => { function getPendingComponent(onMount: () => void) { const PendingComponent = () => { useEffect(() => { @@ -811,7 +810,6 @@ test('cancelMatches after pending timeout', async () => { const routeTree = rootRoute.addChildren([fooRoute, barRoute]) const router = createRouter({ routeTree, history }) render() - await act(() => router.latestLoadPromise) const fooLink = await screen.findByTestId('link-to-foo') fireEvent.click(fooLink) await sleep(WAIT_TIME * 30) @@ -912,30 +910,25 @@ test('reproducer for #6388 - rapid navigation between parameterized routes shoul }) render() - await act(() => router.latestLoadPromise) - - const pendingComponent = screen.findByTestId('pending-component') expect(await screen.findByTestId('home-page')).toBeInTheDocument() - const param1Link = await screen.findByTestId('link-to-param-1') fireEvent.click(param1Link) - expect(await pendingComponent).toBeInTheDocument() + expect(await screen.findByTestId('pending-component')).toBeInTheDocument() const param2Link = await screen.findByTestId('link-to-param-2') fireEvent.click(param2Link) - expect(await pendingComponent).toBeInTheDocument() + expect(await screen.findByTestId('pending-component')).toBeInTheDocument() fireEvent.click(param1Link) - expect(await pendingComponent).toBeInTheDocument() + expect(await screen.findByTestId('pending-component')).toBeInTheDocument() - await act(() => router.latestLoadPromise) + const paramPage = await screen.findByTestId('param-page') expect(onAbortMock).toHaveBeenCalled() expect(errorComponentRenderCount).not.toHaveBeenCalled() expect(screen.queryByTestId('error-component')).not.toBeInTheDocument() - expect(await pendingComponent).not.toBeInTheDocument() + expect(screen.queryByTestId('pending-component')).not.toBeInTheDocument() - const paramPage = await screen.findByTestId('param-page') expect(paramPage).toBeInTheDocument() expect(paramPage).toHaveTextContent('Param Component 1 Done') expect(loaderCompleteMock).toHaveBeenCalled() diff --git a/packages/react-router/tests/on-rendered-same-href-state.test.tsx b/packages/react-router/tests/on-rendered-same-href-state.test.tsx new file mode 100644 index 0000000000..88e097a904 --- /dev/null +++ b/packages/react-router/tests/on-rendered-same-href-state.test.tsx @@ -0,0 +1,50 @@ +import { act } from 'react' +import { cleanup, render, screen, waitFor } from '@testing-library/react' +import { afterEach, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { + Outlet, + RouterProvider, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +afterEach(() => { + cleanup() +}) + +test('onRendered fires for a same-href navigation with a new history key', async () => { + const rootRoute = createRootRoute({ component: () => }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
Index
, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render() + expect(await screen.findByText('Index')).toBeInTheDocument() + + const onRendered = vi.fn() + const unsubscribe = router.subscribe('onRendered', onRendered) + await act(() => + router.navigate({ + to: '/', + state: { sameHrefState: true } as any, + }), + ) + await waitFor(() => expect(onRendered).toHaveBeenCalledTimes(1)) + + const event = onRendered.mock.calls[0]![0] + expect(event.fromLocation?.state.sameHrefState).toBeUndefined() + expect(event.toLocation.state.sameHrefState).toBe(true) + expect(event.fromLocation?.href).toBe('/') + expect(event.toLocation.href).toBe('/') + expect(event.hrefChanged).toBe(false) + + unsubscribe() +}) diff --git a/packages/react-router/tests/pending-fallback-promise-replacement.test.tsx b/packages/react-router/tests/pending-fallback-promise-replacement.test.tsx new file mode 100644 index 0000000000..fc72418bf4 --- /dev/null +++ b/packages/react-router/tests/pending-fallback-promise-replacement.test.tsx @@ -0,0 +1,112 @@ +import * as React from 'react' +import { act } from 'react' +import { afterEach, expect, test, vi } from 'vitest' +import { cleanup, render, screen } from '@testing-library/react' +import { createControlledPromise } from '@tanstack/router-core' +import { + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +afterEach(() => { + vi.useRealTimers() + cleanup() +}) + +test('a mounted pending fallback follows a replacement load promise for the same match', async () => { + const firstReload = createControlledPromise() + const secondReload = createControlledPromise() + const reloads = [firstReload, secondReload] + let loaderCall = 0 + + const rootRoute = createRootRoute({ + component: () => , + }) + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + pendingMs: 0, + pendingMinMs: 100, + pendingComponent: () =>
Loading page...
, + loader: () => { + const generation = ++loaderCall + const gate = reloads[generation - 2] + return gate ? gate.then(() => ({ generation })) : { generation } + }, + component: () => ( +
+ Generation {pageRoute.useLoaderData().generation} +
+ ), + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + render() + expect(await screen.findByText('Generation 1')).toBeInTheDocument() + + vi.useFakeTimers() + + let firstInvalidation!: Promise + await act(async () => { + firstInvalidation = router.invalidate({ forcePending: true }) + await vi.advanceTimersByTimeAsync(0) + }) + + expect(loaderCall).toBe(2) + expect(screen.getByTestId('pending')).toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(25) + }) + + let secondInvalidation!: Promise + await act(async () => { + secondInvalidation = router.invalidate({ forcePending: true }) + await vi.advanceTimersByTimeAsync(0) + }) + + expect(loaderCall).toBe(3) + + await act(async () => { + firstReload.resolve() + await Promise.resolve() + }) + + // Completing the superseded generation cannot release the currently mounted + // fallback or restore its stale loader data. + expect(screen.getByTestId('pending')).toBeInTheDocument() + expect(screen.queryByText('Generation 2')).not.toBeInTheDocument() + + let secondSettled = false + void secondInvalidation.then(() => { + secondSettled = true + }) + await act(async () => { + secondReload.resolve() + await Promise.resolve() + }) + + expect(secondSettled).toBe(false) + expect(screen.getByTestId('pending')).toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(74) + }) + expect(secondSettled).toBe(false) + expect(screen.getByTestId('pending')).toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(1) + }) + await Promise.all([firstInvalidation, secondInvalidation]) + + expect(screen.getByText('Generation 3')).toBeInTheDocument() + expect(screen.queryByTestId('pending')).not.toBeInTheDocument() +}) 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..2198e81348 --- /dev/null +++ b/packages/react-router/tests/preloaded-mount-resolution.test.tsx @@ -0,0 +1,96 @@ +import { afterEach, beforeEach, 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 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) + + try { + // Load fully settles before the provider mounts — the exact shape of the + // memory benchmark's mount/unmount cycle. + await router.load() + reactRoot.render() + + await until( + () => container.querySelector('[data-testid="home"]') !== null, + 'route content to render', + ) + 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() + container.remove() + } +}) diff --git a/packages/react-router/tests/redirect.test.tsx b/packages/react-router/tests/redirect.test.tsx index cc15f0da36..11ff5696b9 100644 --- a/packages/react-router/tests/redirect.test.tsx +++ b/packages/react-router/tests/redirect.test.tsx @@ -14,7 +14,6 @@ import { Outlet, RouterProvider, createBrowserHistory, - createMemoryHistory, createRootRoute, createRoute, createRouter, @@ -45,6 +44,89 @@ const WAIT_TIME = 100 describe('redirect', () => { describe('SPA', () => { configure({ reactStrictMode: true }) + + test('allows a same-location redirect to settle after a side effect', async () => { + let firstLoad = true + const rootRoute = createRootRoute() + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + loader: () => { + if (firstLoad) { + firstLoad = false + throw redirect({ to: '/' }) + } + }, + component: () =>
Index page
, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history, + }) + + render() + + expect(await screen.findByText('Index page')).toBeInTheDocument() + expect(window.location.pathname).toBe('/') + }) + + test('renders an error for a same-location redirect cycle', async () => { + const rootRoute = createRootRoute() + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + loader: () => { + throw redirect({ to: '/' }) + }, + errorComponent: ({ error }) =>
{error.message}
, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history, + }) + + render() + + expect( + await screen.findByText('Redirect cycle detected'), + ).toBeInTheDocument() + expect(window.location.pathname).toBe('/') + }) + + test('renders an error for an alternating redirect cycle', async () => { + const rootRoute = createRootRoute() + const errorComponent = ({ error }: { error: any }) => ( +
{error.message}
+ ) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + loader: () => { + throw redirect({ to: '/other' }) + }, + errorComponent, + }) + const otherRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/other', + loader: () => { + throw redirect({ to: '/' }) + }, + errorComponent, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, otherRoute]), + history, + }) + + render() + + expect( + await screen.findByText('Redirect cycle detected'), + ).toBeInTheDocument() + expect(['/', '/other']).toContain(window.location.pathname) + }) + test('when `redirect` is thrown in `beforeLoad`', async () => { const nestedLoaderMock = vi.fn() const nestedFooLoaderMock = vi.fn() @@ -155,7 +237,6 @@ describe('redirect', () => { expect(await screen.findByTestId('lazy-route-page')).toBeInTheDocument() expect(screen.queryByTestId('pending')).not.toBeInTheDocument() expect(router.state.location.href).toBe('/posts') - expect(router.state.status).toBe('idle') expect(consoleError).not.toHaveBeenCalled() }) @@ -311,116 +392,4 @@ describe('redirect', () => { expect(window.location.pathname).toBe('/final') }) }) - - describe('SSR', () => { - test('when `redirect` is thrown in `beforeLoad`', async () => { - const rootRoute = createRootRoute() - - const indexRoute = createRoute({ - path: '/', - getParentRoute: () => rootRoute, - beforeLoad: () => { - throw redirect({ - to: '/about', - }) - }, - }) - - const aboutRoute = createRoute({ - path: '/about', - getParentRoute: () => rootRoute, - component: () => { - return 'About' - }, - }) - - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute, aboutRoute]), - // Mock server mode - isServer: true, - history: createMemoryHistory({ - initialEntries: ['/'], - }), - }) - - await router.load() - - expect(router.state.redirect).toBeDefined() - expect(router.state.redirect).toBeInstanceOf(Response) - const redirectResponse = router.state.redirect! - - expect(redirectResponse.options).toEqual({ - _fromLocation: expect.objectContaining({ - hash: '', - href: '/', - pathname: '/', - search: {}, - searchStr: '', - }), - to: '/about', - href: '/about', - statusCode: 307, - }) - }) - - test('when `redirect` is thrown in `loader`', async () => { - const rootRoute = createRootRoute() - - const indexRoute = createRoute({ - path: '/', - getParentRoute: () => rootRoute, - loader: () => { - throw redirect({ - to: '/about', - }) - }, - }) - - const aboutRoute = createRoute({ - path: '/about', - getParentRoute: () => rootRoute, - component: () => { - return 'About' - }, - }) - - const router = createRouter({ - history: createMemoryHistory({ - initialEntries: ['/'], - }), - routeTree: rootRoute.addChildren([indexRoute, aboutRoute]), - // Mock server mode - isServer: true, - }) - - await router.load() - - const currentRedirect = router.state.redirect - - expect(currentRedirect).toBeDefined() - expect(currentRedirect).toBeInstanceOf(Response) - const redirectResponse = currentRedirect! - expect(redirectResponse.status).toEqual(307) - expect(redirectResponse.headers.get('Location')).toEqual('/about') - expect(redirectResponse.options).toEqual({ - _fromLocation: { - external: false, - hash: '', - href: '/', - publicHref: '/', - pathname: '/', - search: {}, - searchStr: '', - state: { - __TSR_index: 0, - __TSR_key: redirectResponse.options._fromLocation!.state.__TSR_key, - key: redirectResponse.options._fromLocation!.state.key, - }, - }, - href: '/about', - to: '/about', - statusCode: 307, - }) - }) - }) }) diff --git a/packages/react-router/tests/root-pending-min.test.tsx b/packages/react-router/tests/root-pending-min.test.tsx new file mode 100644 index 0000000000..24ead693bb --- /dev/null +++ b/packages/react-router/tests/root-pending-min.test.tsx @@ -0,0 +1,375 @@ +import * as React from 'react' +import { act, cleanup, render, screen } from '@testing-library/react' +import { hydrateRoot } from 'react-dom/client' +import { renderToString } from 'react-dom/server' +import { afterEach, expect, test, vi } from 'vitest' +import { hydrate } from '../src/ssr/client' +import { + Outlet, + RouterProvider, + createControlledPromise, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +const testCleanups: Array<() => void | Promise> = [] + +afterEach(async () => { + while (testCleanups.length) { + await testCleanups.pop()!() + } + cleanup() + vi.useRealTimers() + delete window.$_TSR +}) + +test('root pending fallback remains visible through pendingMinMs', async () => { + vi.useFakeTimers() + + const loaderGate = createControlledPromise() + const rootRoute = createRootRoute({ + pendingMs: 0, + pendingMinMs: 100, + pendingComponent: () =>
Pending
, + loader: () => loaderGate, + component: () =>
Loaded
, + }) + const router = createRouter({ + routeTree: rootRoute, + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render() + + await act(async () => { + await vi.advanceTimersByTimeAsync(0) + }) + expect(screen.getByTestId('root-pending')).toBeInTheDocument() + expect(screen.queryByTestId('root-content')).not.toBeInTheDocument() + + loaderGate.resolve('loaded') + + await act(async () => { + await vi.advanceTimersByTimeAsync(99) + }) + expect(screen.getByTestId('root-pending')).toBeInTheDocument() + expect(screen.queryByTestId('root-content')).not.toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(1) + }) + expect(screen.queryByTestId('root-pending')).not.toBeInTheDocument() + expect(screen.getByTestId('root-content')).toBeInTheDocument() +}) + +test('hydrated routers show the root pending fallback through pendingMinMs on a later reload', async () => { + const reloadGate = createControlledPromise() + const rootLoader = vi.fn(() => reloadGate.then(() => ({ generation: 2 }))) + const rootRoute = createRootRoute({ + pendingMs: 0, + pendingMinMs: 100, + pendingComponent: () =>
Pending
, + loader: rootLoader, + component: () => ( +
+ Generation {rootRoute.useLoaderData().generation} +
+ ), + }) + const router = createRouter({ + routeTree: rootRoute, + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + const rootMatch = router.matchRoutes(router.latestLocation)[0]! + + // This is the same public bootstrap shape produced by the server. Calling + // hydrate() ensures router.ssr and the active match are established through + // the real client hydration path rather than by mutating router stores. + window.$_TSR = { + router: { + manifest: { routes: {} }, + dehydratedData: {}, + matches: [ + { + i: rootMatch.id, + s: 'success', + ssr: true, + l: { generation: 1 }, + u: Date.now(), + }, + ], + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + initialized: false, + } + + await hydrate(router) + expect(router.ssr).toBeDefined() + + render() + expect(screen.getByTestId('root-content')).toHaveTextContent('Generation 1') + expect(rootLoader).not.toHaveBeenCalled() + + vi.useFakeTimers() + + let invalidation!: Promise + await act(async () => { + invalidation = router.invalidate({ forcePending: true }) + await vi.advanceTimersByTimeAsync(0) + }) + + expect(rootLoader).toHaveBeenCalledTimes(1) + expect(screen.getByTestId('root-pending')).toBeInTheDocument() + expect(screen.queryByTestId('root-content')).not.toBeInTheDocument() + + await act(async () => { + reloadGate.resolve() + await Promise.resolve() + }) + + await act(async () => { + await vi.advanceTimersByTimeAsync(99) + }) + expect(screen.getByTestId('root-pending')).toBeInTheDocument() + expect(screen.queryByTestId('root-content')).not.toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(1) + await invalidation + }) + expect(screen.queryByTestId('root-pending')).not.toBeInTheDocument() + expect(screen.getByTestId('root-content')).toHaveTextContent('Generation 2') +}) + +test('root pending fallback follows an overlapping forcePending generation', async () => { + const firstReload = createControlledPromise() + const secondReload = createControlledPromise() + const reloads = [firstReload, secondReload] + let loaderCall = 0 + + const rootRoute = createRootRoute({ + pendingMs: 0, + pendingMinMs: 100, + pendingComponent: () =>
Pending
, + loader: () => { + const generation = ++loaderCall + const gate = reloads[generation - 2] + return gate ? gate.then(() => ({ generation })) : { generation } + }, + component: () => ( +
+ Generation {rootRoute.useLoaderData().generation} +
+ ), + }) + const router = createRouter({ + routeTree: rootRoute, + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render() + expect(await screen.findByText('Generation 1')).toBeInTheDocument() + + vi.useFakeTimers() + + let firstInvalidation!: Promise + await act(async () => { + firstInvalidation = router.invalidate({ forcePending: true }) + await vi.advanceTimersByTimeAsync(0) + }) + + expect(loaderCall).toBe(2) + expect(screen.getByTestId('root-pending')).toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(25) + }) + + let secondInvalidation!: Promise + await act(async () => { + secondInvalidation = router.invalidate({ forcePending: true }) + await vi.advanceTimersByTimeAsync(0) + }) + + expect(loaderCall).toBe(3) + + await act(async () => { + firstReload.resolve() + await Promise.resolve() + }) + + expect(screen.getByTestId('root-pending')).toBeInTheDocument() + expect(screen.queryByText('Generation 2')).not.toBeInTheDocument() + + let secondSettled = false + void secondInvalidation.then(() => { + secondSettled = true + }) + await act(async () => { + secondReload.resolve() + await Promise.resolve() + }) + + expect(secondSettled).toBe(false) + expect(screen.getByTestId('root-pending')).toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(74) + }) + expect(secondSettled).toBe(false) + expect(screen.getByTestId('root-pending')).toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(1) + await Promise.all([firstInvalidation, secondInvalidation]) + }) + + expect(screen.getByTestId('root-content')).toHaveTextContent('Generation 3') + expect(screen.queryByTestId('root-pending')).not.toBeInTheDocument() +}) + +test('the root suspense boundary stays stable across hydration', async () => { + const mounts = vi.fn() + const unmounts = vi.fn() + const initializers = vi.fn(() => 'preserved') + + const rootRoute = createRootRoute({ + pendingComponent: () =>
Root pending
, + component: function RootComponent() { + const [value] = React.useState(initializers) + React.useEffect(() => { + mounts() + return unmounts + }, []) + return
{value}
+ }, + }) + const router = createRouter({ + routeTree: rootRoute, + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + await router.load() + + // Model the server render and the client router produced by hydrate(). The + // outer root boundary is intentionally absent from both trees, while the + // route's own pending boundary is present in both. + router.ssr = { manifest: { routes: {} } } + router.isServer = true + const html = renderToString() + router.isServer = false + expect(html).toContain('') + + const container = document.createElement('div') + container.innerHTML = html + document.body.appendChild(container) + const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}) + const root = hydrateRoot(container, ) + testCleanups.push(async () => { + await act(() => root.unmount()) + consoleError.mockRestore() + container.remove() + }) + + await act(async () => { + await Promise.resolve() + }) + + expect(container).toHaveTextContent('preserved') + // One initializer belongs to the server render and one to client + // hydration. The stable boundary must preserve that hydrated client + // instance instead of creating a third one. + expect(initializers).toHaveBeenCalledTimes(2) + expect(mounts).toHaveBeenCalledTimes(1) + expect(unmounts).not.toHaveBeenCalled() + expect(consoleError).not.toHaveBeenCalled() +}) + +test('the root pending boundary contains a route component that suspends during server rendering', async () => { + const gate = createControlledPromise() + const rootRoute = createRootRoute({ + pendingComponent: () =>
Server root pending
, + component: () => { + throw gate + }, + }) + const router = createRouter({ + routeTree: rootRoute, + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + router.isServer = true + await router.load() + + const html = renderToString() + + // renderToString cannot wait for Suspense, but the root route's stable + // boundary contains the suspension and emits its fallback. Streaming SSR + // can wait for the same boundary instead. + expect(html).toContain('Server root pending') +}) + +test('remounting a hydrated router loads a history change made while unmounted', async () => { + const rootRoute = createRootRoute({ component: Outlet }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
Index route
, + }) + const nextRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/next', + component: () =>
Next route
, + }) + const history = createMemoryHistory({ initialEntries: ['/'] }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, nextRoute]), + history, + }) + const matches = router.matchRoutes(router.latestLocation) + const now = Date.now() + + window.$_TSR = { + router: { + manifest: { routes: {} }, + dehydratedData: {}, + matches: matches.map((match) => ({ + i: match.id, + s: 'success' as const, + ssr: true, + u: now, + })), + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + initialized: false, + } + + await hydrate(router) + const firstRender = render() + expect(screen.getByText('Index route')).toBeInTheDocument() + + firstRender.unmount() + history.push('/next') + + const secondRender = render() + expect(await screen.findByText('Next route')).toBeInTheDocument() + expect(router.state.location.pathname).toBe('/next') + + secondRender.unmount() + history.push('/next', { marker: 'new history entry' }) + + render() + await vi.waitFor(() => { + expect((router.state.location.state as any).marker).toBe( + 'new history entry', + ) + }) +}) diff --git a/packages/react-router/tests/router.test.tsx b/packages/react-router/tests/router.test.tsx index cf3b1c11fe..59bf8c39bb 100644 --- a/packages/react-router/tests/router.test.tsx +++ b/packages/react-router/tests/router.test.tsx @@ -2205,11 +2205,13 @@ 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 () => { +describe('navigation outcomes', () => { + it('should recover from a not-found route when navigating to a valid route', async () => { const history = createMemoryHistory({ initialEntries: ['/'] }) - const rootRoute = createRootRoute() + const rootRoute = createRootRoute({ + notFoundComponent: () =>
Not Found
, + }) const indexRoute = createRoute({ getParentRoute: () => rootRoute, @@ -2228,23 +2230,21 @@ describe('statusCode', () => { render() - expect(router.state.statusCode).toBe(200) - await act(() => router.navigate({ to: '/' })) - expect(router.state.statusCode).toBe(200) + expect(await screen.findByText('Home')).toBeInTheDocument() await act(() => router.navigate({ to: '/non-existing' })) - expect(router.state.statusCode).toBe(404) + expect(await screen.findByText('Not Found')).toBeInTheDocument() await act(() => router.navigate({ to: '/valid' })) - expect(router.state.statusCode).toBe(200) + expect(await screen.findByText('Valid Route')).toBeInTheDocument() await act(() => router.navigate({ to: '/another-non-existing' })) - expect(router.state.statusCode).toBe(404) + expect(await screen.findByText('Not Found')).toBeInTheDocument() }) describe.each([true, false])( - 'status code is set when loader/beforeLoad throws (isAsync=%s)', + 'loader and beforeLoad outcomes are rendered (isAsync=%s)', async (isAsync) => { const throwingFun = isAsync ? (toThrow: () => void) => async () => { @@ -2259,7 +2259,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('should render notFoundComponent when a route loader throws a notFound()', async () => { const history = createMemoryHistory({ initialEntries: ['/'] }) const rootRoute = createRootRoute() @@ -2287,17 +2287,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('should render notFoundComponent when a route beforeLoad throws a notFound()', async () => { const history = createMemoryHistory({ initialEntries: ['/'] }) const rootRoute = createRootRoute({ @@ -2332,17 +2329,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('should render errorComponent when a route loader throws an Error', async () => { const history = createMemoryHistory({ initialEntries: ['/'] }) const rootRoute = createRootRoute() @@ -2368,15 +2362,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('should render errorComponent when a route beforeLoad throws an Error', async () => { const history = createMemoryHistory({ initialEntries: ['/'] }) const rootRoute = createRootRoute() @@ -2405,10 +2396,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() }) @@ -2417,7 +2405,7 @@ describe('statusCode', () => { }) describe('notFound in beforeLoad with pendingComponent', () => { - it('should transition router.state.status to idle when child beforeLoad throws notFound and parent has pendingComponent with pendingMs: 0', async () => { + it('renders notFound when child beforeLoad throws and parent has an immediate pending component', async () => { const history = createMemoryHistory({ initialEntries: ['/'] }) const rootRoute = createRootRoute({ @@ -2472,23 +2460,14 @@ describe('notFound in beforeLoad with pendingComponent', () => { render() - // Wait for initial load - await act(() => router.latestLoadPromise) - expect(router.state.status).toBe('idle') - expect(screen.getByTestId('home-page')).toBeInTheDocument() + expect(await screen.findByTestId('home-page')).toBeInTheDocument() - // Navigate to the child route that throws notFound in beforeLoad await act(() => router.navigate({ to: '/parent/child' })) - // The router status should eventually become idle - await waitFor(() => { - expect(router.state.status).toBe('idle') - }) - - expect(router.state.statusCode).toBe(404) + expect(await screen.findByText(/Not Found/)).toBeInTheDocument() }) - it('should transition router.state.status to idle when child beforeLoad throws notFound and parent has NO pendingComponent', async () => { + it('renders notFound when child beforeLoad throws without a pending component', async () => { const history = createMemoryHistory({ initialEntries: ['/'] }) const rootRoute = createRootRoute({ @@ -2521,19 +2500,14 @@ describe('notFound in beforeLoad with pendingComponent', () => { render() - await act(() => router.latestLoadPromise) - expect(router.state.status).toBe('idle') + expect(await screen.findByTestId('home-page')).toBeInTheDocument() await act(() => router.navigate({ to: '/child' })) - await waitFor(() => { - expect(router.state.status).toBe('idle') - }) - - expect(router.state.statusCode).toBe(404) + expect(await screen.findByText(/Not Found/)).toBeInTheDocument() }) - it('should transition router.state.status to idle when nested child beforeLoad throws notFound WITHOUT pendingComponent', async () => { + it('renders notFound when nested child beforeLoad throws without a pending component', async () => { const history = createMemoryHistory({ initialEntries: ['/'] }) const rootRoute = createRootRoute({ @@ -2580,19 +2554,14 @@ describe('notFound in beforeLoad with pendingComponent', () => { render() - await act(() => router.latestLoadPromise) - expect(router.state.status).toBe('idle') + expect(await screen.findByTestId('home-page')).toBeInTheDocument() await act(() => router.navigate({ to: '/parent/child' })) - await waitFor(() => { - expect(router.state.status).toBe('idle') - }) - - expect(router.state.statusCode).toBe(404) + expect(await screen.findByText(/Not Found/)).toBeInTheDocument() }) - it('should transition router.state.status to idle when child async beforeLoad throws notFound and parent has pendingComponent with pendingMs: 0', async () => { + it('renders notFound when async child beforeLoad throws and parent has an immediate pending component', async () => { const history = createMemoryHistory({ initialEntries: ['/'] }) const rootRoute = createRootRoute({ @@ -2648,20 +2617,11 @@ describe('notFound in beforeLoad with pendingComponent', () => { render() - // Wait for initial load - await act(() => router.latestLoadPromise) - expect(router.state.status).toBe('idle') - expect(screen.getByTestId('home-page')).toBeInTheDocument() + expect(await screen.findByTestId('home-page')).toBeInTheDocument() - // Navigate to the child route that throws notFound in beforeLoad await act(() => router.navigate({ to: '/parent/child' })) - // The router status should eventually become idle - await waitFor(() => { - expect(router.state.status).toBe('idle') - }) - - expect(router.state.statusCode).toBe(404) + expect(await screen.findByText(/Not Found/)).toBeInTheDocument() }) }) @@ -2867,7 +2827,6 @@ describe('Router rewrite functionality', () => { }, }) render() - await router.latestLoadPromise await waitFor(() => { expect(screen.getByTestId('component')).toHaveTextContent('test Users') }) @@ -3223,8 +3182,6 @@ describe('Router rewrite functionality', () => { const navigateBtn = await screen.findByTestId('navigate-btn') fireEvent.click(navigateBtn) - await router.latestLoadPromise - await screen.findByTestId('dashboard') // Router internal state should show the internal path @@ -3612,7 +3569,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..ec5901dfb9 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 () => { @@ -154,7 +154,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(2) }) test('sync beforeLoad', async () => { @@ -170,7 +170,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 +196,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/transactional-loading.test.tsx b/packages/react-router/tests/transactional-loading.test.tsx new file mode 100644 index 0000000000..001258f1f5 --- /dev/null +++ b/packages/react-router/tests/transactional-loading.test.tsx @@ -0,0 +1,210 @@ +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' +import { + Link, + Outlet, + RouterProvider, + createBrowserHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' +import type { RouterHistory } from '../src' + +type Deferred = { + promise: Promise + resolve: (value: T) => void +} + +function deferred(): Deferred { + let resolve!: (value: T) => void + const promise = new Promise((resolver) => { + resolve = resolver + }) + return { promise, resolve } +} + +let history: RouterHistory + +beforeEach(() => { + history = createBrowserHistory() +}) + +afterEach(() => { + history.destroy() + window.history.replaceState(null, 'root', '/') + cleanup() + vi.useRealTimers() +}) + +describe('transactional route loading', () => { + test('publishes a parent and child background refresh atomically after the child observes fresh parent data', async () => { + const parentRefresh = deferred() + const childRefresh = deferred() + const childObservedFreshParent = deferred() + let parentLoads = 0 + let childLoads = 0 + + const rootRoute = createRootRoute({ + component: () => ( + <> + Other route + Data route + + + ), + }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
Home route
, + }) + const otherRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/other', + component: () =>
Other route content
, + }) + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + staleTime: 0, + gcTime: 60_000, + loader: async () => { + parentLoads += 1 + if (parentLoads === 1) { + return 'parent-v1' + } + return parentRefresh.promise + }, + component: () => ( + <> +
{parentRoute.useLoaderData()}
+ + + ), + }) + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + staleTime: 0, + gcTime: 60_000, + loader: async ({ parentMatchPromise }) => { + childLoads += 1 + const parentMatch = await parentMatchPromise + const parentData = parentMatch.loaderData as string + if (childLoads > 1) { + childObservedFreshParent.resolve(undefined) + await childRefresh.promise + } + return `child-saw-${parentData}` + }, + component: () =>
{childRoute.useLoaderData()}
, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + otherRoute, + parentRoute.addChildren([childRoute]), + ]), + history, + }) + + render() + + expect(await screen.findByText('Home route')).toBeInTheDocument() + fireEvent.click(screen.getByText('Data route')) + + expect(await screen.findByText('parent-v1')).toBeInTheDocument() + expect(await screen.findByText('child-saw-parent-v1')).toBeInTheDocument() + + await new Promise((resolve) => setTimeout(resolve, 2)) + fireEvent.click(screen.getByText('Other route')) + expect(await screen.findByText('Other route content')).toBeInTheDocument() + + await new Promise((resolve) => setTimeout(resolve, 2)) + fireEvent.click(screen.getByText('Data route')) + + expect(await screen.findByText('parent-v1')).toBeInTheDocument() + expect(await screen.findByText('child-saw-parent-v1')).toBeInTheDocument() + + await act(async () => { + parentRefresh.resolve('parent-v2') + await childObservedFreshParent.promise + }) + + expect(screen.getByText('parent-v1')).toBeInTheDocument() + expect(screen.getByText('child-saw-parent-v1')).toBeInTheDocument() + expect(screen.queryByText('parent-v2')).not.toBeInTheDocument() + expect(screen.queryByText('child-saw-parent-v2')).not.toBeInTheDocument() + + await act(async () => { + childRefresh.resolve(undefined) + await Promise.resolve() + }) + + expect(await screen.findByText('parent-v2')).toBeInTheDocument() + expect(await screen.findByText('child-saw-parent-v2')).toBeInTheDocument() + expect(screen.queryByText('parent-v1')).not.toBeInTheDocument() + expect(screen.queryByText('child-saw-parent-v1')).not.toBeInTheDocument() + }) + + test('renders a leaf error at the leaf boundary when its background refresh fails', async () => { + let loads = 0 + const rootRoute = createRootRoute({ + component: () => ( + <> +
Root shell
+ + + ), + }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () => Open child, + }) + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + component: () => ( + <> +
Parent shell
+ + + ), + }) + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: { + staleReloadMode: 'background', + handler: () => { + loads++ + if (loads > 1) { + throw new Error('background refresh failed') + } + return 'child data' + }, + }, + component: () =>
{childRoute.useLoaderData()}
, + errorComponent: () =>
Child refresh failed
, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + ]), + history, + }) + + render() + fireEvent.click(await screen.findByText('Open child')) + expect(await screen.findByText('child data')).toBeInTheDocument() + + await act(() => router.invalidate()) + + expect(await screen.findByText('Child refresh failed')).toBeInTheDocument() + expect(screen.getByText('Root shell')).toBeInTheDocument() + expect(screen.getByText('Parent shell')).toBeInTheDocument() + }) +}) diff --git a/packages/react-router/tests/transitioner-listener-errors.test.tsx b/packages/react-router/tests/transitioner-listener-errors.test.tsx new file mode 100644 index 0000000000..f380f68a88 --- /dev/null +++ b/packages/react-router/tests/transitioner-listener-errors.test.tsx @@ -0,0 +1,77 @@ +import * as React from 'react' +import { act, cleanup, render, screen } from '@testing-library/react' +import { afterEach, expect, test, vi } from 'vitest' +import { + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +const testCleanups: Array<() => void | Promise> = [] + +afterEach(async () => { + while (testCleanups.length) { + await testCleanups.pop()!() + } + cleanup() +}) + +test('a throwing load-event listener cannot interrupt route hooks or later navigations', async () => { + const firstOnEnter = vi.fn() + const secondOnEnter = vi.fn() + const listenerError = new Error('onLoad listener failed') + const laterOnLoad = vi.fn() + + const rootRoute = createRootRoute({ component: Outlet }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
Index route
, + }) + const firstRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/first', + onEnter: firstOnEnter, + component: () =>
First route
, + }) + const secondRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/second', + onEnter: secondOnEnter, + component: () =>
Second route
, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, firstRoute, secondRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render() + expect(await screen.findByText('Index route')).toBeInTheDocument() + + const unsubscribe = router.subscribe('onLoad', (event) => { + if (event.toLocation.pathname === '/first') { + throw listenerError + } + }) + const unsubscribeLater = router.subscribe('onLoad', (event) => { + if (event.toLocation.pathname !== '/') { + laterOnLoad(event) + } + }) + testCleanups.push(unsubscribeLater) + + await act(() => router.navigate({ to: '/first' })) + + expect(screen.getByText('First route')).toBeInTheDocument() + + unsubscribe() + await act(() => router.navigate({ to: '/second' })) + + expect(screen.getByText('Second route')).toBeInTheDocument() + expect(firstOnEnter).toHaveBeenCalledTimes(1) + expect(secondOnEnter).toHaveBeenCalledTimes(1) + expect(laterOnLoad).toHaveBeenCalledTimes(2) +}) diff --git a/packages/react-router/tests/transitioner-render-ack.test.tsx b/packages/react-router/tests/transitioner-render-ack.test.tsx new file mode 100644 index 0000000000..a60505eb5b --- /dev/null +++ b/packages/react-router/tests/transitioner-render-ack.test.tsx @@ -0,0 +1,85 @@ +import { StrictMode, act } from 'react' +import { cleanup, render, screen } from '@testing-library/react' +import { afterEach, expect, test } from 'vitest' +import { + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +afterEach(() => { + cleanup() +}) + +test('same-location invalidation resolves after its refreshed DOM commits', async () => { + let generation = 0 + const rootRoute = createRootRoute({ component: Outlet }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + loader: { + staleReloadMode: 'blocking', + handler: () => ++generation, + }, + component: () =>
Generation {indexRoute.useLoaderData()}
, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render() + expect(await screen.findByText('Generation 1')).toBeInTheDocument() + + const refreshedDomWasVisible: Array = [] + const unsubscribe = router.subscribe('onResolved', () => { + refreshedDomWasVisible.push(screen.queryByText('Generation 2') !== null) + }) + + await act(() => router.invalidate()) + expect(await screen.findByText('Generation 2')).toBeInTheDocument() + expect(refreshedDomWasVisible).toEqual([true]) + + unsubscribe() +}) + +test('StrictMode effect replay preserves renderer commit sequencing', async () => { + const rootRoute = createRootRoute({ component: Outlet }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
Index
, + }) + const nextRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/next', + component: () =>
Next
, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, nextRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render( + + + , + ) + expect(await screen.findByText('Index')).toBeInTheDocument() + + const resolvedWithDestination = new Promise((resolve) => { + const unsubscribe = router.subscribe('onResolved', (event) => { + if (event.toLocation.pathname === '/next') { + expect(screen.getByText('Next')).toBeInTheDocument() + unsubscribe() + resolve() + } + }) + }) + + await act(() => router.navigate({ to: '/next' })) + await resolvedWithDestination +}) diff --git a/packages/react-router/tests/transitioner-router-swap.test.tsx b/packages/react-router/tests/transitioner-router-swap.test.tsx new file mode 100644 index 0000000000..32ca3be816 --- /dev/null +++ b/packages/react-router/tests/transitioner-router-swap.test.tsx @@ -0,0 +1,100 @@ +import { act } from 'react' +import { cleanup, render, screen, waitFor } from '@testing-library/react' +import { afterEach, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { + Outlet, + RouterProvider, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +afterEach(() => { + cleanup() +}) + +function deferred() { + let resolve!: () => void + const promise = new Promise((r) => { + resolve = r + }) + return { promise, resolve } +} + +test('a load finishing on an old router does not resolve the replacement router', async () => { + const slowLoader = deferred() + const rootA = createRootRoute({ component: () => }) + const indexA = createRoute({ + getParentRoute: () => rootA, + path: '/', + component: () =>
Router A
, + }) + const slowA = createRoute({ + getParentRoute: () => rootA, + path: '/slow', + loader: () => slowLoader.promise, + component: () =>
Slow A
, + }) + const routerA = createRouter({ + routeTree: rootA.addChildren([indexA, slowA]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + const rootB = createRootRoute({ component: () => }) + const indexB = createRoute({ + getParentRoute: () => rootB, + path: '/b', + component: () =>
Router B
, + }) + const routerB = createRouter({ + routeTree: rootB.addChildren([indexB]), + history: createMemoryHistory({ initialEntries: ['/b'] }), + }) + + const view = render() + expect(await screen.findByText('Router A')).toBeInTheDocument() + + let oldNavigation!: Promise + act(() => { + oldNavigation = routerA.navigate({ to: '/slow' }) + }) + await waitFor(() => expect(routerA.state.isLoading).toBe(true)) + + const onRendered = vi.fn() + const unsubscribeRendered = routerB.subscribe('onRendered', onRendered) + view.rerender() + expect(await screen.findByText('Router B')).toBeInTheDocument() + await waitFor(() => expect(routerB.state.status).toBe('idle')) + await waitFor(() => expect(onRendered).toHaveBeenCalledTimes(1)) + expect(onRendered.mock.calls[0]![0].fromLocation).toBeUndefined() + expect(onRendered.mock.calls[0]![0].toLocation.pathname).toBe('/b') + + const onLoad = vi.fn() + const onBeforeRouteMount = vi.fn() + const onResolved = vi.fn() + const unsubscribers = [ + routerB.subscribe('onLoad', onLoad), + routerB.subscribe('onBeforeRouteMount', onBeforeRouteMount), + routerB.subscribe('onResolved', onResolved), + ] + + slowLoader.resolve() + await act(() => oldNavigation) + + // Flush the old transition's state update and the replacement provider's + // layout effects. Router B did no work during this interval. + await act(async () => {}) + + expect(onLoad).not.toHaveBeenCalled() + expect(onBeforeRouteMount).not.toHaveBeenCalled() + expect(onResolved).not.toHaveBeenCalled() + expect(routerA.state.isLoading).toBe(false) + expect(routerA.state.matches.at(-1)?.pathname).toBe('/slow') + expect(screen.getByText('Router B')).toBeInTheDocument() + expect(routerB.state.status).toBe('idle') + expect(routerB.state.resolvedLocation?.pathname).toBe('/b') + + unsubscribeRendered() + unsubscribers.forEach((unsubscribe) => unsubscribe()) +}) diff --git a/packages/react-router/tests/useNavigate.test.tsx b/packages/react-router/tests/useNavigate.test.tsx index a473e2c8b2..c255399da3 100644 --- a/packages/react-router/tests/useNavigate.test.tsx +++ b/packages/react-router/tests/useNavigate.test.tsx @@ -7,6 +7,7 @@ import { fireEvent, render, screen, + waitFor, } from '@testing-library/react' import { z } from 'zod' @@ -2415,9 +2416,9 @@ describe.each([{ basepath: '' }, { basepath: '/basepath' }])( // Click the link and ensure the new location fireEvent.click(parentLink) - await router.latestLoadPromise - - expect(window.location.pathname).toBe(`${basepath}/a`) + await waitFor(() => { + expect(window.location.pathname).toBe(`${basepath}/a`) + }) }) test('should navigate to the parent route and keep params', async () => { @@ -2435,9 +2436,9 @@ describe.each([{ basepath: '' }, { basepath: '/basepath' }])( // Click the link and ensure the new location fireEvent.click(parentLink) - await router.latestLoadPromise - - expect(window.location.pathname).toBe(`${basepath}/param/foo/a`) + await waitFor(() => { + expect(window.location.pathname).toBe(`${basepath}/param/foo/a`) + }) }) test('should navigate to the parent route and change params', async () => { @@ -2457,9 +2458,9 @@ describe.each([{ basepath: '' }, { basepath: '/basepath' }])( // Click the link and ensure the new location fireEvent.click(parentLink) - await router.latestLoadPromise - - expect(window.location.pathname).toBe(`${basepath}/param/bar/a`) + await waitFor(() => { + expect(window.location.pathname).toBe(`${basepath}/param/bar/a`) + }) }) test('should navigate to a relative link based on render location with basepath', async () => { @@ -2476,9 +2477,9 @@ describe.each([{ basepath: '' }, { basepath: '/basepath' }])( // Click the link and ensure the new location fireEvent.click(relativeLink) - await router.latestLoadPromise - - expect(window.location.pathname).toBe(`${basepath}/param/foo/a`) + await waitFor(() => { + expect(window.location.pathname).toBe(`${basepath}/param/foo/a`) + }) }) test('should navigate to a parent link based on render location', async () => { @@ -2497,9 +2498,9 @@ describe.each([{ basepath: '' }, { basepath: '/basepath' }])( // Click the link and ensure the new location fireEvent.click(relativeLink) - await router.latestLoadPromise - - expect(window.location.pathname).toBe(`${basepath}/param/foo`) + await waitFor(() => { + expect(window.location.pathname).toBe(`${basepath}/param/foo`) + }) }) test('should navigate to a parent link based on active location', async () => { @@ -2515,9 +2516,9 @@ describe.each([{ basepath: '' }, { basepath: '/basepath' }])( // Click the link and ensure the new location fireEvent.click(relativeLink) - await router.latestLoadPromise - - expect(window.location.pathname).toBe(`${basepath}/param/foo/a`) + await waitFor(() => { + expect(window.location.pathname).toBe(`${basepath}/param/foo/a`) + }) }) test('should navigate to same route with different params', async () => { @@ -2527,15 +2528,16 @@ describe.each([{ basepath: '' }, { basepath: '/basepath' }])( await act(async () => { history.push(`${basepath}/param/foo/a/b`) - await router.latestLoadPromise }) - expect(window.location.pathname).toBe(`${basepath}/param/foo/a/b`) + await waitFor(() => { + expect(window.location.pathname).toBe(`${basepath}/param/foo/a/b`) + }) - const btn = screen.getByTestId('btn-param-bar') + const btn = await screen.findByTestId('btn-param-bar') fireEvent.click(btn) - await router.latestLoadPromise - - expect(window.location.pathname).toBe(`${basepath}/param/bar/a/b`) + await waitFor(() => { + expect(window.location.pathname).toBe(`${basepath}/param/bar/a/b`) + }) }) }, ) diff --git a/packages/router-core/src/Matches.ts b/packages/router-core/src/Matches.ts index 852d186b67..78cd7d3aab 100644 --- a/packages/router-core/src/Matches.ts +++ b/packages/router-core/src/Matches.ts @@ -9,7 +9,7 @@ import type { RouteIds, } from './routeInfo' import type { AnyRouter, RegisteredRouter, SSROption } from './router' -import type { Constrain, ControlledPromise } from './utils' +import type { Constrain } from './utils' export type AnyMatchAndValue = { match: any; value: any } @@ -137,20 +137,6 @@ export interface RouteMatch< paramsError: unknown searchError: unknown updatedAt: number - _nonReactive: { - /** @internal */ - beforeLoadPromise?: ControlledPromise - /** @internal */ - loaderPromise?: ControlledPromise - /** @internal */ - pendingTimeout?: ReturnType - loadPromise?: ControlledPromise - displayPendingPromise?: Promise - minPendingPromise?: ControlledPromise - dehydrated?: boolean - /** @internal */ - error?: unknown - } loaderData?: TLoaderData /** @internal */ __routeContext?: Record @@ -170,8 +156,6 @@ export interface RouteMatch< staticData: StaticDataRouteOption /** This attribute is not reactive */ ssr?: SSROption - _forcePending?: boolean - _displayPending?: boolean } export interface PreValidationErrorHandlingRouteMatch< diff --git a/packages/router-core/src/hydrate.ts b/packages/router-core/src/hydrate.ts new file mode 100644 index 0000000000..233c6a30ee --- /dev/null +++ b/packages/router-core/src/hydrate.ts @@ -0,0 +1,246 @@ +import { invariant } from './invariant' +import { isNotFound } from './not-found' +import { loadRouteChunk } from './route-chunks' +import { hydrateSsrMatchId } from './ssr/ssr-match-id' +import type { AnyRouteMatch } from './Matches' +import type { AnyRoute } from './route' +import type { AnyRouter } from './router' +import type { GLOBAL_SEROVAL, GLOBAL_TSR } from './ssr/constants' +import type { AnySerializationAdapter } from './ssr/serializer/transformer' +import type { TsrSsrGlobal } from './ssr/types' + +declare global { + interface Window { + [GLOBAL_TSR]?: TsrSsrGlobal + [GLOBAL_SEROVAL]?: any + } +} + +export async function hydrate(router: AnyRouter): Promise { + if (!window.$_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!', + ) + } + invariant() + } + + const adapters = router.options.serializationAdapters as + | Array + | undefined + if (adapters?.length) { + window.$_TSR.t = new Map( + adapters.map((adapter) => [adapter.key, adapter.fromSerializable]), + ) + window.$_TSR.buffer.forEach((script) => script()) + } + window.$_TSR.initialized = true + + const dehydratedRouter = window.$_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!', + ) + } + invariant() + } + + for (const match of dehydratedRouter.matches) { + match.i = hydrateSsrMatchId(match.i) + } + router.ssr = { manifest: dehydratedRouter.manifest } + const nonce = ( + document.querySelector('meta[property="csp-nonce"]') as + | HTMLMetaElement + | undefined + )?.content + router.options.ssr = { nonce } + + const owner = router._tx + const isCurrent = () => router._tx === owner + + await router.options.hydrate?.(dehydratedRouter.dehydratedData) + if (!isCurrent()) { + return + } + router.updateLatestLocation() + const location = router.latestLocation + router.stores.location.set(location) + + const candidates = router.matchRoutes(location) + const committed: Array = [] + let index = 0 + let needsClientLoad: true | undefined + + for (const candidate of candidates) { + const dehydrated = dehydratedRouter.matches[index] + if (!dehydrated || dehydrated.i !== candidate.id) { + needsClientLoad = true + break + } + index++ + candidate.id = dehydrated.i + candidate.__beforeLoadContext = dehydrated.b + candidate.loaderData = dehydrated.l + candidate.status = dehydrated.s + candidate.ssr = dehydrated.ssr + ;(router.routesById as Record)[ + candidate.routeId + ]!.options.ssr = candidate.ssr + candidate.updatedAt = dehydrated.u + candidate.error = dehydrated.e + candidate.globalNotFound = dehydrated.g ?? candidate.globalNotFound + + if (candidate.ssr === false || candidate.status === 'pending') { + needsClientLoad = true + break + } + + committed.push(candidate) + if ( + candidate.status === 'error' || + candidate.status === 'notFound' || + candidate.globalNotFound + ) { + break + } + } + + try { + await Promise.all( + committed.map(async (match) => { + const route = (router.routesById as Record)[ + match.routeId + ]! + if (match.globalNotFound) { + await Promise.all([ + loadRouteChunk(route), + loadRouteChunk(route, 'notFoundComponent'), + ]) + } else { + await loadRouteChunk( + route, + match.status === 'error' + ? 'errorComponent' + : match.status === 'notFound' + ? 'notFoundComponent' + : undefined, + ) + } + }), + ) + } catch (cause) { + if (!isCurrent()) { + return + } + throw cause + } + if (!isCurrent()) { + return + } + + // Install lazy options first, then build every context before any head hook + // receives the lane through `matches`. + for (const match of committed) { + const route = (router.routesById as Record)[ + match.routeId + ]! + const parentContext = + committed[match.index - 1]?.context ?? router.options.context + if (route.options.context) { + match.__routeContext = + (await route.options.context({ + deps: match.loaderDeps, + params: match.params, + context: parentContext ?? {}, + location, + navigate: (opts: any) => + router.navigate({ ...opts, _fromLocation: location }), + buildLocation: router.buildLocation, + cause: match.cause, + abortController: match.abortController, + preload: false, + matches: committed, + routeId: route.id, + })) ?? undefined + if (!isCurrent()) { + return + } + } + match.context = { + ...parentContext, + ...match.__routeContext, + ...match.__beforeLoadContext, + } + } + + for (const match of committed) { + try { + const route = (router.routesById as Record)[ + match.routeId + ]! + const context = { + ssr: router.options.ssr, + matches: committed, + match, + params: match.params, + loaderData: match.loaderData, + } + const head = await route.options.head?.(context) + if (!isCurrent()) { + return + } + const scripts = await route.options.scripts?.(context) + if (!isCurrent()) { + return + } + match.meta = head?.meta + match.links = head?.links + match.headScripts = head?.scripts + match.styles = head?.styles + match.scripts = scripts + } catch (cause) { + if (!isCurrent()) { + return + } + if (isNotFound(cause)) { + match.error = { isNotFound: true } + console.error( + `NotFound error during hydration for routeId: ${match.routeId}`, + cause, + ) + } else { + match.error = cause + console.error( + `Error during hydration for route ${match.routeId}:`, + cause, + ) + throw cause + } + } + } + + let presented = candidates.slice(0, index) + for (let boundary = 0; boundary < committed.length; boundary++) { + if (committed[boundary]!.ssr === 'data-only') { + presented = presented.slice(0, boundary + 1) + presented[boundary] = { + ...presented[boundary]!, + status: 'pending', + } + needsClientLoad = true + break + } + } + + router._committedMatches = committed + router.batch(() => { + router.stores.setMatches(presented) + router.stores.status.set('idle') + if (!needsClientLoad) { + router.stores.resolvedLocation.set(router.stores.location.get()) + } + }) +} diff --git a/packages/router-core/src/isServer/client.ts b/packages/router-core/src/isServer/client.ts index f2f86b6ec7..bd0e6bfe84 100644 --- a/packages/router-core/src/isServer/client.ts +++ b/packages/router-core/src/isServer/client.ts @@ -1 +1,3 @@ export const isServer = false +export const loadServer: never = undefined as never +export const loadServerRouter: never = undefined as never diff --git a/packages/router-core/src/isServer/development.ts b/packages/router-core/src/isServer/development.ts index 3632fabf05..4990101f3e 100644 --- a/packages/router-core/src/isServer/development.ts +++ b/packages/router-core/src/isServer/development.ts @@ -1,2 +1,3 @@ // Development/test mode - returns undefined so fallback to router.isServer is used export const isServer: boolean | undefined = undefined +export { loadServer, loadServerRouter } from '../load.server' diff --git a/packages/router-core/src/isServer/server.ts b/packages/router-core/src/isServer/server.ts index cfa181440a..ae9afb6ef8 100644 --- a/packages/router-core/src/isServer/server.ts +++ b/packages/router-core/src/isServer/server.ts @@ -1 +1,2 @@ export const isServer = process.env.NODE_ENV === 'test' ? undefined : true +export { loadServer, loadServerRouter } from '../load.server' diff --git a/packages/router-core/src/load-matches.ts b/packages/router-core/src/load-matches.ts deleted file mode 100644 index f901a0c97d..0000000000 --- a/packages/router-core/src/load-matches.ts +++ /dev/null @@ -1,1278 +0,0 @@ -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 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' - -/** - * 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 */ - 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 -} - -const triggerOnReady = (inner: InnerLoadContext): void | Promise => { - if (!inner.rendered) { - inner.rendered = true - return inner.onReady?.() - } -} - -const hasForcePendingActiveMatch = (router: AnyRouter): boolean => { - return router.stores.matchesId.get().some((matchId) => { - return router.stores.matchStores.get(matchId)?.get()._forcePending - }) -} - -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, - index: number, - includeCurrentMatch: boolean = true, -): 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 getNotFoundBoundaryIndex = ( - inner: InnerLoadContext, - err: NotFoundError, -): number | undefined => { - if (!inner.matches.length) { - return undefined - } - - 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) - - if (startIndex < 0) { - startIndex = rootIndex - } - - for (let i = startIndex; i >= 0; i--) { - const match = inner.matches[i]! - const route = inner.router.looseRoutesById[match.routeId]! - if (route.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 -} - -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 = ( - 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 - } - - 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 - 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, - })) - } - } 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) - } -} - -const loadRouteMatch = async ( - 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 - - 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, - error: undefined, - })) - } - } - } - - // 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']) - } - - // 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 -} - -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/load.client.ts b/packages/router-core/src/load.client.ts new file mode 100644 index 0000000000..e1c5747226 --- /dev/null +++ b/packages/router-core/src/load.client.ts @@ -0,0 +1,1496 @@ +import { isNotFound } from './not-found' +import { isRedirect } from './redirect' +import { loadRouteChunk } from './route-chunks' +import { getLocationChangeInfo } from './router' +import type { ParsedLocation } from './location' +import type { AnyRouteMatch } from './Matches' +import type { NotFoundError } from './not-found' +import type { + AnyRoute, + BeforeLoadContextOptions, + LoaderFnContext, +} from './route' +import type { AnyRedirect } from './redirect' +import type { AnyRouter } from './router' + +declare const lanePhase: unique symbol + +type Phase = 'matched' | 'contextualized' | 'reduced' | 'projected' + +type Lane = { + readonly [lanePhase]?: TPhase + location: ParsedLocation + matches: Array + background?: Array +} + +type MatchedLane = Lane<'matched'> + +type ContextualizedLane = Lane<'contextualized'> + +type ReducedLane = Lane<'reduced'> + +export type ProjectedLane = Lane<'projected'> + +const success = 0 +const error = 1 +const notFound = 2 +const redirected = 3 +const canceled = 4 + +type LoaderOutcome = + | [typeof success, data: unknown] + | [typeof error, error: unknown] + | [typeof notFound, error: NotFoundError] + | [typeof redirected, redirect: AnyRedirect] + | [typeof canceled] + +type IndexedOutcome = [index: number, outcome: LoaderOutcome] + +export type LoaderFlight = [ + outcome: Promise, + controller: AbortController, + leases: number, +] + +type WorkMatch = AnyRouteMatch & { + _flight?: LoaderFlight +} + +type ClientRouter = AnyRouter & { + _flights?: Map +} + +export type LoadTransaction = { + location: ParsedLocation + controller: AbortController + matches: Array + done: Promise + redirects?: number + redirecting?: true +} + +export type PendingSession = { + owner: LoadTransaction + boundary: number + /** Pending reveal time until acknowledged, then minimum-visible-until time. */ + deadline: number + timer?: ReturnType + ack?: Promise +} + +type CoordinatorRouter = ClientRouter & { + _tx?: LoadTransaction + _committedMatches?: Array + _pending?: PendingSession + /** Cancels reentrant synchronous planning without replacing the current writer. */ + _preflight?: AbortController +} + +type WorkerRouter = Pick< + AnyRouter, + 'buildLocation' | 'navigate' | 'options' | 'routeTree' | 'routesById' +> + +type Task = { + outcome: Promise + ready: Promise + match?: Promise +} + +type BackgroundTask = Task & { + index: number + candidate: WorkMatch +} + +export type ExecuteLaneOptions = { + preload?: boolean + sync?: boolean + forceStaleReload?: boolean + controller: AbortController + base?: Array + resolvedPrefix?: number + redirects?: number + onReady?: () => void +} + +type ControlOutcome = + | [typeof redirected, redirect: AnyRedirect] + | [typeof canceled] + +export type LaneResult = ProjectedLane | ControlOutcome + +function waitFor( + value: T | PromiseLike, + signal: AbortSignal, +): Promise { + if (signal.aborted) { + return Promise.reject(signal) + } + return new Promise((resolve, reject) => { + const abort = () => reject(signal) + signal.addEventListener('abort', abort, { once: true }) + Promise.resolve(value) + .then(resolve, reject) + .finally(() => { + signal.removeEventListener('abort', abort) + }) + }) +} + +function getRoute(router: WorkerRouter, match: WorkMatch): AnyRoute { + return (router.routesById as Record)[match.routeId]! +} + +function normalize( + value: unknown, + rejected: boolean, + routeId?: string, +): LoaderOutcome { + if (isRedirect(value)) { + return [redirected, value] + } + if (isNotFound(value)) { + value.routeId ||= routeId + return [notFound, value] + } + return rejected ? [error, value] : [success, value] +} + +function normalizeError( + route: AnyRoute, + cause: unknown, + signal?: AbortSignal, +): LoaderOutcome { + if (signal && (cause as any)?.name === 'AbortError') { + return signal.aborted ? [canceled] : [success, undefined] + } + let outcome = normalize(cause, true, route.id) + if (outcome[0] !== error) { + return outcome + } + try { + route.options.onError?.(cause) + } catch (onErrorCause) { + outcome = normalize(onErrorCause, true, route.id) + } + return outcome +} + +function navigateFrom(router: WorkerRouter, location: ParsedLocation) { + return (opts: any) => + router.navigate({ + ...opts, + _fromLocation: location, + }) +} + +async function contextualize( + router: WorkerRouter, + lane: MatchedLane, + options: ExecuteLaneOptions, +): Promise { + for ( + let index = options.resolvedPrefix ?? 0; + index < lane.matches.length; + index++ + ) { + const match = lane.matches[index]! + const route = getRoute(router, match) + const serialError = match.paramsError ?? match.searchError + + if (serialError !== undefined) { + releaseFlight(router as ClientRouter, match) + return [index, normalizeError(route, serialError)] + } + + match.abortController = options.controller + // Contextualization is serial, so the previous match already contains the + // complete parent context for this route. + const parentContext = + lane.matches[index - 1]?.context ?? router.options.context ?? {} + const context = { + ...parentContext, + ...match.__routeContext, + } + + if (!route.options.beforeLoad) { + match.__beforeLoadContext = {} + match.context = context + continue + } + + const preload = !!options.preload + const beforeLoadContext: BeforeLoadContextOptions< + any, + any, + any, + any, + any, + any, + any, + any, + any + > = { + search: match.search, + abortController: match.abortController, + params: match.params, + preload, + context, + location: lane.location, + navigate: navigateFrom(router, lane.location), + buildLocation: router.buildLocation, + cause: preload ? 'preload' : match.cause, + matches: lane.matches, + routeId: route.id, + ...router.options.additionalContext, + } + + try { + match.isFetching = 'beforeLoad' + const result = await waitFor( + route.options.beforeLoad(beforeLoadContext), + options.controller.signal, + ) + match.isFetching = false + const outcome = normalize(result, false, route.id) + if (outcome[0] !== success) { + releaseFlight(router as ClientRouter, match) + return [index, outcome] + } + match.__beforeLoadContext = result + match.context = { + ...context, + ...result, + } + } catch (cause) { + match.isFetching = false + if (cause === options.controller.signal) { + return [index, [canceled]] + } + if (cause instanceof Promise) { + throw cause + } + releaseFlight(router as ClientRouter, match) + return [index, normalizeError(route, cause)] + } + } + + return +} + +function releaseFlight(router: ClientRouter, match: WorkMatch): void { + const flight = match._flight + if (!flight) { + return + } + match._flight = undefined + if (!--flight[2]) { + flight[1].abort() + if (router._flights?.get(match.id) === flight) { + router._flights.delete(match.id) + } + } +} + +export function discardMatchResources( + router: AnyRouter, + matches: Array, +): void { + transferMatchResources(router, matches, []) +} + +export function transferMatchResources( + router: AnyRouter, + previous: Array, + next: Array, +): void { + for (const match of previous as Array) { + if (!next.includes(match)) { + releaseFlight(router as ClientRouter, match) + } + } +} + +function startFlight( + router: ClientRouter, + key: string, + route: AnyRoute, + invoke: (controller: AbortController) => unknown, +): LoaderFlight { + const controller = new AbortController() + const flight: LoaderFlight = [ + Promise.resolve() + .then(() => invoke(controller)) + .then( + (value) => + controller.signal.aborted + ? [canceled] + : normalize(value, false, route.id), + (cause) => + controller.signal.aborted + ? [canceled] + : normalizeError(route, cause, controller.signal), + ), + controller, + 1, + ] + ;(router._flights ??= new Map()).set(key, flight) + return flight +} + +function closeFlight(router: ClientRouter, match: WorkMatch): void { + const flight = match._flight + if (!flight) { + return + } + if (router._flights?.get(match.id) === flight) { + router._flights.delete(match.id) + } +} + +function getLoaderContext( + router: WorkerRouter, + lane: ContextualizedLane, + match: WorkMatch, + route: AnyRoute, + controller: AbortController, + parentMatchPromise: Promise | undefined, + preload: boolean, +): LoaderFnContext { + return { + params: match.params, + deps: match.loaderDeps, + preload, + parentMatchPromise: parentMatchPromise as any, + abortController: controller, + context: match.context, + location: lane.location, + navigate: navigateFrom(router, lane.location), + cause: preload ? 'preload' : match.cause, + route, + ...router.options.additionalContext, + } +} + +async function loadResource( + router: ClientRouter, + workerRouter: WorkerRouter, + lane: ContextualizedLane, + match: WorkMatch, + route: AnyRoute, + parentMatchPromise: Promise | undefined, + preload: boolean, + signal: AbortSignal, +): Promise { + if (signal.aborted) { + return [canceled] + } + const routeLoader = route.options.loader + const loader = + typeof routeLoader === 'function' ? routeLoader : routeLoader?.handler + if (!loader) { + return [success, undefined] + } + + let flight = match._flight + let joined = !!flight && router._flights?.get(match.id) === flight + for (;;) { + if (!joined) { + releaseFlight(router, match) + flight = startFlight(router, match.id, route, (controller) => + loader( + getLoaderContext( + workerRouter, + lane, + match, + route, + controller, + parentMatchPromise, + preload, + ), + ), + ) + } + match._flight = flight + match.abortController = flight![1] + match.isFetching = 'loader' + try { + const outcome = await waitFor(flight![0], signal) + if (!joined || outcome[0] === success) { + return outcome + } + } catch (cause) { + if (cause === signal) { + releaseFlight(router, match) + return [canceled] + } + throw cause + } + closeFlight(router, match) + releaseFlight(router, match) + joined = false + } +} + +function shouldReload( + router: WorkerRouter, + lane: ContextualizedLane, + match: WorkMatch, + route: AnyRoute, + index: number, + tasks: Array, + options: ExecuteLaneOptions, +): boolean { + if (index < (options.resolvedPrefix ?? 0)) { + return false + } + if (match.status !== 'success') { + return true + } + + const preload = !!options.preload + const preloadStaleTime = route.options.preloadStaleTime + const staleAge = + preload || (match.preload && preloadStaleTime !== undefined) + ? (preloadStaleTime ?? router.options.defaultPreloadStaleTime ?? 30_000) + : (route.options.staleTime ?? router.options.defaultStaleTime ?? 0) + const reload = route.options.shouldReload + const configured = + typeof reload === 'function' + ? reload( + getLoaderContext( + router, + lane, + match, + route, + options.controller, + tasks[index - 1]?.match, + preload, + ), + ) + : reload + const previous = options.base?.find( + (candidate) => candidate.routeId === match.routeId, + ) + + return !!( + match.invalid || + configured || + (configured === undefined && + Date.now() - match.updatedAt >= staleAge && + (options.forceStaleReload || + match.cause === 'enter' || + (!!previous && previous.id !== match.id))) + ) +} + +function applySuccess(match: WorkMatch, data: unknown): void { + if (data !== undefined) { + match.loaderData = data + } + match.error = undefined + match.status = 'success' + match.invalid = false + match.isFetching = false + match.updatedAt = Date.now() +} + +function createTask( + router: ClientRouter, + workerRouter: WorkerRouter, + lane: ContextualizedLane, + index: number, + tasks: Array, + semanticParent: Promise | undefined, + options: ExecuteLaneOptions, +): Promise { + const match = lane.matches[index]! + const route = getRoute(workerRouter, match) + const preload = !!options.preload + let reload = false + let reloadFailure: LoaderOutcome | undefined + try { + reload = shouldReload( + workerRouter, + lane, + match, + route, + index, + tasks, + options, + ) + reload ||= + index < (options.resolvedPrefix ?? 0) && !!router._flights?.get(match.id) + } catch (cause) { + releaseFlight(router, match) + reloadFailure = normalizeError(route, cause) + } + const routeLoader = route.options.loader + const background = !!( + routeLoader && + reload && + match.status === 'success' && + !preload && + !options.sync && + ((typeof routeLoader === 'function' + ? undefined + : routeLoader?.staleReloadMode) ?? + workerRouter.options.defaultStaleReloadMode) !== 'blocking' + ) + const skippedPreload = preload && route.options.preload === false + const loaded = reload && !skippedPreload + if (skippedPreload) { + match.status = 'success' + match.invalid = true + match.isFetching = false + } + const rawOutcome = reloadFailure + ? Promise.resolve(reloadFailure) + : !loaded || background + ? Promise.resolve([success, match.loaderData]) + : loadResource( + router, + workerRouter, + lane, + match, + route, + tasks[index - 1]?.match, + preload, + options.controller.signal, + ) + const outcome = rawOutcome.then((result) => { + if (loaded && !background && result[0] === success) { + applySuccess(match, result[1]) + match.preload = preload + } + return result + }) + + const chunkFailure = Promise.resolve() + .then(() => loadRouteChunk(route)) + .then( + (): IndexedOutcome | undefined => undefined, + (cause): IndexedOutcome => [index, normalizeError(route, cause)], + ) + const ready = outcome + .then((value) => (value[0] === success ? chunkFailure : undefined)) + .then((value) => { + options.onReady?.() + return value + }) + + const task = { + outcome, + ready, + match: outcome.then(() => match), + } + tasks.push(task) + if (!background) { + return task.match + } + const candidate = { + ...match, + _flight: undefined, + } as WorkMatch + const backgroundOutcome = loadResource( + router, + workerRouter, + lane, + candidate, + route, + semanticParent, + false, + options.controller.signal, + ).then((result) => { + if (result[0] === success) { + applySuccess(candidate, result[1]) + } + return result + }) + const backgroundMatch = backgroundOutcome.then(() => candidate) + const backgroundTask = { + index, + candidate, + outcome: backgroundOutcome, + ready: task.ready, + } + ;(lane.background ??= []).push(backgroundTask) + return backgroundMatch +} + +function getNotFoundBoundary( + router: WorkerRouter, + matches: Array, + indexed: IndexedOutcome, +): number { + const [throwingIndex, outcome] = indexed + const cause = outcome[1] as NotFoundError + let index = cause.routeId + ? matches.findIndex((match) => match.routeId === cause.routeId) + : throwingIndex + if (index < 0) { + index = 0 + } + for (let i = index; i >= 0; i--) { + if (getRoute(router, matches[i]!).options.notFoundComponent) { + return i + } + } + return cause.routeId ? index : 0 +} + +async function reduceLane( + router: WorkerRouter & ClientRouter, + lane: ContextualizedLane, + tasks: Array, + options: ExecuteLaneOptions, + serialFailure?: IndexedOutcome, +): Promise { + let control = + serialFailure?.[1][0] === redirected || serialFailure?.[1][0] === canceled + ? serialFailure + : undefined + let firstError = serialFailure?.[1][0] === error ? serialFailure : undefined + let firstNotFound = + serialFailure?.[1][0] === notFound ? serialFailure : undefined + + for (let index = 0; index < tasks.length; index++) { + const task = tasks[index]! + const taskIndex = (task as BackgroundTask).index ?? index + const outcome = await task.outcome + if (outcome[0] === redirected || outcome[0] === canceled) { + control = [taskIndex, outcome] + break + } + if (outcome[0] === error && (!firstError || taskIndex < firstError[0])) { + firstError = [taskIndex, outcome] + } else if ( + outcome[0] === notFound && + (!firstNotFound || taskIndex < firstNotFound[0]) + ) { + firstNotFound = [taskIndex, outcome] + } + } + + if (control?.[1][0] === redirected && !control[1][1].options.reloadDocument) { + if ((options.redirects ?? 0) >= 20) { + firstError = [control[0], [error, new Error('Redirect cycle detected')]] + control = undefined + } + } + + if (control) { + if (lane.background) { + discardMatchResources( + router as AnyRouter, + lane.background.map((task) => task.candidate), + ) + lane.background = undefined + } + return control[1] as ControlOutcome + } + + const failure = firstError ?? firstNotFound + const readinessEnd = failure?.[0] ?? lane.matches.length + for (let index = 0; index < tasks.length; index++) { + const task = tasks[index]! + if (((task as BackgroundTask).index ?? index) >= readinessEnd) { + break + } + const chunkFailure = await task.ready + if (chunkFailure) { + firstError = chunkFailure + break + } + } + + if (firstError) { + const [index, outcome] = firstError + const match = lane.matches[index]! + match.status = 'error' + match.error = outcome[1] + match.isFetching = false + try { + await loadRouteChunk(getRoute(router, match), 'errorComponent') + } catch {} + trimLane(router, lane, index + 1) + return lane as ReducedLane + } + + if (failure?.[1][0] === notFound) { + const boundary = getNotFoundBoundary(router, lane.matches, failure) + const match = lane.matches[boundary]! + const cause = failure[1][1] + cause.routeId = match.routeId + if (match.routeId === router.routeTree.id) { + match.status = 'success' + match.globalNotFound = true + match.error = cause + } else { + match.status = 'notFound' + match.error = cause + } + match.isFetching = false + try { + await loadRouteChunk(getRoute(router, match), 'notFoundComponent') + } catch {} + trimLane(router, lane, boundary + 1) + return lane as ReducedLane + } + + return lane as ReducedLane +} + +function trimLane( + router: ClientRouter, + lane: ContextualizedLane, + length: number, +): void { + discardMatchResources(router as AnyRouter, lane.matches.slice(length)) + lane.matches.length = length + if (!lane.background) { + return + } + let write = 0 + for (const task of lane.background) { + if (task.index < length) { + lane.background[write++] = task + } else { + discardMatchResources(router as AnyRouter, [task.candidate]) + } + } + lane.background.length = write +} + +async function projectLane( + router: WorkerRouter, + lane: ReducedLane, + start = 0, +): Promise { + for (let index = start; index < lane.matches.length; index++) { + const match = lane.matches[index]! + const route = getRoute(router, match) + if (!route.options.head && !route.options.scripts) { + continue + } + try { + const context = { + ssr: router.options.ssr, + matches: lane.matches, + match, + params: match.params, + loaderData: match.loaderData, + } + const [head, scripts] = await Promise.all([ + route.options.head?.(context), + route.options.scripts?.(context), + ]) + match.meta = head?.meta + match.links = head?.links + match.headScripts = head?.scripts + match.styles = head?.styles + match.scripts = scripts + } catch (cause) { + console.error(`Error executing head for route ${route.id}:`, cause) + } + } + return lane as ProjectedLane +} + +export async function executeClientLane( + router: AnyRouter, + location: ParsedLocation, + matches: Array, + options: ExecuteLaneOptions, +): Promise { + const clientRouter = router as ClientRouter + const workerRouter = router as WorkerRouter + const matched = { + location, + matches: matches as Array, + } as MatchedLane + for (const match of matched.matches) { + const flight = clientRouter._flights?.get(match.id) ?? match._flight + if (flight) { + match._flight = flight + flight[2]++ + } + } + const failure = await contextualize(workerRouter, matched, options) + if (failure) { + options.sync = true + } + const contextualized = matched as ContextualizedLane + const tasks: Array = [] + let semanticParent: Promise | undefined + let end = failure?.[0] ?? contextualized.matches.length + if (failure?.[1][0] === notFound) { + end = Math.min( + end, + getNotFoundBoundary(workerRouter, contextualized.matches, failure) + 1, + ) + } else if (failure?.[1][0] === redirected || failure?.[1][0] === canceled) { + end = 0 + } + for (let index = 0; index < end; index++) { + if (options.controller.signal.aborted) { + break + } + semanticParent = createTask( + clientRouter, + workerRouter, + contextualized, + index, + tasks, + semanticParent, + options, + ) + } + const reduced = await reduceLane( + router as WorkerRouter & ClientRouter, + contextualized, + tasks, + options, + failure, + ) + if (Array.isArray(reduced)) { + return reduced + } + return projectLane( + workerRouter, + reduced, + Math.min(options.resolvedPrefix ?? 0, reduced.matches.length - 1), + ) +} + +function semanticMatches(router: CoordinatorRouter): Array { + return router._committedMatches ?? router.stores.matches.get() +} + +function pendingConfig( + router: AnyRouter, + matches: Array, +): [delay: number, boundary: number, min: number] | undefined { + const presented = router.stores.matches.get() + for (let index = 0; index < matches.length; index++) { + const match = matches[index]! + const visible = + match.status === 'success' && + presented[index]?.id === match.id && + presented[index]?.status === 'pending' + if (match.status === 'success' && !visible) { + continue + } + const route = getRoute(router, match as WorkMatch) + const delay = visible + ? 0 + : match.invalid + ? 0 + : (route.options.pendingMs ?? router.options.defaultPendingMs) + return (route.options.pendingComponent ?? + (router.options as any).defaultPendingComponent) && + typeof delay === 'number' && + delay !== Infinity + ? [ + delay, + index, + route.options.pendingMinMs ?? router.options.defaultPendingMinMs ?? 0, + ] + : undefined + } + return undefined +} + +function renderPending( + router: CoordinatorRouter, + tx: LoadTransaction, + boundary: number, +): Promise { + const offered = tx.matches.slice(0, boundary + 1) as Array + offered[boundary] = { + ...offered[boundary]!, + _flight: undefined, + status: 'pending', + } + return router.startTransition(() => { + router.stores.setMatches(offered) + }) +} + +function offerPending(router: CoordinatorRouter, tx: LoadTransaction): void { + if (router._tx !== tx) { + return + } + let session = router._pending + const sessionMatchId = session?.owner.matches[session.boundary]?.id + if (session?.owner !== tx) { + if (session && tx.matches[session.boundary]?.id === sessionMatchId) { + session.owner = tx + } else { + clearTimeout(session?.timer) + router._pending = session = undefined + } + } + const config = pendingConfig(router, tx.matches) + if (!config) { + return + } + const [delay, boundary, min] = config + const matchId = tx.matches[boundary]!.id + if (!session || session.boundary !== boundary || sessionMatchId !== matchId) { + clearTimeout(session?.timer) + const presented = router.stores.matches.get()[boundary] + const visible = presented?.id === matchId && presented.status === 'pending' + router._pending = session = { + owner: tx, + boundary, + deadline: Date.now() + (visible ? min : delay), + ack: visible ? Promise.resolve(true) : undefined, + } + } + if (session.ack) { + return + } + clearTimeout(session.timer) + const remaining = session.deadline - Date.now() + if (remaining > 0) { + session.timer = setTimeout(() => { + offerPending(router, tx) + }, remaining) + return + } + session.ack = renderPending(router, tx, boundary).then((rendered) => { + if (rendered && router._pending === session) { + session.deadline = Date.now() + min + } + return rendered + }) +} + +function finishPending(router: CoordinatorRouter, tx: LoadTransaction): void { + const session = router._pending + if (session?.owner === tx) { + clearTimeout(session.timer) + router._pending = undefined + } +} + +function publishMatches( + router: CoordinatorRouter, + matches: Array, + previous: Array, +): void { + for (let index = 0; index < matches.length; index++) { + const match = matches[index]! + const oldMatch = previous[index] + if (match !== oldMatch) { + match.fetchCount = + (oldMatch?.routeId === match.routeId ? oldMatch!.fetchCount : 0) + 1 + } + closeFlight(router, match as WorkMatch) + } + router.stores.setMatches(matches) + router._committedMatches = matches +} + +function commitMatches( + router: CoordinatorRouter, + tx: LoadTransaction, + matches: Array, +): void { + const stores = router.stores + const previous = semanticMatches(router) + const previousCached = stores.cachedMatches.get() + for (const match of matches) { + match.preload = false + } + const nextIds = new Set(matches.map((match) => match.id)) + const cached = previousCached.filter((match) => !nextIds.has(match.id)) + for (const match of previous) { + if (!nextIds.has(match.id)) { + cached.push({ + ...match, + _flight: undefined, + } as WorkMatch) + } + } + + const now = Date.now() + let write = 0 + for (const match of cached) { + const route = getRoute(router, match as WorkMatch) + const gcTime = + (match.preload + ? (route.options.preloadGcTime ?? router.options.defaultPreloadGcTime) + : (route.options.gcTime ?? router.options.defaultGcTime)) ?? 300_000 + if ( + route.options.loader && + match.status === 'success' && + now - match.updatedAt < gcTime + ) { + cached[write++] = match + } + } + cached.length = write + + router.batch(() => { + publishMatches(router, matches, previous) + stores.setCached(cached) + }) + transferMatchResources( + router, + [...previousCached, ...previous], + [...matches, ...cached], + ) + tx.matches = [] + + const count = Math.max(previous.length, matches.length) + for (let index = 0; index < count; index++) { + const oldMatch = previous[index] + const match = matches[index] + if (oldMatch && oldMatch.routeId !== match?.routeId) { + try { + getRoute(router, oldMatch as WorkMatch).options.onLeave?.(oldMatch) + } catch (cause) { + Promise.reject(cause) + } + } + if (match) { + try { + getRoute(router, match as WorkMatch).options[ + oldMatch?.routeId === match.routeId ? 'onStay' : 'onEnter' + ]?.(match) + } catch (cause) { + Promise.reject(cause) + } + } + } +} + +async function awaitCurrent( + router: CoordinatorRouter, + owner?: LoadTransaction, +): Promise { + let current = router._tx + while (current && current !== owner) { + await current.done + if (router._tx === current) { + return + } + current = router._tx + } +} + +async function runBackground( + router: CoordinatorRouter, + tx: LoadTransaction, + base: Array, + tasks: Array, +): Promise { + const backgroundMatches = tasks.map((task) => task.candidate) + const next = base.slice() as Array + for (const task of tasks) { + next[task.index] = task.candidate + } + const lane = { + location: tx.location, + matches: next, + } as ContextualizedLane + const options: ExecuteLaneOptions = { + controller: tx.controller, + redirects: tx.redirects, + } + const reduced = await reduceLane( + router as WorkerRouter & ClientRouter, + lane, + tasks, + options, + ) + if (Array.isArray(reduced)) { + discardMatchResources(router, backgroundMatches) + if ( + reduced[0] === redirected && + router._tx === tx && + router._committedMatches === base + ) { + tx.redirects = (tx.redirects ?? 0) + 1 + tx.redirecting = true + await router.navigate({ + ...reduced[1].options, + replace: true, + ignoreBlocker: true, + }) + tx.redirecting = undefined + } + return + } + const projected = await projectLane(router as WorkerRouter, reduced) + if (router._tx !== tx || router._committedMatches !== base) { + discardMatchResources(router, backgroundMatches) + return + } + router.batch(() => { + publishMatches(router, projected.matches, base) + }) + transferMatchResources( + router, + [...base, ...backgroundMatches], + projected.matches, + ) +} + +async function runClientTransaction( + router: CoordinatorRouter, + tx: LoadTransaction, + forceStaleReload: boolean, + onReady?: () => void, + sync?: boolean, + resolvedPrefix?: number, +): Promise { + const options: ExecuteLaneOptions = { + controller: tx.controller, + forceStaleReload, + sync, + base: semanticMatches(router), + resolvedPrefix, + redirects: tx.redirects, + onReady, + } + const result = await executeClientLane( + router, + tx.location, + tx.matches, + options, + ) + + if (Array.isArray(result)) { + finishPending(router, tx) + discardMatchResources(router, tx.matches) + if (result[0] === redirected && router._tx === tx) { + tx.redirects = (tx.redirects ?? 0) + 1 + tx.redirecting = true + await router.navigate({ + ...result[1].options, + replace: true, + ignoreBlocker: true, + }) + tx.redirecting = undefined + } + return + } + tx.redirects = undefined + const pending = router._pending + if (pending?.owner === tx) { + clearTimeout(pending.timer) + if (pending.ack) { + const rendered = await pending.ack + if (rendered && router._pending === pending && pending.owner === tx) { + const remaining = pending.deadline - Date.now() + if (remaining > 0) { + await new Promise((resolve) => setTimeout(resolve, remaining)) + } + } + } + } + if (router._tx !== tx) { + finishPending(router, tx) + discardMatchResources(router, result.matches) + return + } + const toLocation = tx.location + const changeInfo = getLocationChangeInfo( + toLocation, + router.stores.resolvedLocation.get(), + ) + await router.startViewTransition(async () => { + if (router._tx !== tx) { + discardMatchResources(router, result.matches) + return + } + const commit = () => { + if (result.background?.length) { + void runBackground(router, tx, result.matches, result.background).catch( + console.error, + ) + } + finishPending(router, tx) + commitMatches(router, tx, result.matches) + } + const rendered = await router.startTransition(commit) + if (router._tx !== tx) { + return + } + router.batch(() => { + router.stores.resolvedLocation.set(toLocation) + router.stores.status.set('idle') + router.emit({ type: 'onLoad', ...changeInfo }) + router.emit({ type: 'onBeforeRouteMount', ...changeInfo }) + if (router._tx === tx) { + router.emit({ type: 'onResolved', ...changeInfo }) + } + if (rendered) { + router.emit({ type: 'onRendered', ...changeInfo }) + } + }) + if (router._tx !== tx) { + return + } + router.commitLocationPromise?.resolve() + router.commitLocationPromise = undefined + }) +} + +export async function loadClientRouter( + router: AnyRouter, + opts?: { + sync?: boolean + resolvedPrefix?: number + /** @internal */ + _refreshRouteId?: string + }, +): Promise { + const clientRouter = router as CoordinatorRouter + const refreshRouteId = + process.env.NODE_ENV !== 'production' ? opts?._refreshRouteId : undefined + const canReuse = refreshRouteId + ? (route: AnyRoute) => { + for (let current: AnyRoute | undefined = route; current; ) { + if (current.id === refreshRouteId) { + return false + } + current = current.parentRoute as AnyRoute | undefined + } + return true + } + : undefined + clientRouter._committedMatches ??= router.stores.matches.get() + const resolvedPrefix = + opts?.resolvedPrefix ?? + (router.ssr && !router.stores.resolvedLocation.get() + ? clientRouter._committedMatches.length + : undefined) + const previousOwner = clientRouter._tx + const previousLocation = + router.stores.resolvedLocation.get() ?? router.stores.location.get() + const controller = new AbortController() + clientRouter._preflight?.abort() + clientRouter._preflight = controller + + router.updateLatestLocation() + const location = router.latestLocation + let matches: Array + try { + matches = router.matchRoutes( + location, + process.env.NODE_ENV !== 'production' && canReuse + ? { _controller: controller, _canReuse: canReuse } + : { _controller: controller }, + ) + } catch (cause) { + const stale = + controller.signal.aborted || clientRouter._tx !== previousOwner + controller.abort() + if (stale) { + await awaitCurrent(clientRouter, previousOwner) + return + } + if (!isRedirect(cause)) { + await awaitCurrent(clientRouter) + router.commitLocationPromise?.resolve() + router.commitLocationPromise = undefined + return + } + await router.navigate({ + ...cause.options, + replace: true, + ignoreBlocker: true, + }) + await awaitCurrent(clientRouter, previousOwner) + return + } + + if (controller.signal.aborted || clientRouter._tx !== previousOwner) { + controller.abort() + await awaitCurrent(clientRouter, previousOwner) + return + } + clientRouter._preflight = undefined + + const tx: LoadTransaction = { + location, + controller, + matches, + done: Promise.resolve() + .then(() => + runClientTransaction( + clientRouter, + tx, + refreshRouteId ? false : previousLocation.href === location.href, + refreshRouteId ? undefined : () => offerPending(clientRouter, tx), + opts?.sync, + resolvedPrefix, + ), + ) + .catch(() => { + if (clientRouter._tx === tx) { + finishPending(clientRouter, tx) + controller.abort() + discardMatchResources(router, tx.matches) + router.batch(() => { + router.stores.status.set('idle') + router.stores.setMatches(clientRouter._committedMatches ?? []) + }) + if (clientRouter._tx !== tx) { + return + } + router.commitLocationPromise?.resolve() + router.commitLocationPromise = undefined + } + }), + redirects: previousOwner?.redirecting ? previousOwner.redirects : undefined, + } + clientRouter._tx = tx + previousOwner?.controller.abort() + if (previousOwner) { + discardMatchResources(router, previousOwner.matches) + } + + router.batch(() => { + router.stores.status.set('pending') + router.stores.location.set(location) + }) + if (!refreshRouteId) { + offerPending(clientRouter, tx) + } + + try { + await tx.done + } finally { + await awaitCurrent(clientRouter, tx) + } +} + +export function refreshClientRoute( + router: AnyRouter, + routeId: string, +): Promise { + const clientRouter = router as CoordinatorRouter + if (clientRouter._flights) { + for (const flight of clientRouter._flights.values()) { + flight[1].abort() + } + clientRouter._flights.clear() + } + router.clearCache() + + return loadClientRouter(router, { sync: true, _refreshRouteId: routeId }) +} + +export async function preloadClientRoute( + router: AnyRouter, + opts: any, + redirects = 0, +): Promise | undefined> { + if (redirects > 20) { + return + } + const clientRouter = router as CoordinatorRouter + const owner = clientRouter._tx + const location = opts._builtLocation ?? router.buildLocation(opts) + const base = semanticMatches(clientRouter) + const plannedCache = router.stores.cachedMatches.get() + const controller = new AbortController() + let matches: Array + try { + matches = router.matchRoutes(location, { + throwOnError: true, + preload: true, + _controller: controller, + _isCurrent: () => clientRouter._tx === owner, + }) + let resolvedPrefix = 0 + while ( + base[resolvedPrefix]?.status === 'success' && + base[resolvedPrefix]?.id === matches[resolvedPrefix]?.id + ) { + resolvedPrefix++ + } + const result = await executeClientLane(router, location, matches, { + controller, + preload: true, + base, + resolvedPrefix, + }) + if (Array.isArray(result)) { + discardMatchResources(router, matches) + if (result[0] === redirected && !result[1].options.reloadDocument) { + return preloadClientRoute( + router, + { + ...result[1].options, + _fromLocation: location, + }, + redirects + 1, + ) + } + return + } + + matches = result.matches + if (matches.some((match) => match.status !== 'success')) { + discardMatchResources(router, matches) + return + } + + const active = new Set( + semanticMatches(clientRouter).map((match) => match.id), + ) + const previous = router.stores.cachedMatches.get() + const candidates: Array = [] + for (const match of matches as Array) { + if ( + active.has(match.id) || + previous.find((candidate) => candidate.id === match.id) !== + plannedCache.find((candidate) => candidate.id === match.id) + ) { + releaseFlight(clientRouter, match) + continue + } + closeFlight(clientRouter, match) + candidates.push(match) + } + const ids = new Set(candidates.map((match) => match.id)) + const cached = previous + .filter((match) => !ids.has(match.id)) + .concat(candidates) + router.stores.setCached(cached) + transferMatchResources(router, previous, [ + ...cached, + ...semanticMatches(clientRouter), + ]) + return matches + } catch (cause) { + controller.abort() + if (clientRouter._tx !== owner) { + return + } + if (isRedirect(cause) && !cause.options.reloadDocument) { + return preloadClientRoute( + router, + { + ...cause.options, + _fromLocation: location, + }, + redirects + 1, + ) + } + if (!isNotFound(cause)) { + console.error(cause) + } + if (matches!) { + discardMatchResources(router, matches) + } + return + } +} diff --git a/packages/router-core/src/load.server.ts b/packages/router-core/src/load.server.ts new file mode 100644 index 0000000000..19ad1675c2 --- /dev/null +++ b/packages/router-core/src/load.server.ts @@ -0,0 +1,757 @@ +import { isNotFound } from './not-found' +import { isRedirect, redirect } from './redirect' +import { rootRouteId } from './root' +import { loadRouteChunk } from './route-chunks' +import type { ParsedLocation } from './location' +import type { AnyRouteMatch } from './Matches' +import type { NotFoundError } from './not-found' +import type { + AnyRoute, + BeforeLoadContextOptions, + LoaderFnContext, + SsrContextOptions, +} from './route' +import type { AnyRedirect } from './redirect' +import type { AnyRouter, SSROption } from './router' + +declare const serverLanePhase: unique symbol + +type ServerLane = { + readonly [serverLanePhase]: TPhase + location: ParsedLocation + matches: Array +} + +type MatchedLane = ServerLane<'matched'> + +type IndexedOutcome = [index: number, outcome: LoadOutcome] + +type ContextualizedLane = ServerLane<'contextualized'> & { + end: number + failure?: IndexedOutcome +} + +type ReducedLane = ServerLane<'reduced'> + +const success = 0 +const error = 1 +const notFound = 2 +const redirected = 3 +const skipped = 4 + +type LoadOutcome = + | [typeof success, data: unknown] + | [typeof error, error: unknown] + | [typeof notFound, error: NotFoundError] + | [typeof redirected, redirect: AnyRedirect] + | [typeof skipped] + +type LoaderTask = { + index: number + outcome: Promise + match: Promise +} + +type ServerWorker = Pick< + AnyRouter, + | 'buildLocation' + | 'isShell' + | 'navigate' + | 'options' + | 'resolveRedirect' + | 'routeTree' + | 'routesById' +> + +export type ServerLoadResult = + | { + type: 'render' + status: 200 | 404 | 500 + matches: Array + } + | { type: 'redirect'; redirect: AnyRedirect } + +function getRoute(router: ServerWorker, match: AnyRouteMatch): AnyRoute { + return (router.routesById as Record)[match.routeId]! +} + +function normalize(value: unknown, rejected: boolean): LoadOutcome { + if (isRedirect(value)) { + return [redirected, value] + } + if (isNotFound(value)) { + return [notFound, value] + } + return rejected ? [error, value] : [success, value] +} + +function normalizeError(route: AnyRoute, cause: unknown): LoadOutcome { + let outcome = normalize(cause, true) + if (outcome[0] !== error) { + return outcome + } + try { + route.options.onError?.(cause) + } catch (onErrorCause) { + outcome = normalize(onErrorCause, true) + } + return outcome +} + +function maybe( + value: TValue, + cause: unknown, +): { status: 'success'; value: TValue } | { status: 'error'; error: unknown } { + if (cause !== undefined) { + return { status: 'error', error: cause } + } + return { status: 'success', value } +} + +function navigateFrom(router: ServerWorker, location: ParsedLocation) { + return (options: any) => + router.navigate({ + ...options, + _fromLocation: location, + }) +} + +async function resolveSsr( + router: ServerWorker, + lane: MatchedLane, + index: number, +): Promise { + const match = lane.matches[index]! + const route = getRoute(router, match) + const parentSsr = lane.matches[index - 1]?.ssr + + if (router.isShell()) { + return route.id === rootRouteId + } + if (parentSsr === false) { + return false + } + + const inherit = (value: SSROption): SSROption => { + return value === true && parentSsr === 'data-only' ? 'data-only' : value + } + const defaultSsr = router.options.defaultSsr ?? true + const option = route.options.ssr + if (option === undefined) { + return inherit(defaultSsr) + } + if (typeof option !== 'function') { + return inherit(option) + } + + const context: SsrContextOptions = { + search: maybe(match.search, match.searchError), + params: maybe(match.params, match.paramsError), + location: lane.location, + matches: lane.matches.map((candidate) => ({ + index: candidate.index, + pathname: candidate.pathname, + fullPath: candidate.fullPath, + staticData: candidate.staticData, + id: candidate.id, + routeId: candidate.routeId, + search: maybe(candidate.search, candidate.searchError), + params: maybe(candidate.params, candidate.paramsError), + ssr: candidate.ssr, + })), + } + return inherit((await option(context)) ?? defaultSsr) +} + +function stampNotFound( + match: AnyRouteMatch, + outcome: LoadOutcome, +): LoadOutcome { + if (outcome[0] === notFound && !outcome[1].routeId) { + outcome[1].routeId = match.routeId + } + return outcome +} + +async function contextualize( + router: ServerWorker, + lane: MatchedLane, + preload: boolean, +): Promise { + let end = lane.matches.length + let failure: IndexedOutcome | undefined + let parentContext: Record = { + ...(router.options.context ?? {}), + } + + for (let index = 0; index < lane.matches.length; index++) { + const match = lane.matches[index]! + const route = getRoute(router, match) + try { + match.ssr = await resolveSsr(router, lane, index) + } catch (cause) { + failure = [index, stampNotFound(match, normalizeError(route, cause))] + end = index + break + } + + const context = { + ...parentContext, + ...match.__routeContext, + } + match.context = context + + const validationError = match.paramsError ?? match.searchError + if (validationError !== undefined) { + failure = [ + index, + stampNotFound(match, normalizeError(route, validationError)), + ] + end = index + break + } + + if (match.ssr === false || !route.options.beforeLoad) { + parentContext = context + continue + } + + const abortController = match.abortController + const options: BeforeLoadContextOptions< + any, + any, + any, + any, + any, + any, + any, + any, + any + > = { + search: match.search, + abortController, + params: match.params, + preload, + context, + location: lane.location, + navigate: navigateFrom(router, lane.location), + buildLocation: router.buildLocation, + cause: preload ? 'preload' : match.cause, + matches: lane.matches, + routeId: route.id, + ...router.options.additionalContext, + } + + try { + const beforeLoadContext = await route.options.beforeLoad(options) + const outcome = stampNotFound(match, normalize(beforeLoadContext, false)) + if (outcome[0] !== success) { + failure = [index, outcome] + end = index + break + } + match.__beforeLoadContext = beforeLoadContext + match.context = { + ...context, + ...beforeLoadContext, + } + parentContext = match.context + } catch (cause) { + if (cause instanceof Promise) { + throw cause + } + failure = [index, stampNotFound(match, normalizeError(route, cause))] + end = index + break + } + } + + return { + location: lane.location, + matches: lane.matches, + end, + failure, + } as ContextualizedLane +} + +function loaderContext( + router: ServerWorker, + lane: ContextualizedLane, + match: AnyRouteMatch, + route: AnyRoute, + index: number, + tasks: Array, + preload: boolean, +): LoaderFnContext { + return { + params: match.params, + deps: match.loaderDeps, + preload, + parentMatchPromise: tasks[index - 1]?.match as any, + abortController: match.abortController, + context: match.context, + location: lane.location, + navigate: navigateFrom(router, lane.location), + cause: preload ? 'preload' : match.cause, + route, + ...router.options.additionalContext, + } +} + +function startLoader( + router: ServerWorker, + lane: ContextualizedLane, + index: number, + tasks: Array, + preload: boolean, +): LoaderTask { + const match = lane.matches[index]! + const route = getRoute(router, match) + let outcome: Promise + + if (match.ssr === false) { + outcome = Promise.resolve([skipped]) + } else { + const option = route.options.loader + const loader = typeof option === 'function' ? option : option?.handler + if (!loader) { + outcome = Promise.resolve([success, undefined]) + } else { + const failed = (cause: unknown): LoadOutcome => + (cause as any)?.name === 'AbortError' && + !match.abortController.signal.aborted + ? [success, undefined] + : normalizeError(route, cause) + let value: unknown + let rejected = false + try { + value = loader( + loaderContext(router, lane, match, route, index, tasks, preload), + ) + } catch (cause) { + value = cause + rejected = true + } + outcome = Promise.resolve(value).then( + (result) => { + const normalized = rejected + ? failed(result) + : normalize(result, false) + return stampNotFound(match, normalized) + }, + (cause) => stampNotFound(match, failed(cause)), + ) + } + } + + const parentMatch = outcome.then((result) => { + const snapshot = { ...match } + if (result[0] === success) { + snapshot.loaderData = result[1] + snapshot.status = 'success' + snapshot.error = undefined + } else if (result[0] === error) { + snapshot.status = 'error' + snapshot.error = result[1] + } else if (result[0] === notFound) { + snapshot.status = 'notFound' + snapshot.error = result[1] + } + return snapshot + }) + + return { index, outcome, match: parentMatch } +} + +function getNotFoundBoundary( + router: ServerWorker, + matches: Array, + indexed: IndexedOutcome, +): number { + const [throwingIndex, outcome] = indexed + const cause = outcome[1] as NotFoundError + let index = cause.routeId + ? matches.findIndex((match) => match.routeId === cause.routeId) + : throwingIndex + if (index < 0) { + index = 0 + } + for (let candidate = index; candidate >= 0; candidate--) { + if (getRoute(router, matches[candidate]!).options.notFoundComponent) { + return candidate + } + } + return cause.routeId ? index : 0 +} + +function chooseFailure( + router: ServerWorker, + matches: Array, + outcomes: Array, +): IndexedOutcome | undefined { + let winner: IndexedOutcome | undefined + let winnerBoundary = Infinity + for (const indexed of outcomes) { + const kind = indexed[1][0] + if (kind === redirected) { + return indexed + } + const boundary = + kind === notFound + ? getNotFoundBoundary(router, matches, indexed) + : indexed[0] + if ( + boundary < winnerBoundary || + (boundary === winnerBoundary && + kind === error && + winner?.[1][0] === notFound) + ) { + winner = indexed + winnerBoundary = boundary + } + } + return winner +} + +function abortMatches(matches: Array, start = 0): void { + for (let index = start; index < matches.length; index++) { + matches[index]!.abortController.abort() + } +} + +function resolveServerRedirect( + router: ServerWorker, + location: ParsedLocation, + value: AnyRedirect, +): ServerLoadResult { + value.options._fromLocation = location + return { type: 'redirect', redirect: router.resolveRedirect(value) } +} + +function applyFailure( + router: ServerWorker, + lane: ContextualizedLane, + indexed: IndexedOutcome | undefined, +): { status: 200 | 404 | 500; boundary?: number; kind?: number } { + if (!indexed) { + const boundary = lane.matches.findIndex((match) => match.globalNotFound) + if (boundary >= 0) { + abortMatches(lane.matches, boundary + 1) + lane.matches.length = boundary + 1 + return { status: 404, boundary, kind: notFound } + } + return { status: 200 } + } + + const [index, outcome] = indexed + if (outcome[0] === error) { + const match = lane.matches[index]! + match.status = 'error' + match.error = outcome[1] + match.isFetching = false + abortMatches(lane.matches, index + 1) + lane.matches.length = index + 1 + return { status: 500, boundary: index, kind: error } + } + + const boundary = getNotFoundBoundary(router, lane.matches, indexed) + const match = lane.matches[boundary]! + const cause = outcome[1] as NotFoundError + cause.routeId = match.routeId + if (match.routeId === router.routeTree.id) { + match.status = 'success' + match.globalNotFound = true + match.error = cause + } else { + match.status = 'notFound' + match.error = cause + } + match.isFetching = false + abortMatches(lane.matches, boundary + 1) + lane.matches.length = boundary + 1 + return { status: 404, boundary, kind: notFound } +} + +async function loadSelectedChunks( + router: ServerWorker, + lane: ContextualizedLane, + terminal: ReturnType, +): Promise> { + const chunks = lane.matches.map(async (match, index) => { + if (match.ssr !== true) { + return undefined + } + const route = getRoute(router, match) + try { + if (terminal.boundary === index && terminal.kind === error) { + await loadRouteChunk(route, 'errorComponent') + } else if (terminal.boundary === index && terminal.kind === notFound) { + if (match.globalNotFound) { + await Promise.all([ + loadRouteChunk(route), + loadRouteChunk(route, 'notFoundComponent'), + ]) + } else { + await loadRouteChunk(route, 'notFoundComponent') + } + } else { + await loadRouteChunk(route) + } + return undefined + } catch (cause) { + return [index, stampNotFound(match, normalizeError(route, cause))] as + | IndexedOutcome + | undefined + } + }) + const settled = await Promise.all(chunks) + return settled.filter(Boolean) as Array +} + +async function ensureFailureChunk( + router: ServerWorker, + lane: ContextualizedLane, + terminal: ReturnType, +): Promise { + if (terminal.boundary === undefined || terminal.kind === undefined) { + return + } + const match = lane.matches[terminal.boundary]! + if (match.ssr !== true) { + return + } + const route = getRoute(router, match) + try { + await loadRouteChunk( + route, + terminal.kind === error ? 'errorComponent' : 'notFoundComponent', + ) + return + } catch (cause) { + return [ + terminal.boundary, + stampNotFound(match, normalizeError(route, cause)), + ] + } +} + +async function project(router: ServerWorker, lane: ReducedLane): Promise { + for (const match of lane.matches) { + const route = getRoute(router, match) + if ( + match.ssr !== true || + (!route.options.head && !route.options.scripts && !route.options.headers) + ) { + continue + } + const context = { + ssr: router.options.ssr, + matches: lane.matches, + match, + params: match.params, + loaderData: match.loaderData, + } + let closed = false + let failAssets!: () => void + const assetFailure = new Promise((resolve) => { + failAssets = resolve + }) + const run = ( + fn: ((context: any) => any) | undefined, + commit: (value: any) => void, + decorative: boolean, + ) => { + let value: unknown + try { + value = fn?.(context) + } catch (cause) { + console.error(`Error executing route asset for ${route.id}:`, cause) + if (decorative) { + failAssets() + } + return Promise.resolve() + } + return Promise.resolve(value).then( + (result) => { + if (!closed) { + commit(result) + } + }, + (cause) => { + console.error(`Error executing route asset for ${route.id}:`, cause) + if (decorative) { + failAssets() + } + }, + ) + } + const head = run( + route.options.head, + (value) => { + match.meta = value?.meta + match.links = value?.links + match.headScripts = value?.scripts + match.styles = value?.styles + }, + true, + ) + const scripts = run( + route.options.scripts, + (value) => { + match.scripts = value + }, + true, + ) + await run( + route.options.headers, + (value) => { + match.headers = value + }, + false, + ) + await Promise.race([Promise.all([head, scripts]), assetFailure]) + closed = true + } +} + +export async function loadServer( + router: AnyRouter, + location: ParsedLocation, + matchedMatches: Array, + preload = false, +): Promise { + const worker = router as ServerWorker + const matched = { + location, + matches: matchedMatches.map((match) => ({ + ...match, + __beforeLoadContext: undefined, + context: {}, + isFetching: false, + abortController: new AbortController(), + })), + } as MatchedLane + const lane = await contextualize(worker, matched, preload) + + let loaderEnd = lane.end + if (lane.failure?.[1][0] === redirected) { + loaderEnd = 0 + } else if (lane.failure?.[1][0] === notFound) { + loaderEnd = Math.min( + loaderEnd, + getNotFoundBoundary(worker, lane.matches, lane.failure) + 1, + ) + } + + const tasks: Array = [] + for (let index = 0; index < loaderEnd; index++) { + const task = startLoader(worker, lane, index, tasks, preload) + tasks.push(task) + } + + const outcomes = lane.failure ? [lane.failure] : [] + for (const task of tasks) { + const outcome = await task.outcome + if (outcome[0] === success) { + const match = lane.matches[task.index]! + match.loaderData = outcome[1] + match.status = 'success' + match.error = undefined + match.invalid = false + match.isFetching = false + match.updatedAt = Date.now() + } else if (outcome[0] !== skipped) { + outcomes.push([task.index, outcome]) + } + } + + let failure = chooseFailure(worker, lane.matches, outcomes) + if (failure?.[1][0] === redirected) { + abortMatches(lane.matches) + return resolveServerRedirect(worker, location, failure[1][1]) + } + + let terminal = applyFailure(worker, lane, failure) + const chunkOutcomes = await loadSelectedChunks(worker, lane, terminal) + if (chunkOutcomes.length) { + failure = chooseFailure(worker, lane.matches, [ + ...outcomes, + ...chunkOutcomes, + ]) + if (failure?.[1][0] === redirected) { + abortMatches(lane.matches) + return resolveServerRedirect(worker, location, failure[1][1]) + } + terminal = applyFailure(worker, lane, failure) + const boundaryFailure = await ensureFailureChunk(worker, lane, terminal) + if (boundaryFailure?.[1][0] === redirected) { + abortMatches(lane.matches) + return resolveServerRedirect(worker, location, boundaryFailure[1][1]) + } else if (boundaryFailure) { + terminal = applyFailure(worker, lane, boundaryFailure) + } + } + + await project(worker, { + location: lane.location, + matches: lane.matches, + } as ReducedLane) + return { type: 'render', status: terminal.status, matches: lane.matches } +} + +export async function loadServerRouter( + router: AnyRouter, + _opts?: Parameters[0], +): Promise { + router.updateLatestLocation() + const next = router.latestLocation + let result: ServerLoadResult + try { + const canonical = router.buildLocation({ + to: next.pathname, + search: true, + params: true, + hash: true, + state: true, + _includeValidateSearch: true, + }) + if (next.publicHref !== canonical.publicHref) { + const href = canonical.publicHref || '/' + throw canonical.external + ? redirect({ href }) + : redirect({ href, _builtLocation: canonical }) + } + + const fromLocation = router.stores.resolvedLocation.get() + const changeInfo = { + fromLocation, + toLocation: next, + pathChanged: fromLocation?.pathname !== next.pathname, + hrefChanged: fromLocation?.href !== next.href, + hashChanged: fromLocation?.hash !== next.hash, + } + router.emit({ type: 'onBeforeNavigate', ...changeInfo }) + router.emit({ type: 'onBeforeLoad', ...changeInfo }) + result = await loadServer(router, next, router.matchRoutes(next)) + } catch (cause) { + if (!isRedirect(cause)) { + throw cause + } + result = { type: 'redirect', redirect: cause } + } + + router._serverResult = result + router.batch(() => { + router.stores.location.set(next) + router.stores.status.set('idle') + if (result.type === 'render') { + router.stores.setMatches(result.matches) + router.stores.resolvedLocation.set(next) + } + }) + if (result.type === 'render') { + router._committedMatches = result.matches + } + router.commitLocationPromise?.resolve() + router.commitLocationPromise = undefined +} diff --git a/packages/router-core/src/redirect.ts b/packages/router-core/src/redirect.ts index b10fac6d7a..2ac387daeb 100644 --- a/packages/router-core/src/redirect.ts +++ b/packages/router-core/src/redirect.ts @@ -21,7 +21,6 @@ export type Redirect< */ _builtLocation?: ParsedLocation } - redirectHandled?: boolean } export type RedirectOptions< diff --git a/packages/router-core/src/route-chunks.ts b/packages/router-core/src/route-chunks.ts new file mode 100644 index 0000000000..f1dcbf5c2a --- /dev/null +++ b/packages/router-core/src/route-chunks.ts @@ -0,0 +1,68 @@ +import type { AnyRoute } from './route' + +type RouteComponentType = + | 'component' + | 'pendingComponent' + | 'errorComponent' + | 'notFoundComponent' + +function preloadComponent( + route: AnyRoute, + type: RouteComponentType, +): Promise | undefined { + return (route.options[type] as any)?.preload?.() +} + +function loadComponents(route: AnyRoute): Promise | undefined { + const component = preloadComponent(route, 'component') + const pending = preloadComponent(route, 'pendingComponent') + if (component && pending) { + return Promise.all([component, pending]).then(() => {}) + } + return component ?? pending +} + +export function loadRouteChunk( + route: AnyRoute, + componentType?: 'errorComponent' | 'notFoundComponent', +): Promise | undefined { + const afterLazy = () => + componentType + ? preloadComponent(route, componentType) + : loadComponents(route) + + const current = route._lazy + if (current) { + return current === true ? afterLazy() : current.then(afterLazy) + } + if (!route.lazyFn) { + route._lazy = true + return afterLazy() + } + + const promise = route.lazyFn().then( + (lazyRoute) => { + // HMR clears the owner before an obsolete import can settle. + if (route._lazy === promise) { + const { id: _id, ...options } = lazyRoute.options + Object.assign(route.options, options) + route._lazy = true + } + }, + (error) => { + if (route._lazy === promise) { + route._lazy = undefined + } + throw error + }, + ) + route._lazy = promise + return promise.then(afterLazy) +} + +export function routeNeedsPreload(route: AnyRoute): boolean { + return !!( + (route.options.component as any)?.preload || + (route.options.pendingComponent as any)?.preload + ) +} diff --git a/packages/router-core/src/route.ts b/packages/router-core/src/route.ts index 2de7dc57f0..eae2f15e30 100644 --- a/packages/router-core/src/route.ts +++ b/packages/router-core/src/route.ts @@ -700,10 +700,6 @@ export interface Route< THandlers > isRoot: TParentRoute extends AnyRoute ? true : false - /** @internal */ - _componentsPromise?: Promise - /** @internal */ - _componentsLoaded?: boolean lazyFn?: () => Promise< LazyRoute< Route< @@ -729,9 +725,7 @@ export interface Route< > > /** @internal */ - _lazyPromise?: Promise - /** @internal */ - _lazyLoaded?: boolean + _lazy?: Promise | true rank: number to: TrimPathRight init: (opts: { originalIndex: number }) => void @@ -1711,10 +1705,7 @@ export class BaseRoute< > > /** @internal */ - _lazyPromise?: Promise - /** @internal */ - _componentsPromise?: Promise - + _lazy?: Promise | true constructor( options?: RouteOptions< TRegister, diff --git a/packages/router-core/src/router.ts b/packages/router-core/src/router.ts index 2197dab737..4f66fe1ab3 100644 --- a/packages/router-core/src/router.ts +++ b/packages/router-core/src/router.ts @@ -1,8 +1,11 @@ import { createBrowserHistory, parseHref } from '@tanstack/history' -import { isServer } from '@tanstack/router-core/isServer' +import { + isServer, + loadServer, + loadServerRouter, +} from '@tanstack/router-core/isServer' import { DEFAULT_PROTOCOL_ALLOWLIST, - createControlledPromise, decodePath, deepEqual, encodePathLikeUrl, @@ -35,8 +38,14 @@ 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 { + discardMatchResources, + loadClientRouter, + preloadClientRoute, + refreshClientRoute, +} from './load.client' +import { loadRouteChunk, routeNeedsPreload } from './route-chunks' import { composeRewrites, executeRewriteInput, @@ -51,6 +60,12 @@ import type { } from './new-process-route-tree' import type { SearchParser, SearchSerializer } from './searchParams' import type { AnyRedirect, ResolvedRedirect } from './redirect' +import type { + LoadTransaction, + LoaderFlight, + PendingSession, +} from './load.client' +import type { ServerLoadResult } from './load.server' import type { HistoryAction, HistoryLocation, @@ -62,7 +77,6 @@ import type { import type { Awaitable, Constrain, - ControlledPromise, NoInfer, NonNullableUpdater, PickAsRequired, @@ -106,7 +120,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 +557,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 { @@ -622,6 +631,23 @@ export interface MatchRoutesOpts { preload?: boolean throwOnError?: boolean dest?: BuildNextOptions + /** @internal */ + _controller?: AbortController + /** @internal */ + _isCurrent?: () => boolean + /** @internal */ + _canReuse?: (route: AnyRoute) => boolean +} + +function assertMatchOwner(opts?: MatchRoutesOpts) { + const controller = opts?._controller + if ( + controller && + (controller.signal.aborted || opts._isCurrent?.() === false) + ) { + controller.abort() + throw controller.signal + } } export type InferRouterContext = @@ -756,7 +782,7 @@ export type CommitLocationFn = ({ ...next }: ParsedLocation & CommitLocationOptions) => Promise -export type StartTransitionFn = (fn: () => void) => void +export type StartTransitionFn = (fn: () => void) => Promise export interface MatchRoutesFn { ( @@ -985,7 +1011,14 @@ export class RouterCore< shouldViewTransition?: boolean | ViewTransitionOptions = undefined isViewTransitionTypesSupported?: boolean = undefined subscribers = new Set>() - viewTransitionPromise?: ControlledPromise + _tx?: LoadTransaction + _flights?: Map + /** Terminal semantic lane; pending presentation never becomes a planning base. */ + _committedMatches?: Array + _pending?: PendingSession + _serverResult?: ServerLoadResult + _rendered?: () => void + declare _refreshRoute: ((routeId: string) => Promise) | undefined // Must build in constructor stores!: RouterStores @@ -1056,11 +1089,10 @@ export class RouterCore< } } - // This is a default implementation that can optionally be overridden - // by the router provider once rendered. We provide this so that the - // router can be used in a non-react environment if necessary - startTransition: StartTransitionFn = (fn) => fn() - + startTransition: StartTransitionFn = async (fn) => { + fn() + return false + } isShell() { return !!this.options.isShell } @@ -1298,7 +1330,9 @@ export class RouterCore< emit: EmitFn = (routerEvent) => { this.subscribers.forEach((listener) => { if (listener.eventType === routerEvent.type) { - listener.fn(routerEvent) + try { + listener.fn(routerEvent) + } catch {} } }) } @@ -1408,10 +1442,6 @@ export class RouterCore< return branch } - get looseRoutesById() { - return this.routesById as Record - } - matchRoutes: MatchRoutesFn = ( pathnameOrNext: string | ParsedLocation, locationSearchOrOpts?: AnySchema | MatchRoutesOpts, @@ -1440,10 +1470,20 @@ export class RouterCore< return parentContext } + private getSemanticMatch(matchId: string) { + const committed = this._committedMatches + return committed + ? (committed.find((match) => match.id === matchId) ?? + this.stores.cachedMatchStores.get(matchId)?.get()) + : this.stores.matchStores.get(matchId)?.get() + } + private matchRoutesInternal( next: ParsedLocation, opts?: MatchRoutesOpts, ): Array { + const canReuse = + process.env.NODE_ENV !== 'production' ? opts?._canReuse : undefined const matchedRoutesResult = this.getMatchedRoutes(next.pathname) const { foundRoute, routeParams } = matchedRoutesResult let { matchedRoutes } = matchedRoutesResult @@ -1474,13 +1514,15 @@ export class RouterCore< // 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()) + for (const match of this._committedMatches ?? this.stores.matches.get()) { + const route = (this.routesById as Record)[match.routeId] + if (route && canReuse?.(route) !== false) { + previousActiveMatchesByRouteId.set(match.routeId, match) } } for (let index = 0; index < matchedRoutes.length; index++) { + assertMatchOwner(opts) const route = matchedRoutes[index]! // Take each matched route and resolve + validate its search params // This has to happen serially because each route's search params @@ -1527,6 +1569,7 @@ export class RouterCore< searchError = searchParamError } } + assertMatchOwner(opts) // This is where we need to call route.options.loaderDeps() to get any additional // deps that the route's loader function might need to run. We need to do this @@ -1539,6 +1582,7 @@ export class RouterCore< }) ?? '' const loaderDepsHash = loaderDeps ? JSON.stringify(loaderDeps) : '' + assertMatchOwner(opts) const { interpolatedPath, usedParams } = interpolatePath({ path: route.fullPath, @@ -1561,7 +1605,8 @@ export class RouterCore< // explicit deps loaderDepsHash - const existingMatch = this.getMatch(matchId) + const existingMatch = + canReuse?.(route) === false ? undefined : this.getSemanticMatch(matchId) const previousMatch = previousActiveMatchesByRouteId.get(route.id) @@ -1632,12 +1677,9 @@ export class RouterCore< error: undefined, paramsError, __routeContext: undefined, - _nonReactive: { - loadPromise: createControlledPromise(), - }, __beforeLoadContext: undefined, context: {}, - abortController: new AbortController(), + abortController: opts?._controller ?? new AbortController(), fetchCount: 0, cause, loaderDeps: previousMatch @@ -1674,9 +1716,15 @@ export class RouterCore< } for (let index = 0; index < matches.length; index++) { + assertMatchOwner(opts) const match = matches[index]! - const route = this.looseRoutesById[match.routeId]! - const existingMatch = this.getMatch(match.id) + const route = (this.routesById as Record)[ + match.routeId + ]! + const existingMatch = + canReuse?.(route) === false + ? undefined + : this.getSemanticMatch(match.id) // Update the match's params const previousMatch = previousActiveMatchesByRouteId.get(match.routeId) @@ -1702,7 +1750,7 @@ export class RouterCore< buildLocation: this.buildLocation, cause: match.cause, abortController: match.abortController, - preload: !!match.preload, + preload: !!opts?.preload, matches, routeId: route.id, } @@ -1733,7 +1781,7 @@ export class RouterCore< /** * Lightweight route matching for buildLocation. * Only computes fullPath, accumulated search, and params - skipping expensive - * operations like AbortController, ControlledPromise, loaderDeps, and full match objects. + * operations like AbortController, loaderDeps, and full match objects. */ private matchRoutesLightweight( location: ParsedLocation, @@ -1808,37 +1856,6 @@ export class RouterCore< return result } - cancelMatch = (id: string) => { - const match = this.getMatch(id) - - if (!match) return - - 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) => { - if (this.stores.pendingMatchStores.has(matchId)) { - return - } - - const match = this.stores.matchStores.get(matchId)?.get() - if (!match) { - return - } - - if (match.status === 'pending' || match.isFetching === 'loader') { - this.cancelMatch(matchId) - } - }) - } - /** * Build the next ParsedLocation from navigation options without committing. * Resolves `to`/`from`, params/search/hash/state, applies search validation @@ -2154,7 +2171,7 @@ export class RouterCore< return buildWithMatches(opts) } - commitLocationPromise: undefined | ControlledPromise + commitLocationPromise: (Promise & { resolve: () => void }) | undefined /** * Commit a previously built location to history (push/replace), optionally @@ -2189,11 +2206,16 @@ export class RouterCore< const isSameUrl = trimPathRight(this.latestLocation.href) === trimPathRight(next.href) - let previousCommitPromise = this.commitLocationPromise - this.commitLocationPromise = createControlledPromise(() => { + const previousCommitPromise = this.commitLocationPromise + let resolve!: () => void + const commitPromise = new Promise((done) => { + resolve = done + }) as Promise & { resolve: () => void } + commitPromise.resolve = () => { + resolve() previousCommitPromise?.resolve() - previousCommitPromise = undefined - }) + } + this.commitLocationPromise = commitPromise // Don't commit to history if nothing changed if (isSameUrl && isSameState()) { @@ -2412,257 +2434,29 @@ export class RouterCore< }) } - latestLoadPromise: undefined | Promise - - 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): Promise => { + if (isServer ?? this.isServer) { + return loadServerRouter(this, opts) + } + + this._serverResult = undefined + this.updateLatestLocation() 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) + if (historyAction) { + locationHistoryActions.set(this.latestLocation, historyAction) + } else { + locationHistoryActions.delete(this.latestLocation) } + const locationChangeInfo = getLocationChangeInfo( + this.latestLocation, + this.stores.resolvedLocation.get(), + ) + this.emit({ type: 'onBeforeNavigate', ...locationChangeInfo }) + this.emit({ type: 'onBeforeLoad', ...locationChangeInfo }) + await loadClientRouter(this, opts) } - startViewTransition = (fn: () => Promise) => { + startViewTransition = async (fn: () => Promise) => { // Determine if we should start a view transition from the navigation // or from the router default const shouldViewTransition = @@ -2697,7 +2491,7 @@ export class RouterCore< : shouldViewTransition.types if (resolvedViewTransitionTypes === false) { - fn() + await fn() return } @@ -2709,58 +2503,19 @@ export class RouterCore< startViewTransitionParams = fn } - document.startViewTransition(startViewTransitionParams) + await document.startViewTransition(startViewTransitionParams) + .updateCallbackDone } else { - fn() + await fn() } } - 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) - } - } - }) - } - - getMatch: GetMatchFn = (matchId: string): AnyRouteMatch | undefined => { - return ( - this.stores.cachedMatchStores.get(matchId)?.get() ?? - this.stores.pendingMatchStores.get(matchId)?.get() ?? - this.stores.matchStores.get(matchId)?.get() - ) - } - /** * Invalidate the current matches and optionally force them back into a pending state. * * - Marks all matches that pass the optional `filter` as `invalid: true`. - * - If `forcePending` is true, or a match is currently in `'error'` or `'notFound'` status, - * its status is reset to `'pending'` and its `error` cleared so that the loader is re-run - * on the next `load()` call (eg. after HMR or a manual invalidation). + * The next load decides when to publish pending UI, so invalidation does not + * mutate the currently rendered status. */ invalidate: InvalidateFn< RouterCore< @@ -2773,12 +2528,17 @@ export class RouterCore< > = (opts) => { const invalidate = (d: MakeRouteMatch) => { if (opts?.filter?.(d as MakeRouteMatchUnion) ?? true) { + const route = this.routesById[d.routeId] as AnyRoute return { ...d, invalid: true, - ...(opts?.forcePending || - d.status === 'error' || - d.status === 'notFound' + ...((opts?.forcePending || + d.status === 'error' || + d.status === 'notFound') && + (route.options.loader || + route.options.beforeLoad || + route.lazyFn || + routeNeedsPreload(route)) ? ({ status: 'pending', error: undefined } as const) : undefined), } @@ -2786,29 +2546,25 @@ export class RouterCore< return d } + const committed = (this._committedMatches ?? this.stores.matches.get()).map( + invalidate, + ) + this._committedMatches = committed 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.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') if (!redirect.options.href || redirect.options._builtLocation) { const location = redirect.options._builtLocation ?? this.buildLocation(redirect.options) - const href = this.getParsedLocationHref(location) + const href = location.publicHref || '/' redirect.options.href = href redirect.headers.set('Location', href) } else if (locationHeader) { @@ -2845,43 +2601,17 @@ export class RouterCore< } clearCache: ClearCacheFn = (opts) => { + const cached = this.stores.cachedMatches.get() const filter = opts?.filter - if (filter !== undefined) { - this.stores.setCached( - this.stores.cachedMatches - .get() - .filter((m) => !filter(m as MakeRouteMatchUnion)), - ) - } else { - this.stores.setCached([]) - } - } - - 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 + const retained: Array = [] + for (const match of cached) { + if (filter && !filter(match as MakeRouteMatchUnion)) { + retained.push(match) + } else { + discardMatchResources(this, [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(retained) } loadRouteChunk = loadRouteChunk @@ -2892,50 +2622,49 @@ 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]) + if (!(isServer ?? this.isServer)) { + return preloadClientRoute(this, opts) } - 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) - } - }, - }) + const next = opts._builtLocation ?? this.buildLocation(opts as any) - return matches + try { + const result = await loadServer( + this, + next, + this.matchRoutes(next, { + throwOnError: true, + preload: true, + dest: opts, + }), + true, + ) + if (result.type === 'redirect') { + if (result.redirect.options.reloadDocument) { + return + } + return this.preloadRoute({ + ...result.redirect.options, + _fromLocation: next, + }) + } + if (result.matches.some((match) => match.status !== 'success')) { + return + } + + const active = new Set(this.stores.matchesId.get()) + const candidates = result.matches.filter((match) => { + match.preload = true + return !active.has(match.id) + }) + const ids = new Set(candidates.map((match) => match.id)) + this.stores.setCached( + this.stores.cachedMatches + .get() + .filter((match) => !ids.has(match.id)) + .concat(candidates), + ) + return result.matches } catch (err) { if (isRedirect(err)) { if (err.options.reloadDocument) { @@ -2976,7 +2705,9 @@ export class RouterCore< } const pending = - opts?.pending === undefined ? !this.stores.isLoading.get() : opts.pending + opts?.pending === undefined + ? this.stores.status.get() !== 'pending' + : opts.pending const baseLocation = pending ? this.latestLocation @@ -3016,11 +2747,19 @@ export class RouterCore< serverSsr?: ServerSsr serverSsrLifecycle?: RouterSsrLifecycle +} - hasNotFoundMatch = () => { - return this.stores.matches - .get() - .some((d) => d.status === 'notFound' || d.globalNotFound) +if (process.env.NODE_ENV !== 'production') { + RouterCore.prototype._refreshRoute = async function (routeId) { + this._serverResult = undefined + this.updateLatestLocation() + const locationChangeInfo = getLocationChangeInfo( + this.latestLocation, + this.stores.resolvedLocation.get(), + ) + this.emit({ type: 'onBeforeNavigate', ...locationChangeInfo }) + this.emit({ type: 'onBeforeLoad', ...locationChangeInfo }) + await refreshClientRoute(this, routeId) } } @@ -3057,14 +2796,11 @@ export function getInitialRouterState( location: ParsedLocation, ): RouterState { return { - loadedAt: 0, isLoading: false, - isTransitioning: false, status: 'idle', resolvedLocation: undefined, location, matches: [], - statusCode: 200, } } @@ -3254,11 +2990,16 @@ function findGlobalNotFoundRouteId( routes: ReadonlyArray, ) { if (notFoundMode !== 'root') { + let fallback for (let i = routes.length - 1; i >= 0; i--) { const route = routes[i]! - if (route.children) { + if (route.options.notFoundComponent) { return route.id } + fallback ||= route.children && route.id + } + if (fallback) { + return fallback } } return rootRouteId diff --git a/packages/router-core/src/ssr/createRequestHandler.ts b/packages/router-core/src/ssr/createRequestHandler.ts index 32377b2bea..d05b217804 100644 --- a/packages/router-core/src/ssr/createRequestHandler.ts +++ b/packages/router-core/src/ssr/createRequestHandler.ts @@ -84,9 +84,9 @@ function getRequestHeaders(opts: { router: AnyRouter }): Headers { } // Handle Redirects - const redirect = opts.router.stores.redirect.get() - if (redirect) { - matchHeaders.push(redirect.headers) + const result = opts.router._serverResult + if (result?.type === 'redirect') { + matchHeaders.push(result.redirect.headers) } return mergeHeaders( diff --git a/packages/router-core/src/ssr/ssr-client.ts b/packages/router-core/src/ssr/ssr-client.ts index 2aa5358ac0..9f79934964 100644 --- a/packages/router-core/src/ssr/ssr-client.ts +++ b/packages/router-core/src/ssr/ssr-client.ts @@ -1,310 +1 @@ -import { invariant } from '../invariant' -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 { AnyRouteMatch } from '../Matches' -import type { AnyRouter } from '../router' -import type { RouteContextOptions } from '../route' -import type { AnySerializationAdapter } from './serializer/transformer' - -declare global { - interface Window { - [GLOBAL_TSR]?: TsrSsrGlobal - [GLOBAL_SEROVAL]?: any - } -} - -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) { - 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!', - ) - } - - invariant() - } - - const serializationAdapters = router.options.serializationAdapters as - | Array - | undefined - - if (serializationAdapters?.length) { - const fromSerializableMap = new Map() - serializationAdapters.forEach((adapter) => { - fromSerializableMap.set(adapter.key, adapter.fromSerializable) - }) - window.$_TSR.t = fromSerializableMap - window.$_TSR.buffer.forEach((script) => script()) - } - window.$_TSR.initialized = true - - if (!window.$_TSR.router) { - 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!', - ) - } - - 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 - - router.ssr = { - manifest, - } - const meta = document.querySelector('meta[property="csp-nonce"]') as - | HTMLMetaElement - | undefined - const nonce = meta?.content - router.options.ssr = { - nonce, - } - - // Allow the user to handle custom hydration data before matching routes. - // This lets hydration install router config that affects matching, e.g. rewrites. - await router.options.hydrate?.(dehydratedData) - - // Hydrate the router state - const matches = router.matchRoutes(router.stores.location.get()) - - // 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 - } - - hydrateMatch(match, dehydratedMatch) - setRouteSsr(match) - - match._nonReactive.dehydrated = match.ssr !== false - - if (match.ssr === 'data-only' || match.ssr === false) { - if (firstNonSsrMatchIndex === undefined) { - firstNonSsrMatchIndex = match.index - setMatchForcePending(match) - } - } - }) - - router.stores.setMatches(matches) - - // 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]! - - 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 = - { - deps: match.loaderDeps, - params: match.params, - context: parentContext ?? {}, - location, - navigate: (opts: any) => - router.navigate({ - ...opts, - _fromLocation: location, - }), - buildLocation: router.buildLocation, - cause: match.cause, - abortController: match.abortController, - preload: false, - matches, - routeId: route.id, - } - match.__routeContext = - route.options.context(contextFnContext) ?? undefined - } - - 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 - }) - // 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 - } - - // 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() - .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.', - ) - } - - invariant() - } - setMatchForcePending(match) - - match._displayPending = true - match._nonReactive.displayPendingPromise = loadPromise - - loadPromise.then(() => { - router.batch(() => { - // ensure router is not in status 'pending' anymore - // this usually happens in Transitioner but if loading synchronously resolves, - // Transitioner won't be rendered while loading so it cannot track the change from loading:true to loading:false - if (router.stores.status.get() === 'pending') { - 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 routeChunkPromise -} +export { hydrate } from '../hydrate' diff --git a/packages/router-core/src/ssr/ssr-server.ts b/packages/router-core/src/ssr/ssr-server.ts index 31db2f5e41..110cf704b5 100644 --- a/packages/router-core/src/ssr/ssr-server.ts +++ b/packages/router-core/src/ssr/ssr-server.ts @@ -540,10 +540,6 @@ export function attachRouterServerSsrUtils({ manifest: manifestToDehydrate, matches, } - const lastMatchId = matchesToDehydrate[matchesToDehydrate.length - 1]?.id - if (lastMatchId) { - dehydratedRouter.lastMatchId = dehydrateSsrMatchId(lastMatchId) - } const dehydratedData = await router.options.dehydrate?.() if (dehydratedData) { dehydratedRouter.dehydratedData = dehydratedData diff --git a/packages/router-core/src/stores.ts b/packages/router-core/src/stores.ts index c2ab8311c3..5f86eef934 100644 --- a/packages/router-core/src/stores.ts +++ b/packages/router-core/src/stores.ts @@ -5,7 +5,6 @@ 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 { @@ -71,24 +70,13 @@ export function createNonReactiveReadonlyStore( 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 */ - cachedIds: RouterWritableStore> matches: ReadableStore> - pendingMatches: ReadableStore> cachedMatches: ReadableStore> - firstId: ReadableStore - hasPending: ReadableStore matchRouteDeps: ReadableStore<{ locationHref: string resolvedLocationHref: string | undefined @@ -97,7 +85,6 @@ export interface RouterStores { __store: RouterReadableStore> matchStores: Map - pendingMatchStores: Map cachedMatchStores: Map /** @@ -111,7 +98,6 @@ export interface RouterStores { ) => RouterReadableStore setMatches: (nextMatches: Array) => void - setPending: (nextMatches: Array) => void setCached: (nextMatches: Array) => void } @@ -123,39 +109,22 @@ export function createRouterStores( // non reactive utilities const matchStores = new Map() - const pendingMatchStores = new Map() const cachedMatchStores = new Map() // atoms 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>([]) // 1st order derived stores const matches = createReadonlyStore(() => readPoolMatches(matchStores, matchesId.get()), ) - const pendingMatches = createReadonlyStore(() => - readPoolMatches(pendingMatchStores, pendingIds.get()), - ) const cachedMatches = createReadonlyStore(() => readPoolMatches(cachedMatchStores, cachedIds.get()), ) - const firstId = createReadonlyStore(() => matchesId.get()[0]) - const hasPending = createReadonlyStore(() => - matchesId.get().some((matchId) => { - const store = matchStores.get(matchId) - return store?.get().status === 'pending' - }), - ) const matchRouteDeps = createReadonlyStore(() => ({ locationHref: location.get().href, resolvedLocationHref: resolvedLocation.get()?.href, @@ -165,14 +134,10 @@ export function createRouterStores( // compatibility "big" state store const __store = createReadonlyStore(() => ({ status: status.get(), - loadedAt: loadedAt.get(), - isLoading: isLoading.get(), - isTransitioning: isTransitioning.get(), + isLoading: status.get() === 'pending', matches: matches.get(), location: location.get(), resolvedLocation: resolvedLocation.get(), - statusCode: statusCode.get(), - redirect: redirect.get(), })) // Per-routeId computed store cache. @@ -215,28 +180,17 @@ export function createRouterStores( const store = { // atoms status, - loadedAt, - isLoading, - isTransitioning, location, resolvedLocation, - statusCode, - redirect, matchesId, - pendingIds, - cachedIds, // derived matches, - pendingMatches, cachedMatches, - firstId, - hasPending, matchRouteDeps, // non-reactive state matchStores, - pendingMatchStores, cachedMatchStores, // compatibility "big" state @@ -247,7 +201,6 @@ export function createRouterStores( // methods setMatches, - setPending, setCached, } @@ -266,16 +219,6 @@ export function createRouterStores( ) } - function setPending(nextMatches: Array) { - reconcileMatchPool( - nextMatches, - pendingMatchStores, - pendingIds, - createMutableStore, - batch, - ) - } - function setCached(nextMatches: Array) { reconcileMatchPool( nextMatches, 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..72d478317e --- /dev/null +++ b/packages/router-core/tests/background-assets-stale.test.ts @@ -0,0 +1,77 @@ +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +describe('background decorative asset failure', () => { + beforeEach(() => { + vi.useFakeTimers() + vi.setSystemTime(0) + }) + + afterEach(() => { + vi.useRealTimers() + }) + + test('commits fresh loader data while preserving the previous projected assets', 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 + // 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 }], + } + }, + 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)) + + resolveStaleReload({ title: 'fresh' }) + await vi.waitFor(() => + expect(getMatch()?.loaderData).toEqual({ title: 'fresh' }), + ) + + expect(getMatch()?.meta).toEqual([{ title: 'old' }]) + }) +}) diff --git a/packages/router-core/tests/background-trim-abort.test.ts b/packages/router-core/tests/background-trim-abort.test.ts new file mode 100644 index 0000000000..a4f506410b --- /dev/null +++ b/packages/router-core/tests/background-trim-abort.test.ts @@ -0,0 +1,120 @@ +import { expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +test('background error trimming aborts a discarded descendant loader signal', async () => { + let parentLoads = 0 + let childLoads = 0 + let retainedParentSignal: AbortSignal | undefined + let discardedChildSignal: AbortSignal | undefined + const parentError = new Error('parent background reload failed') + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: ({ abortController }) => { + if (++parentLoads > 1) { + retainedParentSignal = abortController.signal + throw parentError + } + return 'initial parent data' + }, + errorComponent: () => null, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: ({ abortController }) => { + if (++childLoads > 1) { + discardedChildSignal = abortController.signal + } + return 'child data' + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + }) + + await router.load() + await router.invalidate() + + await expect.poll(() => router.state.matches.at(-1)?.status).toBe('error') + + expect(router.state.matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + parentRoute.id, + ]) + expect(retainedParentSignal).toBeDefined() + expect(discardedChildSignal).toBeDefined() + expect(discardedChildSignal).not.toBe(retainedParentSignal) + expect(retainedParentSignal?.aborted).toBe(false) + expect(discardedChildSignal?.aborted).toBe(true) +}) + +test('foreground supersession aborts every loader in a background batch', async () => { + let parentLoads = 0 + let childLoads = 0 + const backgroundSignals: Array = [] + + const waitForAbort = (signal: AbortSignal) => + new Promise((_resolve, reject) => { + signal.addEventListener( + 'abort', + () => { + const error = new Error('aborted') + error.name = 'AbortError' + reject(error) + }, + { once: true }, + ) + }) + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: ({ abortController }) => { + if (++parentLoads > 1) { + backgroundSignals.push(abortController.signal) + return waitForAbort(abortController.signal) + } + return 'initial parent data' + }, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: ({ abortController }) => { + if (++childLoads > 1) { + backgroundSignals.push(abortController.signal) + return waitForAbort(abortController.signal) + } + return 'initial child data' + }, + }) + const otherRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/other', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([childRoute]), + otherRoute, + ]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + }) + + await router.load() + const revalidation = router.invalidate() + await vi.waitFor(() => expect(backgroundSignals).toHaveLength(2)) + + await router.navigate({ to: '/other' }) + await revalidation + + expect(backgroundSignals[0]).not.toBe(backgroundSignals[1]) + expect(backgroundSignals.every((signal) => signal.aborted)).toBe(true) + expect(router.state.matches.at(-1)?.routeId).toBe(otherRoute.id) +}) 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..3722c08d51 --- /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.state.location.pathname).toBe('/slow') + expect( + router.state.matches.find((m) => m.routeId === slowRoute.id), + ).toMatchObject({ + status: 'success', + loaderData: 'slow data', + }) + unblock() + }) +}) 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..4616f20476 --- /dev/null +++ b/packages/router-core/tests/boundary-component-chunk.test.ts @@ -0,0 +1,83 @@ +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() + + // 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/callbacks.test.ts b/packages/router-core/tests/callbacks.test.ts index 1673626f7e..7a1b062d4f 100644 --- a/packages/router-core/tests/callbacks.test.ts +++ b/packages/router-core/tests/callbacks.test.ts @@ -200,10 +200,6 @@ describe('callbacks', () => { )?.id expect(page2MatchId).toBeDefined() expect(page2MatchId).not.toBe(page1MatchId) - expect( - router.stores.cachedIds.get().some((id) => id === page1MatchId), - ).toBe(true) - await router.navigate({ to: '/foo', search: { page: '1' } }) expect(loader).toHaveBeenCalledTimes(2) expect(router.state.matches.some((d) => d.id === page1MatchId)).toBe(true) @@ -225,10 +221,6 @@ describe('callbacks', () => { )?.id expect(post2MatchId).toBeDefined() expect(post2MatchId).not.toBe(post1MatchId) - expect( - router.stores.cachedIds.get().some((id) => id === post1MatchId), - ).toBe(true) - await router.navigate({ to: '/posts/$postId', params: { postId: '1' } }) expect(loader).toHaveBeenCalledTimes(2) expect(router.state.matches.some((d) => d.id === post1MatchId)).toBe(true) 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..bf9fa369d4 --- /dev/null +++ b/packages/router-core/tests/chunk-failure-lifecycle.test.ts @@ -0,0 +1,82 @@ +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('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 + + 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/client-lane-adversarial.test.ts b/packages/router-core/tests/client-lane-adversarial.test.ts new file mode 100644 index 0000000000..5f2413e0f5 --- /dev/null +++ b/packages/router-core/tests/client-lane-adversarial.test.ts @@ -0,0 +1,448 @@ +import { afterEach, describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { + BaseRootRoute, + BaseRoute, + createControlledPromise, + notFound, + redirect, +} from '../src' +import { createTestRouter } from './routerTestUtils' + +afterEach(() => { + vi.useRealTimers() +}) + +function abortAwareGate(signal: AbortSignal): Promise { + return new Promise((_resolve, reject) => { + signal.addEventListener( + 'abort', + () => { + const error = new Error('aborted') + error.name = 'AbortError' + reject(error) + }, + { once: true }, + ) + }) +} + +describe('adversarial client lane ownership', () => { + test.each(['onBeforeNavigate', 'onBeforeLoad'] as const)( + 'a throwing %s listener cannot interrupt later listeners or navigation finalization', + async (eventType) => { + const listenerError = new Error(`${eventType} listener failed`) + const laterListener = vi.fn() + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const targetLoader = vi.fn(() => 'target data') + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + loader: targetLoader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + router.subscribe(eventType, () => { + throw listenerError + }) + router.subscribe(eventType, laterListener) + + await router.navigate({ to: '/target' }) + await new Promise((resolve) => setTimeout(resolve, 0)) + + expect(laterListener).toHaveBeenCalledTimes(1) + expect(router.state.location.pathname).toBe('/target') + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: targetRoute.id, + status: 'success', + }) + expect(targetLoader).toHaveBeenCalledTimes(1) + }, + ) + + test('superseding a published pending lane diffs lifecycle hooks from the last final lane', async () => { + const aOnLeave = vi.fn() + const bOnEnter = vi.fn() + const bOnLeave = vi.fn() + const cOnEnter = vi.fn() + + const rootRoute = new BaseRootRoute({}) + const aRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/a', + onLeave: aOnLeave, + }) + const bRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/b', + pendingMs: 0, + pendingComponent: () => null, + loader: ({ abortController }) => abortAwareGate(abortController.signal), + onEnter: bOnEnter, + onLeave: bOnLeave, + }) + const cRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/c', + onEnter: cOnEnter, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([aRoute, bRoute, cRoute]), + history: createMemoryHistory({ initialEntries: ['/a'] }), + }) + + await router.load() + aOnLeave.mockClear() + + const bNavigation = router.navigate({ to: '/b' }) + await vi.waitFor(() => + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: bRoute.id, + status: 'pending', + }), + ) + + await router.navigate({ to: '/c' }) + await bNavigation + + expect(router.state.matches.at(-1)?.routeId).toBe(cRoute.id) + expect(aOnLeave).toHaveBeenCalledTimes(1) + expect(bOnEnter).not.toHaveBeenCalled() + expect(bOnLeave).not.toHaveBeenCalled() + expect(cOnEnter).toHaveBeenCalledTimes(1) + }) + + test('a shallow regular error wins over a deeper concurrent notFound', async () => { + const parentError = new Error('parent failed') + const childHead = vi.fn(() => ({ + meta: [{ title: 'unreachable child' }], + })) + const childOnEnter = vi.fn() + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: () => { + throw parentError + }, + errorComponent: () => null, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: () => { + throw notFound() + }, + notFoundComponent: () => null, + head: childHead, + onEnter: childOnEnter, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + }) + + await router.load() + + expect(router.state.matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + parentRoute.id, + ]) + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: parentRoute.id, + status: 'error', + error: parentError, + }) + expect(childHead).not.toHaveBeenCalled() + expect(childOnEnter).not.toHaveBeenCalled() + }) + + test('a redirect aborts the discarded loader generation before pending UI publishes', async () => { + let redirectSignal: AbortSignal | undefined + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const sourceRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/source', + loader: ({ abortController }) => { + redirectSignal = abortController.signal + throw redirect({ to: '/target' }) + }, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, sourceRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.navigate({ to: '/source' }) + + expect(router.state.location.pathname).toBe('/target') + expect(router.state.matches.at(-1)?.routeId).toBe(targetRoute.id) + expect(redirectSignal?.aborted).toBe(true) + }) + + test('trimming a successful descendant aborts its discarded loader generation', async () => { + const parentError = new Error('parent failed') + let childSignal: AbortSignal | undefined + let deferredRequestAborted = false + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: () => { + throw parentError + }, + errorComponent: () => null, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: ({ abortController }) => { + childSignal = abortController.signal + const deferredRequest = new Promise<'aborted'>((resolve) => { + abortController.signal.addEventListener( + 'abort', + () => { + deferredRequestAborted = true + resolve('aborted') + }, + { once: true }, + ) + }) + return { deferredRequest } + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + }) + + await router.load() + + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: parentRoute.id, + status: 'error', + error: parentError, + }) + expect(childSignal?.aborted).toBe(true) + expect(deferredRequestAborted).toBe(true) + }) + + test('preload trimming aborts a successful descendant owned only by the discarded lane', async () => { + const parentError = new Error('preload parent failed') + let childSignal: AbortSignal | undefined + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: () => { + throw parentError + }, + errorComponent: () => null, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: ({ abortController }) => { + childSignal = abortController.signal + return { + deferredRequest: new Promise<'aborted'>((resolve) => { + abortController.signal.addEventListener( + 'abort', + () => resolve('aborted'), + { once: true }, + ) + }), + } + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.preloadRoute({ to: '/parent/child' }) + + expect(childSignal?.aborted).toBe(true) + }) + + test('navigation started by route context cannot be overwritten by the stale matching pass', async () => { + const bLoaderGate = createControlledPromise() + const bLoader = vi.fn(() => bLoaderGate) + let retainedLoaderSignal: AbortSignal | undefined + let abandonedContextSignal: AbortSignal | undefined + let redirected = false + + const rootRoute = new BaseRootRoute({ + staleTime: Infinity, + loader: ({ abortController }) => { + retainedLoaderSignal = abortController.signal + return 'root data' + }, + }) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const aRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/a', + context: ({ navigate, abortController }) => { + abandonedContextSignal = abortController.signal + if (!redirected) { + redirected = true + void navigate({ to: '/b' }) + } + return { fromA: true } + }, + }) + const bRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/b', + loader: bLoader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, aRoute, bRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const navigation = router.navigate({ to: '/a' }) + await vi.waitFor(() => expect(bLoader).toHaveBeenCalledTimes(1)) + + bLoaderGate.resolve() + await navigation + + expect(router.state.location.pathname).toBe('/b') + expect(router.state.matches.at(-1)?.routeId).toBe(bRoute.id) + expect(abandonedContextSignal?.aborted).toBe(true) + expect(retainedLoaderSignal?.aborted).toBe(false) + }) + + test('a context failure aborts pass controllers from the partial preflight lane', async () => { + const contextError = new Error('context failed after starting work') + + let contextSignal: AbortSignal | undefined + let contextWorkAborted = false + const safeLoader = vi.fn(() => 'safe data') + + const rootRoute = new BaseRootRoute({}) + const brokenRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/broken', + context: ({ abortController }) => { + contextSignal = abortController.signal + abortController.signal.addEventListener( + 'abort', + () => { + contextWorkAborted = true + }, + { once: true }, + ) + throw contextError + }, + }) + const safeRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/safe', + loader: safeLoader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([brokenRoute, safeRoute]), + history: createMemoryHistory({ initialEntries: ['/broken'] }), + }) + + await router.load() + expect(contextSignal?.aborted).toBe(true) + expect(contextWorkAborted).toBe(true) + + await router.navigate({ to: '/safe' }) + expect(router.state.location.pathname).toBe('/safe') + expect(safeLoader).toHaveBeenCalledTimes(1) + }) + + test('a failed preflight cannot abort and strand the pending lane it attempted to supersede', async () => { + const preflightError = new Error('next loaderDeps failed') + const pendingGate = createControlledPromise() + let pendingSignal: AbortSignal | undefined + const pendingStarted = createControlledPromise() + + const rootRoute = new BaseRootRoute({}) + const aRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/a', + }) + const pendingRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/pending', + pendingMs: 0, + pendingComponent: () => null, + loader: ({ abortController }) => { + pendingSignal = abortController.signal + pendingStarted.resolve() + return Promise.race([ + pendingGate, + abortAwareGate(abortController.signal), + ]) + }, + }) + const brokenRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/broken', + loaderDeps: (): Record => { + throw preflightError + }, + loader: () => 'never runs', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([aRoute, pendingRoute, brokenRoute]), + history: createMemoryHistory({ initialEntries: ['/a'] }), + }) + + await router.load() + const pendingNavigation = router.navigate({ to: '/pending' }) + await pendingStarted + + const brokenNavigation = router.navigate({ to: '/broken' }) + await new Promise((resolve) => setTimeout(resolve, 0)) + + expect(pendingSignal?.aborted).toBe(false) + + pendingGate.resolve() + await Promise.all([pendingNavigation, brokenNavigation]) + + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: pendingRoute.id, + status: 'success', + }) + }) +}) 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..93c0c262c6 --- /dev/null +++ b/packages/router-core/tests/fatal-load-rejection.test.ts @@ -0,0 +1,68 @@ +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 router rejection (not a route outcome — for example, + * redirect resolution throwing while finalizing a serial beforeLoad + * redirect) must settle without publishing 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 settles the lane', async () => { + const boom = new Error('resolveRedirect failed') + let blockErrorComponentPreload = true + const errorComponentPreload = vi.fn(() => + blockErrorComponentPreload + ? new Promise(() => {}) + : Promise.resolve(), + ) + + 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', + errorComponent: { preload: errorComponentPreload } as any, + }) + const badRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/bad', + beforeLoad: () => { + throw redirect({ + to: '/bad', + search: () => { + throw boom + }, + }) + }, + }) + const safeLoader = vi.fn(() => 'safe data') + const safeRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/safe', + loader: safeLoader, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([badRoute, safeRoute]), + history: createMemoryHistory({ initialEntries: ['/bad'] }), + }) + + await router.load() + expect(errorComponentPreload).not.toHaveBeenCalled() + + blockErrorComponentPreload = false + await router.navigate({ to: '/safe' }) + expect(router.state.location.pathname).toBe('/safe') + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: safeRoute.id, + status: 'success', + loaderData: 'safe data', + }) + expect(safeLoader).toHaveBeenCalledTimes(1) + }) +}) diff --git a/packages/router-core/tests/granular-stores.test.ts b/packages/router-core/tests/granular-stores.test.ts index 54d2a4efab..4b9affe7f2 100644 --- a/packages/router-core/tests/granular-stores.test.ts +++ b/packages/router-core/tests/granular-stores.test.ts @@ -31,60 +31,8 @@ function createRouter() { }) } -function createLoaderRouter({ - initialEntries = ['/posts/123'], - staleTime = 0, -}: { - initialEntries?: Array - staleTime?: number -} = {}) { - let resolveLoader: (() => void) | undefined - let callCount = 0 - - const rootRoute = new BaseRootRoute({}) - - const indexRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/', - }) - - const aboutRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/about', - }) - - const postRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/posts/$postId', - staleTime, - loader: () => { - callCount += 1 - - if (callCount === 1) { - return { version: 'initial' } - } - - return new Promise<{ version: string }>((resolve) => { - resolveLoader = () => resolve({ version: 'reloaded' }) - }) - }, - }) - - const routeTree = rootRoute.addChildren([indexRoute, aboutRoute, postRoute]) - - return { - router: createTestRouter({ - routeTree, - history: createMemoryHistory({ - initialEntries, - }), - }), - resolveLoader: () => resolveLoader?.(), - } -} - describe('granular stores', () => { - test('keeps pool stores correct across active/pending/cached transitions', async () => { + test('keeps pool stores correct across active/cached transitions', async () => { const router = createRouter() await router.navigate({ to: '/posts/123' }) @@ -104,41 +52,16 @@ describe('granular stores', () => { ) }) - const pendingMatches = [...activeMatches].reverse().map((match, index) => ({ - ...match, - id: `${match.id}__pending_${index}`, - })) const cachedMatches = [...activeMatches].map((match, index) => ({ ...match, id: `${match.id}__cached_${index}`, })) - router.stores.setPending(pendingMatches) router.stores.setCached(cachedMatches) expect(router.stores.matchesId.get()).toEqual( activeMatches.map((match) => match.id), ) - expect(router.stores.pendingIds.get()).toEqual( - pendingMatches.map((match) => match.id), - ) - expect(router.stores.cachedIds.get()).toEqual( - cachedMatches.map((match) => match.id), - ) - - // Pending pool has correct routeIds - pendingMatches.forEach((match) => { - const pendingStore = router.stores.pendingMatchStores.get(match.id) - expect(pendingStore).toBeDefined() - expect(pendingStore!.routeId).toBe(match.routeId) - // Pending match is NOT in the active pool - expect(router.stores.matchStores.get(match.id)).toBeUndefined() - // Active pool still has a match for this routeId - expect( - router.stores.getRouteMatchStore(match.routeId).get(), - ).toBeDefined() - }) - const nextActiveMatches = activeMatches.map((match, index) => ({ ...match, id: `${match.id}__active_next_${index}`, @@ -158,43 +81,6 @@ describe('granular stores', () => { }) }) - test('match store updates are isolated to the touched active match', async () => { - const router = createRouter() - await router.navigate({ to: '/posts/123' }) - - const rootMatch = router.state.matches[0] - const leafMatch = router.state.matches[1] - - expect(rootMatch).toBeDefined() - expect(leafMatch).toBeDefined() - - if (!rootMatch || !leafMatch) { - throw new Error('Expected root and leaf matches to exist') - } - - const rootStore = router.stores.matchStores.get(rootMatch.id) - const leafStore = router.stores.matchStores.get(leafMatch.id) - - expect(rootStore).toBeDefined() - expect(leafStore).toBeDefined() - - if (!rootStore || !leafStore) { - throw new Error('Expected root and leaf match stores to exist') - } - - const rootBefore = rootStore.get() - const leafBefore = leafStore.get() - - router.updateMatch(leafMatch.id, (prev) => ({ - ...prev, - status: 'pending', - })) - - expect(rootStore.get()).toBe(rootBefore) - expect(leafStore.get()).not.toBe(leafBefore) - expect(leafStore.get().status).toBe('pending') - }) - test('getRouteMatchStore caches store instances and clears when route is inactive', async () => { const router = createRouter() await router.navigate({ to: '/posts/123' }) @@ -231,124 +117,5 @@ describe('granular stores', () => { expect(store).toBe(activeStoresBefore[i]) expect(store?.get()).toBe(activeStatesBefore[i]) } - - const pendingMatches = activeMatches.map((match) => ({ - ...match, - id: `${match.id}__pending`, - status: 'pending' as const, - })) - - router.stores.setPending(pendingMatches) - - const pendingIdsBefore = router.stores.pendingIds.get() - const pendingStoresBefore = pendingMatches.map((match) => - router.stores.pendingMatchStores.get(match.id), - ) - const pendingStatesBefore = pendingStoresBefore.map((store) => store?.get()) - - router.stores.setPending(pendingMatches) - - expect(router.stores.pendingIds.get()).toBe(pendingIdsBefore) - for (let i = 0; i < pendingMatches.length; i++) { - const match = pendingMatches[i]! - const store = router.stores.pendingMatchStores.get(match.id) - expect(store).toBe(pendingStoresBefore[i]) - expect(store?.get()).toBe(pendingStatesBefore[i]) - } - }) - - test('updateMatch prefers the pending pool when active and pending share an id', async () => { - const { router, resolveLoader } = createLoaderRouter() - - await router.load() - - const activeLeaf = router.state.matches[1] - - expect(activeLeaf).toBeDefined() - - if (!activeLeaf) { - throw new Error('Expected active leaf match to exist') - } - - const activeStore = router.stores.matchStores.get(activeLeaf.id) - - expect(activeStore).toBeDefined() - - if (!activeStore) { - throw new Error('Expected active leaf store to exist') - } - - const activeBefore = activeStore.get() - - const reloadPromise = router.load() - await Promise.resolve() - - const pendingStore = router.stores.pendingMatchStores.get(activeLeaf.id) - - expect(pendingStore).toBeDefined() - expect(router.stores.matchStores.get(activeLeaf.id)).toBe(activeStore) - - if (!pendingStore) { - throw new Error('Expected pending leaf store to exist') - } - - router.updateMatch(activeLeaf.id, (prev) => ({ - ...prev, - status: 'error', - error: new Error('pending-only-update'), - })) - - expect(activeStore.get()).toBe(activeBefore) - expect(activeStore.get().status).toBe('success') - expect(pendingStore.get().status).toBe('error') - expect(pendingStore.get().error).toEqual(new Error('pending-only-update')) - - resolveLoader() - await reloadPromise - }) - - test('supports duplicate ids across pools without cross-pool contamination', async () => { - const router = createRouter() - await router.navigate({ to: '/posts/123' }) - - const activeLeaf = router.state.matches[1]! - const duplicatedId = activeLeaf.id - const pendingDuplicate = { - ...activeLeaf, - status: 'pending' as const, - } - const cachedDuplicate = { - ...activeLeaf, - status: 'success' as const, - } - - router.stores.setPending([pendingDuplicate]) - router.stores.setCached([cachedDuplicate]) - - router.stores.setMatches( - router.state.matches.map((match) => - match.id === duplicatedId - ? { - ...match, - status: 'error' as const, - error: new Error('active-only-update'), - } - : match, - ), - ) - - expect(router.stores.matchStores.get(duplicatedId)?.get().status).toBe( - 'error', - ) - expect( - router.stores.getRouteMatchStore(activeLeaf.routeId).get()?.status, - ).toBe('error') - // Pending pool has its own store for this id - expect( - router.stores.pendingMatchStores.get(duplicatedId)?.get().status, - ).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') }) }) diff --git a/packages/router-core/tests/hydrate.test.ts b/packages/router-core/tests/hydrate.test.ts index efac230e49..e3440974c6 100644 --- a/packages/router-core/tests/hydrate.test.ts +++ b/packages/router-core/tests/hydrate.test.ts @@ -91,7 +91,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 @@ -100,7 +100,6 @@ describe('hydrate', () => { router: { manifest: testManifest, dehydratedData: {}, - lastMatchId: '/', matches: [], }, h: vi.fn(), @@ -129,7 +128,6 @@ describe('hydrate', () => { router: { manifest: testManifest, dehydratedData: {}, - lastMatchId: '/', matches: [], }, h: vi.fn(), @@ -151,7 +149,6 @@ describe('hydrate', () => { router: { manifest: testManifest, dehydratedData: {}, - lastMatchId: '/', matches: [], }, h: vi.fn(), @@ -176,14 +173,12 @@ describe('hydrate', () => { routeId: '/', index: 0, ssr: undefined, - _nonReactive: {}, }, { id: '/other', routeId: '/other', index: 1, ssr: undefined, - _nonReactive: {}, }, ] @@ -204,7 +199,6 @@ describe('hydrate', () => { router: { manifest: testManifest, dehydratedData: {}, - lastMatchId: '/', matches: dehydratedMatches, }, h: vi.fn(), @@ -217,7 +211,8 @@ describe('hydrate', () => { await hydrate(mockRouter) - const { id, loaderData, ssr, status } = mockMatches[0] as AnyRouteMatch + const { id, loaderData, ssr, status } = mockRouter.state + .matches[0] as AnyRouteMatch expect(id).toBe('/') expect(loaderData).toEqual({ indexData: 'server-data' }) expect(status).toBe('success') @@ -231,7 +226,6 @@ describe('hydrate', () => { routeId: '/', index: 0, ssr: undefined, - _nonReactive: {}, }, ] @@ -252,7 +246,6 @@ describe('hydrate', () => { router: { manifest: testManifest, dehydratedData: {}, - lastMatchId: '/', matches: dehydratedMatches, }, h: vi.fn(), @@ -265,7 +258,9 @@ describe('hydrate', () => { await hydrate(mockRouter) - expect((mockMatches[0] as AnyRouteMatch).globalNotFound).toBe(true) + expect((mockRouter.state.matches[0] as AnyRouteMatch).globalNotFound).toBe( + true, + ) }) it('should leave globalNotFound undefined when dehydrated flag is omitted', async () => { @@ -275,7 +270,6 @@ describe('hydrate', () => { routeId: '/', index: 0, ssr: undefined, - _nonReactive: {}, }, ] @@ -295,7 +289,6 @@ describe('hydrate', () => { router: { manifest: testManifest, dehydratedData: {}, - lastMatchId: '/', matches: dehydratedMatches, }, h: vi.fn(), @@ -308,7 +301,9 @@ describe('hydrate', () => { await hydrate(mockRouter) - expect((mockMatches[0] as AnyRouteMatch).globalNotFound).toBeUndefined() + expect( + (mockRouter.state.matches[0] as AnyRouteMatch).globalNotFound, + ).toBeUndefined() }) it('should preserve existing globalNotFound when dehydrated flag is omitted', async () => { @@ -318,7 +313,6 @@ describe('hydrate', () => { routeId: '/', index: 0, ssr: undefined, - _nonReactive: {}, globalNotFound: true, }, ] @@ -339,7 +333,6 @@ describe('hydrate', () => { router: { manifest: testManifest, dehydratedData: {}, - lastMatchId: '/', matches: dehydratedMatches, }, h: vi.fn(), @@ -352,7 +345,9 @@ describe('hydrate', () => { await hydrate(mockRouter) - expect((mockMatches[0] as AnyRouteMatch).globalNotFound).toBe(true) + expect((mockRouter.state.matches[0] as AnyRouteMatch).globalNotFound).toBe( + true, + ) }) it('should decode dehydrated match ids before hydration lookup and SPA-mode checks', async () => { @@ -364,7 +359,6 @@ describe('hydrate', () => { routeId: '/', index: 0, ssr: undefined, - _nonReactive: {}, }, ] @@ -375,7 +369,6 @@ describe('hydrate', () => { router: { manifest: testManifest, dehydratedData: {}, - lastMatchId: dehydrateSsrMatchId('/'), matches: [ { i: dehydrateSsrMatchId('/'), @@ -434,7 +427,6 @@ describe('hydrate', () => { router: { manifest: testManifest, dehydratedData: { rewrite: true }, - lastMatchId: '/internal/internal', matches: [ { i: '__root__/', @@ -473,9 +465,7 @@ describe('hydrate', () => { 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 @@ -484,7 +474,6 @@ describe('hydrate', () => { router: { manifest: testManifest, dehydratedData: {}, - lastMatchId: '/', matches: [ { i: '/', 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..b56b7350d8 --- /dev/null +++ b/packages/router-core/tests/hydrated-stay-match-data.test.ts @@ -0,0 +1,94 @@ +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 a stay match during ordinary client loading', 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: {}, + 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) + await router.load() + + expect( + router.state.matches.find((m) => m.routeId === aRoute.id)?.loaderData, + ).toBe('a client data') + 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' }) + + expect( + router.state.matches.find((m) => m.routeId === bRoute.id)?.loaderData, + ).toBe('b client data') + expect(rootLoader).not.toHaveBeenCalled() + expect( + router.state.matches.find((m) => m.routeId === rootRoute.id)?.loaderData, + ).toEqual({ root: 'server' }) + }) +}) diff --git a/packages/router-core/tests/hydration-asset-context-order.test.ts b/packages/router-core/tests/hydration-asset-context-order.test.ts new file mode 100644 index 0000000000..49113fe819 --- /dev/null +++ b/packages/router-core/tests/hydration-asset-context-order.test.ts @@ -0,0 +1,62 @@ +import { afterEach, expect, test, 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' + +afterEach(() => { + delete (globalThis as any).window +}) + +test('hydration reconstructs every match context before ancestor head reads the lane', async () => { + let childContextSeenByRootHead: unknown + const rootRoute = new BaseRootRoute({ + head: ({ matches }) => { + childContextSeenByRootHead = matches[1]?.context + return { meta: [{ title: 'hydrated' }] } + }, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/child', + beforeLoad: () => ({ user: 'client fallback' }), + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([childRoute]), + history: createMemoryHistory({ initialEntries: ['/child'] }), + isServer: false, + }) + const matches = router.matchRoutes(router.stores.location.get()) + + ;(globalThis as any).window = { + $_TSR: { + router: { + manifest: { routes: {} }, + dehydratedData: {}, + matches: matches.map((match) => ({ + i: match.id, + s: 'success' as const, + ssr: true, + u: Date.now(), + b: + match.routeId === childRoute.id + ? { user: 'server authenticated user' } + : undefined, + })), + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + initialized: false, + } satisfies TsrSsrGlobal, + } + + await hydrate(router) + + expect(childContextSeenByRootHead).toMatchObject({ + user: 'server authenticated user', + }) +}) diff --git a/packages/router-core/tests/hydration-boundary-chunks.test.ts b/packages/router-core/tests/hydration-boundary-chunks.test.ts new file mode 100644 index 0000000000..8983df61d6 --- /dev/null +++ b/packages/router-core/tests/hydration-boundary-chunks.test.ts @@ -0,0 +1,168 @@ +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, notFound } 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('hydration route chunks below a server boundary', () => { + let mockWindow: { $_TSR?: TsrSsrGlobal } + + beforeEach(() => { + mockWindow = {} + ;(global as any).window = mockWindow + }) + + afterEach(() => { + vi.restoreAllMocks() + delete (global as any).window + }) + + test('hydrates an error boundary without requiring its normal component chunk', async () => { + const serverError = new Error('server beforeLoad failed') + const normalChunkError = new Error('normal component chunk unavailable') + const normalComponentPreload = vi.fn(() => Promise.reject(normalChunkError)) + const errorComponentPreload = vi.fn(() => Promise.resolve()) + const NormalComponent = Object.assign(() => null, { + preload: normalComponentPreload, + }) + const ErrorComponent = Object.assign(() => null, { + preload: errorComponentPreload, + }) + + const rootRoute = new BaseRootRoute({}) + const appRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/app', + beforeLoad: () => { + // This is the server-side failure represented by the dehydrated + // boundary below. Hydration must preserve that committed outcome. + throw serverError + }, + component: NormalComponent, + errorComponent: ErrorComponent, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([appRoute]), + history: createMemoryHistory({ initialEntries: ['/app'] }), + isServer: false, + }) + const matches = router.matchRoutes(router.stores.location.get()) + + mockWindow.$_TSR = { + router: { + manifest: testManifest, + dehydratedData: {}, + matches: [ + { + i: matches[0]!.id, + s: 'success', + ssr: true, + u: Date.now(), + }, + { + i: matches[1]!.id, + s: 'error', + e: serverError, + ssr: true, + u: Date.now(), + }, + ], + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + initialized: false, + } + + await expect(hydrate(router)).resolves.toBeUndefined() + + const appMatch = router.state.matches.find( + (match) => match.routeId === appRoute.id, + ) + expect(appMatch?.status).toBe('error') + expect(appMatch?.error).toBe(serverError) + expect(normalComponentPreload).not.toHaveBeenCalled() + expect(errorComponentPreload).toHaveBeenCalledTimes(1) + }) + + test('hydrates an ancestor notFound boundary without loading an omitted descendant chunk', async () => { + const childChunkError = new Error('omitted child chunk unavailable') + const childComponentPreload = vi.fn(() => Promise.reject(childChunkError)) + const ChildComponent = Object.assign(() => null, { + preload: childComponentPreload, + }) + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + notFoundComponent: () => 'not found', + }) + const serverNotFound = notFound({ routeId: parentRoute.id }) + const childLoader = vi.fn(() => { + // This is the server loader outcome that selected and dehydrated the + // parent boundary. The hydration replay must keep this loader skipped. + throw serverNotFound + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: childLoader, + component: ChildComponent, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + isServer: false, + }) + const matches = router.matchRoutes(router.stores.location.get()) + + mockWindow.$_TSR = { + router: { + manifest: testManifest, + dehydratedData: {}, + // The server lane stopped at the parent boundary and never rendered + // or dehydrated the child. + matches: [ + { + i: matches[0]!.id, + s: 'success', + ssr: true, + u: Date.now(), + }, + { + i: matches[1]!.id, + s: 'notFound', + e: serverNotFound, + ssr: true, + u: Date.now(), + }, + ], + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + initialized: false, + } + + await expect(hydrate(router)).resolves.toBeUndefined() + + await vi.waitFor(() => { + expect(router.state.matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + parentRoute.id, + ]) + }) + expect(router.state.matches[1]?.status).toBe('notFound') + expect(childComponentPreload).not.toHaveBeenCalled() + expect(childLoader).not.toHaveBeenCalled() + }) +}) diff --git a/packages/router-core/tests/hydration-currentness.test.ts b/packages/router-core/tests/hydration-currentness.test.ts new file mode 100644 index 0000000000..8199d70ae3 --- /dev/null +++ b/packages/router-core/tests/hydration-currentness.test.ts @@ -0,0 +1,247 @@ +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, createControlledPromise } 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: {} } + +/** + * Hydration asset work is another private lane generation. If a public + * navigation commits while an old hydration head is pending, the hydration + * continuation must not execute more old-lane hooks or mark its captured + * location as resolved. + */ +describe('hydration asset currentness', () => { + let mockWindow: { $_TSR?: TsrSsrGlobal } + + beforeEach(() => { + mockWindow = {} + ;(global as any).window = mockWindow + }) + + afterEach(() => { + vi.restoreAllMocks() + delete (global as any).window + }) + + test('does not resume an old hydration lane after a newer navigation commits', async () => { + const oldHeadGate = createControlledPromise<{ + meta: Array<{ title: string }> + }>() + const oldHead = vi.fn(() => oldHeadGate) + const oldScripts = vi.fn(() => [ + { children: 'window.oldHydrationLaneRan = true' }, + ]) + const newHead = vi.fn(() => ({ + meta: [{ title: 'New route' }], + })) + + const rootRoute = new BaseRootRoute({}) + const oldRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/old', + head: oldHead, + scripts: oldScripts, + }) + const newRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/new', + head: newHead, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([oldRoute, newRoute]), + history: createMemoryHistory({ initialEntries: ['/old'] }), + isServer: false, + }) + const oldMatches = router.matchRoutes(router.stores.location.get()) + + mockWindow.$_TSR = { + router: { + manifest: testManifest, + dehydratedData: {}, + matches: oldMatches.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(router) + await vi.waitFor(() => expect(oldHead).toHaveBeenCalledTimes(1)) + + // No framework history subscriber exists during the initial hydration + // handoff, so navigate() exercises its public direct router.load() path. + await router.navigate({ to: '/new' }) + + expect(router.state.location.pathname).toBe('/new') + expect(router.state.matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + newRoute.id, + ]) + const resolvedAfterNavigation = router.state.resolvedLocation?.pathname + expect(resolvedAfterNavigation).not.toBe('/old') + + oldHeadGate.resolve({ meta: [{ title: 'Old route' }] }) + await hydration + + expect({ + oldScriptsCalls: oldScripts.mock.calls.length, + newHeadCalls: newHead.mock.calls.length, + location: router.state.location.pathname, + routeIds: router.state.matches.map((match) => match.routeId), + hydrationMovedResolvedLocationBackToOld: + resolvedAfterNavigation !== '/old' && + router.state.resolvedLocation?.pathname === '/old', + }).toEqual({ + oldScriptsCalls: 0, + newHeadCalls: 1, + location: '/new', + routeIds: [rootRoute.id, newRoute.id], + hydrationMovedResolvedLocationBackToOld: false, + }) + }) + + test('a synchronous context navigation prevents stale hydration assets from running', async () => { + const oldHead = vi.fn(() => ({ meta: [{ title: 'Old route' }] })) + const oldScripts = vi.fn(() => [ + { children: 'window.oldHydrationLaneRan = true' }, + ]) + const newHead = vi.fn(() => ({ meta: [{ title: 'New route' }] })) + + let router!: ReturnType + let navigation: Promise | undefined + let navigateDuringHydration = false + const rootRoute = new BaseRootRoute({}) + const oldRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/old', + context: () => { + if (navigateDuringHydration) { + navigateDuringHydration = false + navigation = router.navigate({ to: '/new' }) + } + return { source: 'old' } + }, + head: oldHead, + scripts: oldScripts, + }) + const newRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/new', + head: newHead, + }) + router = createTestRouter({ + routeTree: rootRoute.addChildren([oldRoute, newRoute]), + history: createMemoryHistory({ initialEntries: ['/old'] }), + isServer: false, + }) + const oldMatches = router.matchRoutes(router.stores.location.get()) + + mockWindow.$_TSR = { + router: { + manifest: testManifest, + dehydratedData: {}, + matches: oldMatches.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, + } + + navigateDuringHydration = true + await hydrate(router) + await navigation + + expect(router.state.location.pathname).toBe('/new') + expect(oldHead).not.toHaveBeenCalled() + expect(oldScripts).not.toHaveBeenCalled() + expect(newHead).toHaveBeenCalledTimes(1) + }) + + test('a same-href load owns route hooks when an older hydration chunk settles later', async () => { + const routeChunkGate = createControlledPromise() + const Page = Object.assign(() => null, { + preload: vi.fn(() => routeChunkGate), + }) + const routeContext = vi.fn(() => ({ source: 'same-href' })) + const head = vi.fn(() => ({ meta: [{ title: 'Same href' }] })) + const scripts = vi.fn(() => [ + { children: 'window.sameHrefHydrationRan = true' }, + ]) + + const rootRoute = new BaseRootRoute({}) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + component: Page, + context: routeContext, + head, + scripts, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + isServer: false, + }) + const dehydratedMatches = router.matchRoutes(router.stores.location.get()) + + mockWindow.$_TSR = { + router: { + manifest: testManifest, + dehydratedData: {}, + matches: dehydratedMatches.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(router) + await vi.waitFor(() => expect(Page.preload).toHaveBeenCalledTimes(1)) + + routeContext.mockClear() + head.mockClear() + scripts.mockClear() + const replacement = router.load() + routeChunkGate.resolve() + + await Promise.all([hydration, replacement]) + + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: pageRoute.id, + status: 'success', + meta: [{ title: 'Same href' }], + scripts: [{ children: 'window.sameHrefHydrationRan = true' }], + }) + expect(routeContext).toHaveBeenCalledTimes(1) + expect(head).toHaveBeenCalledTimes(1) + expect(scripts).toHaveBeenCalledTimes(1) + }) +}) diff --git a/packages/router-core/tests/invalidate-pre-rematch-failure.test.ts b/packages/router-core/tests/invalidate-pre-rematch-failure.test.ts new file mode 100644 index 0000000000..50f57d5973 --- /dev/null +++ b/packages/router-core/tests/invalidate-pre-rematch-failure.test.ts @@ -0,0 +1,52 @@ +import { expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +/** + * A failed rematch must preserve resources owned by the accepted route and + * leave the router usable for a later retry. + */ +test('a fatal pre-rematch failure preserves the active generation and permits retry', async () => { + const boom = new Error('loaderDeps failed during invalidation rematch') + let failLoaderDeps = false + let activeSignal: AbortSignal | undefined + + const rootRoute = new BaseRootRoute({}) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + loaderDeps: () => { + if (failLoaderDeps) { + throw boom + } + return {} + }, + loader: ({ abortController }) => { + activeSignal = abortController.signal + return 'target data' + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([targetRoute]), + history: createMemoryHistory({ initialEntries: ['/target'] }), + }) + + await router.load() + expect(router.state.matches.at(-1)?.status).toBe('success') + + failLoaderDeps = true + await router.invalidate({ forcePending: true }) + + // The failed replacement never acquired a lane, so it must not cancel + // resources owned by the still-active successful loader generation. + expect(activeSignal?.aborted).toBe(false) + + failLoaderDeps = false + await router.invalidate() + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: targetRoute.id, + status: 'success', + loaderData: 'target data', + }) +}) 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..a5df035609 --- /dev/null +++ b/packages/router-core/tests/issue-3928-rapid-reload-abort.test.ts @@ -0,0 +1,131 @@ +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) { + 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-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-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-4476-preload-navigate-abort.test.ts b/packages/router-core/tests/issue-4476-preload-navigate-abort.test.ts new file mode 100644 index 0000000000..dec4a2a0c0 --- /dev/null +++ b/packages/router-core/tests/issue-4476-preload-navigate-abort.test.ts @@ -0,0 +1,75 @@ +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. + 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') + + // Adoption transfers loader-data lifetime ownership to the active match. + // The shared request remains alive while rendered, then aborts on unload. + await router.navigate({ to: '/' }) + expect(capturedSignal?.aborted).toBe(true) + }) +}) 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-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..828bbfebd7 --- /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, loadServerResponse } 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) + + const response = await loadServerResponse(router, '/fail') + + expect(response.status).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-5106-hydrated-notfound-boundary.test.ts b/packages/router-core/tests/issue-5106-hydrated-notfound-boundary.test.ts new file mode 100644 index 0000000000..abc3e5656d --- /dev/null +++ b/packages/router-core/tests/issue-5106-hydrated-notfound-boundary.test.ts @@ -0,0 +1,242 @@ +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 safeLoader = vi.fn(() => 'safe-data') + const safeRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/safe', + loader: safeLoader, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + postsRoute.addChildren([postRoute]), + safeRoute, + ]), + 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. + 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.state.matches + 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() + + // 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 () => { + 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 safeLoader = vi.fn(() => 'safe-data') + const safeRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/safe', + loader: safeLoader, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + postsRoute.addChildren([postRoute]), + safeRoute, + ]), + 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. + 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) + + // The server boundary is a complete terminal prefix. The omitted child + // is not client work and must remain absent. + expect(router.state.matches).toHaveLength(2) + + const stateMatches = router.state.matches + 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 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-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..279411ef39 --- /dev/null +++ b/packages/router-core/tests/issue-6221-head-waits-for-loader.test.ts @@ -0,0 +1,130 @@ +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-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/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..a52a7f183d --- /dev/null +++ b/packages/router-core/tests/issue-6371-search-default-normalization-abort.test.ts @@ -0,0 +1,109 @@ +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) { + 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-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-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..7dd6972851 --- /dev/null +++ b/packages/router-core/tests/issue-7635-dehydrated-error-child-head.test.ts @@ -0,0 +1,121 @@ +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: {}, + 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' }]) + }) +}) diff --git a/packages/router-core/tests/load-route-chunk.test.ts b/packages/router-core/tests/load-route-chunk.test.ts new file mode 100644 index 0000000000..73179f9f32 --- /dev/null +++ b/packages/router-core/tests/load-route-chunk.test.ts @@ -0,0 +1,30 @@ +import { expect, test } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +test('router.loadRouteChunk exposes a failed lazy import and remains retryable', async () => { + const chunkError = new TypeError('Failed to fetch lazy route') + const component = () => null + let fail = true + const rootRoute = new BaseRootRoute({}) + const route = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/route', + }).lazy(() => { + if (fail) { + fail = false + return Promise.reject(chunkError) + } + return Promise.resolve({ options: { component } } as any) + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([route]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await expect(router.loadRouteChunk(route as any)).rejects.toBe(chunkError) + await router.loadRouteChunk(route as any) + + expect(route.options.component).toBe(component) +}) diff --git a/packages/router-core/tests/load.test.ts b/packages/router-core/tests/load.test.ts index 1ea6fca30e..17c059a67c 100644 --- a/packages/router-core/tests/load.test.ts +++ b/packages/router-core/tests/load.test.ts @@ -8,9 +8,7 @@ import { rootRouteId, } from '../src' import { createTestRouter } from './routerTestUtils' -import { loadMatches } from '../src/load-matches' import type { - AnyRouter, LoaderStaleReloadMode, RootRouteOptions, RouterCore, @@ -72,12 +70,18 @@ describe('redirect resolution', () => { await router.load() - expect(router.state.redirect).toEqual( + expect(router._serverResult).toEqual( expect.objectContaining({ - options: expect.objectContaining({ href: '/undefined' }), + type: 'redirect', + redirect: expect.objectContaining({ + options: expect.objectContaining({ href: '/undefined' }), + }), }), ) - expect(router.state.redirect?.headers.get('Location')).toBe('/undefined') + expect( + router._serverResult?.type === 'redirect' && + router._serverResult.redirect.headers.get('Location'), + ).toBe('/undefined') }, ) }) @@ -153,12 +157,7 @@ describe('beforeLoad skip or exec', () => { test('exec on regular nav', async () => { const beforeLoad = vi.fn(() => Promise.resolve({ hello: 'world' })) const router = setup({ beforeLoad }) - const navigation = router.navigate({ to: '/foo' }) - expect(beforeLoad).toHaveBeenCalledTimes(1) - expect(router.stores.pendingMatches.get()).toEqual( - expect.arrayContaining([expect.objectContaining({ id: '/foo/foo' })]), - ) - await navigation + await router.navigate({ to: '/foo' }) expect(router.state.location.pathname).toBe('/foo') expect(router.state.matches).toEqual( expect.arrayContaining([ @@ -181,7 +180,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,7 +200,6 @@ 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, ) @@ -213,12 +210,10 @@ describe('beforeLoad skip or exec', () => { const beforeLoad = vi.fn() const router = setup({ beforeLoad }) await router.preloadRoute({ to: '/foo' }) - expect(router.stores.cachedMatches.get()).toEqual( - expect.arrayContaining([expect.objectContaining({ id: '/foo/foo' })]), - ) await sleep(10) await router.navigate({ to: '/foo' }) + expect(router.state.location.pathname).toBe('/foo') expect(beforeLoad).toHaveBeenCalledTimes(2) }) @@ -227,11 +222,9 @@ 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' })]), - ) await router.navigate({ to: '/foo' }) + expect(router.state.location.pathname).toBe('/foo') expect(beforeLoad).toHaveBeenCalledTimes(2) }) @@ -274,16 +267,10 @@ describe('beforeLoad skip or exec', () => { beforeLoad, }) await router.preloadRoute({ to: '/foo' }) - expect( - router.stores.cachedMatches.get().some((d) => d.status === 'redirected'), - ).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'), - ).toBe(false) expect(beforeLoad).toHaveBeenCalledTimes(2) }) @@ -297,15 +284,9 @@ 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'), - ).toBe(false) expect(beforeLoad).toHaveBeenCalledTimes(2) }) @@ -421,12 +402,7 @@ describe('loader skip or exec', () => { test('exec on regular nav', async () => { const loader = vi.fn(() => Promise.resolve({ hello: 'world' })) const router = setup({ loader }) - const navigation = router.navigate({ to: '/foo' }) - expect(loader).toHaveBeenCalledTimes(1) - expect(router.stores.pendingMatches.get()).toEqual( - expect.arrayContaining([expect.objectContaining({ id: '/foo/foo' })]), - ) - await navigation + await router.navigate({ to: '/foo' }) expect(router.state.location.pathname).toBe('/foo') expect(router.state.matches).toEqual( expect.arrayContaining([ @@ -445,12 +421,10 @@ describe('loader skip or exec', () => { 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' })]), - ) await sleep(10) await router.navigate({ to: '/foo' }) + expect(router.state.location.pathname).toBe('/foo') expect(loader).toHaveBeenCalledTimes(2) }) @@ -458,12 +432,10 @@ describe('loader skip or exec', () => { const loader = vi.fn() const router = setup({ loader, staleTime: 1000 }) await router.preloadRoute({ to: '/foo' }) - expect(router.stores.cachedMatches.get()).toEqual( - expect.arrayContaining([expect.objectContaining({ id: '/foo/foo' })]), - ) await sleep(10) await router.navigate({ to: '/foo' }) + expect(router.state.location.pathname).toBe('/foo') expect(loader).toHaveBeenCalledTimes(1) }) @@ -472,11 +444,9 @@ describe('loader skip or exec', () => { const router = setup({ loader }) router.preloadRoute({ to: '/foo' }) await Promise.resolve() - expect(router.stores.cachedMatches.get()).toEqual( - expect.arrayContaining([expect.objectContaining({ id: '/foo/foo' })]), - ) await router.navigate({ to: '/foo' }) + expect(router.state.location.pathname).toBe('/foo') expect(loader).toHaveBeenCalledTimes(1) }) @@ -495,7 +465,7 @@ describe('loader skip or exec', () => { expect(loader).toHaveBeenCalledTimes(2) }) - test('skip if pending preload (notFound)', async () => { + test('exec if pending preload returns notFound', async () => { const loader: Loader = vi.fn(async ({ preload }) => { await sleep(100) if (preload) throw notFound() @@ -507,7 +477,9 @@ describe('loader skip or exec', () => { await Promise.resolve() await router.navigate({ to: '/foo' }) - expect(loader).toHaveBeenCalledTimes(1) + expect(router.state.location.pathname).toBe('/foo') + expect(router.state.matches.at(-1)?.status).toBe('success') + expect(loader).toHaveBeenCalledTimes(2) }) test('exec if rejected preload (redirect)', async () => { @@ -519,20 +491,14 @@ describe('loader skip or exec', () => { loader, }) await router.preloadRoute({ to: '/foo' }) - expect( - router.stores.cachedMatches.get().some((d) => d.status === 'redirected'), - ).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'), - ).toBe(false) expect(loader).toHaveBeenCalledTimes(2) }) - test('skip if pending preload (redirect)', async () => { + test('exec if pending preload redirects', async () => { const loader: Loader = vi.fn(async ({ preload }) => { await sleep(100) if (preload) throw redirect({ to: '/bar' }) @@ -542,38 +508,11 @@ 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.stores.cachedMatches.get().some((d) => d.id === '/foo/foo'), - ).toBe(false) - expect( - router.stores.cachedMatches.get().some((d) => d.status === 'redirected'), - ).toBe(false) + expect(router.state.location.pathname).toBe('/foo') + expect(router.state.matches.at(-1)?.status).toBe('success') + expect(loader).toHaveBeenCalledTimes(2) }) test('exec if rejected preload (error)', async () => { @@ -591,7 +530,7 @@ describe('loader skip or exec', () => { expect(loader).toHaveBeenCalledTimes(2) }) - test('skip if pending preload (error)', async () => { + test('exec if pending preload errors', async () => { const loader: Loader = vi.fn(async ({ preload }) => { await sleep(100) if (preload) throw new Error('error') @@ -603,7 +542,9 @@ describe('loader skip or exec', () => { await Promise.resolve() await router.navigate({ to: '/foo' }) - expect(loader).toHaveBeenCalledTimes(1) + expect(router.state.location.pathname).toBe('/foo') + expect(router.state.matches.at(-1)?.status).toBe('success') + expect(loader).toHaveBeenCalledTimes(2) }) }) @@ -698,22 +639,13 @@ describe('stale loader reload triggers', () => { const getMatchById = ( router: RouterCore, id: string, - ) => - router.state.matches.find((match) => match.id === id) ?? - router.stores.pendingMatches.get().find((match) => match.id === id) ?? - router.stores.cachedMatches.get().find((match) => match.id === id) + ) => router.state.matches.find((match) => match.id === id) const hasActiveMatch = ( router: RouterCore, id: string, ) => router.state.matches.some((match) => match.id === id) - const hasPendingMatch = ( - router: RouterCore, - id: string, - ) => - router.stores.pendingMatches.get().some((match) => match.id === id) ?? false - const setup = ({ loader, staleTime, @@ -784,22 +716,18 @@ describe('stale loader reload triggers', () => { await vi.advanceTimersByTimeAsync(1) const revisit = router.navigate({ to: '/foo' }) - await Promise.resolve() - expect(loader).toHaveBeenCalledTimes(2) + await vi.waitFor(() => { + expect(loader).toHaveBeenCalledTimes(2) + }) expect(hasActiveMatch(router, '/bar/bar')).toBe(true) expect(hasActiveMatch(router, '/foo/foo')).toBe(false) - expect(hasPendingMatch(router, '/foo/foo')).toBe(true) - expect(getMatchById(router, '/foo/foo')?.loaderData).toEqual({ - value: 'first', - }) resolveStaleReload() await revisit expect(loader).toHaveBeenCalledTimes(2) 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: 'second', @@ -819,26 +747,20 @@ describe('stale loader reload triggers', () => { await vi.advanceTimersByTimeAsync(1) const revisit = router.navigate({ to: '/foo' }) + await revisit 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', }) resolveStaleReload() - await backgroundReloadPromise - - expect(getMatchById(router, '/foo/foo')?.loaderData).toEqual({ - value: 'second', + await vi.waitFor(() => { + expect(getMatchById(router, '/foo/foo')?.loaderData).toEqual({ + value: 'second', + }) }) } @@ -1154,7 +1076,7 @@ describe('stale loader reload triggers', () => { }) }) -test('cancelMatches after pending timeout', async () => { +test('navigating away from a pending route aborts its loader', async () => { const WAIT_TIME = 5 const onAbortMock = vi.fn() const rootRoute = new BaseRootRoute({}) @@ -1187,36 +1109,27 @@ test('cancelMatches after pending timeout', async () => { router.navigate({ to: '/foo' }) await sleep(WAIT_TIME * 30) - // At this point, pending timeout should have triggered - const fooMatch = router.getMatch('/foo/foo') - expect(fooMatch).toBeDefined() - - // Navigate away, which should cancel the pending match await router.navigate({ to: '/bar' }) - await router.latestLoadPromise expect(router.state.location.pathname).toBe('/bar') - - // Verify that abort was called and pending timeout was cleared expect(onAbortMock).toHaveBeenCalled() - const cancelledFooMatch = router.getMatch('/foo/foo') - expect(cancelledFooMatch?._nonReactive.pendingTimeout).toBeUndefined() }) describe('head execution', () => { + const getTitle = (match: { meta?: unknown }) => + (match.meta as Array<{ title?: string }> | undefined)?.[0]?.title + const setupBeforeLoadNotFoundHierarchy = (throwAtIndex: 1 | 2 | 3) => { const loaderResolvers: Array<(() => void) | undefined> = [] - const makeLoader = (index: number) => - vi.fn(async () => { - await new Promise((resolve) => { - loaderResolvers[index] = resolve - }) - return { level: index } + const makeLoader = (index: number) => async () => { + await new Promise((resolve) => { + loaderResolvers[index] = resolve }) + return { level: index } + } - const makeHead = (label: string) => - vi.fn(() => ({ meta: [{ title: label }] })) + const makeHead = (label: string) => () => ({ meta: [{ title: label }] }) const rootRoute = new BaseRootRoute({ loader: makeLoader(0), @@ -1274,25 +1187,15 @@ describe('head execution', () => { }) const routes = [rootRoute, level1Route, level2Route, level3Route] as const - const loaders = routes.map( - (route) => route.options.loader as ReturnType, - ) - const heads = routes.map( - (route) => route.options.head as ReturnType, - ) - return { router, routes, - loaders, - heads, loaderResolvers, - throwAtIndex, } } const assertBeforeLoadNotFoundHierarchy = async (throwAtIndex: 1 | 2 | 3) => { - const { router, routes, loaders, heads, loaderResolvers } = + const { router, routes, loaderResolvers } = setupBeforeLoadNotFoundHierarchy(throwAtIndex) let loadResolved = false @@ -1303,26 +1206,20 @@ describe('head execution', () => { await Promise.resolve() await Promise.resolve() - for (let i = 0; i < routes.length; i++) { - const loader = loaders[i]! - const expectedCalls = i < throwAtIndex ? 1 : 0 - expect(loader).toHaveBeenCalledTimes(expectedCalls) - } - expect(loadResolved).toBe(false) + await vi.waitFor(() => { + expect(loaderResolvers.slice(0, throwAtIndex)).not.toContain(undefined) + }) for (let i = 0; i < throwAtIndex; i++) { - expect(loaderResolvers[i]).toBeDefined() loaderResolvers[i]!() } await loadPromise - for (let i = 0; i < heads.length; i++) { - const head = heads[i]! - const expectedCalls = i <= throwAtIndex ? 1 : 0 - expect(head).toHaveBeenCalledTimes(expectedCalls) - } + expect(router.state.matches.map(getTitle)).toEqual( + ['Root', 'Level 1', 'Level 2', 'Level 3'].slice(0, throwAtIndex + 1), + ) for (let i = 0; i < throwAtIndex; i++) { const route = routes[i]! @@ -1343,8 +1240,7 @@ describe('head execution', () => { }) }) - test('executes head once when loader throws notFound', async () => { - const head = vi.fn(() => ({ meta: [{ title: 'Test' }] })) + test('projects head when loader throws notFound', async () => { const rootRoute = new BaseRootRoute({}) const testRoute = new BaseRoute({ getParentRoute: () => rootRoute, @@ -1352,7 +1248,7 @@ describe('head execution', () => { loader: () => { throw notFound() }, - head, + head: () => ({ meta: [{ title: 'Test' }] }), }) const routeTree = rootRoute.addChildren([testRoute]) const router = createTestRouter({ @@ -1362,32 +1258,26 @@ describe('head execution', () => { await router.load() - expect(head).toHaveBeenCalledTimes(1) const match = router.state.matches.find((m) => m.routeId === testRoute.id) expect(match?.status).toBe('notFound') + expect(match?.meta).toEqual([{ title: 'Test' }]) }) test('propagates sync beforeLoad non-notFound error running ancestor loaders and heads', async () => { const beforeLoadError = new Error('beforeLoad-sync-error') - const rootLoader = vi.fn(() => ({ level: 0 })) - const rootHead = vi.fn(() => ({ meta: [{ title: 'Root' }] })) - const rootRoute = new BaseRootRoute({ - loader: rootLoader, - head: rootHead, + loader: () => ({ level: 0 }), + head: () => ({ meta: [{ title: 'Root' }] }), }) - const childLoader = vi.fn(() => ({ level: 1 })) - const childHead = vi.fn(() => ({ meta: [{ title: 'Child' }] })) - const childRoute = new BaseRoute({ getParentRoute: () => rootRoute, path: '/test', beforeLoad: () => { throw beforeLoadError }, - loader: childLoader, - head: childHead, + loader: () => ({ level: 1 }), + head: () => ({ meta: [{ title: 'Child' }] }), }) const routeTree = rootRoute.addChildren([childRoute]) @@ -1396,40 +1286,24 @@ describe('head execution', () => { history: createMemoryHistory({ initialEntries: ['/test'] }), }) - const location = router.latestLocation - const matches = router.matchRoutes(location) - router.stores.setPending(matches) + await router.load() - await expect( - loadMatches({ - router, - location, - matches, - updateMatch: router.updateMatch, - }), - ).rejects.toBe(beforeLoadError) + expect( + router.state.matches.find((match) => match.routeId === childRoute.id) + ?.error, + ).toBe(beforeLoadError) - expect(rootLoader).toHaveBeenCalledTimes(1) - expect(childLoader).toHaveBeenCalledTimes(0) - // Head functions still run for ancestors up to the erroring match so that - // SSR produces valid content (e.g. charset, viewport, stylesheets). - expect(rootHead).toHaveBeenCalledTimes(1) - expect(childHead).toHaveBeenCalledTimes(1) + expect(router.state.matches[0]?.loaderData).toEqual({ level: 0 }) + expect(router.state.matches.map(getTitle)).toEqual(['Root', 'Child']) }) 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 })) - const rootHead = vi.fn(() => ({ meta: [{ title: 'Root' }] })) - const rootRoute = new BaseRootRoute({ - loader: rootLoader, - head: rootHead, + loader: () => ({ level: 0 }), + head: () => ({ meta: [{ title: 'Root' }] }), }) - const childLoader = vi.fn(() => ({ level: 1 })) - const childHead = vi.fn(() => ({ meta: [{ title: 'Child' }] })) - const childRoute = new BaseRoute({ getParentRoute: () => rootRoute, path: '/test', @@ -1437,8 +1311,8 @@ describe('head execution', () => { await Promise.resolve() throw beforeLoadError }, - loader: childLoader, - head: childHead, + loader: () => ({ level: 1 }), + head: () => ({ meta: [{ title: 'Child' }] }), }) const routeTree = rootRoute.addChildren([childRoute]) @@ -1447,25 +1321,15 @@ describe('head execution', () => { history: createMemoryHistory({ initialEntries: ['/test'] }), }) - const location = router.latestLocation - const matches = router.matchRoutes(location) - router.stores.setPending(matches) + await router.load() - await expect( - loadMatches({ - router, - location, - matches, - updateMatch: router.updateMatch, - }), - ).rejects.toBe(beforeLoadError) + expect( + router.state.matches.find((match) => match.routeId === childRoute.id) + ?.error, + ).toBe(beforeLoadError) - expect(rootLoader).toHaveBeenCalledTimes(1) - expect(childLoader).toHaveBeenCalledTimes(0) - // Head functions still run for ancestors up to the erroring match so that - // SSR produces valid content (e.g. charset, viewport, stylesheets). - expect(rootHead).toHaveBeenCalledTimes(1) - expect(childHead).toHaveBeenCalledTimes(1) + expect(router.state.matches[0]?.loaderData).toEqual({ level: 0 }) + expect(router.state.matches.map(getTitle)).toEqual(['Root', 'Child']) }) describe('beforeLoad notFound parent loader outcomes', () => { @@ -1478,32 +1342,34 @@ describe('head execution', () => { parentFailures: ParentFailureMap expectedErrorKind: 'notFound' | 'redirect' | 'error' expectedErrorSource?: string - expectedErrorRouteIndex?: 0 | 1 | 2 | 3 - expectedLoaderMaxIndex: number - expectedRenderedHeadMaxIndex: number - withDefaultNotFoundComponent?: boolean + expectedBoundaryIndex?: 0 | 1 | 2 | 3 + expectedHeadTitles: Array beforeLoadNotFoundFactory?: ( routes: readonly [any, any, any, any], ) => ReturnType - expectRootNotFoundComponentAssigned?: boolean } const setupScenario = ({ throwAtIndex, parentFailures, beforeLoadNotFoundFactory, - withDefaultNotFoundComponent, }: { throwAtIndex: ThrowAtIndex parentFailures: ParentFailureMap beforeLoadNotFoundFactory?: Scenario['beforeLoadNotFoundFactory'] - withDefaultNotFoundComponent?: boolean }) => { - const makeHead = (label: string) => - vi.fn(() => ({ meta: [{ title: label }] })) + const makeHead = (label: string) => () => ({ meta: [{ title: label }] }) - const makeLoader = (index: number) => - vi.fn(() => { + const makeLoader = + (index: number) => + ({ location }: { location: { pathname: string } }) => { + // Keep failures scoped to the route under test. A root loader which + // redirects unconditionally would also redirect the destination and + // describe an infinite redirect loop rather than precedence between + // the original lane's settled outcomes. + if (location.pathname === '/redirect-target') { + return { level: index } + } const failure = parentFailures[index as 0 | 1 | 2] if (failure === 'notFound') { throw notFound({ data: { source: `loader-${index}` } }) @@ -1511,8 +1377,11 @@ describe('head execution', () => { if (failure === 'redirect') { throw redirect({ to: '/redirect-target' }) } + if (failure === 'error') { + throw new Error(`loader-${index}-error`) + } return { level: index } - }) + } const rootRoute = new BaseRootRoute({ loader: makeLoader(0), @@ -1552,14 +1421,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 @@ -1573,41 +1434,11 @@ describe('head execution', () => { history: createMemoryHistory({ initialEntries: ['/level-1/level-2/level-3'], }), - ...(withDefaultNotFoundComponent - ? { defaultNotFoundComponent: () => null } - : {}), }) - const loaders = routes.map( - (route) => route.options.loader as ReturnType, - ) - const heads = routes.map( - (route) => route.options.head as ReturnType, - ) - return { router, routes, - loaders, - heads, - } - } - - const runLoadMatchesAndCapture = async (router: AnyRouter) => { - const location = router.latestLocation - const matches = router.matchRoutes(location) - router.stores.setPending(matches) - - try { - await loadMatches({ - router, - location, - matches, - updateMatch: router.updateMatch, - }) - return { error: undefined, matches } - } catch (error) { - return { error, matches } } } @@ -1618,8 +1449,8 @@ describe('head execution', () => { parentFailures: {} as ParentFailureMap, expectedErrorKind: 'notFound' as const, expectedErrorSource: 'beforeLoad-3', - expectedLoaderMaxIndex: 2, - expectedRenderedHeadMaxIndex: 3, + expectedBoundaryIndex: 3, + expectedHeadTitles: ['Root', 'Level 1', 'Level 2', 'Level 3'], }, { name: 'uses parent loader notFound when parent loader throws notFound', @@ -1627,8 +1458,8 @@ describe('head execution', () => { parentFailures: { 1: 'notFound' } as ParentFailureMap, expectedErrorKind: 'notFound' as const, expectedErrorSource: 'loader-1', - expectedLoaderMaxIndex: 2, - expectedRenderedHeadMaxIndex: 1, + expectedBoundaryIndex: 1, + expectedHeadTitles: ['Root', 'Level 1'], }, { name: 'uses first parent loader notFound when multiple parent loaders throw notFound', @@ -1636,8 +1467,8 @@ describe('head execution', () => { parentFailures: { 1: 'notFound', 2: 'notFound' } as ParentFailureMap, expectedErrorKind: 'notFound' as const, expectedErrorSource: 'loader-1', - expectedLoaderMaxIndex: 2, - expectedRenderedHeadMaxIndex: 1, + expectedBoundaryIndex: 1, + expectedHeadTitles: ['Root', 'Level 1'], }, { name: 'uses parent loader notFound when root loader throws notFound', @@ -1645,8 +1476,8 @@ describe('head execution', () => { parentFailures: { 0: 'notFound' } as ParentFailureMap, expectedErrorKind: 'notFound' as const, expectedErrorSource: 'loader-0', - expectedLoaderMaxIndex: 1, - expectedRenderedHeadMaxIndex: 0, + expectedBoundaryIndex: 0, + expectedHeadTitles: ['Root'], }, { name: 'uses explicit routeId from beforeLoad notFound to target ancestor boundary', @@ -1654,9 +1485,8 @@ describe('head execution', () => { parentFailures: {} as ParentFailureMap, expectedErrorKind: 'notFound' as const, expectedErrorSource: 'beforeLoad-explicit-level1', - expectedErrorRouteIndex: 1, - expectedLoaderMaxIndex: 1, - expectedRenderedHeadMaxIndex: 1, + expectedBoundaryIndex: 1, + expectedHeadTitles: ['Root', 'Level 1'], beforeLoadNotFoundFactory: (routes) => notFound({ routeId: routes[1].id as never, @@ -1669,8 +1499,8 @@ describe('head execution', () => { parentFailures: {} as ParentFailureMap, expectedErrorKind: 'notFound' as const, expectedErrorSource: 'beforeLoad-invalid-route', - expectedLoaderMaxIndex: 0, - expectedRenderedHeadMaxIndex: 0, + expectedBoundaryIndex: 0, + expectedHeadTitles: ['Root'], beforeLoadNotFoundFactory: () => notFound({ routeId: '/does-not-exist' as never, @@ -1683,38 +1513,21 @@ describe('head execution', () => { parentFailures: {} as ParentFailureMap, expectedErrorKind: 'notFound' as const, expectedErrorSource: 'beforeLoad-non-exact-route', - expectedLoaderMaxIndex: 0, - expectedRenderedHeadMaxIndex: 0, + expectedBoundaryIndex: 0, + expectedHeadTitles: ['Root'], beforeLoadNotFoundFactory: (routes) => notFound({ routeId: `${routes[1].id}/` as never, data: { source: 'beforeLoad-non-exact-route' }, }), }, - { - name: 'assigns defaultNotFoundComponent on root when unknown routeId falls back to root', - throwAtIndex: 3 as const, - parentFailures: {} as ParentFailureMap, - expectedErrorKind: 'notFound' as const, - expectedErrorSource: 'beforeLoad-invalid-route-default', - expectedLoaderMaxIndex: 0, - expectedRenderedHeadMaxIndex: 0, - withDefaultNotFoundComponent: true, - expectRootNotFoundComponentAssigned: true, - beforeLoadNotFoundFactory: () => - notFound({ - routeId: '/does-not-exist' as never, - data: { source: 'beforeLoad-invalid-route-default' }, - }), - }, { name: 'prioritizes redirect when parent loader throws redirect', throwAtIndex: 3 as const, parentFailures: { 0: 'redirect' } as ParentFailureMap, expectedErrorKind: 'redirect' as const, expectedErrorSource: undefined, - expectedLoaderMaxIndex: 2, - expectedRenderedHeadMaxIndex: -1, + expectedHeadTitles: ['Root'], }, { name: 'prioritizes redirect over root-loader notFound when both appear in settled loaders', @@ -1722,8 +1535,7 @@ describe('head execution', () => { parentFailures: { 0: 'notFound', 1: 'redirect' } as ParentFailureMap, expectedErrorKind: 'redirect' as const, expectedErrorSource: undefined, - expectedLoaderMaxIndex: 2, - expectedRenderedHeadMaxIndex: -1, + expectedHeadTitles: ['Root'], }, { name: 'propagates regular loader error when mixed with loader notFound in settled loaders', @@ -1731,67 +1543,58 @@ describe('head execution', () => { parentFailures: { 1: 'notFound', 2: 'error' } as ParentFailureMap, expectedErrorKind: 'error' as const, expectedErrorSource: 'loader-2-error', - expectedLoaderMaxIndex: 1, - expectedRenderedHeadMaxIndex: -1, + expectedBoundaryIndex: 2, + expectedHeadTitles: ['Root', 'Level 1', 'Level 2'], }, ] satisfies Array test.each(scenarios)('$name', async (scenario) => { - const { router, routes, loaders, heads } = setupScenario({ + const { router, routes } = setupScenario({ throwAtIndex: scenario.throwAtIndex, parentFailures: scenario.parentFailures, beforeLoadNotFoundFactory: scenario.beforeLoadNotFoundFactory, - withDefaultNotFoundComponent: scenario.withDefaultNotFoundComponent, }) - const { error, matches } = await runLoadMatchesAndCapture(router) - - for (let i = 0; i < routes.length; i++) { - const loader = loaders[i]! - const expectedCalls = i <= scenario.expectedLoaderMaxIndex ? 1 : 0 - expect(loader).toHaveBeenCalledTimes(expectedCalls) - } - - for (let i = 0; i < heads.length; i++) { - const head = heads[i]! - const expectedCalls = i <= scenario.expectedRenderedHeadMaxIndex ? 1 : 0 - expect(head).toHaveBeenCalledTimes(expectedCalls) - } + await router.load() + const matches = router.state.matches if (scenario.expectedErrorKind === 'redirect') { - expect(error).toEqual( + expect(router.state.location.pathname).toBe('/redirect-target') + expect(matches.at(-1)).toEqual( expect.objectContaining({ - redirectHandled: true, - options: expect.objectContaining({ - to: '/redirect-target', - }), + pathname: '/redirect-target', + status: 'success', }), ) - 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, - data: { source: scenario.expectedErrorSource }, - }), - ) - - if (scenario.expectedErrorRouteIndex !== undefined) { - expect((error as { routeId?: string }).routeId).toBe( - routes[scenario.expectedErrorRouteIndex]!.id, + } else { + const boundary = matches.at(-1)! + expect(boundary.routeId).toBe( + routes[scenario.expectedBoundaryIndex!]!.id, ) + + if (scenario.expectedErrorKind === 'error') { + expect(boundary.status).toBe('error') + expect((boundary.error as Error).message).toBe( + scenario.expectedErrorSource, + ) + } else if (scenario.expectedBoundaryIndex === 0) { + expect(boundary.status).toBe('success') + expect(boundary.globalNotFound).toBe(true) + } else { + expect(boundary.status).toBe('notFound') + expect(boundary.error).toEqual( + expect.objectContaining({ + isNotFound: true, + routeId: boundary.routeId, + data: { source: scenario.expectedErrorSource }, + }), + ) + } } - if (scenario.expectRootNotFoundComponentAssigned) { - expect(routes[0].options.notFoundComponent).toBeTypeOf('function') - } + expect( + matches.map(getTitle).filter((title) => title !== undefined), + ).toEqual(scenario.expectedHeadTitles) }) test('sets globalNotFound on root match when beforeLoad notFound targets root boundary', async () => { @@ -1805,22 +1608,20 @@ describe('head execution', () => { }), }) - const { error, matches } = await runLoadMatchesAndCapture(router) + await router.load() - expect(error).toEqual( + const rootMatch = router.state.matches.find( + (m) => m.routeId === routes[0].id, + ) + + expect(rootMatch?.globalNotFound).toBe(true) + expect(rootMatch?.status).toBe('success') + expect(rootMatch?.error).toEqual( expect.objectContaining({ isNotFound: true, data: { source: 'beforeLoad-root-explicit' }, }), ) - - const rootMatch = router.stores.pendingMatches - .get() - .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 () => { @@ -1834,88 +1635,20 @@ describe('head execution', () => { }), }) - const first = await runLoadMatchesAndCapture(router) - expect(first.error).toEqual(expect.objectContaining({ isNotFound: true })) + await router.load() + expect(router.state.matches[0]?.globalNotFound).toBe(true) const throwingRoute = routes[3] throwingRoute.options.beforeLoad = undefined - const second = await runLoadMatchesAndCapture(router) - expect(second.error).toBeUndefined() + await router.load() - const rootMatch = router.stores.pendingMatches - .get() - .find((m) => m.routeId === routes[0].id) + const rootMatch = router.state.matches.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({ - loader: rootLoader, - staleTime: Infinity, - shouldReload: () => false, - }) - - const childLoader = vi.fn(() => ({ level: 1 })) - const childRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/test', - loader: childLoader, - staleTime: Infinity, - shouldReload: () => false, - }) - - const routeTree = rootRoute.addChildren([childRoute]) - - const router = createTestRouter({ - routeTree, - history: createMemoryHistory({ initialEntries: ['/test'] }), - }) - - const first = await runLoadMatchesAndCapture(router) - expect(first.error).toBeUndefined() - 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) - - expect(rootLoader).toHaveBeenCalledTimes(1) - - const rootMatch = router.stores.pendingMatches - .get() - .find((m) => m.routeId === rootRoute.id) - - expect(rootMatch?.globalNotFound).toBe(false) - expect(rootMatch?.error).toBeUndefined() - }) }) }) @@ -1975,7 +1708,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) }) }) diff --git a/packages/router-core/tests/preflight-reentrant-context.test.ts b/packages/router-core/tests/preflight-reentrant-context.test.ts new file mode 100644 index 0000000000..5577f356bf --- /dev/null +++ b/packages/router-core/tests/preflight-reentrant-context.test.ts @@ -0,0 +1,148 @@ +import { expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +test('synchronous navigation from route context stops abandoned descendant context work', async () => { + let redirected = false + let redirectNavigation: Promise | undefined + const childContext = vi.fn(() => ({ child: true })) + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + context: ({ navigate }) => { + if (!redirected) { + redirected = true + redirectNavigation = navigate({ to: '/target' }) + } + return { parent: true } + }, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + context: childContext, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + targetRoute, + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.navigate({ to: '/parent/child' }) + await redirectNavigation + + expect(router.state.location.pathname).toBe('/target') + expect(childContext).not.toHaveBeenCalled() +}) + +test('synchronous navigation from preloaded route context stops abandoned descendant context work', async () => { + let redirected = false + let redirectNavigation: Promise | undefined + const childContext = vi.fn(() => ({ child: true })) + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + context: ({ navigate, preload }) => { + if (preload && !redirected) { + redirected = true + redirectNavigation = navigate({ to: '/target' }) + } + return { parent: true } + }, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + context: childContext, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + targetRoute, + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.preloadRoute({ to: '/parent/child' }) + await redirectNavigation + + expect(router.state.location.pathname).toBe('/target') + expect(childContext).not.toHaveBeenCalled() +}) + +test('navigation from loaderDeps toJSON stops later abandoned callbacks', async () => { + let router!: ReturnType + let redirected = false + let redirectNavigation: Promise | undefined + const childContext = vi.fn(() => ({ child: true })) + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loaderDeps: () => ({ + toJSON: () => { + if (!redirected) { + redirected = true + redirectNavigation = router.navigate({ to: '/target' }) + } + return { key: 'parent' } + }, + }), + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + context: childContext, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + targetRoute, + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.navigate({ to: '/parent/child' }) + await redirectNavigation + + expect(router.state.location.pathname).toBe('/target') + expect(childContext).not.toHaveBeenCalled() +}) 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..809e04e529 --- /dev/null +++ b/packages/router-core/tests/preload-adoption.test.ts @@ -0,0 +1,373 @@ +import { afterEach, describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, createControlledPromise } from '../src' +import { createTestRouter } from './routerTestUtils' + +afterEach(() => { + vi.useRealTimers() +}) + +/** + * 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 + * adoption boundary: a donor must have its loader genuinely in flight. A + * preload still in its serial phase can itself be waiting on the navigation + * through the borrow protocol, while a stale successful donor can still have + * fresh loader work pending behind its cached snapshot. + */ + +describe('preload adoption', () => { + test('navigation waits for fresh data from an in-flight stale preload revalidation', async () => { + vi.useFakeTimers() + vi.setSystemTime(0) + + const revalidationGate = createControlledPromise<{ + notifications: Array + }>() + let loaderCalls = 0 + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const notificationsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/notifications', + staleTime: 0, + preloadStaleTime: 0, + gcTime: 60_000, + loader: { + staleReloadMode: 'blocking', + handler: () => { + loaderCalls++ + if (loaderCalls === 1) { + return { notifications: ['old'] } + } + + return revalidationGate + }, + }, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, notificationsRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.preloadRoute({ to: '/notifications' } as any) + + expect(loaderCalls).toBe(1) + + // The cached successful preload is now stale. A second hover starts a + // genuine revalidation while the user clicks the link. + await vi.advanceTimersByTimeAsync(1) + const revalidation = router.preloadRoute({ + to: '/notifications', + } as any) + await vi.waitFor(() => expect(loaderCalls).toBe(2)) + + let navigationSettled = false + const navigation = router.navigate({ to: '/notifications' }).then(() => { + navigationSettled = true + }) + await Promise.resolve() + + // The navigation may share the revalidation, but it must not treat the + // stale cached snapshot as the completed result while fresh work runs. + expect(navigationSettled).toBe(false) + + revalidationGate.resolve({ notifications: ['fresh'] }) + await Promise.all([revalidation, navigation]) + + // A fix may either share the fresh revalidation or run a navigation + // loader of its own; correctness only requires publishing fresh data. + expect(loaderCalls).toBeGreaterThanOrEqual(2) + expect( + router.state.matches.find( + (match) => match.routeId === notificationsRoute.id, + )?.loaderData, + ).toEqual({ notifications: ['fresh'] }) + }) + + 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', + preloadStaleTime: Infinity, + 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]) + + await router.navigate({ to: '/foo' }) + + expect(loader).toHaveBeenCalledTimes(1) + expect( + router.state.matches.find((match) => match.routeId === fooRoute.id) + ?.loaderData, + ).toBe('once') + }) + + test('a fulfilled undefined loader result is adopted as success', 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 preload = router.preloadRoute({ to: '/foo' } as any) + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(1)) + const navigation = router.navigate({ to: '/foo' }) + + loaderGate.resolve(undefined) + await Promise.all([preload, navigation]) + + expect(loader).toHaveBeenCalledTimes(1) + const match = router.state.matches.find( + (candidate) => candidate.routeId === fooRoute.id, + ) + expect(match?.status).toBe('success') + expect(match?.loaderData).toBeUndefined() + }) + + 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 + }) + + test('navigation retries a failed joined preload without starving sibling work', async () => { + let parentLoads = 0 + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: async ({ preload }) => { + parentLoads++ + if (preload) { + await Promise.resolve() + throw new Error('preload failed') + } + return 'navigation data' + }, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: async () => { + await new Promise((resolve) => setTimeout(resolve, 10)) + return 'child data' + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const preload = router.preloadRoute({ to: '/parent/child' } as any) + await vi.waitFor(() => expect(parentLoads).toBe(1)) + + await router.navigate({ to: '/parent/child' }) + await preload + + expect(parentLoads).toBe(2) + expect(router.state.location.pathname).toBe('/parent/child') + expect( + router.state.matches.find((match) => match.routeId === parentRoute.id) + ?.loaderData, + ).toBe('navigation data') + expect( + router.state.matches.find((match) => match.routeId === childRoute.id) + ?.loaderData, + ).toBe('child data') + }) + + test('a route with preload disabled does not discard its preloaded ancestor', async () => { + const parentLoader = vi.fn(() => 'parent data') + const childLoader = vi.fn(() => 'child data') + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + preloadStaleTime: Infinity, + loader: parentLoader, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + preload: false, + loader: childLoader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.preloadRoute({ to: '/parent/child' } as any) + await router.navigate({ to: '/parent/child' }) + + expect(parentLoader).toHaveBeenCalledTimes(1) + expect(childLoader).toHaveBeenCalledTimes(1) + expect( + router.state.matches.find((match) => match.routeId === parentRoute.id) + ?.loaderData, + ).toBe('parent data') + expect( + router.state.matches.find((match) => match.routeId === childRoute.id) + ?.loaderData, + ).toBe('child data') + }) +}) diff --git a/packages/router-core/tests/preload-background-parent-coherence.test.ts b/packages/router-core/tests/preload-background-parent-coherence.test.ts new file mode 100644 index 0000000000..1293d33653 --- /dev/null +++ b/packages/router-core/tests/preload-background-parent-coherence.test.ts @@ -0,0 +1,87 @@ +import { 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 parent while that parent is revalidating in + * the background must derive descendant data from the revalidated generation. + * Otherwise the preload can cache a child snapshot based on stale parent data, + * then combine it with the freshly committed parent on navigation. + */ +test('child preload stays coherent with an overlapping parent background reload', async () => { + const backgroundResponse = createControlledPromise<{ revision: number }>() + let parentLoadCount = 0 + + const parentLoader = vi.fn(() => { + parentLoadCount++ + return parentLoadCount === 1 ? { revision: 1 } : backgroundResponse + }) + const childLoader = vi.fn(async ({ parentMatchPromise }) => { + const parentMatch = await parentMatchPromise + return { + parentRevision: (parentMatch.loaderData as { revision: number }).revision, + } + }) + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: parentLoader, + staleTime: Infinity, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: childLoader, + staleTime: Infinity, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent'] }), + }) + + await router.load() + expect(parentLoader).toHaveBeenCalledTimes(1) + + // Invalidating a successful loader uses the default background revalidation + // mode. The public invalidate promise settles once that private reload has + // started; its network response can remain pending. + await router.invalidate({ + filter: (match) => match.routeId === parentRoute.id, + }) + expect(parentLoader).toHaveBeenCalledTimes(2) + + const childPreload = router.preloadRoute({ to: '/parent/child' }) + + // Let the preload reach the borrowed parent while revision 2 is still in + // flight. This does not require the child to have started: a correct join is + // allowed to wait for the parent response. + await new Promise((resolve) => setTimeout(resolve, 0)) + + backgroundResponse.resolve({ revision: 2 }) + await childPreload + + await vi.waitFor(() => { + const parentMatch = router.state.matches.find( + (match) => match.routeId === parentRoute.id, + ) + expect(parentMatch?.loaderData).toEqual({ revision: 2 }) + }) + + 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, + ) + + expect(parentLoader).toHaveBeenCalledTimes(2) + expect(childLoader).toHaveBeenCalledTimes(1) + expect(parentMatch?.loaderData).toEqual({ revision: 2 }) + expect(childMatch?.loaderData).toEqual({ parentRevision: 2 }) +}) diff --git a/packages/router-core/tests/preload-public-cache-behavior.test.ts b/packages/router-core/tests/preload-public-cache-behavior.test.ts new file mode 100644 index 0000000000..15499f6a70 --- /dev/null +++ b/packages/router-core/tests/preload-public-cache-behavior.test.ts @@ -0,0 +1,206 @@ +import { afterEach, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +afterEach(() => { + vi.restoreAllMocks() + vi.useRealTimers() +}) + +function deferred() { + let resolve!: (value?: T | PromiseLike) => void + const promise = new Promise((done) => { + resolve = (value) => done(value as T) + }) + return { promise, resolve } +} + +// Public contract: preloading a descendant must reuse an already accepted +// ancestor generation instead of executing the active layout loader again. +test('preloading children borrows the active ancestor without rerunning it', async () => { + vi.useFakeTimers() + vi.setSystemTime(1_000) + + const layoutLoader = vi.fn(() => 'layout data') + const childLoader = vi.fn(({ params }: any) => `child ${params.childId}`) + const rootRoute = new BaseRootRoute({}) + const layoutRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/layout', + staleTime: 10, + loader: layoutLoader, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => layoutRoute, + path: '$childId', + loader: childLoader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([layoutRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/layout'] }), + }) + + await router.load() + vi.setSystemTime(2_000) + + await router.preloadRoute({ + to: '/layout/$childId', + params: { childId: 'one' }, + } as any) + await router.preloadRoute({ + to: '/layout/$childId', + params: { childId: 'two' }, + } as any) + await router.preloadRoute({ + to: '/layout/$childId', + params: { childId: 'one' }, + } as any) + + expect(layoutLoader).toHaveBeenCalledTimes(1) + expect(childLoader).toHaveBeenCalledTimes(2) + + await router.navigate({ + to: '/layout/$childId', + params: { childId: 'one' }, + } as any) + expect(layoutLoader).toHaveBeenCalledTimes(1) + // No preloadStaleTime was configured, so navigation follows the existing + // staleTime policy and reloads the leaf while still borrowing the layout. + expect(childLoader).toHaveBeenCalledTimes(3) + expect(router.state.matches.at(-1)?.loaderData).toBe('child one') +}) + +// Public contract: the public stale/gc options determine whether user loader +// code runs. A read-only preload must not silently shorten a navigation-owned +// cache entry's lifetime. +test('fresh navigation data keeps its gc policy when a preload reuses it', async () => { + vi.useFakeTimers() + vi.setSystemTime(1_000) + + let revision = 0 + const loader = vi.fn(() => ++revision) + const rootRoute = new BaseRootRoute({}) + const homeRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const reportsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/reports', + gcTime: 30 * 60_000, + preloadGcTime: 30_000, + preloadStaleTime: 10 * 60_000, + staleTime: Infinity, + loader, + }) + const otherRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/other', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([homeRoute, reportsRoute, otherRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.navigate({ to: '/reports' }) + await router.navigate({ to: '/' }) + expect(loader).toHaveBeenCalledTimes(1) + + vi.setSystemTime(61_000) + await router.preloadRoute({ to: '/reports' }) + await router.navigate({ to: '/other' }) + await router.navigate({ to: '/reports' }) + expect(loader).toHaveBeenCalledTimes(1) + expect(router.state.matches.at(-1)?.loaderData).toBe(1) + + await router.navigate({ to: '/' }) + vi.setSystemTime(1_000 + 31 * 60_000) + await router.navigate({ to: '/other' }) + await router.navigate({ to: '/reports' }) + expect(loader).toHaveBeenCalledTimes(2) + expect(router.state.matches.at(-1)?.loaderData).toBe(2) +}) + +// Public contract: clearCache must remain authoritative even if an older +// preload finishes unrelated asset work after the clear. +test('clearCache during an in-flight preload cannot resurrect its borrowed data', async () => { + const headGate = deferred<{ meta: Array<{ title: string }> }>() + let revision = 0 + let headCalls = 0 + const loader = vi.fn(() => ++revision) + const rootRoute = new BaseRootRoute({}) + const homeRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const reportsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/reports', + staleTime: Infinity, + preloadStaleTime: Infinity, + loader, + head: () => { + headCalls++ + return headCalls === 1 + ? { meta: [{ title: 'Reports' }] } + : headGate.promise + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([homeRoute, reportsRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.navigate({ to: '/reports' }) + await router.navigate({ to: '/' }) + expect(loader).toHaveBeenCalledTimes(1) + + const preload = router.preloadRoute({ to: '/reports' }) + await vi.waitFor(() => expect(headCalls).toBe(2)) + router.clearCache() + headGate.resolve({ meta: [{ title: 'Preloaded Reports' }] }) + await preload + + await router.navigate({ to: '/reports' }) + expect(loader).toHaveBeenCalledTimes(2) + expect(router.state.matches.at(-1)?.loaderData).toBe(2) +}) + +// Probe, not a required cancellation policy: invalidating the accepted route +// need not cancel unrelated private preload work, but the public operations +// must both settle and leave navigation usable. +test('invalidate and an unrelated in-flight preload both settle cleanly', async () => { + const loaderGate = deferred() + const loader = vi.fn(() => loaderGate.promise) + const rootRoute = new BaseRootRoute({}) + const homeRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + preloadStaleTime: Infinity, + staleTime: Infinity, + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([homeRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const preload = router.preloadRoute({ to: '/target' }) + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(1)) + await router.invalidate() + loaderGate.resolve('target data') + await preload + + await router.navigate({ to: '/target' }) + expect(router.state.location.pathname).toBe('/target') + expect(router.state.matches.at(-1)?.loaderData).toBe('target data') + expect(loader).toHaveBeenCalledTimes(1) +}) diff --git a/packages/router-core/tests/preload-public-signal-lifetime.test.ts b/packages/router-core/tests/preload-public-signal-lifetime.test.ts new file mode 100644 index 0000000000..5b48252bf8 --- /dev/null +++ b/packages/router-core/tests/preload-public-signal-lifetime.test.ts @@ -0,0 +1,75 @@ +import { expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +function deferred() { + let resolve!: (value?: T | PromiseLike) => void + const promise = new Promise((done) => { + resolve = (value) => done(value as T) + }) + return { promise, resolve } +} + +// Public contract: the AbortSignal supplied to loader code belongs to the +// accepted data generation. Adopting preloaded data keeps it alive; accepting +// replacement data aborts it; unloading aborts the replacement generation. +test('an adopted loader signal lives until public replacement and unload', async () => { + const replacementGate = deferred<{ generation: number }>() + const signals: Array = [] + const loader = vi.fn( + ({ abortController }: { abortController: AbortController }) => { + signals.push(abortController.signal) + const generation = signals.length + return generation === 1 ? { generation } : replacementGate.promise + }, + ) + + const rootRoute = new BaseRootRoute({}) + const homeRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const reportsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/reports', + staleTime: Infinity, + preloadStaleTime: Infinity, + loader: { + staleReloadMode: 'blocking', + handler: loader, + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([homeRoute, reportsRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.preloadRoute({ to: '/reports' }) + const adoptedSignal = signals[0] + expect(adoptedSignal?.aborted).toBe(false) + + await router.navigate({ to: '/reports' }) + expect(loader).toHaveBeenCalledTimes(1) + expect(router.state.matches.at(-1)?.loaderData).toEqual({ generation: 1 }) + expect(adoptedSignal?.aborted).toBe(false) + + const replacement = router.invalidate({ forcePending: true }) + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(2)) + const replacementSignal = signals[1] + + // Until replacement data is accepted, the currently rendered data still + // owns the adopted signal. + expect(adoptedSignal?.aborted).toBe(false) + expect(replacementSignal?.aborted).toBe(false) + + replacementGate.resolve({ generation: 2 }) + await replacement + expect(router.state.matches.at(-1)?.loaderData).toEqual({ generation: 2 }) + expect(adoptedSignal?.aborted).toBe(true) + expect(replacementSignal?.aborted).toBe(false) + + await router.navigate({ to: '/' }) + expect(replacementSignal?.aborted).toBe(true) +}) diff --git a/packages/router-core/tests/routerTestUtils.ts b/packages/router-core/tests/routerTestUtils.ts index b71c54e347..8078068954 100644 --- a/packages/router-core/tests/routerTestUtils.ts +++ b/packages/router-core/tests/routerTestUtils.ts @@ -5,8 +5,10 @@ import { createNonReactiveMutableStore, createNonReactiveReadonlyStore, } from '../src' +import { createRequestHandler } from '../src/ssr/createRequestHandler' import type { RouterHistory } from '@tanstack/history' import type { + AnyRouter, AnyRoute, GetStoreConfig, RouterConstructorOptions, @@ -46,3 +48,20 @@ export function createTestRouter< ) { return new RouterCore(options, getStoreConfig) } + +/** Materialize the request-local server result as the HTTP response users see. */ +export function loadServerResponse(router: AnyRouter, path: string) { + return createRequestHandler({ + createRouter: () => router, + request: new Request(`http://localhost${path}`), + })(({ router: loadedRouter, responseHeaders }) => { + const result = loadedRouter._serverResult + return new Response(null, { + status: + result?.type === 'redirect' + ? result.redirect.status + : (result?.status ?? 500), + headers: responseHeaders, + }) + }) +} 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/server-async-headers-decorative-hang.test.ts b/packages/router-core/tests/server-async-headers-decorative-hang.test.ts new file mode 100644 index 0000000000..bc7797c515 --- /dev/null +++ b/packages/router-core/tests/server-async-headers-decorative-hang.test.ts @@ -0,0 +1,82 @@ +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, createControlledPromise } from '../src' +import { createTestRouter, loadServerResponse } from './routerTestUtils' + +/** + * Headers affect the HTTP response, so server loading must await them even + * after another asset hook fails synchronously. That does not make an + * unrelated decorative head promise response-significant: once headers have + * settled, a never-ending head must not hold the response open. + */ +describe('server async headers after a decorative asset failure', () => { + beforeEach(() => { + vi.useFakeTimers() + vi.spyOn(console, 'error').mockImplementation(() => {}) + }) + + afterEach(() => { + vi.useRealTimers() + vi.restoreAllMocks() + }) + + test('commits async headers without waiting for a pending head', async () => { + const expectedHeaders = { 'x-response-header': 'kept' } + const headGate = createControlledPromise<{ + meta: Array<{ title: string }> + }>() + const headersGate = createControlledPromise() + const head = vi.fn(() => headGate) + const scripts = vi.fn(() => { + throw new Error('scripts failed synchronously') + }) + const headers = vi.fn(() => headersGate) + + const rootRoute = new BaseRootRoute({}) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + head, + scripts, + headers, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([targetRoute]), + history: createMemoryHistory({ initialEntries: ['/target'] }), + isServer: true, + }) + + const loadPromise = loadServerResponse(router, '/target') + await vi.waitFor(() => { + expect(head).toHaveBeenCalledTimes(1) + expect(scripts).toHaveBeenCalledTimes(1) + expect(headers).toHaveBeenCalledTimes(1) + }) + + headersGate.resolve(expectedHeaders) + + const winnerPromise = Promise.race([ + loadPromise.then(() => 'loaded' as const), + new Promise<'timed-out'>((resolve) => { + setTimeout(() => resolve('timed-out'), 50) + }), + ]) + await vi.advanceTimersByTimeAsync(0) + await vi.advanceTimersByTimeAsync(50) + const winner = await winnerPromise + + // Cleanup happens only after recording the bounded result. On the broken + // path this releases router.load(), but cannot change `winner`. + headGate.resolve({ meta: [{ title: 'late decorative title' }] }) + await loadPromise + + const response = await loadPromise + expect({ + winner, + header: response.headers.get('x-response-header'), + }).toEqual({ + winner: 'loaded', + header: 'kept', + }) + }) +}) diff --git a/packages/router-core/tests/server-beforeload-preload-flag.test.ts b/packages/router-core/tests/server-beforeload-preload-flag.test.ts new file mode 100644 index 0000000000..22509a86c7 --- /dev/null +++ b/packages/router-core/tests/server-beforeload-preload-flag.test.ts @@ -0,0 +1,25 @@ +import { createMemoryHistory } from '@tanstack/history' +import { expect, test } from 'vitest' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +test('server beforeLoad receives preload false', async () => { + const seen: Array = [] + const rootRoute = new BaseRootRoute({}) + const childRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/child', + beforeLoad: ({ preload }) => { + seen.push(preload) + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([childRoute]), + history: createMemoryHistory({ initialEntries: ['/child'] }), + isServer: true, + }) + + await router.load() + + expect(seen).toEqual([false]) +}) 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..c5b7423ef7 --- /dev/null +++ b/packages/router-core/tests/server-chunk-failure-lifecycle.test.ts @@ -0,0 +1,100 @@ +import { describe, expect, test } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, notFound } from '../src' +import { createTestRouter, loadServerResponse } 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, + }) + + const response = await loadServerResponse(router, '/chunked') + + 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(response.status).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, + }) + + const response = await loadServerResponse(router, '/chunked') + + const match = router.state.matches.find( + (item) => item.routeId === chunkedRoute.id, + ) + expect(response.status).toBe(404) + expect(match?.status).toBe('notFound') + expect(match?.error).toEqual(expect.objectContaining({ isNotFound: true })) + }) +}) diff --git a/packages/router-core/tests/server-concurrent-error-notfound.test.ts b/packages/router-core/tests/server-concurrent-error-notfound.test.ts new file mode 100644 index 0000000000..6af4fe5841 --- /dev/null +++ b/packages/router-core/tests/server-concurrent-error-notfound.test.ts @@ -0,0 +1,168 @@ +import { describe, expect, test } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { + BaseRootRoute, + BaseRoute, + createControlledPromise, + notFound, + redirect, +} from '../src' +import { createTestRouter, loadServerResponse } from './routerTestUtils' + +describe('server concurrent route failure ordering', () => { + test.each(['parent-first', 'child-first'] as const)( + 'a shallow regular error wins over a deeper notFound (%s)', + async (settleOrder) => { + const parentGate = createControlledPromise() + const childGate = createControlledPromise() + const parentError = new Error('parent loader failed') + let parentSignal: AbortSignal | undefined + let childSignal: AbortSignal | undefined + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: async ({ abortController }) => { + parentSignal = abortController.signal + await parentGate + throw parentError + }, + errorComponent: () => null, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: async ({ abortController }) => { + childSignal = abortController.signal + await childGate + throw notFound() + }, + notFoundComponent: () => null, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ + initialEntries: ['/parent/child'], + }), + isServer: true, + }) + + const responsePromise = loadServerResponse(router, '/parent/child') + if (settleOrder === 'parent-first') { + parentGate.resolve() + await Promise.resolve() + childGate.resolve() + } else { + childGate.resolve() + await Promise.resolve() + parentGate.resolve() + } + const response = await responsePromise + + expect(response.status).toBe(500) + expect(router.stores.matches.get().map((match) => match.routeId)).toEqual( + [rootRoute.id, parentRoute.id], + ) + expect(router.stores.matches.get()[1]).toMatchObject({ + status: 'error', + error: parentError, + }) + expect(parentSignal?.aborted).toBe(false) + expect(childSignal?.aborted).toBe(true) + }, + ) + + test.each(['parent-first', 'child-first'] as const)( + 'a shallower notFound boundary wins over a deeper regular error (%s)', + async (settleOrder) => { + const parentGate = createControlledPromise() + const childGate = createControlledPromise() + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: async () => { + await parentGate + throw notFound() + }, + notFoundComponent: () => null, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: async () => { + await childGate + throw new Error('child loader failed') + }, + errorComponent: () => null, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ + initialEntries: ['/parent/child'], + }), + isServer: true, + }) + + const responsePromise = loadServerResponse(router, '/parent/child') + if (settleOrder === 'parent-first') { + parentGate.resolve() + await Promise.resolve() + childGate.resolve() + } else { + childGate.resolve() + await Promise.resolve() + parentGate.resolve() + } + const response = await responsePromise + + expect(response.status).toBe(404) + expect(router.stores.matches.get().map((match) => match.routeId)).toEqual( + [rootRoute.id, parentRoute.id], + ) + expect(router.stores.matches.get()[1]).toMatchObject({ + status: 'notFound', + }) + }, + ) + + test('a redirect aborts every generation in its discarded server lane', async () => { + const signals: Array = [] + const rootRoute = new BaseRootRoute({ + loader: ({ abortController }) => { + signals.push(abortController.signal) + return 'root data' + }, + }) + const redirectRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/redirect', + loader: ({ abortController }) => { + signals.push(abortController.signal) + throw redirect({ to: '/target' }) + }, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([redirectRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/redirect'] }), + isServer: true, + }) + + const response = await loadServerResponse(router, '/redirect') + + expect(response.status).toBe(307) + expect(response.headers.get('Location')).toBe('/target') + expect(signals).toHaveLength(2) + expect(signals.every((signal) => signal.aborted)).toBe(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 new file mode 100644 index 0000000000..bd0e32d5bf --- /dev/null +++ b/packages/router-core/tests/server-headers-asset-failure.test.ts @@ -0,0 +1,107 @@ +import { createMemoryHistory } from '@tanstack/history' +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter, loadServerResponse } 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, + }) + + return loadServerResponse(router, '/target') +} + +describe('server asset projection route headers', () => { + test('keeps route headers when head throws synchronously', async () => { + const response = await loadTargetRoute({ asyncHead: false }) + expect(response.headers.get('x-route-header')).toBe('kept') + }) + + test('keeps route headers when head rejects asynchronously', async () => { + const response = await loadTargetRoute({ asyncHead: true }) + expect(response.headers.get('x-route-header')).toBe('kept') + }) + + 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, + }) + + const response = await loadServerResponse(router, '/target') + + 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(response.headers.get('x-route-header')).toBe('kept') + 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({ + 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, + }) + + const response = await loadServerResponse(router, '/target') + expect(response.headers.get('x-route-header')).toBe('kept') + }) +}) 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..a6af9a68fc --- /dev/null +++ b/packages/router-core/tests/server-loader-abort-error.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, test } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter, loadServerResponse } 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, + }) + + const response = await loadServerResponse(router, '/aborting') + + const match = router.state.matches.find( + (item) => item.routeId === abortingRoute.id, + ) + expect(response.status).toBe(200) + 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..346d4a36c1 --- /dev/null +++ b/packages/router-core/tests/server-serial-ssr-notfound.test.ts @@ -0,0 +1,77 @@ +import { describe, expect, test } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, notFound } from '../src' +import { createTestRouter, loadServerResponse } 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') + + const response = await loadServerResponse(router, '/parent/child') + + const parentMatch = router.state.matches.find( + (item) => item.routeId === parentRoute.id, + ) + expect(loaderCalls).toEqual([]) + expect(response.status).toBe(404) + 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') + }) + + const response = await loadServerResponse(router, '/parent/child') + + expect(loaderCalls).toEqual([]) + expect(response.status).toBe(404) + }) +}) diff --git a/packages/router-core/tests/server-ssr-false-assets.test.ts b/packages/router-core/tests/server-ssr-false-assets.test.ts new file mode 100644 index 0000000000..fa33c36b49 --- /dev/null +++ b/packages/router-core/tests/server-ssr-false-assets.test.ts @@ -0,0 +1,91 @@ +import { describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter, loadServerResponse } from './routerTestUtils' + +/** + * `ssr: false` makes a route client-only. Its beforeLoad, loader, component, + * and route assets must all stay out of the server response. Descendants + * inherit that restriction even if they request `ssr: true` themselves. + */ +describe('server assets for ssr:false routes', () => { + test('does not execute or publish assets for the client-only branch', async () => { + const parentHead = vi.fn(() => ({ + meta: [{ title: 'client-only parent' }], + })) + const parentScripts = vi.fn(() => [ + { + children: 'window.parentAssetRan = true', + }, + ]) + const parentHeaders = vi.fn(() => ({ + 'x-client-only-parent': 'unexpected', + })) + const childHead = vi.fn(() => ({ + meta: [{ title: 'client-only child' }], + })) + const childScripts = vi.fn(() => [ + { + children: 'window.childAssetRan = true', + }, + ]) + const childHeaders = vi.fn(() => ({ + 'x-client-only-child': 'unexpected', + })) + + const rootRoute = new BaseRootRoute({}) + const clientOnlyRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/client-only', + ssr: false, + head: parentHead, + scripts: parentScripts, + headers: parentHeaders, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => clientOnlyRoute, + path: '/child', + // A child cannot relax its parent's client-only restriction. + ssr: true, + head: childHead, + scripts: childScripts, + headers: childHeaders, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + clientOnlyRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ + initialEntries: ['/client-only/child'], + }), + isServer: true, + }) + + const response = await loadServerResponse(router, '/client-only/child') + + expect({ + calls: { + parentHead: parentHead.mock.calls.length, + parentScripts: parentScripts.mock.calls.length, + parentHeaders: parentHeaders.mock.calls.length, + childHead: childHead.mock.calls.length, + childScripts: childScripts.mock.calls.length, + childHeaders: childHeaders.mock.calls.length, + }, + responseHeaders: { + parent: response.headers.get('x-client-only-parent'), + child: response.headers.get('x-client-only-child'), + }, + }).toEqual({ + calls: { + parentHead: 0, + parentScripts: 0, + parentHeaders: 0, + childHead: 0, + childScripts: 0, + childHeaders: 0, + }, + responseHeaders: { parent: null, child: null }, + }) + }) +}) diff --git a/packages/router-core/tests/server-ssr-option-error.test.ts b/packages/router-core/tests/server-ssr-option-error.test.ts new file mode 100644 index 0000000000..bbbc471281 --- /dev/null +++ b/packages/router-core/tests/server-ssr-option-error.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter, loadServerResponse } from './routerTestUtils' + +/** + * A functional ssr() option is user route code in the server serial phase. + * If it throws an ordinary error, the route must not be committed as a + * successful 200 response with missing loader data. It follows the same + * renderable route-error lifecycle as beforeLoad and loader failures. + */ +describe('server functional ssr() errors', () => { + test('commits the throwing route as an error and returns 500', async () => { + const boom = new Error('feature flag lookup failed') + const loader = vi.fn(() => 'reports data') + + const rootRoute = new BaseRootRoute({}) + const reportsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/reports', + ssr: () => { + throw boom + }, + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([reportsRoute]), + history: createMemoryHistory({ initialEntries: ['/reports'] }), + isServer: true, + }) + + const response = await loadServerResponse(router, '/reports') + + const reportsMatch = router.state.matches.find( + (match) => match.routeId === reportsRoute.id, + ) + expect(loader).not.toHaveBeenCalled() + expect(response.status).toBe(500) + expect(reportsMatch).toMatchObject({ + status: 'error', + error: boom, + }) + }) +}) 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..209ddcc082 --- /dev/null +++ b/packages/router-core/tests/stay-match-abort.test.ts @@ -0,0 +1,249 @@ +import { afterEach, describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { + BaseRootRoute, + BaseRoute, + createControlledPromise, + notFound, +} from '../src' +import { createTestRouter } from './routerTestUtils' + +afterEach(() => { + vi.restoreAllMocks() +}) + +/** + * 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(reloadGate?: Promise) { + let capturedSignal: AbortSignal | undefined + let deferredRequestAbortCount = 0 + let loaderCalls = 0 + + const rootRoute = new BaseRootRoute({}) + const dashboardRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/dashboard', + staleTime: Infinity, + loader: ({ abortController }: { abortController: AbortController }) => { + loaderCalls++ + capturedSignal = abortController.signal + + // A common streaming pattern is to return immediately-available data + // alongside a request consumed later by . That request must stay + // alive while this layout is reused, then be cancelled when it unloads. + const deferredRequest = new Promise<'aborted'>((resolve) => { + abortController.signal.addEventListener( + 'abort', + () => { + deferredRequestAbortCount++ + resolve('aborted') + }, + { once: true }, + ) + }) + + const data = { critical: 'dashboard data', deferredRequest } + return reloadGate && loaderCalls > 1 ? reloadGate.then(() => data) : data + }, + }) + const settingsRoute = new BaseRoute({ + getParentRoute: () => dashboardRoute, + path: '/settings', + }) + const loginRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/login', + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + dashboardRoute.addChildren([settingsRoute]), + loginRoute, + ]), + history: createMemoryHistory({ initialEntries: ['/dashboard'] }), + }) + + return { + router, + getSignal: () => capturedSignal, + getDeferredRequestAbortCount: () => deferredRequestAbortCount, + } +} + +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('unloading a reused match aborts the signal exposed to its loader', async () => { + const { router, getSignal, getDeferredRequestAbortCount } = setup() + + await router.load() + const dashboardLoaderSignal = getSignal() + + // Reusing the dashboard layout for a child must preserve the lifetime of + // its loader's deferred request. + await router.navigate({ to: '/dashboard/settings' }) + expect(dashboardLoaderSignal?.aborted).toBe(false) + expect(getDeferredRequestAbortCount()).toBe(0) + + // Leaving the layout altogether must now cancel that same request. + await router.navigate({ to: '/login' }) + expect(dashboardLoaderSignal?.aborted).toBe(true) + expect(getDeferredRequestAbortCount()).toBe(1) + }) + + test('background invalidation keeps the old loader signal until fresh data commits', async () => { + const reloadGate = createControlledPromise() + const { router, getSignal } = setup(reloadGate) + + await router.load() + const firstSignal = getSignal() + expect(firstSignal?.aborted).toBe(false) + + const invalidation = router.invalidate() + await vi.waitFor(() => expect(getSignal()).not.toBe(firstSignal)) + + // The old loader data is still the published generation while the + // background replacement is private. + expect(firstSignal?.aborted).toBe(false) + + reloadGate.resolve() + await invalidation + await vi.waitFor(() => expect(firstSignal?.aborted).toBe(true)) + }) + + test.each(['beforeLoad', 'shouldReload'] as const)( + '%s failure replacing a successful stay aborts its loader signal', + async (failureStage) => { + const failure = new Error(`${failureStage} failed`) + const onAbort = vi.fn() + let shouldFail = false + let loaderSignal: AbortSignal | undefined + + const rootRoute = new BaseRootRoute({}) + const accountRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/account', + staleTime: Infinity, + beforeLoad: () => { + if (shouldFail && failureStage === 'beforeLoad') { + throw failure + } + }, + shouldReload: () => { + if (shouldFail && failureStage === 'shouldReload') { + throw failure + } + return false + }, + loader: ({ abortController }: { abortController: AbortController }) => { + loaderSignal = abortController.signal + loaderSignal.addEventListener('abort', onAbort, { once: true }) + return { user: 'Flo' } + }, + errorComponent: () => null, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([accountRoute]), + history: createMemoryHistory({ initialEntries: ['/account'] }), + }) + + await router.load() + expect(loaderSignal?.aborted).toBe(false) + + shouldFail = true + await router.load() + + const match = router.state.matches.find( + (candidate) => candidate.routeId === accountRoute.id, + ) + expect(match?.status).toBe('error') + expect(match?.error).toBe(failure) + expect(loaderSignal?.aborted).toBe(true) + expect(onAbort).toHaveBeenCalledTimes(1) + }, + ) + + test('background notFound replacing successful data aborts its old loader signal', async () => { + let loaderCalls = 0 + let initialSignal: AbortSignal | undefined + + const rootRoute = new BaseRootRoute({}) + const accountRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/account', + staleTime: Infinity, + loader: ({ abortController }: { abortController: AbortController }) => { + loaderCalls++ + if (loaderCalls === 1) { + initialSignal = abortController.signal + return { user: 'Flo' } + } + throw notFound() + }, + notFoundComponent: () => null, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([accountRoute]), + history: createMemoryHistory({ initialEntries: ['/account'] }), + }) + + await router.load() + expect(initialSignal?.aborted).toBe(false) + + await router.invalidate() + await vi.waitFor(() => + expect(router.state.matches.at(-1)?.status).toBe('notFound'), + ) + expect(initialSignal?.aborted).toBe(true) + }) + + test('decorative background asset failure still transfers loader signal ownership', async () => { + vi.spyOn(console, 'error').mockImplementation(() => undefined) + let loaderCalls = 0 + const loaderSignals: Array = [] + + const rootRoute = new BaseRootRoute({}) + const accountRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/account', + staleTime: Infinity, + loader: ({ abortController }: { abortController: AbortController }) => { + loaderSignals.push(abortController.signal) + return { revision: ++loaderCalls } + }, + head: ({ loaderData }) => { + if (loaderData?.revision === 2) { + throw new Error('fresh head failed') + } + return { meta: [{ title: 'account' }] } + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([accountRoute]), + history: createMemoryHistory({ initialEntries: ['/account'] }), + }) + + await router.load() + await router.invalidate() + + expect(router.state.matches.at(-1)?.loaderData).toEqual({ revision: 2 }) + expect(loaderSignals).toHaveLength(2) + expect(loaderSignals[0]?.aborted).toBe(true) + expect(loaderSignals[1]?.aborted).toBe(false) + }) +}) 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/router-devtools-core/src/AgeTicker.tsx b/packages/router-devtools-core/src/AgeTicker.tsx index 27d179fda1..e3bd657358 100644 --- a/packages/router-devtools-core/src/AgeTicker.tsx +++ b/packages/router-devtools-core/src/AgeTicker.tsx @@ -1,6 +1,6 @@ import { clsx as cx } from 'clsx' import { useStyles } from './useStyles' -import type { AnyRouteMatch, AnyRouter } from '@tanstack/router-core' +import type { AnyRoute, AnyRouteMatch, AnyRouter } from '@tanstack/router-core' import type { Accessor } from 'solid-js' function formatTime(ms: number) { @@ -35,7 +35,9 @@ export function AgeTicker({ return null } - const route = router().looseRoutesById[match.routeId]! + const route = (router().routesById as Record)[ + match.routeId + ]! if (!route.options.loader) { return null diff --git a/packages/router-devtools-core/src/BaseTanStackRouterDevtoolsPanel.tsx b/packages/router-devtools-core/src/BaseTanStackRouterDevtoolsPanel.tsx index 79566656b0..5c09dc1b59 100644 --- a/packages/router-devtools-core/src/BaseTanStackRouterDevtoolsPanel.tsx +++ b/packages/router-devtools-core/src/BaseTanStackRouterDevtoolsPanel.tsx @@ -282,30 +282,19 @@ export const BaseTanStackRouterDevtoolsPanel = const [history, setHistory] = createSignal>([]) const [hasHistoryOverflowed, setHasHistoryOverflowed] = createSignal(false) - let pendingMatches: Accessor> + const pendingMatches = () => { + const matches = routerState().matches + return matches.some((match: AnyRouteMatch) => match.status === 'pending') + ? matches + : [] + } let cachedMatches: Accessor> // subscribable implementation - if ('subscribe' in router().stores.pendingMatches) { - const [_pendingMatches, setPending] = createSignal>( - [], - ) - pendingMatches = _pendingMatches - + if ('subscribe' in router().stores.cachedMatches) { const [_cachedMatches, setCached] = createSignal>([]) cachedMatches = _cachedMatches type Subscribe = (fn: () => void) => { unsubscribe: () => void } - createEffect(() => { - const pendingMatchesStore = router().stores.pendingMatches - setPending(pendingMatchesStore.get()) - const subscription = ( - (pendingMatchesStore as any).subscribe as Subscribe - )(() => { - setPending(pendingMatchesStore.get()) - }) - onCleanup(() => subscription.unsubscribe()) - }) - createEffect(() => { const cachedMatchesStore = router().stores.cachedMatches setCached(cachedMatchesStore.get()) @@ -319,7 +308,6 @@ export const BaseTanStackRouterDevtoolsPanel = } // signal implementation else { - pendingMatches = () => router().stores.pendingMatches.get() cachedMatches = () => router().stores.cachedMatches.get() } @@ -392,7 +380,6 @@ export const BaseTanStackRouterDevtoolsPanel = 'stores', 'basepath', 'subscribers', - 'latestLoadPromise', '_scroll', 'tempLocationKey', 'latestLocation', @@ -719,7 +706,9 @@ export const BaseTanStackRouterDevtoolsPanel =
State:
- {pendingMatches().find((d) => d.id === activeMatch()?.id) + {pendingMatches().find( + (d: AnyRouteMatch) => d.id === activeMatch()?.id, + ) ? 'Pending' : routerState().matches.find( (d: any) => d.id === activeMatch()?.id, 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..dcf8c9dcc9 100644 --- a/packages/router-plugin/src/core/hmr/handle-route-update.ts +++ b/packages/router-plugin/src/core/hmr/handle-route-update.ts @@ -1,15 +1,9 @@ -import type { - AnyRoute, - AnyRouteMatch, - AnyRouter, - RouterWritableStore, -} from '@tanstack/router-core' +import type { AnyRoute, AnyRouter } from '@tanstack/router-core' type AnyRouteWithPrivateProps = AnyRoute & { options: Record parentRoute: AnyRoute - _componentsPromise?: Promise - _lazyPromise?: Promise + _lazy?: Promise | true update: (options: Record) => unknown _path: string _id: string @@ -17,37 +11,18 @@ type AnyRouteWithPrivateProps = AnyRoute & { _to: string } -type AnyRouterWithPrivateMaps = AnyRouter & { +type AnyRouterWithPrivateState = AnyRouter & { routesById: Record buildRouteTree: () => Parameters[0] setRoutes: AnyRouter['setRoutes'] - stores: AnyRouter['stores'] & { - cachedMatchStores: Map< - string, - Pick, 'get' | 'set'> - > - pendingMatchStores: Map< - string, - Pick, 'get' | 'set'> - > - matchStores: Map< - string, - Pick, 'get' | 'set'> - > - } -} - -type AnyRouteMatchWithPrivateProps = AnyRouteMatch & { - __beforeLoadContext?: unknown - __routeContext?: Record - context?: Record + _refreshRoute?: (routeId: string) => Promise } function handleRouteUpdate( routeId: string, newRoute: AnyRouteWithPrivateProps, ) { - const router = window.__TSR_ROUTER__ as AnyRouterWithPrivateMaps + const router = window.__TSR_ROUTER__ as AnyRouterWithPrivateState const oldRoute = router.routesById[routeId] as | AnyRouteWithPrivateProps | undefined @@ -66,14 +41,6 @@ function handleRouteUpdate( } }) - const removedKeys = new Set() - Object.keys(oldRoute.options).forEach((key) => { - if (!generatedRouteOptionKeys.has(key) && !(key in newRoute.options)) { - removedKeys.add(key) - delete oldRoute.options[key] - } - }) - const oldHasShellComponent = 'shellComponent' in oldRoute.options const newHasShellComponent = 'shellComponent' in newRoute.options const preserveComponentIdentity = @@ -106,60 +73,12 @@ function handleRouteUpdate( oldRoute.options = nextOptions oldRoute.update(nextOptions) - oldRoute._componentsPromise = undefined - oldRoute._lazyPromise = undefined + oldRoute._lazy = undefined router.setRoutes(router.buildRouteTree()) syncHotRouteExport(oldRoute) router.resolvePathCache.clear() - - const filter = (m: AnyRouteMatch) => m.routeId === oldRoute.id - const activeMatch = router.stores.matches.get().find(filter) - const pendingMatch = router.stores.pendingMatches.get().find(filter) - const cachedMatches = router.stores.cachedMatches.get().filter(filter) - - if (activeMatch || pendingMatch || cachedMatches.length > 0) { - // Clear stale match data for removed route options BEFORE invalidating. - // Without this, router.invalidate() -> matchRoutes() reuses the existing - // 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. - if (removedKeys.has('loader') || removedKeys.has('beforeLoad')) { - const matchIds = [ - activeMatch?.id, - pendingMatch?.id, - ...cachedMatches.map((match) => match.id), - ].filter(Boolean) as Array - router.batch(() => { - for (const matchId of matchIds) { - const store = - router.stores.pendingMatchStores.get(matchId) || - router.stores.matchStores.get(matchId) || - router.stores.cachedMatchStores.get(matchId) - if (store) { - store.set((prev) => { - const next: AnyRouteMatchWithPrivateProps = { ...prev } - - if (removedKeys.has('loader')) { - next.loaderData = undefined - } - if (removedKeys.has('beforeLoad')) { - next.__beforeLoadContext = undefined - next.context = rebuildMatchContextWithoutBeforeLoad(next) - } - - return next - }) - } - } - }) - } - - router.invalidate({ filter, sync: true }) - } + void router._refreshRoute?.(oldRoute.id) function syncHotRouteExport(liveRoute: AnyRouteWithPrivateProps) { // routeTree.gen.ts mutates the original module export with generated @@ -172,66 +91,6 @@ function handleRouteUpdate( newRoute._fullPath = liveRoute._fullPath newRoute._to = liveRoute._to } - - function getStoreMatch(matchId: string) { - return ( - router.stores.pendingMatchStores.get(matchId)?.get() || - router.stores.matchStores.get(matchId)?.get() || - router.stores.cachedMatchStores.get(matchId)?.get() - ) - } - - function getMatchList(matchId: string) { - const pendingMatches = router.stores.pendingMatches.get() - if (pendingMatches.some((match) => match.id === matchId)) { - return pendingMatches - } - - const activeMatches = router.stores.matches.get() - if (activeMatches.some((match) => match.id === matchId)) { - return activeMatches - } - - const cachedMatches = router.stores.cachedMatches.get() - if (cachedMatches.some((match) => match.id === matchId)) { - return cachedMatches - } - - return [] - } - - function getParentMatch(match: AnyRouteMatch) { - const matchList = getMatchList(match.id) - const matchIndex = matchList.findIndex((item) => item.id === match.id) - - if (matchIndex <= 0) { - return undefined - } - - const parentMatch = matchList[matchIndex - 1]! - return getStoreMatch(parentMatch.id) || parentMatch - } - - function rebuildMatchContextWithoutBeforeLoad( - match: AnyRouteMatchWithPrivateProps, - ) { - const parentMatch = getParentMatch(match) - const getParentContext = ( - router as unknown as { - getParentContext?: ( - parentMatch?: AnyRouteMatch, - ) => Record | undefined - } - ).getParentContext - const parentContext = getParentContext - ? getParentContext.call(router, parentMatch) - : (parentMatch?.context ?? router.options.context) - - return { - ...(parentContext ?? {}), - ...(match.__routeContext ?? {}), - } - } } const handleRouteUpdateStr = handleRouteUpdate.toString() diff --git a/packages/router-plugin/tests/add-hmr.test.ts b/packages/router-plugin/tests/add-hmr.test.ts index 4430cef74c..3e1a9135f4 100644 --- a/packages/router-plugin/tests/add-hmr.test.ts +++ b/packages/router-plugin/tests/add-hmr.test.ts @@ -111,7 +111,6 @@ describe('add-hmr works', () => { expect(output).toContain('webpackHot') expect(output).not.toContain('import.meta.hot') expect(output).toContain('oldHasShellComponent') - expect(output).toContain('__routeContext') }) it('supports configurable Vite unsplittable HMR generation', async () => { 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..7c4cf61b8d 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 @@ -52,13 +52,6 @@ if (import.meta.hot) { generatedRouteOptions[key] = oldRoute.options[key]; } }); - const removedKeys = new Set(); - Object.keys(oldRoute.options).forEach(key => { - if (!generatedRouteOptionKeys.has(key) && !(key in newRoute.options)) { - removedKeys.add(key); - delete oldRoute.options[key]; - } - }); const oldHasShellComponent = "shellComponent" in oldRoute.options; const newHasShellComponent = "shellComponent" in newRoute.options; const preserveComponentIdentity = oldHasShellComponent === newHasShellComponent; @@ -77,48 +70,11 @@ if (import.meta.hot) { }; oldRoute.options = nextOptions; oldRoute.update(nextOptions); - oldRoute._componentsPromise = undefined; - oldRoute._lazyPromise = undefined; + oldRoute._lazy = undefined; router.setRoutes(router.buildRouteTree()); syncHotRouteExport(oldRoute); router.resolvePathCache.clear(); - const filter = m => m.routeId === oldRoute.id; - const activeMatch = router.stores.matches.get().find(filter); - const pendingMatch = router.stores.pendingMatches.get().find(filter); - const cachedMatches = router.stores.cachedMatches.get().filter(filter); - if (activeMatch || pendingMatch || cachedMatches.length > 0) { - if (removedKeys.has("loader") || removedKeys.has("beforeLoad")) { - const matchIds = [activeMatch?.id, pendingMatch?.id, ...cachedMatches.map(match => match.id)].filter(Boolean); - router.batch(() => { - for (const matchId of matchIds) { - const store = router.stores.pendingMatchStores.get(matchId) || router.stores.matchStores.get(matchId) || router.stores.cachedMatchStores.get(matchId); - if (store) { - store.set(prev => { - const next = { - ...prev - }; - if (removedKeys.has("loader")) { - next.loaderData = undefined; - } - ; - if (removedKeys.has("beforeLoad")) { - next.__beforeLoadContext = undefined; - next.context = rebuildMatchContextWithoutBeforeLoad(next); - } - ; - return next; - }); - } - } - }); - } - ; - router.invalidate({ - filter, - sync: true - }); - } - ; + void router._refreshRoute?.(oldRoute.id); function syncHotRouteExport(liveRoute) { newRoute.options = liveRoute.options; newRoute.parentRoute = liveRoute.parentRoute; @@ -127,46 +83,6 @@ if (import.meta.hot) { newRoute._fullPath = liveRoute._fullPath; newRoute._to = liveRoute._to; } - function getStoreMatch(matchId) { - return router.stores.pendingMatchStores.get(matchId)?.get() || router.stores.matchStores.get(matchId)?.get() || router.stores.cachedMatchStores.get(matchId)?.get(); - } - function getMatchList(matchId) { - const pendingMatches = router.stores.pendingMatches.get(); - if (pendingMatches.some(match => match.id === matchId)) { - return pendingMatches; - } - ; - const activeMatches = router.stores.matches.get(); - if (activeMatches.some(match => match.id === matchId)) { - return activeMatches; - } - ; - const cachedMatches = router.stores.cachedMatches.get(); - if (cachedMatches.some(match => match.id === matchId)) { - return cachedMatches; - } - ; - return []; - } - function getParentMatch(match) { - const matchList = getMatchList(match.id); - const matchIndex = matchList.findIndex(item => item.id === match.id); - if (matchIndex <= 0) { - return undefined; - } - ; - const parentMatch = matchList[matchIndex - 1]; - return getStoreMatch(parentMatch.id) || parentMatch; - } - function rebuildMatchContextWithoutBeforeLoad(match) { - const parentMatch = getParentMatch(match); - const getParentContext = router.getParentContext; - const parentContext = getParentContext ? getParentContext.call(router, parentMatch) : parentMatch?.context ?? router.options.context; - return { - ...(parentContext ?? {}), - ...(match.__routeContext ?? {}) - }; - } }; const initialRouteId = Route.id ?? hotData['tsr-route-id']; if (initialRouteId) { 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..ac6ddeef6e 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 @@ -38,13 +38,6 @@ if (import.meta.webpackHot) { generatedRouteOptions[key] = oldRoute.options[key]; } }); - const removedKeys = new Set(); - Object.keys(oldRoute.options).forEach(key => { - if (!generatedRouteOptionKeys.has(key) && !(key in newRoute.options)) { - removedKeys.add(key); - delete oldRoute.options[key]; - } - }); const oldHasShellComponent = "shellComponent" in oldRoute.options; const newHasShellComponent = "shellComponent" in newRoute.options; const preserveComponentIdentity = oldHasShellComponent === newHasShellComponent; @@ -63,48 +56,11 @@ if (import.meta.webpackHot) { }; oldRoute.options = nextOptions; oldRoute.update(nextOptions); - oldRoute._componentsPromise = undefined; - oldRoute._lazyPromise = undefined; + oldRoute._lazy = undefined; router.setRoutes(router.buildRouteTree()); syncHotRouteExport(oldRoute); router.resolvePathCache.clear(); - const filter = m => m.routeId === oldRoute.id; - const activeMatch = router.stores.matches.get().find(filter); - const pendingMatch = router.stores.pendingMatches.get().find(filter); - const cachedMatches = router.stores.cachedMatches.get().filter(filter); - if (activeMatch || pendingMatch || cachedMatches.length > 0) { - if (removedKeys.has("loader") || removedKeys.has("beforeLoad")) { - const matchIds = [activeMatch?.id, pendingMatch?.id, ...cachedMatches.map(match => match.id)].filter(Boolean); - router.batch(() => { - for (const matchId of matchIds) { - const store = router.stores.pendingMatchStores.get(matchId) || router.stores.matchStores.get(matchId) || router.stores.cachedMatchStores.get(matchId); - if (store) { - store.set(prev => { - const next = { - ...prev - }; - if (removedKeys.has("loader")) { - next.loaderData = undefined; - } - ; - if (removedKeys.has("beforeLoad")) { - next.__beforeLoadContext = undefined; - next.context = rebuildMatchContextWithoutBeforeLoad(next); - } - ; - return next; - }); - } - } - }); - } - ; - router.invalidate({ - filter, - sync: true - }); - } - ; + void router._refreshRoute?.(oldRoute.id); function syncHotRouteExport(liveRoute) { newRoute.options = liveRoute.options; newRoute.parentRoute = liveRoute.parentRoute; @@ -113,46 +69,6 @@ if (import.meta.webpackHot) { newRoute._fullPath = liveRoute._fullPath; newRoute._to = liveRoute._to; } - function getStoreMatch(matchId) { - return router.stores.pendingMatchStores.get(matchId)?.get() || router.stores.matchStores.get(matchId)?.get() || router.stores.cachedMatchStores.get(matchId)?.get(); - } - function getMatchList(matchId) { - const pendingMatches = router.stores.pendingMatches.get(); - if (pendingMatches.some(match => match.id === matchId)) { - return pendingMatches; - } - ; - const activeMatches = router.stores.matches.get(); - if (activeMatches.some(match => match.id === matchId)) { - return activeMatches; - } - ; - const cachedMatches = router.stores.cachedMatches.get(); - if (cachedMatches.some(match => match.id === matchId)) { - return cachedMatches; - } - ; - return []; - } - function getParentMatch(match) { - const matchList = getMatchList(match.id); - const matchIndex = matchList.findIndex(item => item.id === match.id); - if (matchIndex <= 0) { - return undefined; - } - ; - const parentMatch = matchList[matchIndex - 1]; - return getStoreMatch(parentMatch.id) || parentMatch; - } - function rebuildMatchContextWithoutBeforeLoad(match) { - const parentMatch = getParentMatch(match); - const getParentContext = router.getParentContext; - const parentContext = getParentContext ? getParentContext.call(router, parentMatch) : parentMatch?.context ?? router.options.context; - return { - ...(parentContext ?? {}), - ...(match.__routeContext ?? {}) - }; - } })(routeId, Route); try { const tsrReactRefreshUtils = typeof __react_refresh_utils__ !== 'undefined' ? __react_refresh_utils__ : undefined; 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..ce3efafbe6 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 @@ -41,13 +41,6 @@ if (import.meta.hot) { generatedRouteOptions[key] = oldRoute.options[key]; } }); - const removedKeys = new Set(); - Object.keys(oldRoute.options).forEach(key => { - if (!generatedRouteOptionKeys.has(key) && !(key in newRoute.options)) { - removedKeys.add(key); - delete oldRoute.options[key]; - } - }); const oldHasShellComponent = "shellComponent" in oldRoute.options; const newHasShellComponent = "shellComponent" in newRoute.options; const preserveComponentIdentity = oldHasShellComponent === newHasShellComponent; @@ -66,48 +59,11 @@ if (import.meta.hot) { }; oldRoute.options = nextOptions; oldRoute.update(nextOptions); - oldRoute._componentsPromise = undefined; - oldRoute._lazyPromise = undefined; + oldRoute._lazy = undefined; router.setRoutes(router.buildRouteTree()); syncHotRouteExport(oldRoute); router.resolvePathCache.clear(); - const filter = m => m.routeId === oldRoute.id; - const activeMatch = router.stores.matches.get().find(filter); - const pendingMatch = router.stores.pendingMatches.get().find(filter); - const cachedMatches = router.stores.cachedMatches.get().filter(filter); - if (activeMatch || pendingMatch || cachedMatches.length > 0) { - if (removedKeys.has("loader") || removedKeys.has("beforeLoad")) { - const matchIds = [activeMatch?.id, pendingMatch?.id, ...cachedMatches.map(match => match.id)].filter(Boolean); - router.batch(() => { - for (const matchId of matchIds) { - const store = router.stores.pendingMatchStores.get(matchId) || router.stores.matchStores.get(matchId) || router.stores.cachedMatchStores.get(matchId); - if (store) { - store.set(prev => { - const next = { - ...prev - }; - if (removedKeys.has("loader")) { - next.loaderData = undefined; - } - ; - if (removedKeys.has("beforeLoad")) { - next.__beforeLoadContext = undefined; - next.context = rebuildMatchContextWithoutBeforeLoad(next); - } - ; - return next; - }); - } - } - }); - } - ; - router.invalidate({ - filter, - sync: true - }); - } - ; + void router._refreshRoute?.(oldRoute.id); function syncHotRouteExport(liveRoute) { newRoute.options = liveRoute.options; newRoute.parentRoute = liveRoute.parentRoute; @@ -116,46 +72,6 @@ if (import.meta.hot) { newRoute._fullPath = liveRoute._fullPath; newRoute._to = liveRoute._to; } - function getStoreMatch(matchId) { - return router.stores.pendingMatchStores.get(matchId)?.get() || router.stores.matchStores.get(matchId)?.get() || router.stores.cachedMatchStores.get(matchId)?.get(); - } - function getMatchList(matchId) { - const pendingMatches = router.stores.pendingMatches.get(); - if (pendingMatches.some(match => match.id === matchId)) { - return pendingMatches; - } - ; - const activeMatches = router.stores.matches.get(); - if (activeMatches.some(match => match.id === matchId)) { - return activeMatches; - } - ; - const cachedMatches = router.stores.cachedMatches.get(); - if (cachedMatches.some(match => match.id === matchId)) { - return cachedMatches; - } - ; - return []; - } - function getParentMatch(match) { - const matchList = getMatchList(match.id); - const matchIndex = matchList.findIndex(item => item.id === match.id); - if (matchIndex <= 0) { - return undefined; - } - ; - const parentMatch = matchList[matchIndex - 1]; - return getStoreMatch(parentMatch.id) || parentMatch; - } - function rebuildMatchContextWithoutBeforeLoad(match) { - const parentMatch = getParentMatch(match); - const getParentContext = router.getParentContext; - const parentContext = getParentContext ? getParentContext.call(router, parentMatch) : parentMatch?.context ?? router.options.context; - return { - ...(parentContext ?? {}), - ...(match.__routeContext ?? {}) - }; - } }; const initialRouteId = Route.id ?? hotData['tsr-route-id']; if (initialRouteId) { 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..96f918525e 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 @@ -43,13 +43,6 @@ if (import.meta.hot) { generatedRouteOptions[key] = oldRoute.options[key]; } }); - const removedKeys = new Set(); - Object.keys(oldRoute.options).forEach(key => { - if (!generatedRouteOptionKeys.has(key) && !(key in newRoute.options)) { - removedKeys.add(key); - delete oldRoute.options[key]; - } - }); const oldHasShellComponent = "shellComponent" in oldRoute.options; const newHasShellComponent = "shellComponent" in newRoute.options; const preserveComponentIdentity = oldHasShellComponent === newHasShellComponent; @@ -68,48 +61,11 @@ if (import.meta.hot) { }; oldRoute.options = nextOptions; oldRoute.update(nextOptions); - oldRoute._componentsPromise = undefined; - oldRoute._lazyPromise = undefined; + oldRoute._lazy = undefined; router.setRoutes(router.buildRouteTree()); syncHotRouteExport(oldRoute); router.resolvePathCache.clear(); - const filter = m => m.routeId === oldRoute.id; - const activeMatch = router.stores.matches.get().find(filter); - const pendingMatch = router.stores.pendingMatches.get().find(filter); - const cachedMatches = router.stores.cachedMatches.get().filter(filter); - if (activeMatch || pendingMatch || cachedMatches.length > 0) { - if (removedKeys.has("loader") || removedKeys.has("beforeLoad")) { - const matchIds = [activeMatch?.id, pendingMatch?.id, ...cachedMatches.map(match => match.id)].filter(Boolean); - router.batch(() => { - for (const matchId of matchIds) { - const store = router.stores.pendingMatchStores.get(matchId) || router.stores.matchStores.get(matchId) || router.stores.cachedMatchStores.get(matchId); - if (store) { - store.set(prev => { - const next = { - ...prev - }; - if (removedKeys.has("loader")) { - next.loaderData = undefined; - } - ; - if (removedKeys.has("beforeLoad")) { - next.__beforeLoadContext = undefined; - next.context = rebuildMatchContextWithoutBeforeLoad(next); - } - ; - return next; - }); - } - } - }); - } - ; - router.invalidate({ - filter, - sync: true - }); - } - ; + void router._refreshRoute?.(oldRoute.id); function syncHotRouteExport(liveRoute) { newRoute.options = liveRoute.options; newRoute.parentRoute = liveRoute.parentRoute; @@ -118,46 +74,6 @@ if (import.meta.hot) { newRoute._fullPath = liveRoute._fullPath; newRoute._to = liveRoute._to; } - function getStoreMatch(matchId) { - return router.stores.pendingMatchStores.get(matchId)?.get() || router.stores.matchStores.get(matchId)?.get() || router.stores.cachedMatchStores.get(matchId)?.get(); - } - function getMatchList(matchId) { - const pendingMatches = router.stores.pendingMatches.get(); - if (pendingMatches.some(match => match.id === matchId)) { - return pendingMatches; - } - ; - const activeMatches = router.stores.matches.get(); - if (activeMatches.some(match => match.id === matchId)) { - return activeMatches; - } - ; - const cachedMatches = router.stores.cachedMatches.get(); - if (cachedMatches.some(match => match.id === matchId)) { - return cachedMatches; - } - ; - return []; - } - function getParentMatch(match) { - const matchList = getMatchList(match.id); - const matchIndex = matchList.findIndex(item => item.id === match.id); - if (matchIndex <= 0) { - return undefined; - } - ; - const parentMatch = matchList[matchIndex - 1]; - return getStoreMatch(parentMatch.id) || parentMatch; - } - function rebuildMatchContextWithoutBeforeLoad(match) { - const parentMatch = getParentMatch(match); - const getParentContext = router.getParentContext; - const parentContext = getParentContext ? getParentContext.call(router, parentMatch) : parentMatch?.context ?? router.options.context; - return { - ...(parentContext ?? {}), - ...(match.__routeContext ?? {}) - }; - } }; const initialRouteId = Route.id ?? hotData['tsr-route-id']; if (initialRouteId) { 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..ec488de92c 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 @@ -46,13 +46,6 @@ if (import.meta.hot) { generatedRouteOptions[key] = oldRoute.options[key]; } }); - const removedKeys = new Set(); - Object.keys(oldRoute.options).forEach(key => { - if (!generatedRouteOptionKeys.has(key) && !(key in newRoute.options)) { - removedKeys.add(key); - delete oldRoute.options[key]; - } - }); const oldHasShellComponent = "shellComponent" in oldRoute.options; const newHasShellComponent = "shellComponent" in newRoute.options; const preserveComponentIdentity = oldHasShellComponent === newHasShellComponent; @@ -71,48 +64,11 @@ if (import.meta.hot) { }; oldRoute.options = nextOptions; oldRoute.update(nextOptions); - oldRoute._componentsPromise = undefined; - oldRoute._lazyPromise = undefined; + oldRoute._lazy = undefined; router.setRoutes(router.buildRouteTree()); syncHotRouteExport(oldRoute); router.resolvePathCache.clear(); - const filter = m => m.routeId === oldRoute.id; - const activeMatch = router.stores.matches.get().find(filter); - const pendingMatch = router.stores.pendingMatches.get().find(filter); - const cachedMatches = router.stores.cachedMatches.get().filter(filter); - if (activeMatch || pendingMatch || cachedMatches.length > 0) { - if (removedKeys.has("loader") || removedKeys.has("beforeLoad")) { - const matchIds = [activeMatch?.id, pendingMatch?.id, ...cachedMatches.map(match => match.id)].filter(Boolean); - router.batch(() => { - for (const matchId of matchIds) { - const store = router.stores.pendingMatchStores.get(matchId) || router.stores.matchStores.get(matchId) || router.stores.cachedMatchStores.get(matchId); - if (store) { - store.set(prev => { - const next = { - ...prev - }; - if (removedKeys.has("loader")) { - next.loaderData = undefined; - } - ; - if (removedKeys.has("beforeLoad")) { - next.__beforeLoadContext = undefined; - next.context = rebuildMatchContextWithoutBeforeLoad(next); - } - ; - return next; - }); - } - } - }); - } - ; - router.invalidate({ - filter, - sync: true - }); - } - ; + void router._refreshRoute?.(oldRoute.id); function syncHotRouteExport(liveRoute) { newRoute.options = liveRoute.options; newRoute.parentRoute = liveRoute.parentRoute; @@ -121,46 +77,6 @@ if (import.meta.hot) { newRoute._fullPath = liveRoute._fullPath; newRoute._to = liveRoute._to; } - function getStoreMatch(matchId) { - return router.stores.pendingMatchStores.get(matchId)?.get() || router.stores.matchStores.get(matchId)?.get() || router.stores.cachedMatchStores.get(matchId)?.get(); - } - function getMatchList(matchId) { - const pendingMatches = router.stores.pendingMatches.get(); - if (pendingMatches.some(match => match.id === matchId)) { - return pendingMatches; - } - ; - const activeMatches = router.stores.matches.get(); - if (activeMatches.some(match => match.id === matchId)) { - return activeMatches; - } - ; - const cachedMatches = router.stores.cachedMatches.get(); - if (cachedMatches.some(match => match.id === matchId)) { - return cachedMatches; - } - ; - return []; - } - function getParentMatch(match) { - const matchList = getMatchList(match.id); - const matchIndex = matchList.findIndex(item => item.id === match.id); - if (matchIndex <= 0) { - return undefined; - } - ; - const parentMatch = matchList[matchIndex - 1]; - return getStoreMatch(parentMatch.id) || parentMatch; - } - function rebuildMatchContextWithoutBeforeLoad(match) { - const parentMatch = getParentMatch(match); - const getParentContext = router.getParentContext; - const parentContext = getParentContext ? getParentContext.call(router, parentMatch) : parentMatch?.context ?? router.options.context; - return { - ...(parentContext ?? {}), - ...(match.__routeContext ?? {}) - }; - } }; const initialRouteId = Route.id ?? hotData['tsr-route-id']; if (initialRouteId) { 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..a953380aa9 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 @@ -40,13 +40,6 @@ if (import.meta.hot) { generatedRouteOptions[key] = oldRoute.options[key]; } }); - const removedKeys = new Set(); - Object.keys(oldRoute.options).forEach(key => { - if (!generatedRouteOptionKeys.has(key) && !(key in newRoute.options)) { - removedKeys.add(key); - delete oldRoute.options[key]; - } - }); const oldHasShellComponent = "shellComponent" in oldRoute.options; const newHasShellComponent = "shellComponent" in newRoute.options; const preserveComponentIdentity = oldHasShellComponent === newHasShellComponent; @@ -65,48 +58,11 @@ if (import.meta.hot) { }; oldRoute.options = nextOptions; oldRoute.update(nextOptions); - oldRoute._componentsPromise = undefined; - oldRoute._lazyPromise = undefined; + oldRoute._lazy = undefined; router.setRoutes(router.buildRouteTree()); syncHotRouteExport(oldRoute); router.resolvePathCache.clear(); - const filter = m => m.routeId === oldRoute.id; - const activeMatch = router.stores.matches.get().find(filter); - const pendingMatch = router.stores.pendingMatches.get().find(filter); - const cachedMatches = router.stores.cachedMatches.get().filter(filter); - if (activeMatch || pendingMatch || cachedMatches.length > 0) { - if (removedKeys.has("loader") || removedKeys.has("beforeLoad")) { - const matchIds = [activeMatch?.id, pendingMatch?.id, ...cachedMatches.map(match => match.id)].filter(Boolean); - router.batch(() => { - for (const matchId of matchIds) { - const store = router.stores.pendingMatchStores.get(matchId) || router.stores.matchStores.get(matchId) || router.stores.cachedMatchStores.get(matchId); - if (store) { - store.set(prev => { - const next = { - ...prev - }; - if (removedKeys.has("loader")) { - next.loaderData = undefined; - } - ; - if (removedKeys.has("beforeLoad")) { - next.__beforeLoadContext = undefined; - next.context = rebuildMatchContextWithoutBeforeLoad(next); - } - ; - return next; - }); - } - } - }); - } - ; - router.invalidate({ - filter, - sync: true - }); - } - ; + void router._refreshRoute?.(oldRoute.id); function syncHotRouteExport(liveRoute) { newRoute.options = liveRoute.options; newRoute.parentRoute = liveRoute.parentRoute; @@ -115,46 +71,6 @@ if (import.meta.hot) { newRoute._fullPath = liveRoute._fullPath; newRoute._to = liveRoute._to; } - function getStoreMatch(matchId) { - return router.stores.pendingMatchStores.get(matchId)?.get() || router.stores.matchStores.get(matchId)?.get() || router.stores.cachedMatchStores.get(matchId)?.get(); - } - function getMatchList(matchId) { - const pendingMatches = router.stores.pendingMatches.get(); - if (pendingMatches.some(match => match.id === matchId)) { - return pendingMatches; - } - ; - const activeMatches = router.stores.matches.get(); - if (activeMatches.some(match => match.id === matchId)) { - return activeMatches; - } - ; - const cachedMatches = router.stores.cachedMatches.get(); - if (cachedMatches.some(match => match.id === matchId)) { - return cachedMatches; - } - ; - return []; - } - function getParentMatch(match) { - const matchList = getMatchList(match.id); - const matchIndex = matchList.findIndex(item => item.id === match.id); - if (matchIndex <= 0) { - return undefined; - } - ; - const parentMatch = matchList[matchIndex - 1]; - return getStoreMatch(parentMatch.id) || parentMatch; - } - function rebuildMatchContextWithoutBeforeLoad(match) { - const parentMatch = getParentMatch(match); - const getParentContext = router.getParentContext; - const parentContext = getParentContext ? getParentContext.call(router, parentMatch) : parentMatch?.context ?? router.options.context; - return { - ...(parentContext ?? {}), - ...(match.__routeContext ?? {}) - }; - } }; const initialRouteId = Route.id ?? hotData['tsr-route-id']; if (initialRouteId) { 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..52164d8bee 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 @@ -52,13 +52,6 @@ if (import.meta.hot) { generatedRouteOptions[key] = oldRoute.options[key]; } }); - const removedKeys = new Set(); - Object.keys(oldRoute.options).forEach(key => { - if (!generatedRouteOptionKeys.has(key) && !(key in newRoute.options)) { - removedKeys.add(key); - delete oldRoute.options[key]; - } - }); const oldHasShellComponent = "shellComponent" in oldRoute.options; const newHasShellComponent = "shellComponent" in newRoute.options; const preserveComponentIdentity = oldHasShellComponent === newHasShellComponent; @@ -77,48 +70,11 @@ if (import.meta.hot) { }; oldRoute.options = nextOptions; oldRoute.update(nextOptions); - oldRoute._componentsPromise = undefined; - oldRoute._lazyPromise = undefined; + oldRoute._lazy = undefined; router.setRoutes(router.buildRouteTree()); syncHotRouteExport(oldRoute); router.resolvePathCache.clear(); - const filter = m => m.routeId === oldRoute.id; - const activeMatch = router.stores.matches.get().find(filter); - const pendingMatch = router.stores.pendingMatches.get().find(filter); - const cachedMatches = router.stores.cachedMatches.get().filter(filter); - if (activeMatch || pendingMatch || cachedMatches.length > 0) { - if (removedKeys.has("loader") || removedKeys.has("beforeLoad")) { - const matchIds = [activeMatch?.id, pendingMatch?.id, ...cachedMatches.map(match => match.id)].filter(Boolean); - router.batch(() => { - for (const matchId of matchIds) { - const store = router.stores.pendingMatchStores.get(matchId) || router.stores.matchStores.get(matchId) || router.stores.cachedMatchStores.get(matchId); - if (store) { - store.set(prev => { - const next = { - ...prev - }; - if (removedKeys.has("loader")) { - next.loaderData = undefined; - } - ; - if (removedKeys.has("beforeLoad")) { - next.__beforeLoadContext = undefined; - next.context = rebuildMatchContextWithoutBeforeLoad(next); - } - ; - return next; - }); - } - } - }); - } - ; - router.invalidate({ - filter, - sync: true - }); - } - ; + void router._refreshRoute?.(oldRoute.id); function syncHotRouteExport(liveRoute) { newRoute.options = liveRoute.options; newRoute.parentRoute = liveRoute.parentRoute; @@ -127,46 +83,6 @@ if (import.meta.hot) { newRoute._fullPath = liveRoute._fullPath; newRoute._to = liveRoute._to; } - function getStoreMatch(matchId) { - return router.stores.pendingMatchStores.get(matchId)?.get() || router.stores.matchStores.get(matchId)?.get() || router.stores.cachedMatchStores.get(matchId)?.get(); - } - function getMatchList(matchId) { - const pendingMatches = router.stores.pendingMatches.get(); - if (pendingMatches.some(match => match.id === matchId)) { - return pendingMatches; - } - ; - const activeMatches = router.stores.matches.get(); - if (activeMatches.some(match => match.id === matchId)) { - return activeMatches; - } - ; - const cachedMatches = router.stores.cachedMatches.get(); - if (cachedMatches.some(match => match.id === matchId)) { - return cachedMatches; - } - ; - return []; - } - function getParentMatch(match) { - const matchList = getMatchList(match.id); - const matchIndex = matchList.findIndex(item => item.id === match.id); - if (matchIndex <= 0) { - return undefined; - } - ; - const parentMatch = matchList[matchIndex - 1]; - return getStoreMatch(parentMatch.id) || parentMatch; - } - function rebuildMatchContextWithoutBeforeLoad(match) { - const parentMatch = getParentMatch(match); - const getParentContext = router.getParentContext; - const parentContext = getParentContext ? getParentContext.call(router, parentMatch) : parentMatch?.context ?? router.options.context; - return { - ...(parentContext ?? {}), - ...(match.__routeContext ?? {}) - }; - } }; const initialRouteId = Route.id ?? hotData['tsr-route-id']; if (initialRouteId) { 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..fbd9a5b59d 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 @@ -62,13 +62,6 @@ if (import.meta.hot) { generatedRouteOptions[key] = oldRoute.options[key]; } }); - const removedKeys = new Set(); - Object.keys(oldRoute.options).forEach(key => { - if (!generatedRouteOptionKeys.has(key) && !(key in newRoute.options)) { - removedKeys.add(key); - delete oldRoute.options[key]; - } - }); const oldHasShellComponent = "shellComponent" in oldRoute.options; const newHasShellComponent = "shellComponent" in newRoute.options; const preserveComponentIdentity = oldHasShellComponent === newHasShellComponent; @@ -87,48 +80,11 @@ if (import.meta.hot) { }; oldRoute.options = nextOptions; oldRoute.update(nextOptions); - oldRoute._componentsPromise = undefined; - oldRoute._lazyPromise = undefined; + oldRoute._lazy = undefined; router.setRoutes(router.buildRouteTree()); syncHotRouteExport(oldRoute); router.resolvePathCache.clear(); - const filter = m => m.routeId === oldRoute.id; - const activeMatch = router.stores.matches.get().find(filter); - const pendingMatch = router.stores.pendingMatches.get().find(filter); - const cachedMatches = router.stores.cachedMatches.get().filter(filter); - if (activeMatch || pendingMatch || cachedMatches.length > 0) { - if (removedKeys.has("loader") || removedKeys.has("beforeLoad")) { - const matchIds = [activeMatch?.id, pendingMatch?.id, ...cachedMatches.map(match => match.id)].filter(Boolean); - router.batch(() => { - for (const matchId of matchIds) { - const store = router.stores.pendingMatchStores.get(matchId) || router.stores.matchStores.get(matchId) || router.stores.cachedMatchStores.get(matchId); - if (store) { - store.set(prev => { - const next = { - ...prev - }; - if (removedKeys.has("loader")) { - next.loaderData = undefined; - } - ; - if (removedKeys.has("beforeLoad")) { - next.__beforeLoadContext = undefined; - next.context = rebuildMatchContextWithoutBeforeLoad(next); - } - ; - return next; - }); - } - } - }); - } - ; - router.invalidate({ - filter, - sync: true - }); - } - ; + void router._refreshRoute?.(oldRoute.id); function syncHotRouteExport(liveRoute) { newRoute.options = liveRoute.options; newRoute.parentRoute = liveRoute.parentRoute; @@ -137,46 +93,6 @@ if (import.meta.hot) { newRoute._fullPath = liveRoute._fullPath; newRoute._to = liveRoute._to; } - function getStoreMatch(matchId) { - return router.stores.pendingMatchStores.get(matchId)?.get() || router.stores.matchStores.get(matchId)?.get() || router.stores.cachedMatchStores.get(matchId)?.get(); - } - function getMatchList(matchId) { - const pendingMatches = router.stores.pendingMatches.get(); - if (pendingMatches.some(match => match.id === matchId)) { - return pendingMatches; - } - ; - const activeMatches = router.stores.matches.get(); - if (activeMatches.some(match => match.id === matchId)) { - return activeMatches; - } - ; - const cachedMatches = router.stores.cachedMatches.get(); - if (cachedMatches.some(match => match.id === matchId)) { - return cachedMatches; - } - ; - return []; - } - function getParentMatch(match) { - const matchList = getMatchList(match.id); - const matchIndex = matchList.findIndex(item => item.id === match.id); - if (matchIndex <= 0) { - return undefined; - } - ; - const parentMatch = matchList[matchIndex - 1]; - return getStoreMatch(parentMatch.id) || parentMatch; - } - function rebuildMatchContextWithoutBeforeLoad(match) { - const parentMatch = getParentMatch(match); - const getParentContext = router.getParentContext; - const parentContext = getParentContext ? getParentContext.call(router, parentMatch) : parentMatch?.context ?? router.options.context; - return { - ...(parentContext ?? {}), - ...(match.__routeContext ?? {}) - }; - } }; const initialRouteId = Route.id ?? hotData['tsr-route-id']; if (initialRouteId) { 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..fe97ac99a0 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 @@ -62,13 +62,6 @@ if (import.meta.hot) { generatedRouteOptions[key] = oldRoute.options[key]; } }); - const removedKeys = new Set(); - Object.keys(oldRoute.options).forEach(key => { - if (!generatedRouteOptionKeys.has(key) && !(key in newRoute.options)) { - removedKeys.add(key); - delete oldRoute.options[key]; - } - }); const oldHasShellComponent = "shellComponent" in oldRoute.options; const newHasShellComponent = "shellComponent" in newRoute.options; const preserveComponentIdentity = oldHasShellComponent === newHasShellComponent; @@ -87,48 +80,11 @@ if (import.meta.hot) { }; oldRoute.options = nextOptions; oldRoute.update(nextOptions); - oldRoute._componentsPromise = undefined; - oldRoute._lazyPromise = undefined; + oldRoute._lazy = undefined; router.setRoutes(router.buildRouteTree()); syncHotRouteExport(oldRoute); router.resolvePathCache.clear(); - const filter = m => m.routeId === oldRoute.id; - const activeMatch = router.stores.matches.get().find(filter); - const pendingMatch = router.stores.pendingMatches.get().find(filter); - const cachedMatches = router.stores.cachedMatches.get().filter(filter); - if (activeMatch || pendingMatch || cachedMatches.length > 0) { - if (removedKeys.has("loader") || removedKeys.has("beforeLoad")) { - const matchIds = [activeMatch?.id, pendingMatch?.id, ...cachedMatches.map(match => match.id)].filter(Boolean); - router.batch(() => { - for (const matchId of matchIds) { - const store = router.stores.pendingMatchStores.get(matchId) || router.stores.matchStores.get(matchId) || router.stores.cachedMatchStores.get(matchId); - if (store) { - store.set(prev => { - const next = { - ...prev - }; - if (removedKeys.has("loader")) { - next.loaderData = undefined; - } - ; - if (removedKeys.has("beforeLoad")) { - next.__beforeLoadContext = undefined; - next.context = rebuildMatchContextWithoutBeforeLoad(next); - } - ; - return next; - }); - } - } - }); - } - ; - router.invalidate({ - filter, - sync: true - }); - } - ; + void router._refreshRoute?.(oldRoute.id); function syncHotRouteExport(liveRoute) { newRoute.options = liveRoute.options; newRoute.parentRoute = liveRoute.parentRoute; @@ -137,46 +93,6 @@ if (import.meta.hot) { newRoute._fullPath = liveRoute._fullPath; newRoute._to = liveRoute._to; } - function getStoreMatch(matchId) { - return router.stores.pendingMatchStores.get(matchId)?.get() || router.stores.matchStores.get(matchId)?.get() || router.stores.cachedMatchStores.get(matchId)?.get(); - } - function getMatchList(matchId) { - const pendingMatches = router.stores.pendingMatches.get(); - if (pendingMatches.some(match => match.id === matchId)) { - return pendingMatches; - } - ; - const activeMatches = router.stores.matches.get(); - if (activeMatches.some(match => match.id === matchId)) { - return activeMatches; - } - ; - const cachedMatches = router.stores.cachedMatches.get(); - if (cachedMatches.some(match => match.id === matchId)) { - return cachedMatches; - } - ; - return []; - } - function getParentMatch(match) { - const matchList = getMatchList(match.id); - const matchIndex = matchList.findIndex(item => item.id === match.id); - if (matchIndex <= 0) { - return undefined; - } - ; - const parentMatch = matchList[matchIndex - 1]; - return getStoreMatch(parentMatch.id) || parentMatch; - } - function rebuildMatchContextWithoutBeforeLoad(match) { - const parentMatch = getParentMatch(match); - const getParentContext = router.getParentContext; - const parentContext = getParentContext ? getParentContext.call(router, parentMatch) : parentMatch?.context ?? router.options.context; - return { - ...(parentContext ?? {}), - ...(match.__routeContext ?? {}) - }; - } }; const initialRouteId = Route.id ?? hotData['tsr-route-id']; if (initialRouteId) { 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..a14f7e3895 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 @@ -23,13 +23,6 @@ if (import.meta.hot) { generatedRouteOptions[key] = oldRoute.options[key]; } }); - const removedKeys = new Set(); - Object.keys(oldRoute.options).forEach(key => { - if (!generatedRouteOptionKeys.has(key) && !(key in newRoute.options)) { - removedKeys.add(key); - delete oldRoute.options[key]; - } - }); const oldHasShellComponent = "shellComponent" in oldRoute.options; const newHasShellComponent = "shellComponent" in newRoute.options; const preserveComponentIdentity = oldHasShellComponent === newHasShellComponent; @@ -48,48 +41,11 @@ if (import.meta.hot) { }; oldRoute.options = nextOptions; oldRoute.update(nextOptions); - oldRoute._componentsPromise = undefined; - oldRoute._lazyPromise = undefined; + oldRoute._lazy = undefined; router.setRoutes(router.buildRouteTree()); syncHotRouteExport(oldRoute); router.resolvePathCache.clear(); - const filter = m => m.routeId === oldRoute.id; - const activeMatch = router.stores.matches.get().find(filter); - const pendingMatch = router.stores.pendingMatches.get().find(filter); - const cachedMatches = router.stores.cachedMatches.get().filter(filter); - if (activeMatch || pendingMatch || cachedMatches.length > 0) { - if (removedKeys.has("loader") || removedKeys.has("beforeLoad")) { - const matchIds = [activeMatch?.id, pendingMatch?.id, ...cachedMatches.map(match => match.id)].filter(Boolean); - router.batch(() => { - for (const matchId of matchIds) { - const store = router.stores.pendingMatchStores.get(matchId) || router.stores.matchStores.get(matchId) || router.stores.cachedMatchStores.get(matchId); - if (store) { - store.set(prev => { - const next = { - ...prev - }; - if (removedKeys.has("loader")) { - next.loaderData = undefined; - } - ; - if (removedKeys.has("beforeLoad")) { - next.__beforeLoadContext = undefined; - next.context = rebuildMatchContextWithoutBeforeLoad(next); - } - ; - return next; - }); - } - } - }); - } - ; - router.invalidate({ - filter, - sync: true - }); - } - ; + void router._refreshRoute?.(oldRoute.id); function syncHotRouteExport(liveRoute) { newRoute.options = liveRoute.options; newRoute.parentRoute = liveRoute.parentRoute; @@ -98,46 +54,6 @@ if (import.meta.hot) { newRoute._fullPath = liveRoute._fullPath; newRoute._to = liveRoute._to; } - function getStoreMatch(matchId) { - return router.stores.pendingMatchStores.get(matchId)?.get() || router.stores.matchStores.get(matchId)?.get() || router.stores.cachedMatchStores.get(matchId)?.get(); - } - function getMatchList(matchId) { - const pendingMatches = router.stores.pendingMatches.get(); - if (pendingMatches.some(match => match.id === matchId)) { - return pendingMatches; - } - ; - const activeMatches = router.stores.matches.get(); - if (activeMatches.some(match => match.id === matchId)) { - return activeMatches; - } - ; - const cachedMatches = router.stores.cachedMatches.get(); - if (cachedMatches.some(match => match.id === matchId)) { - return cachedMatches; - } - ; - return []; - } - function getParentMatch(match) { - const matchList = getMatchList(match.id); - const matchIndex = matchList.findIndex(item => item.id === match.id); - if (matchIndex <= 0) { - return undefined; - } - ; - const parentMatch = matchList[matchIndex - 1]; - return getStoreMatch(parentMatch.id) || parentMatch; - } - function rebuildMatchContextWithoutBeforeLoad(match) { - const parentMatch = getParentMatch(match); - const getParentContext = router.getParentContext; - const parentContext = getParentContext ? getParentContext.call(router, parentMatch) : parentMatch?.context ?? router.options.context; - return { - ...(parentContext ?? {}), - ...(match.__routeContext ?? {}) - }; - } }; const initialRouteId = Route.id ?? hotData['tsr-route-id']; if (initialRouteId) { diff --git a/packages/router-plugin/tests/handle-route-update.test.ts b/packages/router-plugin/tests/handle-route-update.test.ts index 9a80bfbeb4..c7e69bee1c 100644 --- a/packages/router-plugin/tests/handle-route-update.test.ts +++ b/packages/router-plugin/tests/handle-route-update.test.ts @@ -6,7 +6,8 @@ import { createNonReactiveReadonlyStore, trimPathRight, } from '@tanstack/router-core' -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' +import { createMemoryHistory } from '../../history/src' import { getHandleRouteUpdateCode } from '../src/core/hmr' import type { AnyRoute, GetStoreConfig } from '@tanstack/router-core' @@ -62,6 +63,18 @@ function createTestRouter(routeTree: AnyRoute) { ) } +function createClientTestRouter(routeTree: AnyRoute, initialEntry: string) { + return new RouterCore( + { + routeTree, + history: createMemoryHistory({ initialEntries: [initialEntry] }), + isServer: false, + origin: 'http://localhost', + }, + getStoreConfig, + ) +} + function withWindowRouter(router: RouterCore) { const previousWindow = (globalThis as any).window ;(globalThis as any).window = { __TSR_ROUTER__: router } @@ -75,6 +88,19 @@ function withWindowRouter(router: RouterCore) { } } +function runHandleRouteUpdate( + router: RouterCore, + routeId: string, + newRoute: AnyRoute, +) { + const restoreWindow = withWindowRouter(router) + try { + getHandleRouteUpdate()(routeId, newRoute) + } finally { + restoreWindow() + } +} + function getProcessedTreeRouteForPath( router: RouterCore, path: string, @@ -217,4 +243,244 @@ describe('handleRouteUpdate', () => { expect((newRoute as any).parentRoute).toBe(rootRoute) expect((newRoute as any).options).toBe((itemRoute as any).options) }) + + it('removes stale loader data when a hot route removes its loader', async () => { + const rootRoute = new BaseRootRoute({ + loader: () => 'stale loader data', + }) + const router = createTestRouter(rootRoute) + await router.load() + + expect(router.state.matches[0]?.loaderData).toBe('stale loader data') + + const restoreWindow = withWindowRouter(router) + try { + getHandleRouteUpdate()(rootRoute.id, new BaseRootRoute({})) + await vi.waitFor(() => { + expect(router.state.matches[0]?.loaderData).toBeUndefined() + }) + } finally { + restoreWindow() + } + }) + + it('keeps hot loader data when an older refresh settles later', async () => { + let resolveStaleRefresh!: (value: string) => void + const staleRefresh = new Promise((resolve) => { + resolveStaleRefresh = resolve + }) + const oldLoader = vi + .fn<() => string | Promise>() + .mockReturnValueOnce('initial') + .mockReturnValueOnce(staleRefresh) + const newLoader = vi.fn(() => 'hot') + const rootRoute = new BaseRootRoute({ loader: oldLoader }) + const router = createClientTestRouter(rootRoute, '/') + + await router.load() + expect(router.state.matches[0]?.loaderData).toBe('initial') + + const oldRefresh = router.invalidate() + await vi.waitFor(() => expect(oldLoader).toHaveBeenCalledTimes(2)) + + runHandleRouteUpdate( + router, + rootRoute.id, + new BaseRootRoute({ loader: newLoader }), + ) + + await vi.waitFor(() => { + expect(router.state.matches[0]?.loaderData).toBe('hot') + }) + + resolveStaleRefresh('stale') + await oldRefresh + + expect(newLoader).toHaveBeenCalled() + expect(router.state.matches[0]?.loaderData).toBe('hot') + }) + + it('does not cache an obsolete inactive preload that settles after a hot update', async () => { + let resolveOldLoader!: (value: string) => void + const oldLoaderResult = new Promise((resolve) => { + resolveOldLoader = resolve + }) + const oldLoader = vi.fn(() => oldLoaderResult) + const newLoader = vi.fn(() => 'hot') + const rootRoute = new BaseRootRoute({}) + const hotRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/hot', + loader: oldLoader, + preloadStaleTime: Infinity, + }) + const router = createClientTestRouter( + rootRoute.addChildren([hotRoute]), + '/', + ) + + await router.load() + const preload = router.preloadRoute({ to: '/hot' }) + await vi.waitFor(() => expect(oldLoader).toHaveBeenCalledOnce()) + + runHandleRouteUpdate( + router, + hotRoute.id, + new BaseRoute({ loader: newLoader } as any), + ) + + resolveOldLoader('obsolete') + await preload + await router.navigate({ to: '/hot' }) + + expect(newLoader).toHaveBeenCalledOnce() + expect(router.state.matches.at(-1)?.loaderData).toBe('hot') + }) + + it('observes hot parser and route-context changes on the active route', async () => { + const rootRoute = new BaseRootRoute({}) + const itemRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/items/$itemId', + params: { + parse: ({ itemId }: { itemId: string }) => ({ + itemId, + parser: 'old', + }), + }, + context: () => ({ source: 'old' }), + }) + const router = createClientTestRouter( + rootRoute.addChildren([itemRoute]), + '/items/abc', + ) + + await router.load() + expect(router.state.matches[1]?.params).toMatchObject({ parser: 'old' }) + expect(router.state.matches[1]?.context).toMatchObject({ source: 'old' }) + + runHandleRouteUpdate( + router, + itemRoute.id, + new BaseRoute({ + params: { + parse: ({ itemId }: { itemId: string }) => ({ + itemId, + parser: 'new', + }), + }, + context: () => ({ source: 'new' }), + } as any), + ) + + await vi.waitFor(() => { + expect(router.state.matches[1]?.params).toMatchObject({ parser: 'new' }) + expect(router.state.matches[1]?.context).toMatchObject({ source: 'new' }) + }) + }) + + it('rematerializes descendants when a parent route definition changes', async () => { + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + context: () => ({ source: 'old' }), + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + context: ({ context }) => ({ inheritedSource: context.source }), + }) + const router = createClientTestRouter( + rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + '/parent/child', + ) + + await router.load() + expect(router.state.matches[2]?.context).toMatchObject({ + inheritedSource: 'old', + }) + + runHandleRouteUpdate( + router, + parentRoute.id, + new BaseRoute({ context: () => ({ source: 'new' }) } as any), + ) + + await vi.waitFor(() => { + expect(router.state.matches[2]?.context).toMatchObject({ + inheritedSource: 'new', + }) + }) + }) + + it('does not run removed loader or beforeLoad callbacks on a later visit', async () => { + const beforeLoad = vi.fn(() => ({ hotBeforeLoad: true })) + const loader = vi.fn(() => 'hot loader data') + const rootRoute = new BaseRootRoute({}) + const hotRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/hot', + beforeLoad, + loader, + staleTime: Infinity, + gcTime: Infinity, + }) + const otherRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/other', + }) + const router = createClientTestRouter( + rootRoute.addChildren([hotRoute, otherRoute]), + '/hot', + ) + + await router.load() + await router.navigate({ to: '/other' }) + expect(beforeLoad).toHaveBeenCalledTimes(1) + expect(loader).toHaveBeenCalledTimes(1) + + runHandleRouteUpdate(router, hotRoute.id, new BaseRoute({} as any)) + await router.navigate({ to: '/hot' }) + + const match = router.state.matches.find( + (candidate) => candidate.routeId === hotRoute.id, + ) + expect(beforeLoad).toHaveBeenCalledTimes(1) + expect(loader).toHaveBeenCalledTimes(1) + expect(match?.loaderData).toBeUndefined() + expect(match?.context).not.toHaveProperty('hotBeforeLoad') + }) + + it('removes projected head and body scripts after a hot update', async () => { + const rootRoute = new BaseRootRoute({}) + const hotRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/hot', + head: () => ({ + meta: [{ title: 'hot title' }], + scripts: [{ src: '/hot-head.js' }], + }), + scripts: () => [{ src: '/hot-body.js' }], + }) + const router = createClientTestRouter( + rootRoute.addChildren([hotRoute]), + '/hot', + ) + + await router.load() + expect(router.state.matches[1]).toMatchObject({ + meta: [{ title: 'hot title' }], + headScripts: [{ src: '/hot-head.js' }], + scripts: [{ src: '/hot-body.js' }], + }) + + runHandleRouteUpdate(router, hotRoute.id, new BaseRoute({} as any)) + + await vi.waitFor(() => { + expect(router.state.matches[1]?.meta).toBeUndefined() + expect(router.state.matches[1]?.headScripts).toBeUndefined() + expect(router.state.matches[1]?.scripts).toBeUndefined() + }) + }) }) diff --git a/packages/solid-router/src/ClientOnly.tsx b/packages/solid-router/src/ClientOnly.tsx index a7c4b71819..621d41974a 100644 --- a/packages/solid-router/src/ClientOnly.tsx +++ b/packages/solid-router/src/ClientOnly.tsx @@ -59,7 +59,9 @@ export function ClientOnly(props: ClientOnlyProps) { let globalHydrated = false export function useHydrated(): Solid.Accessor { - const [hydrated, setHydrated] = Solid.createSignal(globalHydrated) + const [hydrated, setHydrated] = Solid.createSignal( + globalHydrated && !Solid.sharedConfig.context, + ) Solid.onMount(() => { globalHydrated = true diff --git a/packages/solid-router/src/Match.tsx b/packages/solid-router/src/Match.tsx index 205e778689..3909a7ff4a 100644 --- a/packages/solid-router/src/Match.tsx +++ b/packages/solid-router/src/Match.tsx @@ -1,12 +1,5 @@ import * as Solid from 'solid-js' -import { - createControlledPromise, - getLocationChangeInfo, - invariant, - isNotFound, - isRedirect, - rootRouteId, -} from '@tanstack/router-core' +import { invariant, isNotFound, rootRouteId } from '@tanstack/router-core' import { isServer } from '@tanstack/router-core/isServer' import { Dynamic } from 'solid-js/web' import { CatchBoundary, ErrorComponent } from './CatchBoundary' @@ -16,6 +9,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 }) => { @@ -32,7 +26,6 @@ export const Match = (props: { matchId: string }) => { if (!currentMatch) { return null } - const routeId = currentMatch.routeId as string const parentRouteId = (router.routesById[routeId] as AnyRoute)?.parentRoute ?.id @@ -40,23 +33,17 @@ export const Match = (props: { matchId: string }) => { return { matchId: currentMatch.id, routeId, + fetchCount: currentMatch.fetchCount, + status: currentMatch.status, ssr: currentMatch.ssr, - _displayPending: currentMatch._displayPending, parentRouteId: parentRouteId as string | undefined, } }) - 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 ( @@ -104,6 +91,15 @@ export const Match = (props: { matchId: string }) => { SafeFragment) : SafeFragment + const MatchContent = () => ( + } + > + + + ) + return ( @@ -119,7 +115,7 @@ export const Match = (props: { matchId: string }) => { > router.stores.loadedAt.get()} + getResetKey={() => currentMatchState().fetchCount} errorComponent={routeErrorComponent() || ErrorComponent} onCatch={(error: Error) => { // Forward not found errors (we don't want to show the error component for these) @@ -166,17 +162,16 @@ export const Match = (props: { matchId: string }) => { > - } > - - + + - + @@ -185,13 +180,10 @@ export const Match = (props: { matchId: string }) => { {currentMatchState().parentRouteId === rootRouteId ? ( - <> - - {router.options.scrollRestoration && - (isServer ?? router.isServer) ? ( - - ) : null} - + router.options.scrollRestoration && + (isServer ?? router.isServer) ? ( + + ) : null ) : null} ) @@ -200,30 +192,6 @@ export const Match = (props: { matchId: string }) => { ) } -// On Rendered can't happen above the root layout because it needs to run -// after the app has committed below the root layout. Keeping it here lets us -// fire onRendered even after a hydration mismatch above the root layout -// (like bad head/link tags, which is common). -function OnRendered() { - const router = useRouter() - - const location = Solid.createMemo( - () => router.stores.resolvedLocation.get()?.state.__TSR_key, - ) - Solid.createEffect( - Solid.on([location], () => { - router.emit({ - type: 'onRendered', - ...getLocationChangeInfo( - router.stores.location.get(), - router.stores.resolvedLocation.get(), - ), - }) - }), - ) - return null -} - export const MatchInner = (): any => { const router = useRouter() const match = Solid.useContext(nearestMatchContext).match @@ -233,7 +201,6 @@ export const MatchInner = (): any => { if (!currentMatch) { return null } - const routeId = currentMatch.routeId as string const remountFn = @@ -254,8 +221,6 @@ export const MatchInner = (): any => { id: currentMatch.id, status: currentMatch.status, error: currentMatch.error, - _forcePending: currentMatch._forcePending ?? false, - _displayPending: currentMatch._displayPending ?? false, }, } }) @@ -279,22 +244,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,76 +252,6 @@ 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()} - }} - - - {(_) => { - const pendingMinMs = - route().options.pendingMinMs ?? - router.options.defaultPendingMinMs - - 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) - } - } - } - - const [loaderResult] = Solid.createResource(async () => { - await Promise.resolve() - return router.getMatch(currentMatch().id)?._nonReactive - .loadPromise - }) - - const FallbackComponent = - route().options.pendingComponent ?? - router.options.defaultPendingComponent - - return ( - <> - {FallbackComponent && pendingMinMs > 0 ? ( - - ) : null} - {loaderResult()} - - ) - }} - {(_) => { if (!isNotFound(currentMatch().error)) { @@ -395,29 +274,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 +325,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 @@ -492,7 +341,7 @@ export const Outlet = () => { fallback={ {(resolvedRoute) => - renderRouteNotFound(router, resolvedRoute(), undefined) + renderRouteNotFound(router, resolvedRoute(), parentMatch()?.error) } } diff --git a/packages/solid-router/src/Matches.tsx b/packages/solid-router/src/Matches.tsx index 75586f862d..63f2a8f4c7 100644 --- a/packages/solid-router/src/Matches.tsx +++ b/packages/solid-router/src/Matches.tsx @@ -62,20 +62,15 @@ export function Matches() { function MatchesInner() { const router = useRouter() - const matchId = () => router.stores.firstId.get() + const matchId = () => router.stores.matchesId.get()[0] 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 resetKey = () => match()?.fetchCount ?? 0 const nearestMatch = { matchId, routeId, match, - hasPending: hasPendingMatch, } const matchComponent = () => { diff --git a/packages/solid-router/src/Transitioner.tsx b/packages/solid-router/src/Transitioner.tsx index 331aff5864..01092b34f5 100644 --- a/packages/solid-router/src/Transitioner.tsx +++ b/packages/solid-router/src/Transitioner.tsx @@ -5,29 +5,22 @@ import { useRouter } from './useRouter' export function Transitioner() { const router = useRouter() - let mountLoadForRouter = { router, mounted: false } - const isLoading = Solid.createMemo(() => router.stores.isLoading.get()) if (isServer ?? router.isServer) { return null } - const [isSolidTransitioning, startSolidTransition] = Solid.useTransition() - - // Track pending state changes - const hasPending = Solid.createMemo(() => router.stores.hasPending.get()) - - const isAnyPending = Solid.createMemo( - () => isLoading() || isSolidTransitioning() || hasPending(), - ) - - const isPagePending = Solid.createMemo(() => isLoading() || hasPending()) - - router.startTransition = (fn: () => void | Promise) => { - Solid.startTransition(() => { - startSolidTransition(fn) - }) + const previousTransition = router.startTransition + const transition = async (fn: () => void) => { + await Solid.startTransition(fn) + return true } + router.startTransition = transition + Solid.onCleanup(() => { + if (router.startTransition === transition) { + router.startTransition = previousTransition + } + }) // Subscribe to location changes // and try to load the new location @@ -51,6 +44,20 @@ export function Transitioner() { trimPathRight(nextLocation.publicHref) ) { router.commitLocation({ ...nextLocation, replace: true }) + return + } + + const resolvedLocation = router.stores.resolvedLocation.get() + if ( + resolvedLocation?.publicHref === router.latestLocation.publicHref && + resolvedLocation.state.__TSR_key === router.latestLocation.state.__TSR_key + ) { + router.emit({ + type: 'onRendered', + ...getLocationChangeInfo(resolvedLocation, resolvedLocation), + }) + } else { + router.load().catch(console.error) } Solid.onCleanup(() => { @@ -58,81 +65,5 @@ export function Transitioner() { }) }) - // Try to load the initial location - Solid.createRenderEffect(() => { - Solid.untrack(() => { - if ( - // if we are hydrating from SSR, loading is triggered in ssr-client - (typeof window !== 'undefined' && router.ssr) || - (mountLoadForRouter.router === router && mountLoadForRouter.mounted) - ) { - return - } - mountLoadForRouter = { router, mounted: true } - const tryLoad = async () => { - try { - await router.load() - } catch (err) { - console.error(err) - } - } - tryLoad() - }) - }) - - Solid.createRenderEffect((previousIsLoading = false) => { - const currentIsLoading = isLoading() - - if (previousIsLoading && !currentIsLoading) { - router.emit({ - type: 'onLoad', - ...getLocationChangeInfo( - router.stores.location.get(), - router.stores.resolvedLocation.get(), - ), - }) - } - - return currentIsLoading - }) - - Solid.createComputed((previousIsPagePending = false) => { - const currentIsPagePending = isPagePending() - - if (previousIsPagePending && !currentIsPagePending) { - router.emit({ - type: 'onBeforeRouteMount', - ...getLocationChangeInfo( - router.stores.location.get(), - router.stores.resolvedLocation.get(), - ), - }) - } - - return currentIsPagePending - }) - - Solid.createRenderEffect((previousIsAnyPending = false) => { - const currentIsAnyPending = isAnyPending() - - if (previousIsAnyPending && !currentIsAnyPending) { - const changeInfo = getLocationChangeInfo( - router.stores.location.get(), - router.stores.resolvedLocation.get(), - ) - router.emit({ - type: 'onResolved', - ...changeInfo, - }) - - Solid.batch(() => { - router.stores.status.set('idle') - router.stores.resolvedLocation.set(router.stores.location.get()) - }) - } - - return currentIsAnyPending - }) - return null } diff --git a/packages/solid-router/src/lazyRouteComponent.tsx b/packages/solid-router/src/lazyRouteComponent.tsx index 424940522b..4c842bbe61 100644 --- a/packages/solid-router/src/lazyRouteComponent.tsx +++ b/packages/solid-router/src/lazyRouteComponent.tsx @@ -18,6 +18,7 @@ export function lazyRouteComponent< const load = () => { if (!loadPromise) { + error = undefined loadPromise = importer() .then((res) => { loadPromise = undefined @@ -25,6 +26,7 @@ export function lazyRouteComponent< return comp }) .catch((err) => { + loadPromise = undefined error = err }) } 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/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/ssr/renderRouterToStream.tsx b/packages/solid-router/src/ssr/renderRouterToStream.tsx index 8914c117d9..8c284c0375 100644 --- a/packages/solid-router/src/ssr/renderRouterToStream.tsx +++ b/packages/solid-router/src/ssr/renderRouterToStream.tsx @@ -172,7 +172,10 @@ export const renderRouterToStream = async ({ return createSsrStreamResponse( router, new Response(responseStream as any, { - status: router.stores.statusCode.get(), + status: + router._serverResult?.type === 'render' + ? router._serverResult.status + : 200, headers: responseHeaders, }), ) diff --git a/packages/solid-router/src/ssr/renderRouterToString.tsx b/packages/solid-router/src/ssr/renderRouterToString.tsx index 7da982b392..421ac234bc 100644 --- a/packages/solid-router/src/ssr/renderRouterToString.tsx +++ b/packages/solid-router/src/ssr/renderRouterToString.tsx @@ -32,7 +32,10 @@ export const renderRouterToString = ({ html = html.replace(``, () => `${injectedHtml}`) } return new Response(`${html}`, { - status: router.stores.statusCode.get(), + status: + router._serverResult?.type === 'render' + ? router._serverResult.status + : 200, headers: responseHeaders, }) } catch (error) { diff --git a/packages/solid-router/src/useMatch.tsx b/packages/solid-router/src/useMatch.tsx index 858d75be6b..12ef9bb16f 100644 --- a/packages/solid-router/src/useMatch.tsx +++ b/packages/solid-router/src/useMatch.tsx @@ -70,9 +70,8 @@ export function useMatch< ThrowOrOptional, TThrow> > { const router = useRouter() - const nearestMatch = opts.from - ? undefined - : Solid.useContext(nearestMatchContext) + const contextMatch = Solid.useContext(nearestMatchContext) + const nearestMatch = opts.from ? undefined : contextMatch const match = () => { if (opts.from) { @@ -87,15 +86,7 @@ export function useMatch< return } - const hasPendingMatch = opts.from - ? Boolean(router.stores.pendingRouteIds.get()[opts.from!]) - : (nearestMatch?.hasPending() ?? false) - - if ( - !hasPendingMatch && - !router.stores.isTransitioning.get() && - (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!'}`, @@ -110,17 +101,6 @@ export function useMatch< const selectedMatch = match() if (selectedMatch === undefined) { - const hasPendingMatch = opts.from - ? Boolean(router.stores.pendingRouteIds.get()[opts.from!]) - : (nearestMatch?.hasPending() ?? false) - - if ( - prev !== undefined && - (hasPendingMatch || router.stores.isTransitioning.get()) - ) { - return prev - } - return undefined } diff --git a/packages/solid-router/tests/Transitioner.test.tsx b/packages/solid-router/tests/Transitioner.test.tsx index dffe2bd4fd..26fa0da5b4 100644 --- a/packages/solid-router/tests/Transitioner.test.tsx +++ b/packages/solid-router/tests/Transitioner.test.tsx @@ -31,7 +31,6 @@ describe('Transitioner', () => { const loadSpy = vi.spyOn(router, 'load') render(() => ) - await router.latestLoadPromise // Wait for the createRenderEffect to run and call router.load() await waitFor(() => { diff --git a/packages/solid-router/tests/component-preload-retry.test.tsx b/packages/solid-router/tests/component-preload-retry.test.tsx new file mode 100644 index 0000000000..41ec6bbc1a --- /dev/null +++ b/packages/solid-router/tests/component-preload-retry.test.tsx @@ -0,0 +1,61 @@ +import { afterEach, expect, test, vi } from 'vitest' +import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library' +import { + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, + lazyRouteComponent, + useRouter, +} from '../src' +import type { ErrorComponentProps } from '../src' + +afterEach(() => { + cleanup() + vi.restoreAllMocks() +}) + +test('a failed component download is retried from the route error UI', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + + const PageContent = () =>
Page content
+ const importer = vi + .fn<() => Promise<{ default: typeof PageContent }>>() + .mockRejectedValueOnce(new Error('component download failed')) + .mockResolvedValue({ default: PageContent }) + const Page = lazyRouteComponent(importer) + + function RouteError(props: ErrorComponentProps) { + const router = useRouter() + return ( + + ) + } + + const rootRoute = createRootRoute() + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + component: Page, + errorComponent: RouteError, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + render(() => ) + + fireEvent.click(await screen.findByRole('button', { name: 'Retry' })) + + expect(await screen.findByText('Page content')).toBeInTheDocument() +}) diff --git a/packages/solid-router/tests/link.test.tsx b/packages/solid-router/tests/link.test.tsx index d0fc7ae469..154b6bbf23 100644 --- a/packages/solid-router/tests/link.test.tsx +++ b/packages/solid-router/tests/link.test.tsx @@ -1426,10 +1426,12 @@ describe('Link', () => { expect(window.location.pathname).toBe('/Dashboard/posts') expect(window.location.search).toBe('?page=2&filter=inactive') - 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(screen.getByTestId('current-page')).toHaveTextContent('Page: 2') + expect(screen.getByTestId('current-filter')).toHaveTextContent( + 'Filter: inactive', + ) + }) }) test('when navigating to /posts with invalid search', async () => { diff --git a/packages/solid-router/tests/loaders.test.tsx b/packages/solid-router/tests/loaders.test.tsx index 063660f592..7124411943 100644 --- a/packages/solid-router/tests/loaders.test.tsx +++ b/packages/solid-router/tests/loaders.test.tsx @@ -11,7 +11,6 @@ import { createRootRoute, createRoute, createRouter, - useLoaderData, useRouter, } from '../src' @@ -660,7 +659,7 @@ test('reproducer #4546', async () => { } }) -test('clears pendingTimeout when match resolves', async () => { +test('does not show pending UI when loaders finish before their pending delays', async () => { const defaultPendingComponentOnMountMock = vi.fn() const nestedPendingComponentOnMountMock = vi.fn() const fooPendingComponentOnMountMock = vi.fn() @@ -728,7 +727,6 @@ test('clears pendingTimeout when match resolves', async () => { }) render(() => ) - await router.latestLoadPromise const linkToFoo = await screen.findByTestId('link-to-foo') fireEvent.click(linkToFoo) const fooElement = await screen.findByText('Nested Foo page') @@ -742,52 +740,7 @@ test('clears pendingTimeout when match resolves', async () => { expect(fooPendingComponentOnMountMock).not.toHaveBeenCalled() }) -test('useLoaderData retains previous data while route match is pending', async () => { - const history = createMemoryHistory({ initialEntries: ['/app'] }) - const rootRoute = createRootRoute({ - component: () => { - const loaderData = useLoaderData({ from: '/app' }) - - return ( - <> -
{`${loaderData().length}:0`}
- - - ) - }, - }) - const appRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/app', - loader: () => 'loaded', - component: () =>
App route
, - }) - const routeTree = rootRoute.addChildren([appRoute]) - const router = createRouter({ routeTree, history }) - - render(() => ) - - expect(await screen.findByTestId('combined')).toHaveTextContent('6:0') - - const appMatch = router.state.matches.find( - (match) => match.routeId === '/app', - ) - - expect(appMatch).toBeDefined() - - if (!appMatch) { - throw new Error('Expected /app match to be active') - } - - 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') -}) - -test('cancelMatches after pending timeout', async () => { +test('navigating away from a pending route aborts its loader', async () => { function getPendingComponent(onMount: () => void) { const PendingComponent = () => { onMount() @@ -839,7 +792,6 @@ test('cancelMatches after pending timeout', async () => { const routeTree = rootRoute.addChildren([fooRoute, barRoute]) const router = createRouter({ routeTree, history }) render(() => ) - await router.latestLoadPromise const fooLink = await screen.findByTestId('link-to-foo') fireEvent.click(fooLink) await sleep(WAIT_TIME * 30) diff --git a/packages/solid-router/tests/on-rendered-change-info.test.tsx b/packages/solid-router/tests/on-rendered-change-info.test.tsx new file mode 100644 index 0000000000..bf5d53cefb --- /dev/null +++ b/packages/solid-router/tests/on-rendered-change-info.test.tsx @@ -0,0 +1,64 @@ +import { cleanup, render, screen, waitFor } from '@solidjs/testing-library' +import { afterEach, expect, test, vi } from 'vitest' +import { + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +afterEach(() => { + cleanup() +}) + +test('onRendered describes the navigation from the previously rendered location', async () => { + const rootRoute = createRootRoute({ component: () => }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
Index
, + }) + const nextRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/next', + component: () =>
Next
, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, nextRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render(() => ) + expect(await screen.findByText('Index')).toBeInTheDocument() + await waitFor(() => expect(router.state.status).toBe('idle')) + + const onRendered = vi.fn() + const unsubscribe = router.subscribe('onRendered', onRendered) + + await router.navigate({ to: '/next' }) + expect(await screen.findByText('Next')).toBeInTheDocument() + await waitFor(() => expect(onRendered).toHaveBeenCalledTimes(1)) + + const event = onRendered.mock.calls[0]![0] + expect(event.fromLocation?.pathname).toBe('/') + expect(event.toLocation.pathname).toBe('/next') + expect(event.pathChanged).toBe(true) + expect(event.hrefChanged).toBe(true) + + await router.navigate({ + to: '/next', + state: { sameHrefState: true } as any, + }) + await waitFor(() => expect(onRendered).toHaveBeenCalledTimes(2)) + + const stateEvent = onRendered.mock.calls[1]![0] + expect(stateEvent.fromLocation?.state.sameHrefState).toBeUndefined() + expect(stateEvent.toLocation.state.sameHrefState).toBe(true) + expect(stateEvent.fromLocation?.href).toBe('/next') + expect(stateEvent.toLocation.href).toBe('/next') + expect(stateEvent.hrefChanged).toBe(false) + + unsubscribe() +}) diff --git a/packages/solid-router/tests/pending-fallback-promise-replacement.test.tsx b/packages/solid-router/tests/pending-fallback-promise-replacement.test.tsx new file mode 100644 index 0000000000..a6b84fedba --- /dev/null +++ b/packages/solid-router/tests/pending-fallback-promise-replacement.test.tsx @@ -0,0 +1,179 @@ +import { cleanup, render, screen } from '@solidjs/testing-library' +import { afterEach, expect, test, vi } from 'vitest' +import { createControlledPromise } from '@tanstack/router-core' +import { + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +const testCleanups: Array<() => void | Promise> = [] + +afterEach(async () => { + vi.useRealTimers() + while (testCleanups.length) { + await testCleanups.pop()!() + } + cleanup() +}) + +test('a mounted child pending fallback follows a replacement load promise for the same match', async () => { + const firstReload = createControlledPromise() + const secondReload = createControlledPromise() + const reloads = [firstReload, secondReload] + let loaderCall = 0 + + const rootRoute = createRootRoute({ component: () => }) + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + pendingMs: 0, + pendingMinMs: 100, + pendingComponent: () =>
Pending
, + loader: () => { + const generation = ++loaderCall + const gate = reloads[generation - 2] + return gate ? gate.then(() => generation) : generation + }, + component: () =>
Generation {pageRoute.useLoaderData()()}
, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + render(() => ) + expect(await screen.findByText('Generation 1')).toBeInTheDocument() + + vi.useFakeTimers() + const firstInvalidation = router.invalidate({ forcePending: true }) + const invalidations = [firstInvalidation] + testCleanups.push(async () => { + firstReload.resolve() + secondReload.resolve() + await Promise.allSettled(invalidations) + }) + await vi.advanceTimersByTimeAsync(0) + expect(screen.getByTestId('pending')).toBeInTheDocument() + + await vi.advanceTimersByTimeAsync(25) + let secondSettled = false + const secondInvalidation = router + .invalidate({ forcePending: true }) + .then(() => { + secondSettled = true + }) + invalidations.push(secondInvalidation) + + firstReload.resolve() + secondReload.resolve() + await Promise.resolve() + + await vi.advanceTimersByTimeAsync(74) + expect(secondSettled).toBe(false) + expect(screen.getByTestId('pending')).toBeInTheDocument() + + await vi.advanceTimersByTimeAsync(1) + await Promise.all(invalidations) + expect(screen.getByText('Generation 3')).toBeInTheDocument() + expect(screen.queryByTestId('pending')).not.toBeInTheDocument() +}) + +test('the root pending fallback follows a replacement load promise for the same match', async () => { + const firstReload = createControlledPromise() + const secondReload = createControlledPromise() + const reloads = [firstReload, secondReload] + let loaderCall = 0 + + const rootRoute = createRootRoute({ + pendingMs: 0, + pendingMinMs: 100, + pendingComponent: () =>
Pending
, + loader: () => { + const generation = ++loaderCall + const gate = reloads[generation - 2] + return gate ? gate.then(() => generation) : generation + }, + component: () =>
Generation {rootRoute.useLoaderData()()}
, + }) + const router = createRouter({ + routeTree: rootRoute, + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render(() => ) + expect(await screen.findByText('Generation 1')).toBeInTheDocument() + + vi.useFakeTimers() + const firstInvalidation = router.invalidate({ forcePending: true }) + const invalidations = [firstInvalidation] + testCleanups.push(async () => { + firstReload.resolve() + secondReload.resolve() + await Promise.allSettled(invalidations) + }) + await vi.advanceTimersByTimeAsync(0) + expect(screen.getByTestId('root-pending')).toBeInTheDocument() + + await vi.advanceTimersByTimeAsync(25) + let secondSettled = false + const secondInvalidation = router + .invalidate({ forcePending: true }) + .then(() => { + secondSettled = true + }) + invalidations.push(secondInvalidation) + + firstReload.resolve() + secondReload.resolve() + await Promise.resolve() + + await vi.advanceTimersByTimeAsync(74) + expect(secondSettled).toBe(false) + expect(screen.getByTestId('root-pending')).toBeInTheDocument() + + await vi.advanceTimersByTimeAsync(1) + await Promise.all(invalidations) + expect(screen.getByText('Generation 3')).toBeInTheDocument() + expect(screen.queryByTestId('root-pending')).not.toBeInTheDocument() +}) + +test('forcePending honors pendingMinMs when the reload settles before pendingMs', async () => { + const reload = createControlledPromise() + let loaderCall = 0 + + const rootRoute = createRootRoute({ component: () => }) + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + pendingMinMs: 100, + pendingComponent: () =>
Pending
, + loader: async () => { + if (++loaderCall > 1) { + await reload + } + return loaderCall + }, + component: () =>
Generation {pageRoute.useLoaderData()()}
, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + render(() => ) + expect(await screen.findByText('Generation 1')).toBeInTheDocument() + + const invalidation = router.invalidate({ forcePending: true }) + expect(await screen.findByTestId('fast-pending')).toBeInTheDocument() + reload.resolve() + + await new Promise((resolve) => setTimeout(resolve, 25)) + expect(screen.getByTestId('fast-pending')).toBeInTheDocument() + + await invalidation + expect(await screen.findByText('Generation 2')).toBeInTheDocument() +}) diff --git a/packages/solid-router/tests/redirect.test.tsx b/packages/solid-router/tests/redirect.test.tsx index 81bd1f6bc6..e045383d31 100644 --- a/packages/solid-router/tests/redirect.test.tsx +++ b/packages/solid-router/tests/redirect.test.tsx @@ -7,7 +7,6 @@ import { Outlet, RouterProvider, createBrowserHistory, - createMemoryHistory, createRootRoute, createRoute, createRouter, @@ -147,7 +146,6 @@ describe('redirect', () => { expect(await screen.findByTestId('lazy-route-page')).toBeInTheDocument() expect(screen.queryByTestId('pending')).not.toBeInTheDocument() expect(router.state.location.href).toBe('/posts') - expect(router.state.status).toBe('idle') expect(consoleError).not.toHaveBeenCalled() }) @@ -303,116 +301,4 @@ describe('redirect', () => { expect(window.location.pathname).toBe('/final') }) }) - - describe('SSR', () => { - test('when `redirect` is thrown in `beforeLoad`', async () => { - const rootRoute = createRootRoute() - - const indexRoute = createRoute({ - path: '/', - getParentRoute: () => rootRoute, - beforeLoad: () => { - throw redirect({ - to: '/about', - }) - }, - }) - - const aboutRoute = createRoute({ - path: '/about', - getParentRoute: () => rootRoute, - component: () => { - return 'About' - }, - }) - - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute, aboutRoute]), - // Mock server mode - isServer: true, - history: createMemoryHistory({ - initialEntries: ['/'], - }), - }) - - await router.load() - - expect(router.state.redirect).toBeDefined() - expect(router.state.redirect).toBeInstanceOf(Response) - const redirectResponse = router.state.redirect! - - expect(redirectResponse.options).toEqual({ - _fromLocation: expect.objectContaining({ - hash: '', - href: '/', - pathname: '/', - search: {}, - searchStr: '', - }), - to: '/about', - href: '/about', - statusCode: 307, - }) - }) - }) - - test('when `redirect` is thrown in `loader`', async () => { - const rootRoute = createRootRoute() - - const indexRoute = createRoute({ - path: '/', - getParentRoute: () => rootRoute, - loader: () => { - throw redirect({ - to: '/about', - }) - }, - }) - - const aboutRoute = createRoute({ - path: '/about', - getParentRoute: () => rootRoute, - component: () => { - return 'About' - }, - }) - - const router = createRouter({ - history: createMemoryHistory({ - initialEntries: ['/'], - }), - routeTree: rootRoute.addChildren([indexRoute, aboutRoute]), - // Mock server mode - isServer: true, - }) - - await router.load() - - const currentRedirect = router.state.redirect - - expect(currentRedirect).toBeDefined() - expect(currentRedirect).toBeInstanceOf(Response) - const redirectResponse = currentRedirect! - expect(redirectResponse.status).toEqual(307) - expect(redirectResponse.headers.get('Location')).toEqual('/about') - expect(redirectResponse.options).toEqual({ - _fromLocation: { - external: false, - publicHref: '/', - hash: '', - href: '/', - pathname: '/', - search: {}, - searchStr: '', - state: { - __TSR_index: 0, - __TSR_key: redirectResponse.options._fromLocation!.state.__TSR_key, - key: redirectResponse.options._fromLocation!.state.key, - }, - }, - href: '/about', - to: '/about', - statusCode: 307, - }) - }) }) diff --git a/packages/solid-router/tests/router.test.tsx b/packages/solid-router/tests/router.test.tsx index 1ee017937a..dcec6f0012 100644 --- a/packages/solid-router/tests/router.test.tsx +++ b/packages/solid-router/tests/router.test.tsx @@ -1720,12 +1720,13 @@ 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 () => { +describe('navigation outcomes', () => { + it('should recover from a not-found route when navigating to a valid route', async () => { const history = createMemoryHistory({ initialEntries: ['/'] }) const rootRoute = createRootRoute({ component: () => , + notFoundComponent: () =>
Not Found
, }) const indexRoute = createRoute({ @@ -1745,23 +1746,21 @@ describe('statusCode reset on navigation', () => { render(() => ) - expect(router.state.statusCode).toBe(200) - await router.navigate({ to: '/' }) - await waitFor(() => expect(router.state.statusCode).toBe(200)) + expect(await screen.findByText('Home')).toBeInTheDocument() await router.navigate({ to: '/non-existing' }) - await waitFor(() => expect(router.state.statusCode).toBe(404)) + expect(await screen.findByText('Not Found')).toBeInTheDocument() await router.navigate({ to: '/valid' }) - await waitFor(() => expect(router.state.statusCode).toBe(200)) + expect(await screen.findByText('Valid Route')).toBeInTheDocument() await router.navigate({ to: '/another-non-existing' }) - await waitFor(() => expect(router.state.statusCode).toBe(404)) + expect(await screen.findByText('Not Found')).toBeInTheDocument() }) describe.each([true, false])( - 'status code is set when loader/beforeLoad throws (isAsync=%s)', + 'loader and beforeLoad outcomes are rendered (isAsync=%s)', (isAsync) => { const throwingFun = isAsync ? (toThrow: () => void) => async () => { @@ -1776,7 +1775,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('should render notFoundComponent when a route loader throws a notFound()', async () => { const history = createMemoryHistory({ initialEntries: ['/'] }) const rootRoute = createRootRoute() @@ -1804,17 +1803,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('should render notFoundComponent when a route beforeLoad throws a notFound()', async () => { const history = createMemoryHistory({ initialEntries: ['/'] }) const rootRoute = createRootRoute({ @@ -1849,17 +1845,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('should render errorComponent when a route loader throws an Error', async () => { const history = createMemoryHistory({ initialEntries: ['/'] }) const rootRoute = createRootRoute() @@ -1885,15 +1878,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('should render errorComponent when a route beforeLoad throws an Error', async () => { const history = createMemoryHistory({ initialEntries: ['/'] }) const rootRoute = createRootRoute() @@ -1922,10 +1912,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 +2044,6 @@ describe('basepath', () => { }) expect(router.state.location.pathname).toBe('/') - expect(router.state.statusCode).toBe(200) }, ) 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..755f28c835 --- /dev/null +++ b/packages/solid-router/tests/same-route-pending-blank.test.tsx @@ -0,0 +1,103 @@ +import { cleanup, render, screen } 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() + const page2Started = 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) { + page2Started.resolve() + 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 navigation = router.navigate({ + to: '/posts', + search: { page: 2 }, + }) + pendingNavigation = navigation + + await page2Started.promise + + 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() +}) diff --git a/packages/solid-router/tests/server/errorComponent.test.tsx b/packages/solid-router/tests/server/errorComponent.test.tsx index f342aaae0d..618c9a0039 100644 --- a/packages/solid-router/tests/server/errorComponent.test.tsx +++ b/packages/solid-router/tests/server/errorComponent.test.tsx @@ -39,7 +39,6 @@ describe('errorComponent (server)', () => { )) - expect(router.state.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..ded5e5bc2f 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(3) }) test('redirection in preload', async () => { @@ -172,7 +172,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(3) }) test('nothing', async () => { @@ -183,7 +183,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(3) + expect(updates).toBe(2) }) test('not found in beforeLoad', async () => { @@ -198,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(2) }) test('hover preload, then navigate, w/ async loaders', async () => { @@ -240,7 +240,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(3) + expect(updates).toBe(2) }) test('navigate, w/ preloaded & sync loaders', async () => { @@ -256,7 +256,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(3) + expect(updates).toBe(2) }) test('navigate, w/ previous navigation & async loader', async () => { @@ -272,7 +272,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(3) + expect(updates).toBe(2) }) test('preload a preloaded route w/ async loader', async () => { diff --git a/packages/solid-router/tests/transitioner-listener-errors.test.tsx b/packages/solid-router/tests/transitioner-listener-errors.test.tsx new file mode 100644 index 0000000000..58d7ed392a --- /dev/null +++ b/packages/solid-router/tests/transitioner-listener-errors.test.tsx @@ -0,0 +1,61 @@ +import { cleanup, render, screen } from '@solidjs/testing-library' +import { afterEach, expect, test, vi } from 'vitest' +import { + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +afterEach(() => { + cleanup() +}) + +test('a throwing load-event listener cannot interrupt route hooks or later navigations', async () => { + const firstOnEnter = vi.fn() + const secondOnEnter = vi.fn() + const listenerError = new Error('onLoad listener failed') + + const rootRoute = createRootRoute({ component: () => }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
Index route
, + }) + const firstRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/first', + onEnter: firstOnEnter, + component: () =>
First route
, + }) + const secondRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/second', + onEnter: secondOnEnter, + component: () =>
Second route
, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, firstRoute, secondRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render(() => ) + expect(await screen.findByText('Index route')).toBeInTheDocument() + + const unsubscribe = router.subscribe('onLoad', (event) => { + if (event.toLocation.pathname === '/first') { + throw listenerError + } + }) + + await router.navigate({ to: '/first' }) + expect(await screen.findByText('First route')).toBeInTheDocument() + expect(firstOnEnter).toHaveBeenCalledTimes(1) + + unsubscribe() + await router.navigate({ to: '/second' }) + expect(await screen.findByText('Second route')).toBeInTheDocument() + expect(secondOnEnter).toHaveBeenCalledTimes(1) +}) diff --git a/packages/solid-router/tests/transitioner-remount.test.tsx b/packages/solid-router/tests/transitioner-remount.test.tsx new file mode 100644 index 0000000000..cbccf15df2 --- /dev/null +++ b/packages/solid-router/tests/transitioner-remount.test.tsx @@ -0,0 +1,82 @@ +import { cleanup, render, screen, waitFor } from '@solidjs/testing-library' +import { afterEach, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { + Outlet, + RouterProvider, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +afterEach(() => { + cleanup() +}) + +test('remounting an SSR-marked router loads a history change that happened while unmounted', async () => { + const rootRoute = createRootRoute({ component: () => }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
Index
, + }) + const nextRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/next', + component: () =>
Next
, + }) + const history = createMemoryHistory({ initialEntries: ['/'] }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, nextRoute]), + history, + }) + + // This is the stable post-hydration shape: server matches are active and + // the persistent SSR marker tells the first Transitioner mount not to load. + await router.load() + router.ssr = { manifest: { routes: {} } } + + const firstRender = render(() => ) + expect(await screen.findByText('Index')).toBeInTheDocument() + + firstRender.unmount() + history.push('/next') + + const secondRender = render(() => ) + expect(await screen.findByText('Next')).toBeInTheDocument() + expect(router.state.location.pathname).toBe('/next') + + secondRender.unmount() + history.replace('/next', { remounted: true }) + + render(() => ) + await waitFor(() => { + expect((router.state.location.state as any).remounted).toBe(true) + }) +}) + +test('remounting the provider emits onRendered for the newly mounted DOM', async () => { + const rootRoute = createRootRoute({ component: () => }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
Index
, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + const onRendered = vi.fn() + const unsubscribe = router.subscribe('onRendered', onRendered) + + const firstRender = render(() => ) + expect(await screen.findByText('Index')).toBeInTheDocument() + await waitFor(() => expect(onRendered).toHaveBeenCalledTimes(1)) + + firstRender.unmount() + render(() => ) + expect(await screen.findByText('Index')).toBeInTheDocument() + await waitFor(() => expect(onRendered).toHaveBeenCalledTimes(2)) + + unsubscribe() +}) diff --git a/packages/solid-router/tests/transitioner-render-ack.test.tsx b/packages/solid-router/tests/transitioner-render-ack.test.tsx new file mode 100644 index 0000000000..08c62f53dc --- /dev/null +++ b/packages/solid-router/tests/transitioner-render-ack.test.tsx @@ -0,0 +1,158 @@ +import { cleanup, render, screen, waitFor } from '@solidjs/testing-library' +import { afterEach, expect, test } from 'vitest' +import { + Outlet, + RouterProvider, + createControlledPromise, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +afterEach(() => { + cleanup() +}) + +test('onRendered observes the committed destination DOM', async () => { + const nextLoader = createControlledPromise() + const rootRoute = createRootRoute({ component: () => }) + const firstRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/first', + component: () =>
First
, + }) + const nextRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/next', + loader: () => nextLoader, + component: () =>
Next
, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([firstRoute, nextRoute]), + history: createMemoryHistory({ initialEntries: ['/first'] }), + }) + + render(() => ) + expect(await screen.findByText('First')).toBeInTheDocument() + await waitFor(() => expect(router.state.status).toBe('idle')) + + const renderedDom: Array<{ destination: boolean; outgoing: boolean }> = [] + const unsubscribe = router.subscribe('onRendered', () => { + renderedDom.push({ + destination: screen.queryByText('Next') !== null, + outgoing: screen.queryByText('First') !== null, + }) + }) + + const navigation = router.navigate({ to: '/next' }) + + expect(screen.queryByText('Next')).toBeNull() + expect(renderedDom).toEqual([]) + + nextLoader.resolve() + await navigation + await waitFor(() => expect(renderedDom).toHaveLength(1)) + + expect(renderedDom).toEqual([{ destination: true, outgoing: false }]) + + unsubscribe() +}) + +test('an older rendered destination cannot resolve a superseding navigation', async () => { + const nextLoader = createControlledPromise() + const rootRoute = createRootRoute({ component: () => }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
Index
, + }) + const firstRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/first', + component: () =>
First
, + }) + const nextRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/next', + loader: () => nextLoader, + component: () =>
Next
, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, firstRoute, nextRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render(() => ) + expect(await screen.findByText('Index')).toBeInTheDocument() + await waitFor(() => expect(router.state.status).toBe('idle')) + + const renderedPaths: Array = [] + const resolvedPaths: Array = [] + let nextNavigation: Promise | undefined + const unsubscribers = [ + router.subscribe('onLoad', (event) => { + if (event.toLocation.pathname === '/first') { + nextNavigation = router.navigate({ to: '/next' }) + } + }), + router.subscribe('onRendered', (event) => { + renderedPaths.push(event.toLocation.pathname) + }), + router.subscribe('onResolved', (event) => { + resolvedPaths.push(event.toLocation.pathname) + }), + ] + + const firstNavigation = router.navigate({ to: '/first' }) + + await waitFor(() => { + expect(nextNavigation).toBeDefined() + }) + expect(screen.getByText('First')).toBeInTheDocument() + expect(screen.queryByText('Next')).not.toBeInTheDocument() + expect(renderedPaths).toEqual(['/first']) + expect(resolvedPaths).toEqual([]) + + nextLoader.resolve() + await Promise.all([firstNavigation, nextNavigation!]) + + await waitFor(() => { + expect(screen.getByText('Next')).toBeInTheDocument() + }) + expect(renderedPaths).toEqual(['/first', '/next']) + expect(resolvedPaths).toEqual(['/next']) + + for (const unsubscribe of unsubscribers) { + unsubscribe() + } +}) + +test('same-location invalidation resolves after its refreshed DOM commits', async () => { + let generation = 0 + const rootRoute = createRootRoute({ component: () => }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + loader: () => ++generation, + component: () =>
Generation {indexRoute.useLoaderData()()}
, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render(() => ) + expect(await screen.findByText('Generation 1')).toBeInTheDocument() + + const refreshedDomWasVisible: Array = [] + const unsubscribe = router.subscribe('onResolved', () => { + refreshedDomWasVisible.push(screen.queryByText('Generation 2') !== null) + }) + + await router.invalidate() + expect(await screen.findByText('Generation 2')).toBeInTheDocument() + expect(refreshedDomWasVisible).toEqual([true]) + + unsubscribe() +}) diff --git a/packages/solid-router/tests/use-match-outgoing-transition.test.tsx b/packages/solid-router/tests/use-match-outgoing-transition.test.tsx new file mode 100644 index 0000000000..c76c4d78ef --- /dev/null +++ b/packages/solid-router/tests/use-match-outgoing-transition.test.tsx @@ -0,0 +1,108 @@ +import * as Solid from 'solid-js' +import { cleanup, render, screen } from '@solidjs/testing-library' +import { afterEach, expect, test } from 'vitest' +import { + Outlet, + RouterProvider, + createControlledPromise, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, + useMatch, +} from '../src' + +afterEach(() => { + cleanup() +}) + +test('an outgoing component never observes its own active match disappear', async () => { + const observedRouteIds: Array = [] + const rootRoute = createRootRoute({ component: () => }) + const firstRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/first', + component: () => { + const match = useMatch({ from: '/first', shouldThrow: false }) + Solid.createRenderEffect(() => { + observedRouteIds.push(match()?.routeId) + }) + return
First
+ }, + }) + const nextRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/next', + component: () =>
Next
, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([firstRoute, nextRoute]), + history: createMemoryHistory({ initialEntries: ['/first'] }), + }) + + render(() => ) + expect(await screen.findByText('First')).toBeInTheDocument() + + await router.navigate({ to: '/next' }) + expect(await screen.findByText('Next')).toBeInTheDocument() + + expect(observedRouteIds).toEqual(['/first']) +}) + +test('a persistent observer releases an explicit match only with the destination render', async () => { + const nextLoader = createControlledPromise() + const observations: Array<{ + routeId: string | undefined + destinationRendered: boolean + }> = [] + + const rootRoute = createRootRoute({ + component: () => { + const routeId = useMatch({ + from: '/first', + shouldThrow: false, + select: (match) => match.routeId, + }) + Solid.createRenderEffect(() => { + observations.push({ + routeId: routeId(), + destinationRendered: screen.queryByText('Next') !== null, + }) + }) + return + }, + }) + const firstRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/first', + component: () =>
First
, + }) + const nextRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/next', + loader: () => nextLoader, + component: () =>
Next
, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([firstRoute, nextRoute]), + history: createMemoryHistory({ initialEntries: ['/first'] }), + }) + + render(() => ) + expect(await screen.findByText('First')).toBeInTheDocument() + + const navigation = router.navigate({ to: '/next' }) + await Promise.resolve() + expect(screen.queryByText('Next')).toBeNull() + expect(observations.every(({ routeId }) => routeId === '/first')).toBe(true) + + nextLoader.resolve() + await navigation + expect(await screen.findByText('Next')).toBeInTheDocument() + + const missing = observations.filter(({ routeId }) => routeId === undefined) + expect(missing.length).toBeGreaterThan(0) + expect(missing.every(({ destinationRendered }) => destinationRendered)).toBe( + true, + ) +}) diff --git a/packages/start-server-core/src/createStartHandler.ts b/packages/start-server-core/src/createStartHandler.ts index 90d4e706f9..edafbbc43c 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._serverResult?.type === 'redirect') { + return normalizeSsrResponse(routerInstance._serverResult.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..17e479aa65 100644 --- a/packages/vue-router/src/Match.tsx +++ b/packages/vue-router/src/Match.tsx @@ -1,23 +1,12 @@ import * as Vue from 'vue' -import { - createControlledPromise, - getLocationChangeInfo, - invariant, - isNotFound, - isRedirect, - rootRouteId, -} from '@tanstack/router-core' +import { invariant, isNotFound, rootRouteId } from '@tanstack/router-core' import { isServer } from '@tanstack/router-core/isServer' import { useStore } from '@tanstack/vue-store' 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' @@ -61,13 +50,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(() => { const match = activeMatch.value if (!match) { @@ -77,9 +59,8 @@ export const Match = Vue.defineComponent({ return { matchId: match.id, routeId, - loadedAt: loadedAt.value, + fetchCount: match.fetchCount, ssr: match.ssr, - _displayPending: match._displayPending, } }) @@ -137,15 +118,12 @@ export const Match = Vue.defineComponent({ ) Vue.provide(matchContext, matchIdRef) - Vue.provide(pendingMatchContext, isPendingMatchRef) - return (): VNode => { const actualMatchId = matchData.value?.matchId ?? props.matchId const resolvedNoSsr = matchData.value?.ssr === false || matchData.value?.ssr === 'data-only' - const shouldClientOnly = - resolvedNoSsr || !!matchData.value?._displayPending + const shouldClientOnly = resolvedNoSsr const renderMatchContent = (): VNode => { const matchInner = Vue.h(MatchInner, { matchId: actualMatchId }) @@ -186,7 +164,7 @@ export const Match = Vue.defineComponent({ // Wrap in error boundary if needed if (routeErrorComponent.value) { content = CatchBoundary({ - getResetKey: () => matchData.value?.loadedAt ?? 0, + getResetKey: () => matchData.value?.fetchCount ?? 0, errorComponent: routeErrorComponent.value || ErrorComponent, onCatch: (error: Error) => { // Forward not found errors (we don't want to show the error component for these) @@ -208,7 +186,6 @@ export const Match = Vue.defineComponent({ content, isChildOfRoot ? Vue.h(Vue.Fragment, null, [ - Vue.h(OnRendered), router.options.scrollRestoration && (isServer ?? router.isServer) ? Vue.h(ScrollRestoration) @@ -239,48 +216,6 @@ export const Match = Vue.defineComponent({ }) // On Rendered can't happen above the root layout because it actually -// renders a dummy dom element to track the rendered state of the app. -// We render a script tag with a key that changes based on the current -// location state.__TSR_key. Also, because it's below the root layout, it -// allows us to fire onRendered events even after a hydration mismatch -// error that occurred above the root layout (like bad head/link tags, -// which is common). -const OnRendered = Vue.defineComponent({ - name: 'OnRendered', - setup() { - const router = useRouter() - - const location = useStore( - router.stores.resolvedLocation, - (resolvedLocation) => resolvedLocation?.state.__TSR_key, - ) - - let prevHref: string | undefined - - 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 - } - } - }, - { immediate: true }, - ) - - return () => null - }, -}) - export const MatchInner = Vue.defineComponent({ name: 'MatchInner', props: { @@ -333,9 +268,6 @@ export const MatchInner = Vue.defineComponent({ status: match.status, error: match.error, ssr: match.ssr, - _forcePending: match._forcePending, - _displayPending: match._displayPending, - _nonReactive: match._nonReactive, }, remountKey, } @@ -349,43 +281,11 @@ 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 +297,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 +323,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 = @@ -540,7 +406,11 @@ export const Outlet = Vue.defineComponent({ if (!route.value) { return null } - return renderRouteNotFound(router, route.value, undefined) + return renderRouteNotFound( + router, + route.value, + parentMatch.value?.error, + ) } if (!childMatchData.value) { diff --git a/packages/vue-router/src/Matches.tsx b/packages/vue-router/src/Matches.tsx index da8220db29..740e423a02 100644 --- a/packages/vue-router/src/Matches.tsx +++ b/packages/vue-router/src/Matches.tsx @@ -99,8 +99,12 @@ const MatchesInner = Vue.defineComponent({ setup() { const router = useRouter() - const matchId = useStore(router.stores.firstId, (id) => id) - const resetKey = useStore(router.stores.loadedAt, (loadedAt) => loadedAt) + const matchId = useStore(router.stores.matchesId, (ids) => ids[0]) + const resetKey = Vue.computed(() => + matchId.value + ? (router.stores.matchStores.get(matchId.value)?.get().fetchCount ?? 0) + : 0, + ) // Create a ref for the match id to provide const matchIdRef = Vue.computed(() => matchId.value) diff --git a/packages/vue-router/src/Transitioner.tsx b/packages/vue-router/src/Transitioner.tsx index b0133d965c..93ec028a72 100644 --- a/packages/vue-router/src/Transitioner.tsx +++ b/packages/vue-router/src/Transitioner.tsx @@ -1,107 +1,23 @@ 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 { useRouter } from './useRouter' -import { usePrevious } from './utils' -// Track mount state per router to avoid double-loading -let mountLoadForRouter = { router: null as any, mounted: false } - -/** - * Composable that sets up router transition logic. - * This is called from MatchesContent to set up: - * - router.startTransition - * - router.startViewTransition - * - History subscription - * - Router event watchers - * - * Must be called during component setup phase. - */ export function useTransitionerSetup() { const router = useRouter() - - // Skip on server - no transitions needed if (isServer ?? router.isServer) { return } - const isLoading = useStore(router.stores.isLoading, (value) => value) - - // Track if we're in a transition - using a ref to track async transitions - const isTransitioning = Vue.ref(false) - - // Track pending state changes - const hasPending = useStore(router.stores.hasPending, (value) => value) - - const previousIsLoading = usePrevious(() => isLoading.value) - - 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) - - // 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) => { - 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 = () => { - // Use nextTick to ensure Vue has processed all reactive updates - 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 + const previousTransition = router.startTransition + const transition = async (fn: () => void) => { fn() - - // End the transition on next tick to allow Vue to process reactive updates - endTransition() + await Vue.nextTick() + return true } + router.startTransition = transition - // 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) = - (router as any).__tsrOriginalStartViewTransition ?? - router.startViewTransition - - ;(router as any).__tsrOriginalStartViewTransition = - originalStartViewTransition - - router.startViewTransition = (fn: () => Promise) => { - return originalStartViewTransition?.(async () => { - await fn() - await Vue.nextTick() - }) - } - - // Subscribe to location changes - // and try to load the new location let unsubscribe: (() => void) | undefined - Vue.onMounted(() => { unsubscribe = router.history.subscribe(router.load) @@ -114,130 +30,37 @@ export function useTransitionerSetup() { _includeValidateSearch: true, }) - // Check if the current URL matches the canonical form. - // Compare publicHref (browser-facing URL) for consistency with - // the server-side redirect check in router.beforeLoad. if ( trimPathRight(router.latestLocation.publicHref) !== trimPathRight(nextLocation.publicHref) ) { router.commitLocation({ ...nextLocation, replace: true }) + return } - }) - // Track if component is mounted to prevent updates after unmount - const isMounted = Vue.ref(false) - - 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()) - }) - } + const resolvedLocation = router.stores.resolvedLocation.get() + if ( + resolvedLocation?.publicHref === router.latestLocation.publicHref && + resolvedLocation.state.__TSR_key === router.latestLocation.state.__TSR_key + ) { + router.emit({ + type: 'onRendered', + ...getLocationChangeInfo(resolvedLocation, resolvedLocation), + }) + } else { + router.load().catch(console.error) } }) Vue.onUnmounted(() => { - isMounted.value = false - if (unsubscribe) { - unsubscribe() - } - }) - - // Try to load the initial location - Vue.onMounted(() => { - if ( - (typeof window !== 'undefined' && router.ssr) || - (mountLoadForRouter.router === router && mountLoadForRouter.mounted) - ) { - return - } - mountLoadForRouter = { router, mounted: true } - const tryLoad = async () => { - try { - await router.load() - } catch (err) { - console.error(err) - } - } - 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(), - ), - }) - } - } 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 + unsubscribe?.() + if (router.startTransition === transition) { + router.startTransition = previousTransition } }) } -/** - * @deprecated Use useTransitionerSetup() composable instead. - * This component is kept for backwards compatibility but the setup logic - * has been moved to useTransitionerSetup() for better SSR hydration. - */ +/** @deprecated Use useTransitionerSetup() instead. */ export const Transitioner = Vue.defineComponent({ name: 'Transitioner', setup() { diff --git a/packages/vue-router/src/lazyRouteComponent.tsx b/packages/vue-router/src/lazyRouteComponent.tsx index 77a2233573..527f3d15ad 100644 --- a/packages/vue-router/src/lazyRouteComponent.tsx +++ b/packages/vue-router/src/lazyRouteComponent.tsx @@ -44,6 +44,7 @@ export function lazyRouteComponent< // Use existing promise or create new one if (!loadPromise) { + error = undefined loadPromise = importer() .then((res) => { loadPromise = undefined diff --git a/packages/vue-router/src/matchContext.tsx b/packages/vue-router/src/matchContext.tsx index 1a8b7fb167..201408b5d0 100644 --- a/packages/vue-router/src/matchContext.tsx +++ b/packages/vue-router/src/matchContext.tsx @@ -1,39 +1,14 @@ -import * as Vue from 'vue' +import type { InjectionKey, Ref } from 'vue' // Reactive nearest-match context used by hooks that work relative to the // current match in the tree. -export const matchContext = Symbol('TanStackRouterMatch') as Vue.InjectionKey< - Vue.Ref +export const matchContext = Symbol('TanStackRouterMatch') as InjectionKey< + 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)) -} +) as InjectionKey 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/ssr/renderRouterToStream.tsx b/packages/vue-router/src/ssr/renderRouterToStream.tsx index efad4fc2eb..64b7040006 100644 --- a/packages/vue-router/src/ssr/renderRouterToStream.tsx +++ b/packages/vue-router/src/ssr/renderRouterToStream.tsx @@ -112,7 +112,10 @@ export const renderRouterToStream = async ({ } return new Response(`${fullHtml}`, { - status: router.stores.statusCode.get(), + status: + router._serverResult?.type === 'render' + ? router._serverResult.status + : 200, headers: responseHeaders, }) } finally { @@ -217,7 +220,10 @@ export const renderRouterToStream = async ({ return createSsrStreamResponse( router, new Response(responseStream as any, { - status: router.stores.statusCode.get(), + status: + router._serverResult?.type === 'render' + ? router._serverResult.status + : 200, headers: responseHeaders, }), ) diff --git a/packages/vue-router/src/ssr/renderRouterToString.tsx b/packages/vue-router/src/ssr/renderRouterToString.tsx index b551dc5dfc..723aa0b91e 100644 --- a/packages/vue-router/src/ssr/renderRouterToString.tsx +++ b/packages/vue-router/src/ssr/renderRouterToString.tsx @@ -24,7 +24,10 @@ export const renderRouterToString = async ({ } return new Response(`${html}`, { - status: router.stores.statusCode.get(), + status: + router._serverResult?.type === 'render' + ? router._serverResult.status + : 200, headers: responseHeaders, }) } catch (error) { diff --git a/packages/vue-router/src/useMatch.tsx b/packages/vue-router/src/useMatch.tsx index 29047e5d48..96e1937567 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,11 +110,9 @@ export function useMatch< > } - const hasPendingNearestMatch = opts.from - ? injectDummyPendingMatch() - : injectPendingMatch() // Set up reactive match value based on lookup strategy. let match: Readonly> + const nearestRouteId = Vue.inject(routeIdContext) if (opts.from) { // routeId case: single subscription via per-routeId computed store. @@ -129,7 +123,6 @@ export function useMatch< // matchId case: use routeId from context for stable store lookup. // The routeId is provided by the nearest Match component and doesn't // change for the component's lifetime, so the store is stable. - const nearestRouteId = Vue.inject(routeIdContext) if (nearestRouteId) { match = useStore( router.stores.getRouteMatchStore(nearestRouteId), @@ -141,26 +134,10 @@ 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 result = Vue.computed(() => { const selectedMatch = match.value if (selectedMatch === undefined) { - const hasPendingMatch = opts.from - ? Boolean(hasPendingRouteMatch?.value[opts.from!]) - : hasPendingNearestMatch.value - if ( - !hasPendingMatch && - !isTransitioning.value && - (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/tests/Matches.test.tsx b/packages/vue-router/tests/Matches.test.tsx index 4e9e9afa51..b398fd98c7 100644 --- a/packages/vue-router/tests/Matches.test.tsx +++ b/packages/vue-router/tests/Matches.test.tsx @@ -134,7 +134,7 @@ test('when filtering useMatches by loaderData', async () => { // Vue Suspense requires async setup functions or top-level await to trigger fallback. // Since TanStack Router throws Promises from render (not setup), Vue doesn't show // the pending component during initial load. Navigation-triggered pending states -// DO work - see loaders.test.tsx 'cancelMatches after pending timeout'. +// DO work - see loaders.test.tsx 'navigating away from a pending route aborts its loader'. test('should show pendingComponent of root route', async () => { const root = createRootRoute({ pendingComponent: () =>
, diff --git a/packages/vue-router/tests/Transitioner.test.tsx b/packages/vue-router/tests/Transitioner.test.tsx index 8fc6095f94..5d463c9dc8 100644 --- a/packages/vue-router/tests/Transitioner.test.tsx +++ b/packages/vue-router/tests/Transitioner.test.tsx @@ -9,7 +9,7 @@ import { import { RouterProvider } from '../src/RouterProvider' describe('Transitioner', () => { - it('should call router.load() when Transitioner mounts on the client', async () => { + it('loads the initial route when the provider mounts', async () => { const loader = vi.fn() const rootRoute = createRootRoute() const indexRoute = createRoute({ @@ -27,18 +27,11 @@ describe('Transitioner', () => { }), }) - // Mock router.load() to verify it gets called - const loadSpy = vi.spyOn(router, 'load') + const view = render() - render() - await router.latestLoadPromise - - // Wait for the createRenderEffect to run and call router.load() await waitFor(() => { - expect(loadSpy).toHaveBeenCalledTimes(1) expect(loader).toHaveBeenCalledTimes(1) + expect(view.getByText('Index')).toBeInTheDocument() }) - - loadSpy.mockRestore() }) }) diff --git a/packages/vue-router/tests/component-preload-retry.test.tsx b/packages/vue-router/tests/component-preload-retry.test.tsx new file mode 100644 index 0000000000..0cf7e0f19e --- /dev/null +++ b/packages/vue-router/tests/component-preload-retry.test.tsx @@ -0,0 +1,61 @@ +import { afterEach, expect, test, vi } from 'vitest' +import { cleanup, fireEvent, render, screen } from '@testing-library/vue' +import { + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, + lazyRouteComponent, + useRouter, +} from '../src' +import type { ErrorComponentProps } from '../src' + +afterEach(() => { + cleanup() + vi.restoreAllMocks() +}) + +test('a failed component download is retried from the route error UI', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + + const PageContent = () =>
Page content
+ const importer = vi + .fn<() => Promise<{ default: typeof PageContent }>>() + .mockRejectedValueOnce(new Error('component download failed')) + .mockResolvedValue({ default: PageContent }) + const Page = lazyRouteComponent(importer) + + function RouteError(props: ErrorComponentProps) { + const router = useRouter() + return ( + + ) + } + + const rootRoute = createRootRoute() + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + component: Page, + errorComponent: RouteError, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + render() + + await fireEvent.click(await screen.findByRole('button', { name: 'Retry' })) + + expect(await screen.findByText('Page content')).toBeInTheDocument() +}) diff --git a/packages/vue-router/tests/hydration-capped-boundary-pending.test.tsx b/packages/vue-router/tests/hydration-capped-boundary-pending.test.tsx new file mode 100644 index 0000000000..02eb2e8002 --- /dev/null +++ b/packages/vue-router/tests/hydration-capped-boundary-pending.test.tsx @@ -0,0 +1,161 @@ +import * as Vue from 'vue' +import { renderToString } from 'vue/server-renderer' +import { afterEach, describe, expect, test, vi } from 'vitest' +import { hydrate as hydrateRouter } from '@tanstack/router-core/ssr/client' +import { + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, + notFound, +} from '../src' +import type { TsrSsrGlobal } from '@tanstack/router-core/ssr/client' + +declare global { + interface Window { + $_TSR?: TsrSsrGlobal + } +} + +const testCleanups: Array<() => void | Promise> = [] + +afterEach(async () => { + while (testCleanups.length) { + await testCleanups.pop()!() + } + vi.restoreAllMocks() + window.$_TSR = undefined + document.body.innerHTML = '' +}) + +describe('hydrating a server-capped boundary lane', () => { + test.each([ + ['error', 'parent'], + ['notFound', 'root'], + ] as const)( + 'keeps the server-rendered %s %s boundary visible while the client replays it', + async (outcome, boundary) => { + const childLoader = vi.fn(() => 'child data') + const makeRouteTree = () => { + const boundaryOptions = { + beforeLoad: () => { + throw outcome === 'notFound' + ? notFound() + : new Error('server route failure') + }, + pendingComponent: () => ( +
Boundary pending
+ ), + errorComponent: () => ( +
Boundary error
+ ), + notFoundComponent: () => ( +
Boundary not found
+ ), + } + const rootRoute = createRootRoute({ + component: Outlet, + ...(boundary === 'root' ? boundaryOptions : {}), + }) + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + component: Outlet, + ...(boundary === 'parent' ? boundaryOptions : {}), + }) + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: childLoader, + component: () =>
Child
, + }) + return rootRoute.addChildren([parentRoute.addChildren([childRoute])]) + } + + const serverRouter = createRouter({ + routeTree: makeRouteTree(), + ...(boundary === 'root' ? { isShell: true } : {}), + history: createMemoryHistory({ + initialEntries: ['/parent/child'], + }), + }) + serverRouter.isServer = true + await serverRouter.load() + + const serverMatches = serverRouter.stores.matches.get() + expect(serverMatches).toHaveLength(boundary === 'root' ? 1 : 2) + expect(serverMatches.at(-1)).toMatchObject( + boundary === 'root' + ? { status: 'success', globalNotFound: true } + : { status: 'error' }, + ) + + const serverApp = Vue.createSSRApp( + Vue.defineComponent({ + setup: () => () => , + }), + ) + const serverHtml = await renderToString(serverApp) + const expectedBoundary = + outcome === 'notFound' ? 'Boundary not found' : 'Boundary error' + expect(serverHtml).toContain(expectedBoundary) + + const clientRouter = createRouter({ + routeTree: makeRouteTree(), + history: createMemoryHistory({ + initialEntries: ['/parent/child'], + }), + }) + + window.$_TSR = { + router: { + manifest: { routes: {} }, + dehydratedData: {}, + matches: serverMatches.map((match) => ({ + i: match.id, + u: match.updatedAt, + s: match.status, + l: match.loaderData, + e: match.error, + ssr: match.ssr, + ...(match.globalNotFound ? { g: true } : {}), + })), + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + initialized: false, + } + + await hydrateRouter(clientRouter) + + const container = document.createElement('div') + container.innerHTML = serverHtml + document.body.appendChild(container) + const consoleError = vi + .spyOn(console, 'error') + .mockImplementation(() => {}) + const consoleWarn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const clientApp = Vue.createSSRApp( + Vue.defineComponent({ + setup: () => () => , + }), + ) + testCleanups.push(() => clientApp.unmount()) + + clientApp.mount(container) + await Vue.nextTick() + + expect(container).toHaveTextContent(expectedBoundary) + expect(container).not.toHaveTextContent('Boundary pending') + expect( + [consoleError.mock.calls, consoleWarn.mock.calls].flat(2).join(' '), + ).not.toMatch(/hydration|mismatch/i) + expect(childLoader).not.toHaveBeenCalled() + }, + ) +}) diff --git a/packages/vue-router/tests/link.test.tsx b/packages/vue-router/tests/link.test.tsx index e047fe5993..be5e9bf70b 100644 --- a/packages/vue-router/tests/link.test.tsx +++ b/packages/vue-router/tests/link.test.tsx @@ -1365,15 +1365,16 @@ describe('Link', () => { expect(window.location.search).toBe('?page=2&filter=inactive') }) - const updatedPage = await screen.findByTestId('current-page') - const updatedFilter = await screen.findByTestId('current-filter') - // Verify search was updated 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(screen.getByTestId('current-page')).toHaveTextContent('Page: 2') + expect(screen.getByTestId('current-filter')).toHaveTextContent( + 'Filter: inactive', + ) + }) }) test('when navigation to . from /posts while updating search from / and using base path', async () => { @@ -1491,10 +1492,12 @@ describe('Link', () => { expect(window.location.pathname).toBe('/Dashboard/posts') expect(window.location.search).toBe('?page=2&filter=inactive') - 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(screen.getByTestId('current-page')).toHaveTextContent('Page: 2') + expect(screen.getByTestId('current-filter')).toHaveTextContent( + 'Filter: inactive', + ) + }) }) test('when navigating to /posts with invalid search', async () => { diff --git a/packages/vue-router/tests/loaders.test.tsx b/packages/vue-router/tests/loaders.test.tsx index ae267ac2ae..4c60731063 100644 --- a/packages/vue-router/tests/loaders.test.tsx +++ b/packages/vue-router/tests/loaders.test.tsx @@ -635,7 +635,7 @@ test('reproducer #4546', async () => { } }) -test('clears pendingTimeout when match resolves', async () => { +test('does not show pending UI when routes resolve before their thresholds', async () => { const defaultPendingComponentOnMountMock = vi.fn() const nestedPendingComponentOnMountMock = vi.fn() const fooPendingComponentOnMountMock = vi.fn() @@ -703,7 +703,7 @@ test('clears pendingTimeout when match resolves', async () => { }) render() - await router.latestLoadPromise + await screen.findByText('Index page') const linkToFoo = await screen.findByTestId('link-to-foo') fireEvent.click(linkToFoo) const fooElement = await screen.findByText('Nested Foo page') @@ -717,7 +717,7 @@ test('clears pendingTimeout when match resolves', async () => { expect(fooPendingComponentOnMountMock).not.toHaveBeenCalled() }) -test('cancelMatches after pending timeout', async () => { +test('navigating away from pending UI aborts its loader', async () => { function getPendingComponent(onMount: () => void) { const PendingComponent = () => { onMount() @@ -769,7 +769,7 @@ test('cancelMatches after pending timeout', async () => { const routeTree = rootRoute.addChildren([fooRoute, barRoute]) const router = createRouter({ routeTree, history }) render() - await router.latestLoadPromise + await screen.findByText('Index page') const fooLink = await screen.findByTestId('link-to-foo') fireEvent.click(fooLink) await sleep(WAIT_TIME * 30) diff --git a/packages/vue-router/tests/pending-fallback-promise-replacement.test.tsx b/packages/vue-router/tests/pending-fallback-promise-replacement.test.tsx new file mode 100644 index 0000000000..8cab6d41f0 --- /dev/null +++ b/packages/vue-router/tests/pending-fallback-promise-replacement.test.tsx @@ -0,0 +1,78 @@ +import { cleanup, render, screen } from '@testing-library/vue' +import { afterEach, expect, test, vi } from 'vitest' +import { createControlledPromise } from '@tanstack/router-core' +import { + RouterProvider, + createMemoryHistory, + createRootRoute, + createRouter, +} from '../src' + +const testCleanups: Array<() => void | Promise> = [] + +afterEach(async () => { + vi.useRealTimers() + while (testCleanups.length) { + await testCleanups.pop()!() + } + cleanup() +}) + +test('a continuously visible fallback keeps its deadline across replacement loads', async () => { + const firstReload = createControlledPromise() + const secondReload = createControlledPromise() + const reloads = [firstReload, secondReload] + let loaderCall = 0 + + const rootRoute = createRootRoute({ + pendingMs: 0, + pendingMinMs: 100, + pendingComponent: () =>
Pending
, + loader: () => { + const generation = ++loaderCall + const gate = reloads[generation - 2] + return gate ? gate.then(() => generation) : generation + }, + component: () =>
Content
, + }) + const router = createRouter({ + routeTree: rootRoute, + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render() + expect(await screen.findByText('Content')).toBeInTheDocument() + + vi.useFakeTimers() + const firstInvalidation = router.invalidate({ forcePending: true }) + const invalidations = [firstInvalidation] + testCleanups.push(async () => { + firstReload.resolve() + secondReload.resolve() + await Promise.allSettled(invalidations) + }) + await vi.advanceTimersByTimeAsync(0) + expect(screen.getByTestId('pending')).toBeInTheDocument() + + await vi.advanceTimersByTimeAsync(25) + let secondSettled = false + const secondInvalidation = router + .invalidate({ forcePending: true }) + .then(() => { + secondSettled = true + }) + invalidations.push(secondInvalidation) + + firstReload.resolve() + secondReload.resolve() + await Promise.resolve() + + await vi.advanceTimersByTimeAsync(74) + expect(secondSettled).toBe(false) + expect(screen.getByTestId('pending')).toBeInTheDocument() + + await vi.advanceTimersByTimeAsync(1) + await Promise.all(invalidations) + expect(screen.getByText('Content')).toBeInTheDocument() + expect(screen.queryByTestId('pending')).not.toBeInTheDocument() +}) diff --git a/packages/vue-router/tests/redirect.test.tsx b/packages/vue-router/tests/redirect.test.tsx index b7ba2e1af3..3f475652f3 100644 --- a/packages/vue-router/tests/redirect.test.tsx +++ b/packages/vue-router/tests/redirect.test.tsx @@ -292,108 +292,4 @@ describe('redirect', () => { expect(window.location.pathname).toBe('/final') }) }) - - describe('SSR', () => { - test('when `redirect` is thrown in `beforeLoad`', async () => { - const rootRoute = createRootRoute() - - const indexRoute = createRoute({ - path: '/', - getParentRoute: () => rootRoute, - beforeLoad: () => { - throw redirect({ - to: '/about', - }) - }, - }) - - const aboutRoute = createRoute({ - path: '/about', - getParentRoute: () => rootRoute, - component: () => { - return <>About - }, - }) - - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute, aboutRoute]), - // Mock server mode - isServer: true, - history: createMemoryHistory({ - initialEntries: ['/'], - }), - }) - - await router.load() - - expect(router.state.redirect).toBeDefined() - expect(router.state.redirect).toBeInstanceOf(Response) - const redirectResponse = router.state.redirect! - - expect(redirectResponse.options).toEqual({ - _fromLocation: expect.objectContaining({ - hash: '', - href: '/', - pathname: '/', - search: {}, - searchStr: '', - }), - to: '/about', - href: '/about', - statusCode: 307, - }) - }) - - test('when `redirect` is thrown in `loader`', async () => { - const rootRoute = createRootRoute() - - const indexRoute = createRoute({ - path: '/', - getParentRoute: () => rootRoute, - loader: () => { - throw redirect({ - to: '/about', - }) - }, - }) - - const aboutRoute = createRoute({ - path: '/about', - getParentRoute: () => rootRoute, - component: () => { - return <>About - }, - }) - - const router = createRouter({ - history: createMemoryHistory({ - initialEntries: ['/'], - }), - routeTree: rootRoute.addChildren([indexRoute, aboutRoute]), - // Mock server mode - isServer: true, - }) - - await router.load() - - const currentRedirect = router.state.redirect - - expect(currentRedirect).toBeDefined() - expect(currentRedirect).toBeInstanceOf(Response) - const redirectResponse = currentRedirect! - - expect(redirectResponse.options).toEqual({ - _fromLocation: expect.objectContaining({ - hash: '', - href: '/', - pathname: '/', - search: {}, - searchStr: '', - }), - to: '/about', - href: '/about', - statusCode: 307, - }) - }) - }) }) diff --git a/packages/vue-router/tests/router.test.tsx b/packages/vue-router/tests/router.test.tsx index 44a7acd43c..9f2ccdea62 100644 --- a/packages/vue-router/tests/router.test.tsx +++ b/packages/vue-router/tests/router.test.tsx @@ -1724,12 +1724,13 @@ 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 () => { +describe('route result reset on navigation', () => { + it('renders the requested route after navigating away from a not-found result', async () => { const history = createMemoryHistory({ initialEntries: ['/'] }) const rootRoute = createRootRoute({ component: () => , + notFoundComponent: () =>
Not Found
, }) const indexRoute = createRoute({ @@ -1749,23 +1750,23 @@ describe('statusCode reset on navigation', () => { render() - expect(router.state.statusCode).toBe(200) - - await router.navigate({ to: '/' }) - await waitFor(() => expect(router.state.statusCode).toBe(200)) + expect(await screen.findByText('Home')).toBeInTheDocument() await router.navigate({ to: '/non-existing' }) - await waitFor(() => expect(router.state.statusCode).toBe(404)) + expect(await screen.findByText('Not Found')).toBeInTheDocument() + expect(screen.queryByText('Home')).not.toBeInTheDocument() await router.navigate({ to: '/valid' }) - await waitFor(() => expect(router.state.statusCode).toBe(200)) + expect(await screen.findByText('Valid Route')).toBeInTheDocument() + expect(screen.queryByText('Not Found')).not.toBeInTheDocument() await router.navigate({ to: '/another-non-existing' }) - await waitFor(() => expect(router.state.statusCode).toBe(404)) + expect(await screen.findByText('Not Found')).toBeInTheDocument() + expect(screen.queryByText('Valid Route')).not.toBeInTheDocument() }) describe.each([true, false])( - 'status code is set when loader/beforeLoad throws (isAsync=%s)', + 'load failures render their route boundary (isAsync=%s)', (isAsync) => { const throwingFun = isAsync ? (toThrow: () => void) => async () => { @@ -1808,10 +1809,7 @@ 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() @@ -1853,10 +1851,7 @@ 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() @@ -1889,10 +1884,7 @@ 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() }) @@ -1926,10 +1918,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() }) @@ -2061,7 +2050,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..6235e04406 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(3) }) test('redirection in preload', async () => { @@ -157,7 +157,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(5) + expect(updates).toBe(2) }) test('sync beforeLoad', async () => { @@ -174,7 +174,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(3) }) test('nothing', async () => { @@ -186,7 +186,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(2) }) test('not found in beforeLoad', async () => { @@ -202,7 +202,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(2) }) test('hover preload, then navigate, w/ async loaders', async () => { @@ -229,7 +229,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 +246,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(2) }) test('navigate, w/ preloaded & sync loaders', async () => { @@ -263,7 +263,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(2) }) test('navigate, w/ previous navigation & async loader', async () => { @@ -280,7 +280,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(2) }) test('preload a preloaded route w/ async loader', async () => { @@ -299,6 +299,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/packages/vue-router/tests/transitioner-idle-after-render.test.tsx b/packages/vue-router/tests/transitioner-idle-after-render.test.tsx new file mode 100644 index 0000000000..4cfd74f86f --- /dev/null +++ b/packages/vue-router/tests/transitioner-idle-after-render.test.tsx @@ -0,0 +1,46 @@ +import { cleanup, render, screen } from '@testing-library/vue' +import { afterEach, expect, test } from 'vitest' +import { + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +afterEach(() => { + cleanup() +}) + +test('onResolved fires only after Vue commits the destination DOM', async () => { + const rootRoute = createRootRoute({ component: () => }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
Index
, + }) + const nextRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/next', + component: () =>
Next
, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, nextRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render() + expect(await screen.findByText('Index')).toBeInTheDocument() + + const destinationWasRenderedWhenResolved: Array = [] + const unsubscribe = router.subscribe('onResolved', () => { + destinationWasRenderedWhenResolved.push(screen.queryByText('Next') !== null) + }) + + await router.navigate({ to: '/next' }) + expect(await screen.findByText('Next')).toBeInTheDocument() + + expect(destinationWasRenderedWhenResolved).toEqual([true]) + unsubscribe() +}) diff --git a/packages/vue-router/tests/transitioner-listener-errors.test.tsx b/packages/vue-router/tests/transitioner-listener-errors.test.tsx new file mode 100644 index 0000000000..c3efef7119 --- /dev/null +++ b/packages/vue-router/tests/transitioner-listener-errors.test.tsx @@ -0,0 +1,61 @@ +import { cleanup, render, screen } from '@testing-library/vue' +import { afterEach, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { + Outlet, + RouterProvider, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +afterEach(() => { + cleanup() +}) + +test('a throwing load-event listener cannot interrupt route hooks or later navigations', async () => { + const firstOnEnter = vi.fn() + const secondOnEnter = vi.fn() + const listenerError = new Error('onLoad listener failed') + + const rootRoute = createRootRoute({ component: () => }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
Index route
, + }) + const firstRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/first', + onEnter: firstOnEnter, + component: () =>
First route
, + }) + const secondRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/second', + onEnter: secondOnEnter, + component: () =>
Second route
, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, firstRoute, secondRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render() + expect(await screen.findByText('Index route')).toBeTruthy() + + const unsubscribe = router.subscribe('onLoad', (event) => { + if (event.toLocation.pathname === '/first') { + throw listenerError + } + }) + + await router.navigate({ to: '/first' }) + expect(await screen.findByText('First route')).toBeTruthy() + expect(firstOnEnter).toHaveBeenCalledTimes(1) + + unsubscribe() + await router.navigate({ to: '/second' }) + expect(await screen.findByText('Second route')).toBeTruthy() + expect(secondOnEnter).toHaveBeenCalledTimes(1) +}) diff --git a/packages/vue-router/tests/transitioner-remount-rendered.test.tsx b/packages/vue-router/tests/transitioner-remount-rendered.test.tsx new file mode 100644 index 0000000000..d5c5b63f15 --- /dev/null +++ b/packages/vue-router/tests/transitioner-remount-rendered.test.tsx @@ -0,0 +1,129 @@ +import { cleanup, render, screen, waitFor } from '@testing-library/vue' +import { afterEach, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { + Outlet, + RouterProvider, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +afterEach(() => { + cleanup() +}) + +function setup() { + const rootRoute = createRootRoute({ component: () => }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
Index
, + }) + const nextRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/next', + component: () =>
Next
, + }) + const history = createMemoryHistory({ initialEntries: ['/'] }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, nextRoute]), + history, + }) + return { history, router } +} + +test('remounting the same router loads a history change that happened while unmounted', async () => { + const { history, router } = setup() + const firstRender = render() + expect(await screen.findByText('Index')).toBeTruthy() + + firstRender.unmount() + history.push('/next') + + render() + expect(await screen.findByText('Next')).toBeTruthy() + expect(router.state.location.pathname).toBe('/next') +}) + +test('remounting the provider emits onRendered for the newly mounted DOM', async () => { + const { router } = setup() + const onRendered = vi.fn() + const unsubscribe = router.subscribe('onRendered', onRendered) + + const firstRender = render() + expect(await screen.findByText('Index')).toBeTruthy() + await waitFor(() => expect(onRendered).toHaveBeenCalledTimes(1)) + + firstRender.unmount() + render() + expect(await screen.findByText('Index')).toBeTruthy() + await waitFor(() => expect(onRendered).toHaveBeenCalledTimes(2)) + + unsubscribe() +}) + +test('remounting an SSR-marked router loads a history change that happened while unmounted', async () => { + const { history, router } = setup() + + // This is the stable post-hydration shape: server matches are active and + // the persistent SSR marker tells the first Transitioner mount not to load. + await router.load() + router.ssr = { manifest: { routes: {} } } + + const firstRender = render() + expect(await screen.findByText('Index')).toBeTruthy() + + firstRender.unmount() + history.push('/next') + + render() + expect(await screen.findByText('Next')).toBeTruthy() + expect(router.state.location.pathname).toBe('/next') +}) + +test('onRendered runs after the destination DOM has committed', async () => { + const { router } = setup() + const initialRendered = vi.fn() + const unsubscribeInitial = router.subscribe('onRendered', initialRendered) + render() + expect(await screen.findByText('Index')).toBeTruthy() + await waitFor(() => expect(initialRendered).toHaveBeenCalledTimes(1)) + unsubscribeInitial() + + const destinationWasRendered: Array = [] + const unsubscribe = router.subscribe('onRendered', () => { + destinationWasRendered.push(screen.queryByText('Next') !== null) + }) + + await router.navigate({ to: '/next' }) + await waitFor(() => expect(destinationWasRendered).toHaveLength(1)) + expect(destinationWasRendered).toEqual([true]) + + unsubscribe() +}) + +test('onRendered fires for a same-href navigation with a new history key', async () => { + const { router } = setup() + const onRendered = vi.fn() + const unsubscribe = router.subscribe('onRendered', onRendered) + render() + expect(await screen.findByText('Index')).toBeTruthy() + await waitFor(() => expect(onRendered).toHaveBeenCalledTimes(1)) + onRendered.mockClear() + + await router.navigate({ + to: '/', + state: { sameHrefState: true } as any, + }) + await waitFor(() => expect(onRendered).toHaveBeenCalledTimes(1)) + + const event = onRendered.mock.calls[0]![0] + expect(event.fromLocation?.state.sameHrefState).toBeUndefined() + expect(event.toLocation.state.sameHrefState).toBe(true) + expect(event.fromLocation?.href).toBe('/') + expect(event.toLocation.href).toBe('/') + expect(event.hrefChanged).toBe(false) + + unsubscribe() +}) From adf73dd544d5663f12c1ec1995bcae3f0545d059 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Mon, 13 Jul 2026 11:06:14 +0200 Subject: [PATCH 02/59] fix client/server build --- packages/router-core/src/isServer/development.ts | 2 +- packages/router-core/src/isServer/server.ts | 2 +- packages/router-core/src/{load.client.ts => load-client.ts} | 2 ++ packages/router-core/src/{load.server.ts => load-server.ts} | 2 ++ packages/router-core/src/router.ts | 6 +++--- 5 files changed, 9 insertions(+), 5 deletions(-) rename packages/router-core/src/{load.client.ts => load-client.ts} (99%) rename packages/router-core/src/{load.server.ts => load-server.ts} (99%) diff --git a/packages/router-core/src/isServer/development.ts b/packages/router-core/src/isServer/development.ts index 4990101f3e..5a19543e21 100644 --- a/packages/router-core/src/isServer/development.ts +++ b/packages/router-core/src/isServer/development.ts @@ -1,3 +1,3 @@ // Development/test mode - returns undefined so fallback to router.isServer is used export const isServer: boolean | undefined = undefined -export { loadServer, loadServerRouter } from '../load.server' +export { loadServer, loadServerRouter } from '../load-server' diff --git a/packages/router-core/src/isServer/server.ts b/packages/router-core/src/isServer/server.ts index ae9afb6ef8..e363962e89 100644 --- a/packages/router-core/src/isServer/server.ts +++ b/packages/router-core/src/isServer/server.ts @@ -1,2 +1,2 @@ export const isServer = process.env.NODE_ENV === 'test' ? undefined : true -export { loadServer, loadServerRouter } from '../load.server' +export { loadServer, loadServerRouter } from '../load-server' diff --git a/packages/router-core/src/load.client.ts b/packages/router-core/src/load-client.ts similarity index 99% rename from packages/router-core/src/load.client.ts rename to packages/router-core/src/load-client.ts index e1c5747226..4146335668 100644 --- a/packages/router-core/src/load.client.ts +++ b/packages/router-core/src/load-client.ts @@ -1,3 +1,5 @@ +// Keep this filename free of a secondary extension so declaration generation +// can rewrite relative imports for both ESM and CJS. import { isNotFound } from './not-found' import { isRedirect } from './redirect' import { loadRouteChunk } from './route-chunks' diff --git a/packages/router-core/src/load.server.ts b/packages/router-core/src/load-server.ts similarity index 99% rename from packages/router-core/src/load.server.ts rename to packages/router-core/src/load-server.ts index 19ad1675c2..3e3fcffedc 100644 --- a/packages/router-core/src/load.server.ts +++ b/packages/router-core/src/load-server.ts @@ -1,3 +1,5 @@ +// Keep this filename free of a secondary extension so declaration generation +// can rewrite relative imports for both ESM and CJS. import { isNotFound } from './not-found' import { isRedirect, redirect } from './redirect' import { rootRouteId } from './root' diff --git a/packages/router-core/src/router.ts b/packages/router-core/src/router.ts index 4f66fe1ab3..8544a5109f 100644 --- a/packages/router-core/src/router.ts +++ b/packages/router-core/src/router.ts @@ -44,7 +44,7 @@ import { loadClientRouter, preloadClientRoute, refreshClientRoute, -} from './load.client' +} from './load-client' import { loadRouteChunk, routeNeedsPreload } from './route-chunks' import { composeRewrites, @@ -64,8 +64,8 @@ import type { LoadTransaction, LoaderFlight, PendingSession, -} from './load.client' -import type { ServerLoadResult } from './load.server' +} from './load-client' +import type { ServerLoadResult } from './load-server' import type { HistoryAction, HistoryLocation, From 6f75f500232a57810b29846e21dc7ebd03fa8bbe Mon Sep 17 00:00:00 2001 From: Sheraff Date: Mon, 13 Jul 2026 13:20:56 +0200 Subject: [PATCH 03/59] adopt preloaded beforeLoad --- docs/router/guide/preloading.md | 2 + packages/router-core/src/load-client.ts | 146 +++-- .../tests/preload-beforeload-reuse.test.ts | 607 ++++++++++++++++++ 3 files changed, 706 insertions(+), 49 deletions(-) create mode 100644 packages/router-core/tests/preload-beforeload-reuse.test.ts diff --git a/docs/router/guide/preloading.md b/docs/router/guide/preloading.md index 453294ab6e..092a869685 100644 --- a/docs/router/guide/preloading.md +++ b/docs/router/guide/preloading.md @@ -130,6 +130,8 @@ export const Route = createFileRoute('/posts/$postId')({ }) ``` +Client-side preloading also runs each new route's `beforeLoad` with `preload: true`. When a completed successful preload is still fresh under the built-in freshness and invalidation policy used for preloaded loader data, the client router can reuse the context returned by that invocation instead of calling `beforeLoad` again with `preload: false`. Reuse follows route match identity, including `loaderDeps`, and requires a reusable parent context. The `shouldReload` option remains loader-only. Pending, failed, invalidated, or stale preloads do not donate their `beforeLoad` context to a client navigation. + ## Preloading with External Libraries When integrating external caching libraries like React Query, which have their own mechanisms for determining stale data, you may want to override the default preloading and stale-while-revalidate logic of TanStack Router. These libraries often use options like staleTime to control the freshness of data. diff --git a/packages/router-core/src/load-client.ts b/packages/router-core/src/load-client.ts index 4146335668..db9ecbe2bf 100644 --- a/packages/router-core/src/load-client.ts +++ b/packages/router-core/src/load-client.ts @@ -57,6 +57,8 @@ export type LoaderFlight = [ type WorkMatch = AnyRouteMatch & { _flight?: LoaderFlight + _preloadContext?: number + _preloadBeforeLoad?: AnyRoute['options']['beforeLoad'] } type ClientRouter = AnyRouter & { @@ -192,6 +194,7 @@ async function contextualize( lane: MatchedLane, options: ExecuteLaneOptions, ): Promise { + let reusePreloadContext = !options.preload for ( let index = options.resolvedPrefix ?? 0; index < lane.matches.length; @@ -206,6 +209,8 @@ async function contextualize( return [index, normalizeError(route, serialError)] } + // Fresh matches already own this lane's controller; cached matches do not. + reusePreloadContext &&= match.abortController !== options.controller match.abortController = options.controller // Contextualization is serial, so the previous match already contains the // complete parent context for this route. @@ -216,13 +221,33 @@ async function contextualize( ...match.__routeContext, } - if (!route.options.beforeLoad) { + const beforeLoad = route.options.beforeLoad + if (!beforeLoad) { match.__beforeLoadContext = {} match.context = context continue } const preload = !!options.preload + // A child can only reuse context from the same parent generation. + const donor = match._preloadContext + const reuse = + reusePreloadContext && + donor != null && + !shouldReloadMatch(router, match, route, options, undefined, donor) + match._preloadContext = undefined + if (process.env.NODE_ENV !== 'production') { + match._preloadBeforeLoad = undefined + } + if (reuse) { + match.context = { + ...context, + ...match.__beforeLoadContext, + } + continue + } + reusePreloadContext = false + const beforeLoadContext: BeforeLoadContextOptions< any, any, @@ -251,7 +276,7 @@ async function contextualize( try { match.isFetching = 'beforeLoad' const result = await waitFor( - route.options.beforeLoad(beforeLoadContext), + beforeLoad(beforeLoadContext), options.controller.signal, ) match.isFetching = false @@ -265,6 +290,12 @@ async function contextualize( ...context, ...result, } + if (preload && route.options.preload !== false) { + match._preloadContext = Date.now() + if (process.env.NODE_ENV !== 'production') { + match._preloadBeforeLoad = beforeLoad + } + } } catch (cause) { match.isFetching = false if (cause === options.controller.signal) { @@ -435,18 +466,14 @@ async function loadResource( } } -function shouldReload( +function shouldReloadMatch( router: WorkerRouter, - lane: ContextualizedLane, match: WorkMatch, route: AnyRoute, - index: number, - tasks: Array, options: ExecuteLaneOptions, + configured?: any, + donor?: number, ): boolean { - if (index < (options.resolvedPrefix ?? 0)) { - return false - } if (match.status !== 'success') { return true } @@ -454,36 +481,21 @@ function shouldReload( const preload = !!options.preload const preloadStaleTime = route.options.preloadStaleTime const staleAge = - preload || (match.preload && preloadStaleTime !== undefined) + preload || + ((donor != null || match.preload) && preloadStaleTime !== undefined) ? (preloadStaleTime ?? router.options.defaultPreloadStaleTime ?? 30_000) : (route.options.staleTime ?? router.options.defaultStaleTime ?? 0) - const reload = route.options.shouldReload - const configured = - typeof reload === 'function' - ? reload( - getLoaderContext( - router, - lane, - match, - route, - options.controller, - tasks[index - 1]?.match, - preload, - ), - ) - : reload - const previous = options.base?.find( - (candidate) => candidate.routeId === match.routeId, - ) - return !!( match.invalid || configured || (configured === undefined && - Date.now() - match.updatedAt >= staleAge && + Date.now() - (donor ?? match.updatedAt) >= staleAge && (options.forceStaleReload || match.cause === 'enter' || - (!!previous && previous.id !== match.id))) + options.base?.some( + (candidate) => + candidate.routeId === match.routeId && candidate.id !== match.id, + ))) ) } @@ -513,17 +525,34 @@ function createTask( let reload = false let reloadFailure: LoaderOutcome | undefined try { - reload = shouldReload( - workerRouter, - lane, - match, - route, - index, - tasks, - options, - ) - reload ||= - index < (options.resolvedPrefix ?? 0) && !!router._flights?.get(match.id) + if (index < (options.resolvedPrefix ?? 0)) { + reload = !!router._flights?.get(match.id) + } else { + let configured + if (match.status === 'success') { + configured = route.options.shouldReload + if (typeof configured === 'function') { + configured = configured( + getLoaderContext( + workerRouter, + lane, + match, + route, + options.controller, + tasks[index - 1]?.match, + preload, + ), + ) + } + } + reload = shouldReloadMatch( + workerRouter, + match, + route, + options, + configured, + ) + } } catch (cause) { releaseFlight(router, match) reloadFailure = normalizeError(route, cause) @@ -1021,15 +1050,23 @@ function commitMatches( const now = Date.now() let write = 0 for (const match of cached) { - const route = getRoute(router, match as WorkMatch) - const gcTime = - (match.preload - ? (route.options.preloadGcTime ?? router.options.defaultPreloadGcTime) - : (route.options.gcTime ?? router.options.defaultGcTime)) ?? 300_000 + const work = match as WorkMatch + const route = getRoute(router, work) + const preloadGcTime = + route.options.preloadGcTime ?? + router.options.defaultPreloadGcTime ?? + 300_000 + const donor = work._preloadContext if ( - route.options.loader && match.status === 'success' && - now - match.updatedAt < gcTime + ((donor != null && now - donor < preloadGcTime) || + (route.options.loader && + now - match.updatedAt < + (match.preload + ? preloadGcTime + : (route.options.gcTime ?? + router.options.defaultGcTime ?? + 300_000)))) ) { cached[write++] = match } @@ -1450,7 +1487,18 @@ export async function preloadClientRoute( ) const previous = router.stores.cachedMatches.get() const candidates: Array = [] + let obsoleteContext = false for (const match of matches as Array) { + if (process.env.NODE_ENV !== 'production') { + obsoleteContext ||= + match._preloadContext != null && + match._preloadBeforeLoad !== + getRoute(router, match).options.beforeLoad + if (obsoleteContext) { + releaseFlight(clientRouter, match) + continue + } + } if ( active.has(match.id) || previous.find((candidate) => candidate.id === match.id) !== diff --git a/packages/router-core/tests/preload-beforeload-reuse.test.ts b/packages/router-core/tests/preload-beforeload-reuse.test.ts new file mode 100644 index 0000000000..916fd23ee4 --- /dev/null +++ b/packages/router-core/tests/preload-beforeload-reuse.test.ts @@ -0,0 +1,607 @@ +import { afterEach, describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, createControlledPromise } from '../src' +import { createTestRouter } from './routerTestUtils' + +afterEach(() => { + vi.useRealTimers() +}) + +describe('preloaded beforeLoad context reuse', () => { + test('reuses fresh nested context for navigation and child loaders', async () => { + const parentBeforeLoad = vi.fn(({ preload }: { preload: boolean }) => ({ + parent: preload ? 'preloaded parent' : 'loaded parent', + })) + const childBeforeLoad = vi.fn( + ({ + context, + preload, + }: { + context: { parent: string } + preload: boolean + }) => ({ + child: `${context.parent}:${preload}`, + }), + ) + const childLoader = vi.fn( + ({ + context, + preload, + }: { + context: { parent: string; child: string } + preload: boolean + }) => ({ context, preload }), + ) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + staleTime: Infinity, + beforeLoad: parentBeforeLoad, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + staleTime: Infinity, + beforeLoad: childBeforeLoad, + loader: childLoader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.preloadRoute({ to: '/parent/child' }) + await router.navigate({ to: '/parent/child' }) + + expect(parentBeforeLoad).toHaveBeenCalledTimes(1) + expect(parentBeforeLoad).toHaveBeenCalledWith( + expect.objectContaining({ preload: true }), + ) + expect(childBeforeLoad).toHaveBeenCalledTimes(1) + expect(childBeforeLoad).toHaveBeenCalledWith( + expect.objectContaining({ + context: expect.objectContaining({ parent: 'preloaded parent' }), + preload: true, + }), + ) + expect(childLoader).toHaveBeenCalledTimes(1) + const match = router.state.matches.find( + (candidate) => candidate.routeId === childRoute.id, + ) + expect(match?.context).toEqual({ + parent: 'preloaded parent', + child: 'preloaded parent:true', + }) + expect(match?.loaderData).toEqual({ + context: { + parent: 'preloaded parent', + child: 'preloaded parent:true', + }, + preload: true, + }) + }) + + test('keeps beforeLoad independent while joining a pending preload loader', async () => { + const loaderGate = createControlledPromise() + const beforeLoad = vi.fn(({ preload }: { preload: boolean }) => ({ + guard: preload ? 'preloaded' : 'loaded', + })) + const loader = vi.fn(() => loaderGate) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const guardedRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/guarded', + preloadStaleTime: Infinity, + beforeLoad, + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, guardedRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const preload = router.preloadRoute({ to: '/guarded' }) + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(1)) + + const navigation = router.navigate({ to: '/guarded' }) + await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledTimes(2)) + expect(beforeLoad.mock.calls.map(([context]) => context.preload)).toEqual([ + true, + false, + ]) + expect(loader).toHaveBeenCalledTimes(1) + + loaderGate.resolve('shared loader data') + await Promise.all([preload, navigation]) + + expect(router.state.matches.at(-1)?.context).toEqual({ guard: 'loaded' }) + expect(router.state.matches.at(-1)?.loaderData).toBe('shared loader data') + }) + + test.each([ + { age: 50, expected: [false, true], guard: 'preloaded' }, + { age: 100, expected: [false, true, false], guard: 'loaded' }, + ])( + 'uses the beforeLoad completion time when loader data remains navigation-owned at age $age', + async ({ age, expected, guard }) => { + vi.useFakeTimers() + vi.setSystemTime(1_000) + const beforeLoad = vi.fn(({ preload }: { preload: boolean }) => ({ + guard: preload ? 'preloaded' : 'loaded', + })) + const loader = vi.fn(({ preload }: { preload: boolean }) => preload) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const guardedRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/guarded', + staleTime: Infinity, + preloadStaleTime: 100, + beforeLoad, + shouldReload: false, + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, guardedRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.navigate({ to: '/guarded' }) + await router.navigate({ to: '/' }) + vi.setSystemTime(5_000) + await router.preloadRoute({ to: '/guarded' }) + vi.setSystemTime(5_000 + age) + await router.navigate({ to: '/guarded' }) + + expect(beforeLoad.mock.calls.map(([context]) => context.preload)).toEqual( + expected, + ) + expect(loader.mock.calls.map(([context]) => context.preload)).toEqual([ + false, + ]) + expect(router.state.matches.at(-1)?.context).toEqual({ guard }) + }, + ) + + test('keeps a fresh beforeLoad-only preload across an unrelated navigation', async () => { + const beforeLoad = vi.fn(({ preload }: { preload: boolean }) => ({ + guard: preload ? 'preloaded' : 'loaded', + })) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const otherRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/other', + }) + const guardedRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/guarded', + preloadStaleTime: Infinity, + preloadGcTime: Infinity, + beforeLoad, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, otherRoute, guardedRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.preloadRoute({ to: '/guarded' }) + await router.navigate({ to: '/other' }) + await router.navigate({ to: '/guarded' }) + + expect(beforeLoad.mock.calls.map(([context]) => context.preload)).toEqual([ + true, + ]) + expect(router.state.matches.at(-1)?.context).toEqual({ + guard: 'preloaded', + }) + }) + + test('does not reuse child context under a different parent match', async () => { + const childBeforeLoad = vi.fn( + ({ + context, + preload, + }: { + context: { version: number } + preload: boolean + }) => ({ + childVersion: context.version, + }), + ) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loaderDeps: ({ search }: { search: Record }) => ({ + version: Number(search.version), + }), + context: ({ deps }: { deps: { version: number } }) => ({ + version: deps.version, + }), + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + preloadStaleTime: Infinity, + beforeLoad: childBeforeLoad, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.preloadRoute({ + to: '/parent/child', + search: { version: 1 }, + } as any) + await router.navigate({ + to: '/parent/child', + search: { version: 2 }, + } as any) + + expect( + childBeforeLoad.mock.calls.map(([context]) => context.preload), + ).toEqual([true, false]) + expect(router.state.matches.at(-1)?.context).toEqual({ + version: 2, + childVersion: 2, + }) + }) + + test('does not publish context from a beforeLoad replaced during preload', async () => { + const oldBeforeLoadGate = createControlledPromise() + const oldBeforeLoad = vi.fn(async () => { + await oldBeforeLoadGate + return { version: 'old' } + }) + const newBeforeLoad = vi.fn(() => ({ version: 'new' })) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const guardedRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/guarded', + preloadStaleTime: Infinity, + beforeLoad: oldBeforeLoad, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, guardedRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const preload = router.preloadRoute({ to: '/guarded' }) + await vi.waitFor(() => expect(oldBeforeLoad).toHaveBeenCalledTimes(1)) + + guardedRoute.options.beforeLoad = newBeforeLoad as any + await router._refreshRoute?.(guardedRoute.id) + oldBeforeLoadGate.resolve() + await preload + await router.navigate({ to: '/guarded' }) + + expect(oldBeforeLoad).toHaveBeenCalledTimes(1) + expect(newBeforeLoad).toHaveBeenCalledTimes(1) + expect(router.state.matches.at(-1)?.context).toEqual({ version: 'new' }) + }) + + test('does not publish descendants of a beforeLoad replaced during preload', async () => { + const oldBeforeLoadGate = createControlledPromise() + const oldBeforeLoad = vi.fn(async () => { + await oldBeforeLoadGate + return { version: 'old' } + }) + const newBeforeLoad = vi.fn(() => ({ version: 'new' })) + const childLoader = vi.fn( + ({ context }: { context: { version: string } }) => context.version, + ) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + preloadStaleTime: Infinity, + beforeLoad: oldBeforeLoad, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + staleTime: Infinity, + preloadStaleTime: Infinity, + loader: childLoader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const preload = router.preloadRoute({ to: '/parent/child' }) + await vi.waitFor(() => expect(oldBeforeLoad).toHaveBeenCalledTimes(1)) + + parentRoute.options.beforeLoad = newBeforeLoad as any + await router._refreshRoute?.(parentRoute.id) + oldBeforeLoadGate.resolve() + await preload + await router.navigate({ to: '/parent/child' }) + + expect(oldBeforeLoad).toHaveBeenCalledTimes(1) + expect(newBeforeLoad).toHaveBeenCalledTimes(1) + expect(childLoader).toHaveBeenCalledTimes(2) + expect(router.state.matches.at(-1)?.loaderData).toBe('new') + }) + + test('reruns beforeLoad when the completed preload reaches its stale boundary', async () => { + vi.useFakeTimers() + vi.setSystemTime(1_000) + const seen: Array = [] + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const guardedRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/guarded', + staleTime: Infinity, + preloadStaleTime: 100, + beforeLoad: ({ preload }) => { + seen.push(preload) + return { generation: preload ? 'preload' : 'navigation' } + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, guardedRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.preloadRoute({ to: '/guarded' }) + vi.setSystemTime(1_100) + await router.navigate({ to: '/guarded' }) + + expect(seen).toEqual([true, false]) + expect(router.state.matches.at(-1)?.context).toEqual({ + generation: 'navigation', + }) + }) + + test('reruns descendant context after an ancestor becomes stale', async () => { + vi.useFakeTimers() + vi.setSystemTime(1_000) + const parentSeen: Array = [] + const childSeen: Array = [] + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + staleTime: Infinity, + preloadStaleTime: 100, + beforeLoad: ({ preload }) => { + parentSeen.push(preload) + return { parent: preload ? 'preloaded parent' : 'loaded parent' } + }, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + staleTime: Infinity, + preloadStaleTime: 1_000, + beforeLoad: ({ context, preload }) => { + childSeen.push(preload) + return { child: `${context.parent}:${preload}` } + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.preloadRoute({ to: '/parent/child' }) + vi.setSystemTime(1_100) + await router.navigate({ to: '/parent/child' }) + + expect(parentSeen).toEqual([true, false]) + expect(childSeen).toEqual([true, false]) + expect(router.state.matches.at(-1)?.context).toEqual({ + parent: 'loaded parent', + child: 'loaded parent:false', + }) + }) + + test('invalidation prevents reuse of completed preload context', async () => { + const seen: Array = [] + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const guardedRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/guarded', + staleTime: Infinity, + beforeLoad: ({ preload }) => { + seen.push(preload) + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, guardedRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.preloadRoute({ to: '/guarded' }) + await router.invalidate({ + filter: (match) => match.routeId === guardedRoute.id, + }) + await router.navigate({ to: '/guarded' }) + + expect(seen).toEqual([true, false]) + }) + + test('preload false leaves beforeLoad context unresolved for navigation', async () => { + const seen: Array = [] + const loader = vi.fn() + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const guardedRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/guarded', + preload: false, + staleTime: Infinity, + beforeLoad: ({ preload }) => { + seen.push(preload) + }, + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, guardedRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.preloadRoute({ to: '/guarded' }) + await router.navigate({ to: '/guarded' }) + + expect(seen).toEqual([true, false]) + expect(loader).toHaveBeenCalledTimes(1) + }) + + test('shouldReload remains scoped to loader data', async () => { + const beforeLoad = vi.fn(({ preload }: { preload: boolean }) => ({ + guard: preload ? 'preloaded' : 'loaded', + })) + const loader = vi.fn(({ preload }: { preload: boolean }) => preload) + const shouldReload = vi.fn(() => true) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const guardedRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/guarded', + staleTime: Infinity, + beforeLoad, + shouldReload, + loader: { + staleReloadMode: 'blocking', + handler: loader, + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, guardedRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.preloadRoute({ to: '/guarded' }) + await router.navigate({ to: '/guarded' }) + + expect(beforeLoad).toHaveBeenCalledTimes(1) + expect(loader).toHaveBeenCalledTimes(2) + expect(loader.mock.calls.map(([context]) => context.preload)).toEqual([ + true, + false, + ]) + expect(shouldReload).toHaveBeenCalledTimes(1) + expect(shouldReload).toHaveBeenCalledWith( + expect.objectContaining({ + context: expect.objectContaining({ guard: 'preloaded' }), + preload: false, + }), + ) + }) + + test('shouldReload false does not keep stale beforeLoad context', async () => { + vi.useFakeTimers() + vi.setSystemTime(1_000) + const beforeLoad = vi.fn(({ preload }: { preload: boolean }) => ({ + guard: preload ? 'preloaded' : 'loaded', + })) + const loader = vi.fn(({ preload }: { preload: boolean }) => preload) + const shouldReload = vi.fn(() => false) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const guardedRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/guarded', + staleTime: Infinity, + preloadStaleTime: 100, + beforeLoad, + shouldReload, + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, guardedRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.preloadRoute({ to: '/guarded' }) + vi.setSystemTime(1_100) + await router.navigate({ to: '/guarded' }) + + expect(beforeLoad.mock.calls.map(([context]) => context.preload)).toEqual([ + true, + false, + ]) + expect(loader.mock.calls.map(([context]) => context.preload)).toEqual([ + true, + ]) + expect(shouldReload).toHaveBeenCalledTimes(1) + expect(router.state.matches.at(-1)?.context).toEqual({ guard: 'loaded' }) + }) +}) From f4b893487ccbe027821dfc6fc74d91dd98a5402f Mon Sep 17 00:00:00 2001 From: Sheraff Date: Mon, 13 Jul 2026 15:13:57 +0200 Subject: [PATCH 04/59] fix adoption of server data --- .../basic/src/routes/specialChars/search.tsx | 7 + .../basic/tests/special-characters.spec.ts | 5 + packages/react-router/src/Transitioner.tsx | 11 +- packages/router-core/src/load-client.ts | 47 +++- packages/router-core/src/router.ts | 10 +- .../tests/hydrated-stay-match-data.test.ts | 15 +- .../tests/hydration-currentness.test.ts | 251 ++++++++++++++++++ packages/solid-router/src/Transitioner.tsx | 2 +- .../tests/transitioner-render-ack.test.tsx | 4 +- packages/vue-router/src/Transitioner.tsx | 2 +- 10 files changed, 322 insertions(+), 32 deletions(-) diff --git a/e2e/react-start/basic/src/routes/specialChars/search.tsx b/e2e/react-start/basic/src/routes/specialChars/search.tsx index 9e4b42e888..5840d425ab 100644 --- a/e2e/react-start/basic/src/routes/specialChars/search.tsx +++ b/e2e/react-start/basic/src/routes/specialChars/search.tsx @@ -7,6 +7,9 @@ export const Route = createFileRoute('/specialChars/search')({ validateSearch: z.object({ searchParam: z.string(), }), + beforeLoad: () => ({ + beforeLoadOn: isBrowser ? 'client' : 'server', + }), loader: async () => { console.log(`[loader] Running on ${isBrowser ? 'client' : 'server'}`) return { @@ -18,11 +21,15 @@ export const Route = createFileRoute('/specialChars/search')({ function RouteComponent() { const search = Route.useSearch() + const { beforeLoadOn } = Route.useRouteContext() const { loadedOn } = Route.useLoaderData() return (
Hello "/specialChars/search"! +
+ Before load on: {beforeLoadOn} +
Loaded on: {loadedOn}
{search.searchParam}
diff --git a/e2e/react-start/basic/tests/special-characters.spec.ts b/e2e/react-start/basic/tests/special-characters.spec.ts index 7cf50c39c8..188d1f10a6 100644 --- a/e2e/react-start/basic/tests/special-characters.spec.ts +++ b/e2e/react-start/basic/tests/special-characters.spec.ts @@ -104,11 +104,16 @@ test.describe('Unicode route rendering', () => { const loadedOn = await page .getByTestId('special-search-loaded-info') .textContent() + const beforeLoadOn = await page + .getByTestId('special-search-before-load-info') + .textContent() if (isSpaMode) { expect(loadedOn).toBe('Loaded on: client') + expect(beforeLoadOn).toBe('Before load on: client') } else { expect(loadedOn).toBe('Loaded on: server') + expect(beforeLoadOn).toBe('Before load on: server') } }) diff --git a/packages/react-router/src/Transitioner.tsx b/packages/react-router/src/Transitioner.tsx index 90862c27e4..ead1ca6c57 100644 --- a/packages/react-router/src/Transitioner.tsx +++ b/packages/react-router/src/Transitioner.tsx @@ -54,8 +54,9 @@ export function Transitioner() { mountLoadForRouter.current = [router, router.history] router.updateLatestLocation() + const location = router.latestLocation const nextLocation = router.buildLocation({ - to: router.latestLocation.pathname, + to: location.pathname, search: true, params: true, hash: true, @@ -67,7 +68,7 @@ export function Transitioner() { // Compare publicHref (browser-facing URL) for consistency with // the server-side redirect check in router.beforeLoad. if ( - trimPathRight(router.latestLocation.publicHref) !== + trimPathRight(location.publicHref) !== trimPathRight(nextLocation.publicHref) ) { router.commitLocation({ ...nextLocation, replace: true }) @@ -75,11 +76,9 @@ export function Transitioner() { } const resolvedLocation = router.stores.resolvedLocation.get() - const historyLocation = router.history.location if ( - resolvedLocation && - resolvedLocation.publicHref === historyLocation.href && - resolvedLocation.state.__TSR_key === historyLocation.state.__TSR_key + resolvedLocation?.href === location.href && + resolvedLocation.state.__TSR_key === location.state.__TSR_key ) { router.emit({ type: 'onRendered', diff --git a/packages/router-core/src/load-client.ts b/packages/router-core/src/load-client.ts index db9ecbe2bf..9f625b89a9 100644 --- a/packages/router-core/src/load-client.ts +++ b/packages/router-core/src/load-client.ts @@ -1255,6 +1255,13 @@ async function runClientTransaction( } finishPending(router, tx) commitMatches(router, tx, result.matches) + if (router._tx !== tx) { + return + } + router.emit({ type: 'onLoad', ...changeInfo }) + if (router._tx === tx) { + router.emit({ type: 'onBeforeRouteMount', ...changeInfo }) + } } const rendered = await router.startTransition(commit) if (router._tx !== tx) { @@ -1263,8 +1270,6 @@ async function runClientTransaction( router.batch(() => { router.stores.resolvedLocation.set(toLocation) router.stores.status.set('idle') - router.emit({ type: 'onLoad', ...changeInfo }) - router.emit({ type: 'onBeforeRouteMount', ...changeInfo }) if (router._tx === tx) { router.emit({ type: 'onResolved', ...changeInfo }) } @@ -1284,7 +1289,6 @@ export async function loadClientRouter( router: AnyRouter, opts?: { sync?: boolean - resolvedPrefix?: number /** @internal */ _refreshRouteId?: string }, @@ -1303,20 +1307,15 @@ export async function loadClientRouter( return true } : undefined - clientRouter._committedMatches ??= router.stores.matches.get() - const resolvedPrefix = - opts?.resolvedPrefix ?? - (router.ssr && !router.stores.resolvedLocation.get() - ? clientRouter._committedMatches.length - : undefined) + const committed = (clientRouter._committedMatches ??= + router.stores.matches.get()) const previousOwner = clientRouter._tx - const previousLocation = - router.stores.resolvedLocation.get() ?? router.stores.location.get() + const resolvedLocation = router.stores.resolvedLocation.get() + const previousLocation = resolvedLocation ?? router.stores.location.get() const controller = new AbortController() clientRouter._preflight?.abort() clientRouter._preflight = controller - router.updateLatestLocation() const location = router.latestLocation let matches: Array try { @@ -1355,6 +1354,28 @@ export async function loadClientRouter( return } clientRouter._preflight = undefined + const sameHref = previousLocation.href === location.href + + let resolvedPrefix: number | undefined + if ( + !refreshRouteId && + router.ssr && + !resolvedLocation && + sameHref && + previousLocation.state.__TSR_key === location.state.__TSR_key && + committed.every( + (match, index) => !match.invalid && match.id === matches[index]?.id, + ) + ) { + resolvedPrefix = committed.length + if ( + resolvedPrefix && + (committed[resolvedPrefix - 1]!.status !== 'success' || + committed[resolvedPrefix - 1]!.globalNotFound) + ) { + matches.length = resolvedPrefix + } + } const tx: LoadTransaction = { location, @@ -1365,7 +1386,7 @@ export async function loadClientRouter( runClientTransaction( clientRouter, tx, - refreshRouteId ? false : previousLocation.href === location.href, + refreshRouteId ? false : sameHref, refreshRouteId ? undefined : () => offerPending(clientRouter, tx), opts?.sync, resolvedPrefix, diff --git a/packages/router-core/src/router.ts b/packages/router-core/src/router.ts index 8544a5109f..048b3ce10c 100644 --- a/packages/router-core/src/router.ts +++ b/packages/router-core/src/router.ts @@ -2441,14 +2441,12 @@ export class RouterCore< this._serverResult = undefined this.updateLatestLocation() - const historyAction = opts?.action?.type - if (historyAction) { - locationHistoryActions.set(this.latestLocation, historyAction) - } else { - locationHistoryActions.delete(this.latestLocation) + const location = this.latestLocation + if (opts?.action) { + locationHistoryActions.set(location, opts.action.type) } const locationChangeInfo = getLocationChangeInfo( - this.latestLocation, + location, this.stores.resolvedLocation.get(), ) this.emit({ type: 'onBeforeNavigate', ...locationChangeInfo }) 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 b56b7350d8..fdc4ff5f7b 100644 --- a/packages/router-core/tests/hydrated-stay-match-data.test.ts +++ b/packages/router-core/tests/hydrated-stay-match-data.test.ts @@ -22,10 +22,14 @@ describe('hydrated stay match data preservation', () => { }) it('keeps server loader data on a stay match during ordinary client loading', async () => { + const rootBeforeLoad = vi.fn(() => ({ auth: 'client' })) const rootLoader = vi.fn(() => ({ root: 'client' })) const history = createMemoryHistory({ initialEntries: ['/a'] }) - const rootRoute = new BaseRootRoute({ loader: rootLoader }) + const rootRoute = new BaseRootRoute({ + beforeLoad: rootBeforeLoad, + loader: rootLoader, + }) const aRoute = new BaseRoute({ getParentRoute: () => rootRoute, path: '/a', @@ -56,6 +60,7 @@ describe('hydrated stay match data preservation', () => { i: rootMatch.id, s: 'success' as const, ssr: true, + b: { auth: 'server' }, l: { root: 'server' }, u: Date.now(), }, @@ -75,10 +80,14 @@ describe('hydrated stay match data preservation', () => { expect( router.state.matches.find((m) => m.routeId === aRoute.id)?.loaderData, ).toBe('a client data') + expect(rootBeforeLoad).not.toHaveBeenCalled() expect(rootLoader).not.toHaveBeenCalled() expect( - router.state.matches.find((m) => m.routeId === rootRoute.id)?.loaderData, - ).toEqual({ root: 'server' }) + router.state.matches.find((m) => m.routeId === rootRoute.id), + ).toMatchObject({ + context: { auth: 'server' }, + loaderData: { root: 'server' }, + }) // Client-side navigation: root is a stay match and must keep server data. await router.navigate({ to: '/b' }) diff --git a/packages/router-core/tests/hydration-currentness.test.ts b/packages/router-core/tests/hydration-currentness.test.ts index 8199d70ae3..58db76d1c3 100644 --- a/packages/router-core/tests/hydration-currentness.test.ts +++ b/packages/router-core/tests/hydration-currentness.test.ts @@ -177,6 +177,257 @@ describe('hydration asset currentness', () => { expect(newHead).toHaveBeenCalledTimes(1) }) + test('a navigation during hydration handoff does not adopt a different route prefix', async () => { + const oldBeforeLoad = vi.fn(() => ({ source: 'old-client' })) + const oldLoader = vi.fn(() => 'old-client') + const newBeforeLoad = vi.fn(() => ({ source: 'new-client' })) + const newLoader = vi.fn(() => 'new-client') + const rootRoute = new BaseRootRoute({}) + const oldRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/old', + beforeLoad: oldBeforeLoad, + loader: oldLoader, + }) + const newRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/new', + beforeLoad: newBeforeLoad, + loader: newLoader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([oldRoute, newRoute]), + history: createMemoryHistory({ initialEntries: ['/old'] }), + isServer: false, + }) + const oldMatches = router.matchRoutes(router.stores.location.get()) + + mockWindow.$_TSR = { + router: { + manifest: testManifest, + dehydratedData: {}, + matches: [ + { + i: oldMatches[0]!.id, + s: 'success', + ssr: true, + u: Date.now(), + }, + { + i: oldMatches[1]!.id, + s: 'success', + ssr: 'data-only', + b: { source: 'old-server' }, + l: 'old-server', + u: Date.now(), + }, + ], + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + initialized: false, + } + + await hydrate(router) + await router.navigate({ to: '/new' }) + + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: newRoute.id, + status: 'success', + context: { source: 'new-client' }, + loaderData: 'new-client', + }) + expect(newBeforeLoad).toHaveBeenCalledTimes(1) + expect(newLoader).toHaveBeenCalledTimes(1) + expect(oldBeforeLoad).not.toHaveBeenCalled() + expect(oldLoader).not.toHaveBeenCalled() + }) + + test('same-location hydration only adopts the matching server match identities', async () => { + let version = 1 + const beforeLoad = vi.fn(() => ({ source: 'client' })) + const loader = vi.fn(() => 'client') + const rootRoute = new BaseRootRoute({}) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + loaderDeps: () => ({ version }), + beforeLoad, + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + isServer: false, + }) + const serverMatches = router.matchRoutes(router.stores.location.get()) + + mockWindow.$_TSR = { + router: { + manifest: testManifest, + dehydratedData: {}, + matches: [ + { + i: serverMatches[0]!.id, + s: 'success', + ssr: true, + u: Date.now(), + }, + { + i: serverMatches[1]!.id, + s: 'success', + ssr: 'data-only', + b: { source: 'server' }, + l: 'server', + u: Date.now(), + }, + ], + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + initialized: false, + } + + await hydrate(router) + version = 2 + await router.load() + + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: pageRoute.id, + status: 'success', + context: { source: 'client' }, + loaderData: 'client', + }) + expect(beforeLoad).toHaveBeenCalledTimes(1) + expect(loader).toHaveBeenCalledTimes(1) + }) + + test('invalidation during hydration handoff reloads the server prefix', async () => { + const rootLoader = vi.fn(() => 'client') + const rootRoute = new BaseRootRoute({ loader: rootLoader }) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + isServer: false, + }) + const serverMatches = router.matchRoutes(router.stores.location.get()) + + mockWindow.$_TSR = { + router: { + manifest: testManifest, + dehydratedData: {}, + matches: [ + { + i: serverMatches[0]!.id, + s: 'success', + ssr: true, + l: 'server', + u: Date.now(), + }, + { + i: serverMatches[1]!.id, + s: 'success', + ssr: 'data-only', + u: Date.now(), + }, + ], + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + initialized: false, + } + + await hydrate(router) + await router.invalidate({ + filter: (match) => match.routeId === rootRoute.id, + }) + + expect(rootLoader).toHaveBeenCalledTimes(1) + expect(router.state.matches[0]).toMatchObject({ + routeId: rootRoute.id, + status: 'success', + loaderData: 'client', + }) + }) + + test('an adopted data-only error does not run its server-omitted descendants', async () => { + const childBeforeLoad = vi.fn() + const childLoader = vi.fn() + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + beforeLoad: childBeforeLoad, + loader: childLoader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + isServer: false, + }) + const serverMatches = router.matchRoutes(router.stores.location.get()) + const serverError = new Error('server failed') + + mockWindow.$_TSR = { + router: { + manifest: testManifest, + dehydratedData: {}, + matches: [ + { + i: serverMatches[0]!.id, + s: 'success', + ssr: true, + u: Date.now(), + }, + { + i: serverMatches[1]!.id, + s: 'error', + ssr: 'data-only', + e: serverError, + u: Date.now(), + }, + ], + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + initialized: false, + } + + await hydrate(router) + await router.load() + + expect(router.state.matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + parentRoute.id, + ]) + expect(router.state.matches.at(-1)).toMatchObject({ + status: 'error', + error: serverError, + }) + expect(childBeforeLoad).not.toHaveBeenCalled() + expect(childLoader).not.toHaveBeenCalled() + }) + test('a same-href load owns route hooks when an older hydration chunk settles later', async () => { const routeChunkGate = createControlledPromise() const Page = Object.assign(() => null, { diff --git a/packages/solid-router/src/Transitioner.tsx b/packages/solid-router/src/Transitioner.tsx index 01092b34f5..1997ef87f0 100644 --- a/packages/solid-router/src/Transitioner.tsx +++ b/packages/solid-router/src/Transitioner.tsx @@ -49,7 +49,7 @@ export function Transitioner() { const resolvedLocation = router.stores.resolvedLocation.get() if ( - resolvedLocation?.publicHref === router.latestLocation.publicHref && + resolvedLocation?.href === router.latestLocation.href && resolvedLocation.state.__TSR_key === router.latestLocation.state.__TSR_key ) { router.emit({ diff --git a/packages/solid-router/tests/transitioner-render-ack.test.tsx b/packages/solid-router/tests/transitioner-render-ack.test.tsx index 08c62f53dc..99f09d7bc0 100644 --- a/packages/solid-router/tests/transitioner-render-ack.test.tsx +++ b/packages/solid-router/tests/transitioner-render-ack.test.tsx @@ -111,7 +111,7 @@ test('an older rendered destination cannot resolve a superseding navigation', as }) expect(screen.getByText('First')).toBeInTheDocument() expect(screen.queryByText('Next')).not.toBeInTheDocument() - expect(renderedPaths).toEqual(['/first']) + expect(renderedPaths).toEqual([]) expect(resolvedPaths).toEqual([]) nextLoader.resolve() @@ -120,7 +120,7 @@ test('an older rendered destination cannot resolve a superseding navigation', as await waitFor(() => { expect(screen.getByText('Next')).toBeInTheDocument() }) - expect(renderedPaths).toEqual(['/first', '/next']) + expect(renderedPaths).toEqual(['/next']) expect(resolvedPaths).toEqual(['/next']) for (const unsubscribe of unsubscribers) { diff --git a/packages/vue-router/src/Transitioner.tsx b/packages/vue-router/src/Transitioner.tsx index 93ec028a72..6cec279a49 100644 --- a/packages/vue-router/src/Transitioner.tsx +++ b/packages/vue-router/src/Transitioner.tsx @@ -40,7 +40,7 @@ export function useTransitionerSetup() { const resolvedLocation = router.stores.resolvedLocation.get() if ( - resolvedLocation?.publicHref === router.latestLocation.publicHref && + resolvedLocation?.href === router.latestLocation.href && resolvedLocation.state.__TSR_key === router.latestLocation.state.__TSR_key ) { router.emit({ From 7b5436bfe7305ce40f416d8a2209ef6ac051ec8a Mon Sep 17 00:00:00 2001 From: Sheraff Date: Mon, 13 Jul 2026 17:09:00 +0200 Subject: [PATCH 05/59] fix internal error propagation, only user code is try/catch --- packages/router-core/src/load-client.ts | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/packages/router-core/src/load-client.ts b/packages/router-core/src/load-client.ts index 9f625b89a9..2636919de3 100644 --- a/packages/router-core/src/load-client.ts +++ b/packages/router-core/src/load-client.ts @@ -1461,7 +1461,7 @@ export async function preloadClientRoute( const base = semanticMatches(clientRouter) const plannedCache = router.stores.cachedMatches.get() const controller = new AbortController() - let matches: Array + let matches: Array | undefined try { matches = router.matchRoutes(location, { throwOnError: true, @@ -1542,6 +1542,12 @@ export async function preloadClientRoute( ]) return matches } catch (cause) { + if (!matches) { + if (controller.signal.aborted) { + return + } + throw cause + } controller.abort() if (clientRouter._tx !== owner) { return @@ -1559,9 +1565,7 @@ export async function preloadClientRoute( if (!isNotFound(cause)) { console.error(cause) } - if (matches!) { - discardMatchResources(router, matches) - } + discardMatchResources(router, matches) return } } From fb21a428b04a3e66272da585b38e296bf1b21d28 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Mon, 13 Jul 2026 17:28:49 +0200 Subject: [PATCH 06/59] fix: solid Transitionner unsub cleanup before early return --- packages/solid-router/src/Transitioner.tsx | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/packages/solid-router/src/Transitioner.tsx b/packages/solid-router/src/Transitioner.tsx index 1997ef87f0..72d5f10300 100644 --- a/packages/solid-router/src/Transitioner.tsx +++ b/packages/solid-router/src/Transitioner.tsx @@ -26,6 +26,7 @@ export function Transitioner() { // and try to load the new location Solid.onMount(() => { const unsub = router.history.subscribe(router.load) + Solid.onCleanup(unsub) const nextLocation = router.buildLocation({ to: router.latestLocation.pathname, @@ -59,10 +60,6 @@ export function Transitioner() { } else { router.load().catch(console.error) } - - Solid.onCleanup(() => { - unsub() - }) }) return null From bf9060267c5019792de15cd40d3165d4e4b42dcc Mon Sep 17 00:00:00 2001 From: Sheraff Date: Mon, 13 Jul 2026 17:33:44 +0200 Subject: [PATCH 07/59] fix: react-router not found ambiguous assertion --- packages/react-router/tests/router.test.tsx | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/react-router/tests/router.test.tsx b/packages/react-router/tests/router.test.tsx index 59bf8c39bb..5cdd6d7dc0 100644 --- a/packages/react-router/tests/router.test.tsx +++ b/packages/react-router/tests/router.test.tsx @@ -2464,7 +2464,10 @@ describe('notFound in beforeLoad with pendingComponent', () => { await act(() => router.navigate({ to: '/parent/child' })) - expect(await screen.findByText(/Not Found/)).toBeInTheDocument() + expect(await screen.findByTestId('parent-not-found')).toHaveTextContent( + 'Parent Not Found', + ) + expect(screen.queryByTestId('root-not-found')).not.toBeInTheDocument() }) it('renders notFound when child beforeLoad throws without a pending component', async () => { From f2ccae2407f588fd9e926a85964e1ceba37e9d60 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Mon, 13 Jul 2026 18:14:57 +0200 Subject: [PATCH 08/59] docs --- packages/router-core/INTERNALS.md | 919 ++++++++++++++++++++++++++++++ 1 file changed, 919 insertions(+) create mode 100644 packages/router-core/INTERNALS.md diff --git a/packages/router-core/INTERNALS.md b/packages/router-core/INTERNALS.md new file mode 100644 index 0000000000..153d1b9763 --- /dev/null +++ b/packages/router-core/INTERNALS.md @@ -0,0 +1,919 @@ +# Router Match Loading Internals + +This document describes the match-loading architecture shared by router core and +the React, Solid, and Vue adapters. It is intended for maintainers changing +navigation, preloading, pending UI, SSR, hydration, route chunks, or route HMR. + +The implementation is deliberately a small ownership and publication protocol, +not a second match-status state machine. TypeScript brands constrain +phase-specific call sites, and closed outcome unions make control results +exhaustive. Reentrancy, cancellation, resource ownership, pending timing, and +publication remain runtime concerns enforced by the identities described below. + +All `_`-prefixed fields and functions discussed here are internal. Their exact +shape is not a compatibility contract. + +## Design constraints + +The loader is built around these rules: + +1. A foreground navigation builds a private lane. Only the current transaction + may commit it, and presentation remains separate from accepted semantics. +2. Context is materialized serially from parent to child; independent loader and + chunk work runs concurrently, then reduces in structural route order. +3. Shared work never grants publication authority. Losing work releases its + resources and cannot publish after it becomes stale. +4. Runtime state exists only for a real ownership, publication, or completion + boundary. Phase naming and impossible local transitions belong in TypeScript. + +Correctness takes priority over size, but the architecture must remain lean. In +particular, do not reify TypeScript-only phases as runtime state, and do not add a +second cache for work already cached by the JavaScript module system. + +## Navigation at a glance + +The normal client path is: + +```text +Router.load lifecycle events + -> synchronous matching under foreground preflight ownership + -> install transaction and requested location + -> serial beforeLoad contextualization + -> concurrent loader and route-chunk work + -> structural reduction + -> projection + -> guarded foreground commit + -> transition acknowledgement + -> resolved location, idle status, and navigation completion +``` + +Pending presentation may publish while the private lane runs. A guarded +background reload may publish a later semantic replacement after the foreground +commit. Neither is a second foreground transaction. + +The location and match references intentionally advance at different moments: + +| Moment | `stores.location` | `stores.resolvedLocation` | `_committedMatches` | `stores.matches` | Status | +| --------------------------------------- | ----------------- | ------------------------- | ------------------- | ------------------------------ | --------- | +| Idle | old | old | old lane | old lane | `idle` | +| Transaction installed | new | old | old lane | old lane or new pending prefix | `pending` | +| Terminal commit, before acknowledgement | new | old | new lane | new lane | `pending` | +| Transition acknowledgement settled | new | new | new lane | new lane | `idle` | + +`latestLocation` is the parsed history input captured before planning. It is not +another published phase. In particular, `stores.location` advancing does not +mean that destination matches have committed or rendered. + +## File map + +- `src/router.ts` matches locations, owns the router-level authorities, and + starts client or server loads. +- `src/load-client.ts` contains client lanes, foreground transactions, loader + flights, preloads, pending presentation, background reloads, and atomic + commits. +- `src/load-server.ts` contains the request-local server lane and SSR selection. +- `src/hydrate.ts` reconstructs the server-resolved prefix and hands unresolved + work to the ordinary client loader. +- `src/route-chunks.ts` owns lazy-route option installation and component + preloading. +- `src/stores.ts` projects matches into fine-grained framework stores. These + stores are reactive presentation/indexing machinery, not another loading + authority. +- `src/ssr/` serializes and streams server results. +- `packages/{react,solid,vue}-router/src/Transitioner.*` connect history and + renderer transitions to router core. +- `packages/{react,solid,vue}-router/src/Match.*` render pending, error, + not-found, selective-SSR, and client-only boundaries. +- `packages/router-plugin/src/core/hmr/handle-route-update.ts` installs route + updates and asks core for a development-only refresh. + +## Vocabulary + +**Match** is the state for one route at one location. Its semantic fields include +route and `beforeLoad` context, loader data, status, and failure information. +Match identity is derived from route id, interpolated path, and loader +dependencies. It controls semantic and cache reuse. + +**Lane** is an ordered root-to-leaf array of matches for one location. Its +semantic result is private until commit; pending UI may project a presentation +prefix from it without acquiring semantic authority. + +**Transaction** is the identity that authorizes foreground publication for a +client navigation. It owns a lane, a cancellation controller, and a completion +promise. The latest transaction remains installed after settlement, so its mere +presence does not mean loading is active. + +**Presentation** is what `stores.matches` currently exposes to the framework. It +may temporarily be a shortened lane ending in a pending match. + +**Committed lane** is the accepted active semantic generation in +`router._committedMatches`. It normally contains the last terminal result and +remains the planning base while pending UI is presented. + +**Terminal lane** is a reduced and projected client lane ready for semantic +publication. It may end in success, an ordinary error, or not-found. + +**Resolved prefix** is the count of accepted leading matches whose semantic work +is already complete, usually from SSR hydration or the active lane. It is a +length, not a zero-based boundary index. + +**Terminal cache** is the set of off-screen semantic matches exposed by +`stores.cachedMatches`. The cache is neither active presentation nor a registry +of in-progress work. + +**Flight** is one loader generation and its outcome. Registry membership means a +flight may be joined; a lease means a particular match owns that generation and +its `AbortSignal`. + +**Projection** computes non-loader route output such as head metadata, scripts, +styles, and server headers after semantic outcomes have been reduced. + +**Authority** is an identity or state comparison whose equality permits a +publication or resource mutation. A boolean that merely restates an authority is +not a new authority. + +## The runtime authorities + +There are intentionally few independent authorities: + +| Authority | Meaning | Must not be used as | +| -------------------------- | -------------------------------------------------------------- | -------------------------------------- | +| `router._tx` | Latest foreground transaction; equality authorizes publication | A loading boolean; use `stores.status` | +| `router._committedMatches` | Accepted active semantic generation | The currently rendered lane | +| `stores.matches` | Current presentation | A semantic planning base | +| `stores.cachedMatches` | Off-screen semantic cache | Active routes or in-progress work | +| `stores.status` | Public loading-state projection | Foreground writer identity | +| `stores.location` | Requested location | Proof that loading finished | +| `stores.resolvedLocation` | Last location whose load/hydration settled | The requested location | +| `router._pending` | One pending reveal/minimum-duration session | A second navigation transaction | +| `router._preflight` | Owner of synchronous foreground planning | A second writer | +| `router._flights` | Joinable loader work by match id | Ownership of every flight | +| `route._lazy` | Current lazy-route import owner or loaded marker | A component-module cache | + +The most important separation is: + +```text +transaction/preload lanes -> private work; no semantic publication yet +_committedMatches -> active semantic reuse, planning, background CAS +stores.cachedMatches -> inactive semantic reuse and preload cache CAS +stores.matches -> renderer presentation, including pending prefixes +``` + +Pending presentation can remove hidden suffix entries from the reactive match +pool. Planning from it would therefore forget valid committed matches and make +presentation timing affect loader semantics. Once `_committedMatches` is +initialized, all semantic lookups use it and the terminal cache. + +### Completion scopes + +Promises also have deliberately narrow ownership: + +| Promise or acknowledgement | Scope | +| -------------------------- | ------------------------------------------------------ | +| Flight outcome | Shareable loader work | +| `tx.done` | One private foreground transaction | +| Pending/transition ack | Settlement and render confirmation for one publication | +| `commitLocationPromise` | History/navigation completion | +| `parentMatchPromise` | One loader's view of its semantic parent result | + +These scopes are not interchangeable. A new “latest load” promise usually +duplicates transaction or history-completion authority and makes supersession +ambiguous. + +## Planning a lane + +`matchRoutesInternal` performs synchronous, parent-first planning in two passes. + +The first pass: + +1. validates and accumulates search, +2. computes `loaderDeps`, +3. interpolates and parses params, +4. derives the match id, +5. reuses a committed or cached semantic match when allowed, and +6. creates a fresh work match otherwise. + +The second pass finalizes params and runs route `context` functions for fresh +matches in parent-first order. + +Route continuity and match reuse are related but distinct: + +- Match id controls semantic/cache reuse. +- Route id controls `enter`, `stay`, and `leave` lifecycle semantics. +- The previous active match for a route stabilizes params, search, and loader + dependencies. A cached match is not an active route merely because it is + reusable. + +### Why `_preflight` exists + +Planning calls user code synchronously: search validators, `loaderDeps`, param +parsers, route context, and related hooks can trigger reentrant navigation. +`assertMatchOwner` checkpoints after these calls. A new foreground plan aborts +the previous `_preflight`, so an obsolete stack frame cannot later install +itself as writer. + +`_preflight` is not a second completion authority. `_tx` remains the sole writer +until a replacement has finished matching successfully. Folding preflight into +`_tx` would require publishing a partially constructed transaction and then +rolling it back if matching throws. The small preflight controller represents a +real synchronous ownership boundary and avoids that invalid partial state. + +Client preloads do not replace `_preflight`. They use a local controller and a +snapshot of `_tx`, because speculative work may be canceled by foreground +navigation but may never claim foreground planning authority. A merely built or +blocked navigation likewise does not change `_tx`; only a successfully planned +foreground lane installs a replacement transaction. + +### Planning failures are not lane outcomes + +The owner of an error depends on whether matching produced a lane: + +- A foreground plan invalidated by reentrant navigation quietly follows the + successor transaction. A planning redirect starts a replacement navigation. + Any other planning failure leaves the previous committed lane and its + resources in place, then settles the pending history waiter. +- If client preload matching produces no lane because its local controller was + aborted, preload returns as canceled. If no lane was produced and the + controller is still current, the planning/input error is rethrown to the + caller. It must not become an unconditional core `console.error`. +- Once a lane exists, its ordinary route, loader, and chunk failures are reduced + as lane outcomes. The lane owner is then responsible for cleanup and redirect + handling. + +This boundary is why planning cancellation is detected from the existing +controller rather than another flag. + +## Typed lane pipeline + +Client lanes use phantom TypeScript phases: + +```text +MatchedLane -> ContextualizedLane -> ReducedLane -> ProjectedLane +``` + +The phase marker emits no runtime state and prevents accidental phase mixing in +phase-specific helper signatures. `executeClientLane` exposes only a projected +lane or a control outcome, and its current callers commit only the projected +branch. Runtime ownership, currentness, and the commit itself are not type +guarantees. The server uses corresponding matched, contextualized, and reduced +phases. + +Explicit construction casts mean these brands guard local orchestration, not the +whole runtime protocol. + +Client loader results are a closed tuple union: + +```text +success(data) | error(error) | notFound(error) | redirected(redirect) | canceled +``` + +The server counterpart uses `skipped` for an `ssr: false` loader instead of +`canceled`. + +The compact numeric representation is internal. The union matters because +cancellation and redirects are control outcomes, not match states, while errors +and not-found results become terminal match semantics at the reducer's selected +cutoff. Resolved and thrown redirects/not-found values normalize to the same +outcomes. `onError` may transform an ordinary error by throwing a control value. + +The client phase driver, `executeClientLane`, performs: + +```text +adopt flight leases + -> contextualize serially + -> start loader/chunk tasks concurrently + -> reduce outcomes in route order + -> project assets +``` + +No phase publishes router state. + +## Contextualization and concurrent work + +`beforeLoad` is deliberately serial. For each match, contextualization: + +1. handles param/search validation failures, +2. combines the completed parent context with route context, +3. reuses an accepted preloaded result only while the contiguous parent prefix + remains reusable, otherwise awaits `beforeLoad`, and +4. merges the selected result before advancing to the child. + +This guarantees that child `beforeLoad`, child loader context, and +`parentMatchPromise` never observe a partially updated parent context. + +### Match reuse, `beforeLoad` reuse, and loader reload are separate + +Matching first decides whether a semantic match object can be reused by id. +Execution then makes two independent decisions: + +- `beforeLoad` normally reruns for navigation. It is skipped only for an adopted + hydration prefix or a fresh, completed client-preload donor. The donor's + `beforeLoad` completion timestamp is its own freshness and cache-GC origin; + custom `shouldReload` remains loader-only. Donation is prefix-closed, so a + parent that cannot donate forces every descendant `beforeLoad` to rerun. +- Loader execution considers status, invalidation, configured `shouldReload`, + freshness, navigation cause/forced reload, and blocking versus background + reload mode. Reusing a match therefore does not imply reusing its loader data. + +An accepted `beforeLoad` donor may have run with `preload: true`. Navigation +intentionally reuses that context without rerunning the hook merely to call it +with `preload: false`. Pending or failed `beforeLoad` work is never donated. A +pending loader flight may still be shared while navigation runs its own serial +`beforeLoad` chain. + +`preload: false` does not suppress speculative `beforeLoad`: the hook still runs +with `preload: true`, but its context is not donated. The loader is skipped and +the match remains invalid, so navigation reruns `beforeLoad` and performs the +loader work. + +After contextualization reaches its terminal prefix, task creation starts loader +and route-chunk work without awaiting siblings. Loaders therefore run +concurrently. Each task exposes three related milestones: + +- `outcome`: the semantic loader result, +- `ready`: a successful outcome plus the route's render chunk readiness, and +- `match`: the parent-facing match promise; the server resolves it to a snapshot. + +Separating `outcome` from `ready` is essential. A redirect or error can win +without waiting for irrelevant successful descendant chunks, while a successful +lane cannot commit before the chunks it needs to render are ready. + +`resolvedPrefix` skips repeated contextualization and loader work while +preserving the task chain needed for parent promises and chunk readiness. A +client preload derives it from the contiguous active successful same-id prefix. +The initial hydration handoff instead adopts its entire committed prefix or none +of it, under the href/key/id/currentness checks described below. Joinable work +already attached to an adopted prefix is still accounted for, and projection may +restart at its retained terminal match. + +## Ordered reduction and failure boundaries + +Although work runs concurrently, reduction consumes it in structural route +order. The reducer: + +1. recognizes redirect/cancel control outcomes, +2. selects the terminal error or not-found outcome, +3. checks relevant successful route chunks in route order, +4. loads the component required by the selected terminal match, +5. trims descendants beyond the semantic cutoff, and +6. releases resources owned by the trimmed suffix. + +Errors take precedence over not-found outcomes on the client when both are +present. An ordinary error marks the throwing match and trims its descendants; +the framework's nested catch boundaries may ultimately render a parent, default, +or root error component. A not-found outcome is instead assigned to the nearest +eligible ancestor not-found match before trimming. The semantic cutoff and the +component that visibly handles a failure are therefore related but not +identical. A global root not-found remains a successful root match marked +`globalNotFound`, because the root shell still renders while presenting the +global not-found result. + +Control outcomes take precedence over error and not-found outcomes regardless of +relative route depth. After that, client and server selection deliberately +differ: + +| Environment | Selection rule | +| ----------- | ----------------------------------------------------------------------------------------------------------------------------- | +| Client | Redirect/cancel is control flow. Otherwise any ordinary error wins over not-found, with route order selecting within a kind. | +| Server | Redirect wins. Otherwise the structurally earliest render boundary wins, with ordinary error winning a tie against not-found. | + +Redirect and cancellation outcomes never become committed match states. Internal +redirects are followed by a replacement navigation. Redirect depth is inherited +one hop at a time across the whole redirect-produced replacement chain and is +capped at 20. The current transaction's `redirecting` marker authorizes only its +redirect successor to inherit the count; an unrelated superseding navigation +must not inherit it. The count clears when a semantic lane completes without +redirecting. + +Projection runs only after reduction, so head/scripts see the final lane and +loader data. Client projection failures are decorative: they are logged without +replacing a semantic loader result. + +## Foreground transaction lifecycle + +`RouterCore.load` refreshes `latestLocation` once, uses that same parsed object +for the history action and before-navigation events, and delegates to +`loadClientRouter`. The client loader must not parse a second location object; +location object identity is also how scroll restoration associates a history +action with the later lifecycle event. + +`loadClientRouter` first plans under `_preflight`. Only after planning succeeds +and both the preflight owner and previous writer are still current does it install +a `LoadTransaction` as `_tx`. Installation then: + +1. aborts and releases the previous writer's private lane, +2. publishes the requested location and `status: 'pending'` together, +3. offers pending presentation, and +4. runs the private lane pipeline. + +The transaction may publish a terminal lane only while `router._tx === tx`. +Currentness is checked before committing, inside the view transition, and after +the framework transition acknowledgement. A losing lane releases its matches and +returns without touching committed state. + +Expected route failures have already become typed lane outcomes by this point. +If orchestration itself rejects unexpectedly, the transaction aborts and +releases its private work, restores the committed lane as presentation, returns +the router to idle, and settles the pending history completion. It never +publishes a partially reduced lane or turns that orchestration failure into route +error UI. `tx.done` and `commitLocationPromise` are waiters, not publication +authority; equality with `_tx` remains the write guard. + +On success, `commitMatches`: + +1. derives the next terminal cache, +2. publishes presentation, `_committedMatches`, and the terminal cache in one + batch, +3. transfers flight leases from old/cache/private owners to the new owners, +4. clears the transaction's reference to its transferred lane, and +5. runs route enter/stay/leave callbacks. + +The `tx.matches = []` assignment is intentional. The same array has become the +committed lane, so setting its `.length = 0` would erase committed state. Replacing +the transaction's reference records the ownership transfer without adding an +ownership flag. + +Transition settlement gates resolved-location, idle, and history-completion +publication; a `true` acknowledgement additionally permits `onRendered`. + +`awaitCurrent` follows successor transactions, so a superseded call to +`router.load()` does not resolve while the navigation that replaced it is still +active. + +### Lifecycle event order + +Client lifecycle ordering is part of the protocol: + +1. `RouterCore.load` synchronously emits `onBeforeNavigate`, then `onBeforeLoad`. +2. Inside the framework transition, terminal matches/cache publish and route + `onLeave`/`onEnter`/`onStay` callbacks run. +3. If those callbacks did not supersede the writer, core emits `onLoad`, then + `onBeforeRouteMount`. The latter is therefore before destination mount/effects. +4. After the transition acknowledgement settles, core sets the resolved location + and idle status. It emits `onResolved` while the transaction is still current, + then emits `onRendered` only when the framework confirmed that the publication + rendered. + +Listeners may start another navigation. Currentness is checked again while +emitting lifecycle events: a route callback suppresses stale `onLoad`, and an +`onLoad` listener that supersedes the writer suppresses stale +`onBeforeRouteMount`, `onResolved`, and `onRendered`. Listener exceptions are +isolated and do not stop later listeners or leave acknowledgement cleanup +unfinished. + +## Pending presentation and renderer acknowledgement + +Pending UI is a projection of an in-progress transaction, never a semantic lane. +`renderPending` publishes a prefix ending at the selected pending boundary. It +clones that boundary, changes only its presentation status to `pending`, and +removes `_flight` so a rendered clone cannot accidentally own loader work. + +The boundary is the shallowest non-success match, or the shallowest successful +match already visibly presented as pending. If that boundary has no route or +default pending component, or its effective `pendingMs` is non-numeric or +`Infinity`, no pending session is offered; core does not skip it to search for a deeper +fallback. Task readiness offers pending again, so the shallowest unresolved +boundary may move deeper as ancestors settle. An invalid boundary has zero +reveal delay; the pending-session rules still determine whether it is actually +presented and how long confirmed presentation remains. + +There is one `PendingSession`: + +```text +reveal deadline -> renderer acknowledgement -> minimum-visible deadline +``` + +Before acknowledgement, `deadline` is the time at which pending UI may be +offered. After the renderer reports that the pending lane was actually rendered, +the same field becomes the earliest time it may be replaced. This single absolute +deadline avoids copied timers and competing completion authorities. + +An acknowledgement **settles** when the framework transition is no longer +pending, even if it resolves `false`. A `true` value **confirms rendering**. +Settlement of the terminal commit gates resolved-location/idle publication; +confirmation alone gates `onRendered`, and confirmation of pending presentation +gates its minimum duration. + +A replacement transaction may adopt the session only if the same boundary index +has the same match id. Otherwise the old timer/session is discarded. A completed +transaction waits for `pendingMinMs` only when the renderer confirms that the +pending state appeared; queued work that never rendered does not incur a minimum +duration. If core reconstructs a session around an already-visible pending +boundary rather than adopting its original session, it conservatively starts the +minimum duration from the time it observes that presentation. + +Framework adapters implement `startTransition` as +`Promise`: + +- React queues acknowledgements around `React.startTransition`; `MatchesInner` + resolves them from a layout effect after the new matches render. Cleanup + resolves abandoned acknowledgements as `false`. +- Solid awaits `Solid.startTransition` and returns `true`. +- Vue runs the update, awaits `nextTick`, and returns `true`. +- Core's fallback applies synchronously and returns `false`, because it cannot + prove that a framework rendered the update. + +This acknowledgement is also why `onRendered` and navigation completion cannot +be inferred from a store write alone. In React, every publication passed through +`startTransition` must still cause the aggregate matches store to notify and the +layout effect to run. Reusing exact work objects while suppressing the match-store +write can strand the acknowledgement promise; preserve this liveness property +when optimizing store reconciliation. Test it through navigation completion and +rendered output, not `_rendered` itself. + +## Loader flights and resource ownership + +A `LoaderFlight` contains one outcome promise, its own abort controller, and a +lease count. The controller belongs to the shared work rather than any one +transaction. + +Two facts must remain separate: + +- `_flights.get(match.id) === flight` means the flight is joinable. +- `match._flight === flight` means that match owns one lease. + +`closeFlight` removes joinability but does not release the owner's lease. +`releaseFlight` removes one lease; only the last release aborts the loader and +removes the registry entry. `transferMatchResources` and +`discardMatchResources` are the bulk ownership operations, based on match object +identity. + +The lease intentionally may outlive promise settlement. Once successful data is +accepted, closing registry membership prevents new joins while the accepted +match keeps the loader generation's public `AbortSignal` alive. That signal is +aborted only when the last owner is replaced, unloaded, expired, or rejected from +cache. Promise state therefore cannot replace the lease count. + +Every semantic publication closes joinability for the published matches. A +later navigation cannot join already-published work through `_flights`, even +though the accepted matches continue to own their leases and signals. + +A navigation may join a preload's same-id flight. It adopts only a successful +outcome. If shared work yields an error, not-found, redirect, or cancellation, +the joining lane closes/releases that flight and runs its own loader. This lets +work be shared without allowing a preload's control outcome or failure context to +govern a navigation. + +Transaction cancellation races the shared promise through `waitFor`. Losing the +race releases that lane's lease; it does not abort work still leased elsewhere. +The flight also checks its own controller after both loader resolution and +rejection. A loader that ignores `AbortSignal` therefore still normalizes to +canceled and cannot resurrect obsolete cache state. + +Every losing, trimmed, superseded, expired, or cache-rejected match must release +its lease exactly once. Do not replace the lease protocol with boolean ownership +flags. + +## Client preloading and the terminal cache + +Client preloading uses the same matcher, contextualizer, task builder, reducer, +projector, and flight protocol as navigation, but it never becomes `_tx`. + +`beforeLoad` donation, loader reload, and `preload: false` behavior are defined in +the contextualization section above. Preloading adds speculative ownership, +redirect handling, and cache publication; it does not add another reuse policy. + +A preload snapshots the current writer and plans with an `_isCurrent` guard. It +derives the already-resolved active prefix, executes the lane, follows internal +redirects up to its redirect limit, and caches only an all-success result. +The planning cancellation/error distinction is described above. Routes with +`preload: false` still run `beforeLoad`, but skip their loader and remain invalid +as described in the reuse section. + +The `_isCurrent` guard protects synchronous planning. Once a preload lane exists, +a new foreground transaction does not blindly abort it: useful loader flights may +still be shared, while active-id and cache-entry identity checks prevent obsolete +cache publication. Unexpected post-plan exceptions belong to the preload lane. +It aborts its controller; while still current, it follows eligible redirects, +absorbs not-found, logs other unexpected failures, and releases its resources. A +superseded lane must likewise release its resources before returning. + +Cache publication is an identity compare-and-swap. A preload candidate is +discarded if it became active or if the corresponding cache entry changed since +planning. This prevents late preloads from overwriting fresher cache data without +adding a version counter. Development refreshes also reject context produced by a +`beforeLoad` function that is no longer installed, together with the descendant +suffix that depended on it. + +Foreground commits retain successful exiting matches only when they have either +fresh loader-backed data within the applicable normal/preload GC window or +reusable preloaded `beforeLoad` context within `preloadGcTime`. Active ids are +removed from the cache; failed, not-found, expired, and loaderless entries +without reusable context provenance are discarded. Clearing the cache releases +leases before publishing the retained cache entries. + +Server `preloadRoute` is different: it runs the request-local server lane and may +cache an all-success result, but it has no client transaction or loader-flight +protocol. + +## Background stale reloads + +A stale successful match may keep its current data visible while a private +candidate reloads in the background. This is used only for loader-backed, +non-preload, non-sync work whose effective stale reload mode is not blocking. + +Foreground reduction and commit proceed with the existing successful match. The +background candidate uses the same loader outcome and projection rules. It may +publish only if both conditions still hold: + +```text +router._tx === owningTransaction +router._committedMatches === exactForegroundBase +``` + +The writer check rejects superseding navigation. The reference-identity check is +an inexpensive compare-and-swap that rejects invalidation, rematching, another +background publication, or any reentrant commit based on the same location. Both +checks are required after asynchronous reduction/projection; one cannot replace +the other. + +A current background redirect uses the same guards and one-hop redirect depth +handoff. Losing background candidates release their resources. Background +publication updates matches through the normal publication primitive rather +than inventing a second commit protocol. + +Background publication replaces an already-resolved presentation directly. It +does not enter the pending/renderer-acknowledgement protocol, change +`stores.status` or `resolvedLocation`, or emit foreground navigation lifecycle +events. Framework stores still receive the ordinary match publication. + +## Invalidation + +Invalidation replaces the committed and cached semantic entries with invalid +generations, then routes the reload through the ordinary foreground transaction. +It does not mutate `stores.matches` merely to manufacture pending UI; the new +transaction owns that presentation decision. `forcePending` may mark invalidated +semantic entries as pending when the route has work. Even without `forcePending`, +an invalidated error or not-found entry with route work resets to pending and +clears its error. The renderer still changes only through pending presentation or +terminal commit. + +The invalidated clones carry the accepted generation's existing flight reference; +invalidation does not duplicate its lease or invent new loader ownership. + +Replacing `_committedMatches` also changes its array identity. Any background +candidate based on the previous generation therefore fails the existing +exact-base compare-and-swap. Invalidation needs no scheduler, version counter, or +background-specific cancellation flag. + +## Route chunks + +Normal successful readiness loads the route component and pending component. +Error and not-found component preloads are requested only for the semantic +terminal match selected by reduction. A framework may still bubble an ordinary +error to a visibly different ancestor catch boundary. Client chunk work begins +alongside loader work, but a normal chunk failure is semantically considered only +when its loader outcome succeeds. + +`route._lazy` has three compact states: + +```text +undefined = no current owner +Promise = current lazy option import +true = lazy options installed +``` + +Only the promise still stored in `_lazy` may install options or clear a failed +import. HMR clears `_lazy`, so a late obsolete import cannot mutate the updated +route. Lazy options never overwrite the generated route id. + +There is deliberately no component-promise cache. Dynamic import and framework +component preload machinery already cache loaded JavaScript modules. Repeating a +component preload call is cheaper and safer than maintaining another runtime +authority. `route._lazy` remains necessary because it owns lazy-option +installation, rejects obsolete HMR settlements, and resets failed imports for +retry. + +## Server loading + +Server loading is request-local and needs no global transaction coordinator. It +uses a separate typed lane with the same high-level ordering: + +```text +match -> resolve SSR + contextualize serially -> run loaders concurrently + -> reduce -> load selected chunks -> project -> render or redirect +``` + +SSR policy is resolved parent-first before each route's `beforeLoad`: + +- `ssr: true` runs `beforeLoad`, loads data and render chunks, and projects + assets. +- `ssr: 'data-only'` loads data but does not render that route's component or + project its assets on the server. Its `beforeLoad` still runs. +- `ssr: false` skips server `beforeLoad`, loader, chunks, and assets for that + route. Its synchronous route context was already created during matching. +- A `false` parent forces descendants to `false`; a `data-only` parent caps any + `true` descendant at `data-only`, whether explicit, computed, or inherited. +- Shell mode renders only the root route. + +Hydration adopts the semantic work produced by `true` and `data-only`; +`data-only` still requires client rendering, while `false` begins the unresolved +client suffix. Prefix adoption is governed by exact location and match identity, +not stale-time rules. The handoff rules are detailed below. + +Loaders start concurrently and retain parent match promises. Server failure +precedence follows the comparison above. The request-local lane awaits every +started loader before selecting the winner, aborts the trimmed suffix, and gives +a newly selected failure-boundary chunk one final attempt. + +Server projection runs only for `ssr: true` matches. Headers are response output +and are always awaited; a header failure is logged and non-fatal. Head and scripts +are decorative; their failure is logged and must not hang the request or +overwrite loader semantics. + +The final result is a closed union: either a render result with status and +matches, or a redirect. `loadServerRouter` is the only publisher of that result +to router stores. + +## Hydration handoff + +Hydration reconstructs what the server actually resolved; it does not rerun a +parallel hydration loader. + +For the current location, `hydrate`: + +1. matches a fresh candidate lane, +2. walks the serialized server matches while ids agree, +3. copies serialized loader/before-load/error/SSR data into a local resolved + prefix, +4. loads the chunks needed to hydrate that prefix, +5. rebuilds complete route contexts before running any head/script hook, +6. rebuilds client head/script projection and derives the presentation frontier, + and +7. after all asynchronous work and currentness checks, installs + `_committedMatches` and publishes the presentation frontier. + +The presentation frontier is the candidate prefix initially shown to the +renderer. The committed prefix includes server-resolved `true` and `data-only` +matches and excludes the first `ssr: false`, pending, or otherwise unresolved +match. The frontier may include that first unresolved match, or a pending clone +for `data-only`. For the initial handoff, committed `beforeLoad` and loader work +is authoritative and does not rerun; hydration rebuilds route context, chunks, +and client head/script output as required. + +If the whole location was resolved, hydration sets `resolvedLocation`. Otherwise +the framework Transitioner observes the unresolved location and starts an +ordinary client transaction. That transaction adopts the whole committed prefix +or none of it. Adoption requires the same canonical href and history key, exact +match ids at every committed index, and no invalidated match or development +refresh. A terminal adopted prefix also caps the candidate lane, so descendants +omitted below a server error/not-found boundary cannot execute on the client. +These checks derive `resolvedPrefix` from existing authorities; there is no +hydration-specific scheduler, flag, or completion authority. + +Candidate matching may already have invoked route `context`. After lazy options +are installed, hydration deliberately rebuilds context parent-first for the +accepted prefix and awaits each result before projection. Context functions must +therefore tolerate this hydration re-entry. Hydration also copies each serialized +SSR decision onto the route options so later client planning and framework +rendering observe the server's resolved mode. + +Unlike ordinary decorative projection, a non-not-found head/script failure +during hydration rejects hydration. A not-found is logged and attached to its +match. Preserve this call-site-specific policy. + +Hydration snapshots `_tx` and checks it after asynchronous user/chunk work. A +navigation that starts during hydration wins; stale hydration does not overwrite +it. + +Framework `Match` implementations combine the SSR mode with match presentation. +`ssr: false` and `data-only` content is behind `ClientOnly`, with the pending +component as fallback. Solid's hydration signal must also respect +`Solid.sharedConfig.context`; a process-global “already hydrated” value alone can +otherwise reveal client-only content during a later hydration root. + +## Development route refresh + +Route HMR is a development-only client transaction, not direct mutation of live +match state. + +The plugin preserves generated route options and component identity where Fast +Refresh requires it, installs new route options, rebuilds route indexes, syncs +the hot module's route export, clears the lazy owner and path cache, and calls +`router._refreshRoute(routeId)`. Core then: + +1. aborts and retires joinable flights, +2. clears cached match leases, +3. plans synchronously while refusing semantic reuse for the changed route and + its descendants, and +4. commits through the ordinary foreground transaction protocol without pending + presentation. + +Flight/cache retirement is deliberately global because old route code may own +work outside the visible subtree. Semantic rematerialization remains scoped to +the changed route and descendants; ancestors stay reusable. + +The reuse predicate is planner-local. HMR does not temporarily mutate +`_committedMatches`, reach into loader-flight internals from the plugin, or create +a separate refresh lane. `_refreshRoute` and its special planning path must remain +dead-code-eliminable from production builds. + +## Framework bootstrap + +Each Transitioner subscribes to history before deciding whether an initial load +is needed. It canonicalizes the current URL, then either emits the initial +`onRendered` for an already-resolved location or calls `router.load()` once. + +On a canonical mismatch, the adapter subscribes first, performs a replacing +`commitLocation`, and returns; the resulting history notification performs the +sole load. For an already-resolved location, the canonical parsed href and +history state key must agree before the adapter skips loading and emits +`onRendered`. The same href with a new key is a distinct history entry and must +not be mistaken for an already-rendered mount. + +React additionally guards the router/history pair across Strict Mode effect +replay and refreshes `latestLocation` from history before canonicalization. +Swapping routers or histories still installs the correct subscription and initial +load. Listener errors must not prevent cleanup or leave transition +acknowledgements unresolved. + +## Invariants to preserve + +When modifying this system, keep these invariants explicit: + +1. `stores.matches` never becomes a semantic planning base after + `_committedMatches` exists. +2. Only the current `_tx` may redirect foreground client navigation, commit its + lane, or publish its completion; only the current `PendingSession` owner may + finish that session. +3. `_preflight` can invalidate synchronous foreground planning but cannot + publish; preload planning uses its local controller and foreground-owner + snapshot. +4. A foreground lane's semantic result remains private until one atomic terminal + commit; pending is presentation only. +5. Parent route context is materialized first, and parent `beforeLoad` context is + complete before child `beforeLoad` or loader work. +6. Match id controls reuse; route id controls enter/stay/leave semantics. +7. Outcome ordering is structural, not promise-settlement ordering. +8. Pending UI is a flight-free presentation clone and never semantic authority. +9. Flight registry membership and flight lease ownership are different facts; + an accepted generation's lease and public signal may outlive promise + settlement. +10. Every discarded match releases its resources exactly once. +11. A shared preload result may donate successful work, not control or failure + authority. +12. Preloaded `beforeLoad` provenance is independent from loader-data provenance, + and its reuse is prefix-closed. +13. Background publication requires both current-writer identity and exact-base + identity. +14. Hydration builds its resolved prefix privately, publishes it only after + currentness checks, and delegates the remainder to the normal client + transaction. +15. Planning cancellation is not a lane failure; a current preload planning + error remains the caller's error. +16. Invalidation replaces semantic generation identity and reloads through the + normal foreground protocol. +17. Route lazy ownership is not a general component cache. +18. Runtime state is added only for a real authority or resource owner; phase + naming and impossible transitions belong in TypeScript whenever possible. + +## Testing changes + +Tests should assert user-visible behavior: rendered content, loader calls and +signals, documented public router state, navigation promises, lifecycle events, +HTTP status, headers, redirects, hydration output, and absence of stale +publication. Avoid asserting private phase names, tuple tags, timers, internal +promises, or the exact shape of `_`-prefixed fields. + +When boundary selection is the behavior under test, give root, parent, and child +boundaries distinct visible output. Assert output unique to the intended boundary +and the absence of broader/default boundary output. A generic `/Not Found/` or +`/Error/` assertion is insufficient. + +Useful category-level suites include: + +- `packages/router-core/tests/client-lane-adversarial.test.ts` and + `preflight-reentrant-context.test.ts` for ordering and reentrancy; plus + `fatal-load-rejection.test.ts`, `blocked-navigation-current-load.test.ts`, and + `superseded-load-await.test.ts` for planning, rollback, and waiter ownership, +- `preload-adoption.test.ts`, `preload-public-cache-behavior.test.ts`, and + `preload-background-parent-coherence.test.ts` for shared work and cache + publication, and `preload-beforeload-reuse.test.ts` for serial context + donation, +- `background-assets-stale.test.ts`, `background-trim-abort.test.ts`, and + `invalidate-pre-rematch-failure.test.ts` for identity-CAS publication, +- `preload-public-signal-lifetime.test.ts` and `stay-match-abort.test.ts` for + flight lease and accepted-generation signal lifetime, +- `hydration-currentness.test.ts`, `hydration-boundary-chunks.test.ts`, and the + framework hydration suites for the server/client frontier, +- `server-concurrent-error-notfound.test.ts`, + `server-chunk-failure-lifecycle.test.ts`, and the selective-SSR E2E suites for + server reduction, +- framework `store-updates-during-navigation.test.*`, pending-min, transitioner + acknowledgement, and transactional-loading suites for rendered behavior. + +Framework coverage should include canonicalization, exact href/key reuse, +same-href new-key navigation, unmounted catch-up, remount/Strict Mode, +router/history swaps, transition acknowledgement, and listener failures. The +relevant suites follow the `transitioner-*`, `on-rendered-*`, +`preloaded-mount-*`, and listener-error naming patterns. + +Run category suites while developing, then the affected core/framework unit and +type suites. Changes to client runtime paths must also run the production bundle +benchmarks. Development-only helpers, diagnostics, and HMR paths must be verified +as absent from production output. + +If a regression appears to require another flag, counter, copied deadline, or +completion authority, stop and identify which existing authority is ambiguous. +Fix the category at the architecture boundary rather than layering a local patch +onto one test. From da5cb82da9d3c0e901fc96a384f7408550f37c09 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Mon, 13 Jul 2026 18:23:02 +0200 Subject: [PATCH 09/59] fix: preload always releases its borrowed lease --- packages/router-core/src/load-client.ts | 2 +- .../preload-public-signal-lifetime.test.ts | 46 +++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/packages/router-core/src/load-client.ts b/packages/router-core/src/load-client.ts index 2636919de3..7292a6bfe4 100644 --- a/packages/router-core/src/load-client.ts +++ b/packages/router-core/src/load-client.ts @@ -1549,6 +1549,7 @@ export async function preloadClientRoute( throw cause } controller.abort() + discardMatchResources(router, matches) if (clientRouter._tx !== owner) { return } @@ -1565,7 +1566,6 @@ export async function preloadClientRoute( if (!isNotFound(cause)) { console.error(cause) } - discardMatchResources(router, matches) return } } diff --git a/packages/router-core/tests/preload-public-signal-lifetime.test.ts b/packages/router-core/tests/preload-public-signal-lifetime.test.ts index 5b48252bf8..f3678963c3 100644 --- a/packages/router-core/tests/preload-public-signal-lifetime.test.ts +++ b/packages/router-core/tests/preload-public-signal-lifetime.test.ts @@ -73,3 +73,49 @@ test('an adopted loader signal lives until public replacement and unload', async await router.navigate({ to: '/' }) expect(replacementSignal?.aborted).toBe(true) }) + +test('a superseded preload releases its borrowed loader signal lease', async () => { + const signals: Array = [] + let navigation!: Promise + + const rootRoute = new BaseRootRoute({}) + const homeRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: ({ abortController }) => { + signals.push(abortController.signal) + return 'parent data' + }, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + beforeLoad: ({ navigate, preload }) => { + if (preload) { + navigation = navigate({ to: '/' }) + throw navigation + } + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + homeRoute, + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/parent'] }), + }) + + await router.load() + const signal = signals[0] + expect(signal?.aborted).toBe(false) + + await router.preloadRoute({ to: '/parent/child' }) + await navigation + + expect(router.state.location.pathname).toBe('/') + expect(signal?.aborted).toBe(true) +}) From cc21be0de7b337dd1f97451bbfdca5aa931da9bb Mon Sep 17 00:00:00 2001 From: Sheraff Date: Tue, 14 Jul 2026 00:22:49 +0200 Subject: [PATCH 10/59] error priority handling --- packages/react-router/tests/router.test.tsx | 40 ++- packages/router-core/INTERNALS.md | 156 ++++++++---- packages/router-core/src/load-client.ts | 206 ++++++++------- packages/router-core/src/load-server.ts | 238 ++++++------------ .../tests/background-trim-abort.test.ts | 57 ++++- .../tests/client-lane-adversarial.test.ts | 2 +- packages/router-core/tests/load.test.ts | 19 +- ...rver-async-headers-decorative-hang.test.ts | 105 +++----- .../server-chunk-failure-lifecycle.test.ts | 40 ++- .../server-concurrent-error-notfound.test.ts | 197 ++++++--------- .../server-headers-asset-failure.test.ts | 107 -------- 11 files changed, 533 insertions(+), 634 deletions(-) delete mode 100644 packages/router-core/tests/server-headers-asset-failure.test.ts diff --git a/packages/react-router/tests/router.test.tsx b/packages/react-router/tests/router.test.tsx index 5cdd6d7dc0..e8e216b549 100644 --- a/packages/react-router/tests/router.test.tsx +++ b/packages/react-router/tests/router.test.tsx @@ -8,7 +8,11 @@ import { waitFor, } from '@testing-library/react' import { z } from 'zod' -import { composeRewrites, notFound } from '@tanstack/router-core' +import { + composeRewrites, + createControlledPromise, + notFound, +} from '@tanstack/router-core' import { Link, Outlet, @@ -2564,8 +2568,9 @@ describe('notFound in beforeLoad with pendingComponent', () => { expect(await screen.findByText(/Not Found/)).toBeInTheDocument() }) - it('renders notFound when async child beforeLoad throws and parent has an immediate pending component', async () => { + it('renders the parent notFound after showing pending UI for the child', async () => { const history = createMemoryHistory({ initialEntries: ['/'] }) + const beforeLoad = createControlledPromise() const rootRoute = createRootRoute({ component: () => , @@ -2587,10 +2592,6 @@ describe('notFound in beforeLoad with pendingComponent', () => { const parentRoute = createRoute({ getParentRoute: () => rootRoute, path: '/parent', - pendingMs: 0, - pendingComponent: () => ( -
Loading...
- ), component: () => (
Parent @@ -2605,8 +2606,12 @@ describe('notFound in beforeLoad with pendingComponent', () => { const childRoute = createRoute({ getParentRoute: () => parentRoute, path: '/child', + pendingMs: 0, + pendingComponent: () => ( +
Loading...
+ ), beforeLoad: async () => { - await new Promise((resolve) => setTimeout(resolve, 10)) + await beforeLoad throw notFound() }, component: () =>
Child
, @@ -2622,9 +2627,26 @@ describe('notFound in beforeLoad with pendingComponent', () => { expect(await screen.findByTestId('home-page')).toBeInTheDocument() - await act(() => router.navigate({ to: '/parent/child' })) + let navigation!: Promise + act(() => { + navigation = router.navigate({ to: '/parent/child' }) + }) - expect(await screen.findByText(/Not Found/)).toBeInTheDocument() + try { + expect(await screen.findByTestId('pending-component')).toHaveTextContent( + 'Loading...', + ) + } finally { + await act(async () => { + beforeLoad.resolve() + await navigation + }) + } + + expect(await screen.findByTestId('parent-not-found')).toHaveTextContent( + 'Parent Not Found', + ) + expect(screen.queryByTestId('root-not-found')).not.toBeInTheDocument() }) }) diff --git a/packages/router-core/INTERNALS.md b/packages/router-core/INTERNALS.md index 153d1b9763..cc05ae9555 100644 --- a/packages/router-core/INTERNALS.md +++ b/packages/router-core/INTERNALS.md @@ -19,8 +19,9 @@ The loader is built around these rules: 1. A foreground navigation builds a private lane. Only the current transaction may commit it, and presentation remains separate from accepted semantics. -2. Context is materialized serially from parent to child; independent loader and - chunk work runs concurrently, then reduces in structural route order. +2. Context is materialized serially from parent to child. Independent loader and + chunk work starts concurrently, while each parallel phase consumes results in + structural route order. 3. Shared work never grants publication authority. Losing work releases its resources and cannot publish after it becomes stale. 4. Runtime state exists only for a real ownership, publication, or completion @@ -40,7 +41,7 @@ Router.load lifecycle events -> install transaction and requested location -> serial beforeLoad contextualization -> concurrent loader and route-chunk work - -> structural reduction + -> phase-local reduction -> projection -> guarded foreground commit -> transition acknowledgement @@ -324,15 +325,16 @@ pending loader flight may still be shared while navigation runs its own serial `preload: false` does not suppress speculative `beforeLoad`: the hook still runs with `preload: true`, but its context is not donated. The loader is skipped and the match remains invalid, so navigation reruns `beforeLoad` and performs the -loader work. +loader work. Normal component and pending-component readiness may still run for +the preload. -After contextualization reaches its terminal prefix, task creation starts loader -and route-chunk work without awaiting siblings. Loaders therefore run -concurrently. Each task exposes three related milestones: +On the client, after contextualization reaches its terminal prefix, task +creation starts loader and route-chunk work without awaiting siblings. Loaders +therefore run concurrently. Each client task exposes three related milestones: - `outcome`: the semantic loader result, - `ready`: a successful outcome plus the route's render chunk readiness, and -- `match`: the parent-facing match promise; the server resolves it to a snapshot. +- `match`: the parent-facing match promise. Separating `outcome` from `ready` is essential. A redirect or error can win without waiting for irrelevant successful descendant chunks, while a successful @@ -346,36 +348,58 @@ of it, under the href/key/id/currentness checks described below. Joinable work already attached to an adopted prefix is still accounted for, and projection may restart at its retained terminal match. -## Ordered reduction and failure boundaries +## Phase-local reduction and failure boundaries -Although work runs concurrently, reduction consumes it in structural route -order. The reducer: +Failure selection deliberately follows execution phases instead of running a +global comparator over every possible boundary. The client and server use the +same small reduction policy: -1. recognizes redirect/cancel control outcomes, -2. selects the terminal error or not-found outcome, -3. checks relevant successful route chunks in route order, -4. loads the component required by the selected terminal match, -5. trims descendants beyond the semantic cutoff, and -6. releases resources owned by the trimmed suffix. +1. Param/search validation and `beforeLoad` run serially. The first terminal + outcome stops contextualization. Route `context` ran earlier during planning; + if it throws, no lane exists and the planning-failure rules apply. +2. Loaders for the permitted ancestor prefix have already started concurrently. + Their promises are consumed from root to leaf. The first ordinary error or + not-found fills one loader-failure slot; redirect/cancel is kept separately as + control flow. +3. Control flow wins. Otherwise the loader-failure slot wins, falling back to + the serial failure when loaders succeeded. +4. The selected outcome determines one semantic cutoff. Only successful normal + chunks needed before that cutoff are considered, again in route order. The + first relevant chunk failure replaces the selected failure; if that failure + is a redirect, it becomes control flow. +5. Core applies the result once, trims once, and attempts the selected terminal + component once. Terminal-component preload is best-effort: rejection is + swallowed, does not call route `onError`, and does not restart selection. +6. Projection runs after semantic reduction and cannot replace its result. -Errors take precedence over not-found outcomes on the client when both are -present. An ordinary error marks the throwing match and trims its descendants; -the framework's nested catch boundaries may ultimately render a parent, default, -or root error component. A not-found outcome is instead assigned to the nearest -eligible ancestor not-found match before trimming. The semantic cutoff and the -component that visibly handles a failure are therefore related but not -identical. A global root not-found remains a successful root match marked +An ordinary serial failure still permits loaders above its effective boundary to +run, so the terminal render keeps the ancestor data it is allowed to expose. A +serial redirect/cancel starts no loader work. + +“First” inside a concurrent phase means structural route order, not promise +settlement timing. There is no error-over-not-found priority, render-boundary +ranking, sorting, or convergence loop. Consumption stops at the first structural +redirect/cancel; already-started later work may settle, but it is not considered +for this lane. + +An ordinary error marks its throwing match and trims descendants. The +framework's nested catch boundaries may ultimately render a parent, default, or +root error component. A not-found is assigned to the nearest eligible ancestor +not-found match before trimming. Its throwing route and terminal match may +therefore differ. A global root not-found remains a successful root match marked `globalNotFound`, because the root shell still renders while presenting the global not-found result. -Control outcomes take precedence over error and not-found outcomes regardless of -relative route depth. After that, client and server selection deliberately -differ: +The server uses redirect control flow and `skipped` for `ssr: false`; the client +also has cancellation control flow. Those representation differences do not +change the failure-selection policy. -| Environment | Selection rule | -| ----------- | ----------------------------------------------------------------------------------------------------------------------------- | -| Client | Redirect/cancel is control flow. Otherwise any ordinary error wins over not-found, with route order selecting within a kind. | -| Server | Redirect wins. Otherwise the structurally earliest render boundary wins, with ordinary error winning a tie against not-found. | +A `globalNotFound` assigned while matching is planned presentation metadata, not +a thrown lane outcome. The client retains the planned lane and the framework +stops rendering below the marked boundary. The server caps and trims its +request-local lane at that boundary before rendering the 404. Do not feed this +case into the thrown-outcome reducer merely to make the two storage shapes look +identical. Redirect and cancellation outcomes never become committed match states. Internal redirects are followed by a replacement navigation. Redirect depth is inherited @@ -385,9 +409,12 @@ redirect successor to inherit the count; an unrelated superseding navigation must not inherit it. The count clears when a semantic lane completes without redirecting. -Projection runs only after reduction, so head/scripts see the final lane and -loader data. Client projection failures are decorative: they are logged without -replacing a semantic loader result. +Projection runs only after reduction, so head/scripts/headers see the final lane +and loader data. Projection hooks for one route start together. Their results are +applied only if that group resolves; a rejection is logged and swallowed without +replacing the semantic result. Discarding a failed group means applying no new +projection output; reused matches may retain output from their previous +generation. ## Foreground transaction lifecycle @@ -454,19 +481,22 @@ Client lifecycle ordering is part of the protocol: then emits `onRendered` only when the framework confirmed that the publication rendered. -Listeners may start another navigation. Currentness is checked again while -emitting lifecycle events: a route callback suppresses stale `onLoad`, and an +Listeners may start another navigation. Currentness is checked while emitting +the pre-mount lifecycle: a route callback suppresses stale `onLoad`, and an `onLoad` listener that supersedes the writer suppresses stale -`onBeforeRouteMount`, `onResolved`, and `onRendered`. Listener exceptions are +`onBeforeRouteMount` and later completion publication. Listener exceptions are isolated and do not stop later listeners or leave acknowledgement cleanup unfinished. ## Pending presentation and renderer acknowledgement Pending UI is a projection of an in-progress transaction, never a semantic lane. -`renderPending` publishes a prefix ending at the selected pending boundary. It -clones that boundary, changes only its presentation status to `pending`, and -removes `_flight` so a rendered clone cannot accidentally own loader work. +`renderPending` publishes a cloned prefix ending at the selected pending +boundary. Every visible match is a snapshot with `_flight` removed, and only the +terminal snapshot changes status to `pending`. Presentation therefore never +shares a mutable match object with the private writer lane. A later failure may +bubble to a visible ancestor without mutating the pending UI in place or being +hidden from fine-grained match stores by unchanged object identity. The boundary is the shallowest non-success match, or the shallowest successful match already visibly presented as pending. If that boundary has no route or @@ -632,6 +662,15 @@ handoff. Losing background candidates release their resources. Background publication updates matches through the normal publication primitive rather than inventing a second commit protocol. +A background lane intentionally has mixed ownership. Reload task indexes contain +private candidates, while untouched indexes still reference the committed base. +An ordinary failure can mutate its private candidate directly. If a not-found +bubbles to an untouched ancestor, reduction first clones that boundary and +removes `_flight`; the committed generation retains its object and lease until +the guarded publication succeeds. Trimming a background lane likewise leaves +shared suffix resources alone. The final transfer or discard of the background +batch is the single resource authority. + Background publication replaces an already-resolved presentation directly. It does not enter the pending/renderer-acknowledgement protocol, change `stores.status` or `resolvedLocation`, or emit foreground navigation lifecycle @@ -661,9 +700,10 @@ background-specific cancellation flag. Normal successful readiness loads the route component and pending component. Error and not-found component preloads are requested only for the semantic terminal match selected by reduction. A framework may still bubble an ordinary -error to a visibly different ancestor catch boundary. Client chunk work begins -alongside loader work, but a normal chunk failure is semantically considered only -when its loader outcome succeeds. +error to a visibly different ancestor catch boundary. Terminal-component +preloading is best-effort; failure is swallowed because semantic selection has +already finished. Client chunk work begins alongside loader work, but a normal +chunk failure is semantically considered only when its loader outcome succeeds. `route._lazy` has three compact states: @@ -691,7 +731,9 @@ uses a separate typed lane with the same high-level ordering: ```text match -> resolve SSR + contextualize serially -> run loaders concurrently - -> reduce -> load selected chunks -> project -> render or redirect + -> select serial/loader result -> load normal chunks before its cutoff + -> apply and trim once -> preload terminal component once + -> project -> render or redirect ``` SSR policy is resolved parent-first before each route's `beforeLoad`: @@ -706,20 +748,27 @@ SSR policy is resolved parent-first before each route's `beforeLoad`: `true` descendant at `data-only`, whether explicit, computed, or inherited. - Shell mode renders only the root route. +If an `ssr` callback throws, the server normalizes it through that route's +`onError`, records it as the serial failure for the route, and stops serial +descent just like a `beforeLoad` failure. + Hydration adopts the semantic work produced by `true` and `data-only`; `data-only` still requires client rendering, while `false` begins the unresolved client suffix. Prefix adoption is governed by exact location and match identity, not stale-time rules. The handoff rules are detailed below. -Loaders start concurrently and retain parent match promises. Server failure -precedence follows the comparison above. The request-local lane awaits every -started loader before selecting the winner, aborts the trimmed suffix, and gives -a newly selected failure-boundary chunk one final attempt. +Loaders start concurrently and retain parent match promises. The request-local +lane consumes their outcomes in route order, keeping redirect as control flow and +the first ordinary error/not-found as its loader failure. Only after loader +selection does the server start normal route-chunk work concurrently for the +permitted prefix and consume those results in route order. It applies and trims +once, then attempts the terminal component once. For a planned global 404, the +server preloads both the normal shell and not-found component at the boundary. -Server projection runs only for `ssr: true` matches. Headers are response output -and are always awaited; a header failure is logged and non-fatal. Head and scripts -are decorative; their failure is logged and must not hang the request or -overwrite loader semantics. +Server projection runs only for `ssr: true` matches. Head, scripts, and headers +start together for each route. If any rejects, the rejection is logged and the +route's projection group is discarded; projection failure is non-fatal and never +overwrites loader semantics. The final result is a closed union: either a render result with status and matches, or a redirect. `loadServerRouter` is the only publisher of that result @@ -844,7 +893,8 @@ When modifying this system, keep these invariants explicit: 5. Parent route context is materialized first, and parent `beforeLoad` context is complete before child `beforeLoad` or loader work. 6. Match id controls reuse; route id controls enter/stay/leave semantics. -7. Outcome ordering is structural, not promise-settlement ordering. +7. Concurrent loader and normal-chunk selection is structural, not + promise-settlement ordering. 8. Pending UI is a flight-free presentation clone and never semantic authority. 9. Flight registry membership and flight lease ownership are different facts; an accepted generation's lease and public signal may outlive promise diff --git a/packages/router-core/src/load-client.ts b/packages/router-core/src/load-client.ts index 7292a6bfe4..465aab6212 100644 --- a/packages/router-core/src/load-client.ts +++ b/packages/router-core/src/load-client.ts @@ -37,6 +37,7 @@ export type ProjectedLane = Lane<'projected'> const success = 0 const error = 1 const notFound = 2 +// Control outcomes stay contiguous so the hot path can test them together. const redirected = 3 const canceled = 4 @@ -601,7 +602,7 @@ function createTask( const chunkFailure = Promise.resolve() .then(() => loadRouteChunk(route)) .then( - (): IndexedOutcome | undefined => undefined, + () => undefined, (cause): IndexedOutcome => [index, normalizeError(route, cause)], ) const ready = outcome @@ -620,10 +621,10 @@ function createTask( if (!background) { return task.match } - const candidate = { + const candidate: WorkMatch = { ...match, _flight: undefined, - } as WorkMatch + } const backgroundOutcome = loadResource( router, workerRouter, @@ -678,36 +679,66 @@ async function reduceLane( options: ExecuteLaneOptions, serialFailure?: IndexedOutcome, ): Promise { + // Background reductions do not compare against the committed lane. + const background = !options.base let control = - serialFailure?.[1][0] === redirected || serialFailure?.[1][0] === canceled - ? serialFailure - : undefined - let firstError = serialFailure?.[1][0] === error ? serialFailure : undefined - let firstNotFound = - serialFailure?.[1][0] === notFound ? serialFailure : undefined + (serialFailure?.[1][0] ?? 0) >= redirected ? serialFailure : undefined + let loaderFailure: IndexedOutcome | undefined for (let index = 0; index < tasks.length; index++) { const task = tasks[index]! - const taskIndex = (task as BackgroundTask).index ?? index const outcome = await task.outcome - if (outcome[0] === redirected || outcome[0] === canceled) { + const taskIndex = (task as BackgroundTask).index ?? index + if (outcome[0] >= redirected) { control = [taskIndex, outcome] break } - if (outcome[0] === error && (!firstError || taskIndex < firstError[0])) { - firstError = [taskIndex, outcome] - } else if ( - outcome[0] === notFound && - (!firstNotFound || taskIndex < firstNotFound[0]) - ) { - firstNotFound = [taskIndex, outcome] + if (outcome[0] !== success) { + loaderFailure ||= [taskIndex, outcome] } } - if (control?.[1][0] === redirected && !control[1][1].options.reloadDocument) { - if ((options.redirects ?? 0) >= 20) { - firstError = [control[0], [error, new Error('Redirect cycle detected')]] - control = undefined + let failure = loaderFailure ?? serialFailure + + if ( + control?.[1][0] === redirected && + !control[1][1].options.reloadDocument && + (options.redirects ?? 0) >= 20 + ) { + failure = [control[0], [error, new Error('Redirect cycle detected')]] + control = undefined + } + + if (!control) { + const readinessEnd = failure + ? failure[1][0] === notFound + ? getNotFoundBoundary(router, lane.matches, failure) + : failure[0] + : lane.matches.length + for (let index = 0; index < tasks.length; index++) { + const task = tasks[index]! + if (((task as BackgroundTask).index ?? index) >= readinessEnd) { + break + } + const chunkFailure = await task.ready + if (chunkFailure) { + if (chunkFailure[1][0] === redirected) { + if ( + !chunkFailure[1][1].options.reloadDocument && + (options.redirects ?? 0) >= 20 + ) { + failure = [ + chunkFailure[0], + [error, new Error('Redirect cycle detected')], + ] + } else { + control = chunkFailure + } + } else { + failure = chunkFailure + } + break + } } } @@ -722,51 +753,42 @@ async function reduceLane( return control[1] as ControlOutcome } - const failure = firstError ?? firstNotFound - const readinessEnd = failure?.[0] ?? lane.matches.length - for (let index = 0; index < tasks.length; index++) { - const task = tasks[index]! - if (((task as BackgroundTask).index ?? index) >= readinessEnd) { - break + if (failure) { + const [index, outcome] = failure + const kind = outcome[0] + const boundary = + kind === notFound + ? getNotFoundBoundary(router, lane.matches, failure) + : index + let match = lane.matches[boundary]! + if ( + background && + !(tasks as Array).some((task) => task.index === boundary) + ) { + match = lane.matches[boundary] = { ...match, _flight: undefined } } - const chunkFailure = await task.ready - if (chunkFailure) { - firstError = chunkFailure - break - } - } - - if (firstError) { - const [index, outcome] = firstError - const match = lane.matches[index]! - match.status = 'error' - match.error = outcome[1] - match.isFetching = false - try { - await loadRouteChunk(getRoute(router, match), 'errorComponent') - } catch {} - trimLane(router, lane, index + 1) - return lane as ReducedLane - } - - if (failure?.[1][0] === notFound) { - const boundary = getNotFoundBoundary(router, lane.matches, failure) - const match = lane.matches[boundary]! - const cause = failure[1][1] - cause.routeId = match.routeId - if (match.routeId === router.routeTree.id) { - match.status = 'success' - match.globalNotFound = true - match.error = cause + const cause = outcome[1] + match.globalNotFound = undefined + if (kind === error) { + match.status = 'error' } else { - match.status = 'notFound' - match.error = cause + ;(cause as NotFoundError).routeId = match.routeId + if (match.routeId === router.routeTree.id) { + match.status = 'success' + match.globalNotFound = true + } else { + match.status = 'notFound' + } } + match.error = cause match.isFetching = false try { - await loadRouteChunk(getRoute(router, match), 'notFoundComponent') + await loadRouteChunk( + getRoute(router, match), + kind === error ? 'errorComponent' : 'notFoundComponent', + ) } catch {} - trimLane(router, lane, boundary + 1) + trimLane(router, lane, boundary + 1, background) return lane as ReducedLane } @@ -777,10 +799,13 @@ function trimLane( router: ClientRouter, lane: ContextualizedLane, length: number, + background: boolean, ): void { - discardMatchResources(router as AnyRouter, lane.matches.slice(length)) + if (!background) { + discardMatchResources(router as AnyRouter, lane.matches.slice(length)) + } lane.matches.length = length - if (!lane.background) { + if (!lane.background || background) { return } let write = 0 @@ -801,29 +826,28 @@ async function projectLane( ): Promise { for (let index = start; index < lane.matches.length; index++) { const match = lane.matches[index]! - const route = getRoute(router, match) - if (!route.options.head && !route.options.scripts) { - continue - } - try { - const context = { - ssr: router.options.ssr, - matches: lane.matches, - match, - params: match.params, - loaderData: match.loaderData, + const routeOptions = getRoute(router, match).options + if (routeOptions.head || routeOptions.scripts) { + try { + const context = { + ssr: router.options.ssr, + matches: lane.matches, + match, + params: match.params, + loaderData: match.loaderData, + } + const [head, scripts] = await Promise.all([ + routeOptions.head?.(context), + routeOptions.scripts?.(context), + ]) + match.meta = head?.meta + match.links = head?.links + match.headScripts = head?.scripts + match.styles = head?.styles + match.scripts = scripts + } catch (cause) { + console.error(cause) } - const [head, scripts] = await Promise.all([ - route.options.head?.(context), - route.options.scripts?.(context), - ]) - match.meta = head?.meta - match.links = head?.links - match.headScripts = head?.scripts - match.styles = head?.styles - match.scripts = scripts - } catch (cause) { - console.error(`Error executing head for route ${route.id}:`, cause) } } return lane as ProjectedLane @@ -861,7 +885,7 @@ export async function executeClientLane( end, getNotFoundBoundary(workerRouter, contextualized.matches, failure) + 1, ) - } else if (failure?.[1][0] === redirected || failure?.[1][0] === canceled) { + } else if ((failure?.[1][0] ?? 0) >= redirected) { end = 0 } for (let index = 0; index < end; index++) { @@ -938,12 +962,10 @@ function renderPending( tx: LoadTransaction, boundary: number, ): Promise { - const offered = tx.matches.slice(0, boundary + 1) as Array - offered[boundary] = { - ...offered[boundary]!, - _flight: undefined, - status: 'pending', - } + const offered = tx.matches + .slice(0, boundary + 1) + .map((match) => ({ ...match, _flight: undefined })) + offered[boundary]!.status = 'pending' return router.startTransition(() => { router.stores.setMatches(offered) }) diff --git a/packages/router-core/src/load-server.ts b/packages/router-core/src/load-server.ts index 3e3fcffedc..341eef28c1 100644 --- a/packages/router-core/src/load-server.ts +++ b/packages/router-core/src/load-server.ts @@ -386,35 +386,6 @@ function getNotFoundBoundary( return cause.routeId ? index : 0 } -function chooseFailure( - router: ServerWorker, - matches: Array, - outcomes: Array, -): IndexedOutcome | undefined { - let winner: IndexedOutcome | undefined - let winnerBoundary = Infinity - for (const indexed of outcomes) { - const kind = indexed[1][0] - if (kind === redirected) { - return indexed - } - const boundary = - kind === notFound - ? getNotFoundBoundary(router, matches, indexed) - : indexed[0] - if ( - boundary < winnerBoundary || - (boundary === winnerBoundary && - kind === error && - winner?.[1][0] === notFound) - ) { - winner = indexed - winnerBoundary = boundary - } - } - return winner -} - function abortMatches(matches: Array, start = 0): void { for (let index = start; index < matches.length; index++) { matches[index]!.abortController.abort() @@ -448,6 +419,7 @@ function applyFailure( const [index, outcome] = indexed if (outcome[0] === error) { const match = lane.matches[index]! + match.globalNotFound = undefined match.status = 'error' match.error = outcome[1] match.isFetching = false @@ -460,6 +432,7 @@ function applyFailure( const match = lane.matches[boundary]! const cause = outcome[1] as NotFoundError cause.routeId = match.routeId + match.globalNotFound = undefined if (match.routeId === router.routeTree.id) { match.status = 'success' match.globalNotFound = true @@ -474,75 +447,41 @@ function applyFailure( return { status: 404, boundary, kind: notFound } } -async function loadSelectedChunks( +async function loadNormalChunks( router: ServerWorker, lane: ContextualizedLane, - terminal: ReturnType, -): Promise> { + end: number, +): Promise { const chunks = lane.matches.map(async (match, index) => { - if (match.ssr !== true) { + if (index >= end || match.ssr !== true || match.status !== 'success') { return undefined } const route = getRoute(router, match) try { - if (terminal.boundary === index && terminal.kind === error) { - await loadRouteChunk(route, 'errorComponent') - } else if (terminal.boundary === index && terminal.kind === notFound) { - if (match.globalNotFound) { - await Promise.all([ - loadRouteChunk(route), - loadRouteChunk(route, 'notFoundComponent'), - ]) - } else { - await loadRouteChunk(route, 'notFoundComponent') - } - } else { - await loadRouteChunk(route) - } - return undefined + await loadRouteChunk(route) } catch (cause) { - return [index, stampNotFound(match, normalizeError(route, cause))] as - | IndexedOutcome - | undefined + return [ + index, + stampNotFound(match, normalizeError(route, cause)), + ] as IndexedOutcome } + return undefined }) - const settled = await Promise.all(chunks) - return settled.filter(Boolean) as Array -} - -async function ensureFailureChunk( - router: ServerWorker, - lane: ContextualizedLane, - terminal: ReturnType, -): Promise { - if (terminal.boundary === undefined || terminal.kind === undefined) { - return - } - const match = lane.matches[terminal.boundary]! - if (match.ssr !== true) { - return - } - const route = getRoute(router, match) - try { - await loadRouteChunk( - route, - terminal.kind === error ? 'errorComponent' : 'notFoundComponent', - ) - return - } catch (cause) { - return [ - terminal.boundary, - stampNotFound(match, normalizeError(route, cause)), - ] + for (const chunk of chunks) { + const indexed = await chunk + if (indexed) { + return indexed + } } + return undefined } async function project(router: ServerWorker, lane: ReducedLane): Promise { for (const match of lane.matches) { - const route = getRoute(router, match) + const routeOptions = getRoute(router, match).options if ( match.ssr !== true || - (!route.options.head && !route.options.scripts && !route.options.headers) + (!routeOptions.head && !routeOptions.scripts && !routeOptions.headers) ) { continue } @@ -553,66 +492,21 @@ async function project(router: ServerWorker, lane: ReducedLane): Promise { params: match.params, loaderData: match.loaderData, } - let closed = false - let failAssets!: () => void - const assetFailure = new Promise((resolve) => { - failAssets = resolve - }) - const run = ( - fn: ((context: any) => any) | undefined, - commit: (value: any) => void, - decorative: boolean, - ) => { - let value: unknown - try { - value = fn?.(context) - } catch (cause) { - console.error(`Error executing route asset for ${route.id}:`, cause) - if (decorative) { - failAssets() - } - return Promise.resolve() - } - return Promise.resolve(value).then( - (result) => { - if (!closed) { - commit(result) - } - }, - (cause) => { - console.error(`Error executing route asset for ${route.id}:`, cause) - if (decorative) { - failAssets() - } - }, - ) + try { + const [head, scripts, headers] = await Promise.all([ + routeOptions.head?.(context), + routeOptions.scripts?.(context), + routeOptions.headers?.(context), + ]) + match.meta = head?.meta + match.links = head?.links + match.headScripts = head?.scripts + match.styles = head?.styles + match.scripts = scripts + match.headers = headers + } catch (cause) { + console.error(cause) } - const head = run( - route.options.head, - (value) => { - match.meta = value?.meta - match.links = value?.links - match.headScripts = value?.scripts - match.styles = value?.styles - }, - true, - ) - const scripts = run( - route.options.scripts, - (value) => { - match.scripts = value - }, - true, - ) - await run( - route.options.headers, - (value) => { - match.headers = value - }, - false, - ) - await Promise.race([Promise.all([head, scripts]), assetFailure]) - closed = true } } @@ -651,7 +545,8 @@ export async function loadServer( tasks.push(task) } - const outcomes = lane.failure ? [lane.failure] : [] + let loaderFailure: IndexedOutcome | undefined + let control = lane.failure?.[1][0] === redirected ? lane.failure : undefined for (const task of tasks) { const outcome = await task.outcome if (outcome[0] === success) { @@ -662,35 +557,56 @@ export async function loadServer( match.invalid = false match.isFetching = false match.updatedAt = Date.now() + } else if (outcome[0] === redirected) { + control = [task.index, outcome] + break } else if (outcome[0] !== skipped) { - outcomes.push([task.index, outcome]) + loaderFailure ??= [task.index, outcome] } } - let failure = chooseFailure(worker, lane.matches, outcomes) - if (failure?.[1][0] === redirected) { + if (control?.[1][0] === redirected) { abortMatches(lane.matches) - return resolveServerRedirect(worker, location, failure[1][1]) + return resolveServerRedirect(worker, location, control[1][1]) } - let terminal = applyFailure(worker, lane, failure) - const chunkOutcomes = await loadSelectedChunks(worker, lane, terminal) - if (chunkOutcomes.length) { - failure = chooseFailure(worker, lane.matches, [ - ...outcomes, - ...chunkOutcomes, - ]) - if (failure?.[1][0] === redirected) { + let failure = loaderFailure ?? lane.failure + const plannedBoundary = lane.matches.findIndex( + (match) => match.globalNotFound, + ) + const readinessEnd = failure + ? failure[1][0] === notFound + ? getNotFoundBoundary(worker, lane.matches, failure) + : failure[0] + : plannedBoundary < 0 + ? lane.matches.length + : plannedBoundary + const chunkFailure = await loadNormalChunks(worker, lane, readinessEnd) + if (chunkFailure) { + if (chunkFailure[1][0] === redirected) { abortMatches(lane.matches) - return resolveServerRedirect(worker, location, failure[1][1]) + return resolveServerRedirect(worker, location, chunkFailure[1][1]) } - terminal = applyFailure(worker, lane, failure) - const boundaryFailure = await ensureFailureChunk(worker, lane, terminal) - if (boundaryFailure?.[1][0] === redirected) { - abortMatches(lane.matches) - return resolveServerRedirect(worker, location, boundaryFailure[1][1]) - } else if (boundaryFailure) { - terminal = applyFailure(worker, lane, boundaryFailure) + failure = chunkFailure + } + + const terminal = applyFailure(worker, lane, failure) + if (terminal.boundary !== undefined) { + const match = lane.matches[terminal.boundary]! + if (match.ssr === true) { + const route = getRoute(worker, match) + try { + if (terminal.kind === error) { + await loadRouteChunk(route, 'errorComponent') + } else if (match.globalNotFound) { + await Promise.all([ + loadRouteChunk(route), + loadRouteChunk(route, 'notFoundComponent'), + ]) + } else { + await loadRouteChunk(route, 'notFoundComponent') + } + } catch {} } } diff --git a/packages/router-core/tests/background-trim-abort.test.ts b/packages/router-core/tests/background-trim-abort.test.ts index a4f506410b..b680460120 100644 --- a/packages/router-core/tests/background-trim-abort.test.ts +++ b/packages/router-core/tests/background-trim-abort.test.ts @@ -1,6 +1,11 @@ import { expect, test, vi } from 'vitest' import { createMemoryHistory } from '@tanstack/history' -import { BaseRootRoute, BaseRoute } from '../src' +import { + BaseRootRoute, + BaseRoute, + createControlledPromise, + notFound, +} from '../src' import { createTestRouter } from './routerTestUtils' test('background error trimming aborts a discarded descendant loader signal', async () => { @@ -54,6 +59,56 @@ test('background error trimming aborts a discarded descendant loader signal', as expect(discardedChildSignal?.aborted).toBe(true) }) +test('a background notFound stays private until its parent boundary is ready', async () => { + const boundaryReady = createControlledPromise() + const ParentNotFound = Object.assign(() => null, { + preload: () => boundaryReady, + }) + let childLoads = 0 + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + notFoundComponent: ParentNotFound, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: () => { + if (++childLoads > 1) { + throw notFound() + } + return 'initial child data' + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + }) + + await router.load() + await router.invalidate({ + filter: (match) => match.routeId === childRoute.id, + }) + await vi.waitFor(() => expect(childLoads).toBe(2)) + + expect(router.state.matches.map((match) => match.status)).toEqual([ + 'success', + 'success', + 'success', + ]) + + boundaryReady.resolve() + await vi.waitFor(() => { + expect(router.state.matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + parentRoute.id, + ]) + expect(router.state.matches.at(-1)?.status).toBe('notFound') + }) +}) + test('foreground supersession aborts every loader in a background batch', async () => { let parentLoads = 0 let childLoads = 0 diff --git a/packages/router-core/tests/client-lane-adversarial.test.ts b/packages/router-core/tests/client-lane-adversarial.test.ts index 5f2413e0f5..d84fad1c57 100644 --- a/packages/router-core/tests/client-lane-adversarial.test.ts +++ b/packages/router-core/tests/client-lane-adversarial.test.ts @@ -121,7 +121,7 @@ describe('adversarial client lane ownership', () => { expect(cOnEnter).toHaveBeenCalledTimes(1) }) - test('a shallow regular error wins over a deeper concurrent notFound', async () => { + test('commits a failing parent loader without projecting its trimmed child', async () => { const parentError = new Error('parent failed') const childHead = vi.fn(() => ({ meta: [{ title: 'unreachable child' }], diff --git a/packages/router-core/tests/load.test.ts b/packages/router-core/tests/load.test.ts index 17c059a67c..e569b8de00 100644 --- a/packages/router-core/tests/load.test.ts +++ b/packages/router-core/tests/load.test.ts @@ -1340,7 +1340,7 @@ describe('head execution', () => { name: string throwAtIndex: ThrowAtIndex parentFailures: ParentFailureMap - expectedErrorKind: 'notFound' | 'redirect' | 'error' + expectedErrorKind: 'notFound' | 'redirect' expectedErrorSource?: string expectedBoundaryIndex?: 0 | 1 | 2 | 3 expectedHeadTitles: Array @@ -1538,13 +1538,13 @@ describe('head execution', () => { expectedHeadTitles: ['Root'], }, { - name: 'propagates regular loader error when mixed with loader notFound in settled loaders', + name: 'keeps the first loader notFound when a later loader errors', throwAtIndex: 3 as const, parentFailures: { 1: 'notFound', 2: 'error' } as ParentFailureMap, - expectedErrorKind: 'error' as const, - expectedErrorSource: 'loader-2-error', - expectedBoundaryIndex: 2, - expectedHeadTitles: ['Root', 'Level 1', 'Level 2'], + expectedErrorKind: 'notFound' as const, + expectedErrorSource: 'loader-1', + expectedBoundaryIndex: 1, + expectedHeadTitles: ['Root', 'Level 1'], }, ] satisfies Array @@ -1572,12 +1572,7 @@ describe('head execution', () => { routes[scenario.expectedBoundaryIndex!]!.id, ) - if (scenario.expectedErrorKind === 'error') { - expect(boundary.status).toBe('error') - expect((boundary.error as Error).message).toBe( - scenario.expectedErrorSource, - ) - } else if (scenario.expectedBoundaryIndex === 0) { + if (scenario.expectedBoundaryIndex === 0) { expect(boundary.status).toBe('success') expect(boundary.globalNotFound).toBe(true) } else { diff --git a/packages/router-core/tests/server-async-headers-decorative-hang.test.ts b/packages/router-core/tests/server-async-headers-decorative-hang.test.ts index bc7797c515..ea514a4e7a 100644 --- a/packages/router-core/tests/server-async-headers-decorative-hang.test.ts +++ b/packages/router-core/tests/server-async-headers-decorative-hang.test.ts @@ -1,82 +1,37 @@ -import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' +import { expect, test, vi } from 'vitest' import { createMemoryHistory } from '@tanstack/history' -import { BaseRootRoute, BaseRoute, createControlledPromise } from '../src' +import { BaseRootRoute, BaseRoute } from '../src' import { createTestRouter, loadServerResponse } from './routerTestUtils' -/** - * Headers affect the HTTP response, so server loading must await them even - * after another asset hook fails synchronously. That does not make an - * unrelated decorative head promise response-significant: once headers have - * settled, a never-ending head must not hold the response open. - */ -describe('server async headers after a decorative asset failure', () => { - beforeEach(() => { - vi.useFakeTimers() - vi.spyOn(console, 'error').mockImplementation(() => {}) +test('a rejected projection hook is logged without failing the response', async () => { + const projectionError = new Error('scripts failed') + const log = vi.spyOn(console, 'error').mockImplementation(() => {}) + const head = vi.fn(() => ({ meta: [{ title: 'discarded' }] })) + const scripts = vi.fn(async () => { + throw projectionError + }) + const headers = vi.fn(() => ({ 'x-response-header': 'discarded' })) + + const rootRoute = new BaseRootRoute({}) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + head, + scripts, + headers, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([targetRoute]), + history: createMemoryHistory({ initialEntries: ['/target'] }), + isServer: true, }) - afterEach(() => { - vi.useRealTimers() - vi.restoreAllMocks() - }) + const response = await loadServerResponse(router, '/target') - test('commits async headers without waiting for a pending head', async () => { - const expectedHeaders = { 'x-response-header': 'kept' } - const headGate = createControlledPromise<{ - meta: Array<{ title: string }> - }>() - const headersGate = createControlledPromise() - const head = vi.fn(() => headGate) - const scripts = vi.fn(() => { - throw new Error('scripts failed synchronously') - }) - const headers = vi.fn(() => headersGate) - - const rootRoute = new BaseRootRoute({}) - const targetRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/target', - head, - scripts, - headers, - }) - const router = createTestRouter({ - routeTree: rootRoute.addChildren([targetRoute]), - history: createMemoryHistory({ initialEntries: ['/target'] }), - isServer: true, - }) - - const loadPromise = loadServerResponse(router, '/target') - await vi.waitFor(() => { - expect(head).toHaveBeenCalledTimes(1) - expect(scripts).toHaveBeenCalledTimes(1) - expect(headers).toHaveBeenCalledTimes(1) - }) - - headersGate.resolve(expectedHeaders) - - const winnerPromise = Promise.race([ - loadPromise.then(() => 'loaded' as const), - new Promise<'timed-out'>((resolve) => { - setTimeout(() => resolve('timed-out'), 50) - }), - ]) - await vi.advanceTimersByTimeAsync(0) - await vi.advanceTimersByTimeAsync(50) - const winner = await winnerPromise - - // Cleanup happens only after recording the bounded result. On the broken - // path this releases router.load(), but cannot change `winner`. - headGate.resolve({ meta: [{ title: 'late decorative title' }] }) - await loadPromise - - const response = await loadPromise - expect({ - winner, - header: response.headers.get('x-response-header'), - }).toEqual({ - winner: 'loaded', - header: 'kept', - }) - }) + expect(response.status).toBe(200) + expect(response.headers.get('x-response-header')).toBeNull() + expect(head).toHaveBeenCalledTimes(1) + expect(scripts).toHaveBeenCalledTimes(1) + expect(headers).toHaveBeenCalledTimes(1) + expect(log).toHaveBeenCalledWith(projectionError) }) diff --git a/packages/router-core/tests/server-chunk-failure-lifecycle.test.ts b/packages/router-core/tests/server-chunk-failure-lifecycle.test.ts index c5b7423ef7..67b58e2239 100644 --- a/packages/router-core/tests/server-chunk-failure-lifecycle.test.ts +++ b/packages/router-core/tests/server-chunk-failure-lifecycle.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from 'vitest' import { createMemoryHistory } from '@tanstack/history' -import { BaseRootRoute, BaseRoute, notFound } from '../src' +import { BaseRootRoute, BaseRoute, notFound, redirect } from '../src' import { createTestRouter, loadServerResponse } from './routerTestUtils' /** @@ -97,4 +97,42 @@ describe('server route chunk failure lifecycle', () => { expect(match?.status).toBe('notFound') expect(match?.error).toEqual(expect.objectContaining({ isNotFound: true })) }) + + test('the first route-order chunk failure determines the response', async () => { + const rootError = new Error('root component failed') + const RootComponent = Object.assign(() => null, { + preload: () => Promise.reject(rootError), + }) + const ChildComponent = Object.assign(() => null, { + preload: () => Promise.reject(new Error('child component failed')), + }) + + const rootRoute = new BaseRootRoute({ + component: RootComponent as any, + errorComponent: () => null, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/child', + component: ChildComponent as any, + onError: () => { + throw redirect({ to: '/elsewhere' }) + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([childRoute]), + history: createMemoryHistory({ initialEntries: ['/child'] }), + isServer: true, + }) + + const response = await loadServerResponse(router, '/child') + + expect(response.status).toBe(500) + expect(router.state.matches).toHaveLength(1) + expect(router.state.matches[0]).toMatchObject({ + routeId: rootRoute.id, + status: 'error', + error: rootError, + }) + }) }) diff --git a/packages/router-core/tests/server-concurrent-error-notfound.test.ts b/packages/router-core/tests/server-concurrent-error-notfound.test.ts index 6af4fe5841..e5fa5428d0 100644 --- a/packages/router-core/tests/server-concurrent-error-notfound.test.ts +++ b/packages/router-core/tests/server-concurrent-error-notfound.test.ts @@ -1,136 +1,89 @@ import { describe, expect, test } from 'vitest' import { createMemoryHistory } from '@tanstack/history' -import { - BaseRootRoute, - BaseRoute, - createControlledPromise, - notFound, - redirect, -} from '../src' +import { BaseRootRoute, BaseRoute, notFound, redirect } from '../src' import { createTestRouter, loadServerResponse } from './routerTestUtils' describe('server concurrent route failure ordering', () => { - test.each(['parent-first', 'child-first'] as const)( - 'a shallow regular error wins over a deeper notFound (%s)', - async (settleOrder) => { - const parentGate = createControlledPromise() - const childGate = createControlledPromise() - const parentError = new Error('parent loader failed') - let parentSignal: AbortSignal | undefined - let childSignal: AbortSignal | undefined + test('commits the first failing route loader and aborts its descendants', async () => { + const parentError = new Error('parent loader failed') + let parentSignal: AbortSignal | undefined + let childSignal: AbortSignal | undefined - const rootRoute = new BaseRootRoute({}) - const parentRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/parent', - loader: async ({ abortController }) => { - parentSignal = abortController.signal - await parentGate - throw parentError - }, - errorComponent: () => null, - }) - const childRoute = new BaseRoute({ - getParentRoute: () => parentRoute, - path: '/child', - loader: async ({ abortController }) => { - childSignal = abortController.signal - await childGate - throw notFound() - }, - notFoundComponent: () => null, - }) - const router = createTestRouter({ - routeTree: rootRoute.addChildren([ - parentRoute.addChildren([childRoute]), - ]), - history: createMemoryHistory({ - initialEntries: ['/parent/child'], - }), - isServer: true, - }) + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: ({ abortController }) => { + parentSignal = abortController.signal + throw parentError + }, + errorComponent: () => null, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: ({ abortController }) => { + childSignal = abortController.signal + throw notFound() + }, + notFoundComponent: () => null, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + isServer: true, + }) - const responsePromise = loadServerResponse(router, '/parent/child') - if (settleOrder === 'parent-first') { - parentGate.resolve() - await Promise.resolve() - childGate.resolve() - } else { - childGate.resolve() - await Promise.resolve() - parentGate.resolve() - } - const response = await responsePromise + const response = await loadServerResponse(router, '/parent/child') - expect(response.status).toBe(500) - expect(router.stores.matches.get().map((match) => match.routeId)).toEqual( - [rootRoute.id, parentRoute.id], - ) - expect(router.stores.matches.get()[1]).toMatchObject({ - status: 'error', - error: parentError, - }) - expect(parentSignal?.aborted).toBe(false) - expect(childSignal?.aborted).toBe(true) - }, - ) + expect(response.status).toBe(500) + expect(router.stores.matches.get().map((match) => match.routeId)).toEqual([ + rootRoute.id, + parentRoute.id, + ]) + expect(router.stores.matches.get()[1]).toMatchObject({ + status: 'error', + error: parentError, + }) + expect(parentSignal?.aborted).toBe(false) + expect(childSignal?.aborted).toBe(true) + }) - test.each(['parent-first', 'child-first'] as const)( - 'a shallower notFound boundary wins over a deeper regular error (%s)', - async (settleOrder) => { - const parentGate = createControlledPromise() - const childGate = createControlledPromise() + test('does not replace an earlier loader notFound with a later error', async () => { + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: () => { + throw notFound() + }, + notFoundComponent: () => null, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: () => { + throw new Error('child loader failed') + }, + errorComponent: () => null, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + isServer: true, + }) - const rootRoute = new BaseRootRoute({}) - const parentRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/parent', - loader: async () => { - await parentGate - throw notFound() - }, - notFoundComponent: () => null, - }) - const childRoute = new BaseRoute({ - getParentRoute: () => parentRoute, - path: '/child', - loader: async () => { - await childGate - throw new Error('child loader failed') - }, - errorComponent: () => null, - }) - const router = createTestRouter({ - routeTree: rootRoute.addChildren([ - parentRoute.addChildren([childRoute]), - ]), - history: createMemoryHistory({ - initialEntries: ['/parent/child'], - }), - isServer: true, - }) + const response = await loadServerResponse(router, '/parent/child') - const responsePromise = loadServerResponse(router, '/parent/child') - if (settleOrder === 'parent-first') { - parentGate.resolve() - await Promise.resolve() - childGate.resolve() - } else { - childGate.resolve() - await Promise.resolve() - parentGate.resolve() - } - const response = await responsePromise - - expect(response.status).toBe(404) - expect(router.stores.matches.get().map((match) => match.routeId)).toEqual( - [rootRoute.id, parentRoute.id], - ) - expect(router.stores.matches.get()[1]).toMatchObject({ - status: 'notFound', - }) - }, - ) + expect(response.status).toBe(404) + expect(router.stores.matches.get().map((match) => match.routeId)).toEqual([ + rootRoute.id, + parentRoute.id, + ]) + expect(router.stores.matches.get()[1]).toMatchObject({ + status: 'notFound', + }) + }) test('a redirect aborts every generation in its discarded server lane', async () => { const signals: Array = [] diff --git a/packages/router-core/tests/server-headers-asset-failure.test.ts b/packages/router-core/tests/server-headers-asset-failure.test.ts deleted file mode 100644 index bd0e32d5bf..0000000000 --- a/packages/router-core/tests/server-headers-asset-failure.test.ts +++ /dev/null @@ -1,107 +0,0 @@ -import { createMemoryHistory } from '@tanstack/history' -import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' -import { BaseRootRoute, BaseRoute } from '../src' -import { createTestRouter, loadServerResponse } 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, - }) - - return loadServerResponse(router, '/target') -} - -describe('server asset projection route headers', () => { - test('keeps route headers when head throws synchronously', async () => { - const response = await loadTargetRoute({ asyncHead: false }) - expect(response.headers.get('x-route-header')).toBe('kept') - }) - - test('keeps route headers when head rejects asynchronously', async () => { - const response = await loadTargetRoute({ asyncHead: true }) - expect(response.headers.get('x-route-header')).toBe('kept') - }) - - 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, - }) - - const response = await loadServerResponse(router, '/target') - - 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(response.headers.get('x-route-header')).toBe('kept') - 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({ - 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, - }) - - const response = await loadServerResponse(router, '/target') - expect(response.headers.get('x-route-header')).toBe('kept') - }) -}) From af0f0c742fd2013c032265518653daaa9a87eebc Mon Sep 17 00:00:00 2001 From: Sheraff Date: Tue, 14 Jul 2026 12:45:51 +0200 Subject: [PATCH 11/59] tests --- e2e/react-router/issue-7457/index.html | 10 ++ e2e/react-router/issue-7457/package.json | 28 ++++ .../issue-7457/playwright.config.ts | 25 ++++ e2e/react-router/issue-7457/src/main.tsx | 30 +++++ .../issue-7457/src/routeTree.gen.ts | 77 +++++++++++ .../issue-7457/src/routes/__root.tsx | 25 ++++ .../issue-7457/src/routes/another.tsx | 5 + .../issue-7457/src/routes/index.tsx | 8 ++ e2e/react-router/issue-7457/src/vite-env.d.ts | 1 + .../issue-7457/tests/issue-7457.repro.spec.ts | 35 +++++ e2e/react-router/issue-7457/tsconfig.json | 15 +++ e2e/react-router/issue-7457/vite.config.js | 10 ++ e2e/react-start/basic/src/routes/posts.tsx | 8 ++ e2e/react-start/basic/tests/not-found.spec.ts | 18 +++ .../selective-ssr/src/routeTree.gen.ts | 24 +++- e2e/react-start/selective-ssr/src/router.tsx | 3 + .../selective-ssr/src/routes/__root.tsx | 40 +++++- .../selective-ssr/src/routes/issue-4614.tsx | 15 +++ .../selective-ssr/tests/app.spec.ts | 63 +++++++++ packages/react-router/package.json | 1 + ...ssue-2905-root-beforeload-pending.test.tsx | 59 +++++++++ ...sue-4476-react-query-cancellation.test.tsx | 122 ++++++++++++++++++ ...8-router-provider-context-preload.test.tsx | 102 +++++++++++++++ ...e-6107-lazy-chunk-error-component.test.tsx | 84 ++++++++++++ packages/react-router/tests/loaders.test.tsx | 62 ++++++++- ...tsx => redirect-chain-first-load.test.tsx} | 3 +- .../issue-3179-preload-cached-cause.test.ts | 57 ++++++++ .../issue-3293-on-enter-after-loader.test.ts | 52 ++++++++ ...4572-preload-root-beforeload-flags.test.ts | 51 +++++++- ...arent-context-search-normalization.test.ts | 86 ++++++++++++ ...nt-beforeload-context-child-loader.test.ts | 76 +++++++++++ ...ts => preload-navigation-adoption.test.ts} | 14 +- .../tests/server-loader-abort-error.test.ts | 15 ++- packages/solid-router/tests/loaders.test.tsx | 61 ++++++++- pnpm-lock.yaml | 40 ++++++ 35 files changed, 1286 insertions(+), 39 deletions(-) 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/selective-ssr/src/routes/issue-4614.tsx create mode 100644 packages/react-router/tests/issue-2905-root-beforeload-pending.test.tsx create mode 100644 packages/react-router/tests/issue-4476-react-query-cancellation.test.tsx create mode 100644 packages/react-router/tests/issue-5778-router-provider-context-preload.test.tsx create mode 100644 packages/react-router/tests/issue-6107-lazy-chunk-error-component.test.tsx rename packages/react-router/tests/{issue-7457-redirect-chain-first-load.test.tsx => redirect-chain-first-load.test.tsx} (96%) create mode 100644 packages/router-core/tests/issue-3179-preload-cached-cause.test.ts create mode 100644 packages/router-core/tests/issue-3293-on-enter-after-loader.test.ts create mode 100644 packages/router-core/tests/issue-4696-parent-context-search-normalization.test.ts create mode 100644 packages/router-core/tests/issue-7602-parent-beforeload-context-child-loader.test.ts rename packages/router-core/tests/{issue-4476-preload-navigate-abort.test.ts => preload-navigation-adoption.test.ts} (79%) 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..3220a4dbb4 --- /dev/null +++ b/e2e/react-router/issue-7457/package.json @@ -0,0 +1,28 @@ +{ + "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-query": "^5.99.0", + "@tanstack/react-router": "workspace:^", + "@tanstack/router-plugin": "workspace:^", + "react": "^19.0.0", + "react-dom": "^19.0.0" + }, + "devDependencies": { + "@playwright/test": "^1.61.0", + "@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..61a995a815 --- /dev/null +++ b/e2e/react-router/issue-7457/playwright.config.ts @@ -0,0 +1,25 @@ +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 dev:e2e --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..70bf4bfacb --- /dev/null +++ b/e2e/react-router/issue-7457/src/main.tsx @@ -0,0 +1,30 @@ +import { StrictMode } from 'react' +import { createRoot } from 'react-dom/client' +import { QueryClient } from '@tanstack/react-query' +import { RouterProvider, createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +const queryClient = new QueryClient() +const router = createRouter({ + routeTree, + context: { queryClient }, + 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..988ba76263 --- /dev/null +++ b/e2e/react-router/issue-7457/src/routes/__root.tsx @@ -0,0 +1,25 @@ +import { Outlet, createRootRouteWithContext } from '@tanstack/react-router' +import type { QueryClient } from '@tanstack/react-query' + +export const Route = createRootRouteWithContext<{ + queryClient: QueryClient +}>()({ + beforeLoad: async ({ context }) => { + await context.queryClient.ensureQueryData({ + queryKey: ['issue-7457-root'], + queryFn: async () => { + await new Promise((resolve) => setTimeout(resolve, 1_500)) + return true + }, + }) + }, + 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..6b6caa55b3 --- /dev/null +++ b/e2e/react-router/issue-7457/src/routes/another.tsx @@ -0,0 +1,5 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/another')({ + component: () =>
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..daaae2aeed --- /dev/null +++ b/e2e/react-router/issue-7457/src/routes/index.tsx @@ -0,0 +1,8 @@ +import { createFileRoute, redirect } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + beforeLoad: () => { + throw redirect({ to: '/another', replace: true }) + }, + component: () =>
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..8b20fac1eb --- /dev/null +++ b/e2e/react-router/issue-7457/tests/issue-7457.repro.spec.ts @@ -0,0 +1,35 @@ +import { expect, test } from '@playwright/test' + +test('#7457: initial child redirect after async root beforeLoad does not blank', 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$/) + const target = page.getByText('Hello "/another"!') + await expect + .poll(async () => ({ + targetCount: await target.count(), + pageErrors: [...pageErrors], + consoleErrors: [...consoleErrors], + })) + .toEqual({ targetCount: 1, pageErrors: [], consoleErrors: [] }) + await expect(target).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/basic/src/routes/posts.tsx b/e2e/react-start/basic/src/routes/posts.tsx index 0f69c18341..22fb7e60a8 100644 --- a/e2e/react-start/basic/src/routes/posts.tsx +++ b/e2e/react-start/basic/src/routes/posts.tsx @@ -1,3 +1,4 @@ +import { useState } from 'react' import { Link, Outlet, createFileRoute } from '@tanstack/react-router' import { fetchPosts } from '~/utils/posts' @@ -16,9 +17,16 @@ export const Route = createFileRoute('/posts')({ function PostsComponent() { const posts = Route.useLoaderData() + const [hydrationCount, setHydrationCount] = useState(0) return (
+
    {[...posts, { id: 'i-do-not-exist', title: 'Non-existent Post' }].map( (post) => { diff --git a/e2e/react-start/basic/tests/not-found.spec.ts b/e2e/react-start/basic/tests/not-found.spec.ts index d6e91696e3..339f841b21 100644 --- a/e2e/react-start/basic/tests/not-found.spec.ts +++ b/e2e/react-start/basic/tests/not-found.spec.ts @@ -12,6 +12,24 @@ test.use({ ], }) test.describe('not-found', () => { + test('direct nested not-found hydrates its already-rendered parent route', async ({ + page, + }) => { + test.skip(isSpaMode, 'issue #5106 requires a server-rendered direct visit') + + const response = await page.goto('/posts/i-do-not-exist') + await page.waitForLoadState('networkidle') + + const serverHtml = await response?.text() + expect(serverHtml).toContain('posts-parent-hydration-counter') + expect(serverHtml).toContain('Post not found') + await expect(page.getByText('Post not found')).toBeInViewport() + const counter = page.getByTestId('posts-parent-hydration-counter') + await expect(counter).toHaveText('Parent hydration count: 0') + await counter.click() + await expect(counter).toHaveText('Parent hydration count: 1') + }) + test(`global not found`, async ({ page }) => { const response = await page.goto(`/this-page-does-not-exist/foo/bar`) diff --git a/e2e/react-start/selective-ssr/src/routeTree.gen.ts b/e2e/react-start/selective-ssr/src/routeTree.gen.ts index 188cd5c91a..ae0edad1e1 100644 --- a/e2e/react-start/selective-ssr/src/routeTree.gen.ts +++ b/e2e/react-start/selective-ssr/src/routeTree.gen.ts @@ -10,6 +10,7 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as PostsRouteImport } from './routes/posts' +import { Route as Issue4614RouteImport } from './routes/issue-4614' import { Route as IndexRouteImport } from './routes/index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' @@ -18,6 +19,11 @@ const PostsRoute = PostsRouteImport.update({ path: '/posts', getParentRoute: () => rootRouteImport, } as any) +const Issue4614Route = Issue4614RouteImport.update({ + id: '/issue-4614', + path: '/issue-4614', + getParentRoute: () => rootRouteImport, +} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', @@ -31,30 +37,34 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ export interface FileRoutesByFullPath { '/': typeof IndexRoute + '/issue-4614': typeof Issue4614Route '/posts': typeof PostsRouteWithChildren '/posts/$postId': typeof PostsPostIdRoute } export interface FileRoutesByTo { '/': typeof IndexRoute + '/issue-4614': typeof Issue4614Route '/posts': typeof PostsRouteWithChildren '/posts/$postId': typeof PostsPostIdRoute } export interface FileRoutesById { __root__: typeof rootRouteImport '/': typeof IndexRoute + '/issue-4614': typeof Issue4614Route '/posts': typeof PostsRouteWithChildren '/posts/$postId': typeof PostsPostIdRoute } export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/posts' | '/posts/$postId' + fullPaths: '/' | '/issue-4614' | '/posts' | '/posts/$postId' fileRoutesByTo: FileRoutesByTo - to: '/' | '/posts' | '/posts/$postId' - id: '__root__' | '/' | '/posts' | '/posts/$postId' + to: '/' | '/issue-4614' | '/posts' | '/posts/$postId' + id: '__root__' | '/' | '/issue-4614' | '/posts' | '/posts/$postId' fileRoutesById: FileRoutesById } export interface RootRouteChildren { IndexRoute: typeof IndexRoute + Issue4614Route: typeof Issue4614Route PostsRoute: typeof PostsRouteWithChildren } @@ -67,6 +77,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsRouteImport parentRoute: typeof rootRouteImport } + '/issue-4614': { + id: '/issue-4614' + path: '/issue-4614' + fullPath: '/issue-4614' + preLoaderRoute: typeof Issue4614RouteImport + parentRoute: typeof rootRouteImport + } '/': { id: '/' path: '/' @@ -96,6 +113,7 @@ const PostsRouteWithChildren = PostsRoute._addFileChildren(PostsRouteChildren) const rootRouteChildren: RootRouteChildren = { IndexRoute: IndexRoute, + Issue4614Route: Issue4614Route, PostsRoute: PostsRouteWithChildren, } export const routeTree = rootRouteImport diff --git a/e2e/react-start/selective-ssr/src/router.tsx b/e2e/react-start/selective-ssr/src/router.tsx index 82a730704a..d227bfa5d2 100644 --- a/e2e/react-start/selective-ssr/src/router.tsx +++ b/e2e/react-start/selective-ssr/src/router.tsx @@ -5,6 +5,9 @@ export function getRouter() { const router = createRouter({ routeTree, scrollRestoration: true, + defaultPreload: 'intent', + defaultPreloadDelay: 0, + defaultPreloadStaleTime: 0, }) return router diff --git a/e2e/react-start/selective-ssr/src/routes/__root.tsx b/e2e/react-start/selective-ssr/src/routes/__root.tsx index 1672e3ff68..3465abf298 100644 --- a/e2e/react-start/selective-ssr/src/routes/__root.tsx +++ b/e2e/react-start/selective-ssr/src/routes/__root.tsx @@ -9,10 +9,10 @@ import { createRootRoute, useRouterState, } from '@tanstack/react-router' +import { TanStackRouterDevtools } from '@tanstack/react-router-devtools' import { z } from 'zod' import { ssrSchema } from '~/search' import appCss from '~/styles/app.css?url' -import { TanStackRouterDevtools } from '@tanstack/react-router-devtools' export const Route = createRootRoute({ head: () => ({ @@ -30,7 +30,11 @@ export const Route = createRootRoute({ ], links: [{ rel: 'stylesheet', href: appCss }], }), - validateSearch: z.object({ root: ssrSchema }), + validateSearch: z.object({ + root: ssrSchema, + issue4614: z.string().optional(), + }), + loaderDeps: ({ search }) => ({ issue4614: search.issue4614 }), ssr: ({ search }) => { if (typeof window !== 'undefined') { const error = `ssr() for ${Route.id} should not be called on the client` @@ -41,7 +45,7 @@ export const Route = createRootRoute({ return search.value.root?.ssr } }, - beforeLoad: ({ search }) => { + beforeLoad: ({ search, location, cause, preload }) => { console.log( `beforeLoad for ${Route.id} called on the ${typeof window !== 'undefined' ? 'client' : 'server'}`, ) @@ -53,9 +57,21 @@ export const Route = createRootRoute({ console.error(error) throw new Error(error) } + const root = typeof window === 'undefined' ? 'server' : 'client' + const issue4614Context = `${root}:${search.issue4614 ?? 'cached'}` + if (typeof window !== 'undefined' && location.pathname === '/issue-4614') { + const calls = ((globalThis as any).__issue4614RootBeforeLoads ??= []) + calls.push({ + cause, + preload, + root, + issue4614Context, + }) + } return { - root: typeof window === 'undefined' ? 'server' : 'client', + root, search, + issue4614Context, } }, loader: ({ context }) => { @@ -133,6 +149,22 @@ function RootDocument({ children }: { children: React.ReactNode }) { > Home + + Issue 4614 cached parent + + + Issue 4614 reloaded parent +

diff --git a/e2e/react-start/selective-ssr/src/routes/issue-4614.tsx b/e2e/react-start/selective-ssr/src/routes/issue-4614.tsx new file mode 100644 index 0000000000..7e59b8d0ac --- /dev/null +++ b/e2e/react-start/selective-ssr/src/routes/issue-4614.tsx @@ -0,0 +1,15 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/issue-4614')({ + ssr: false, + beforeLoad: ({ context, cause, preload, search }) => { + ;(globalThis as any).__issue4614TargetBeforeLoad = { + cause, + preload, + rootContext: context.root, + issue4614Context: context.issue4614Context, + scenario: search.issue4614 ?? 'cached', + } + }, + component: () =>
Issue 4614
, +}) diff --git a/e2e/react-start/selective-ssr/tests/app.spec.ts b/e2e/react-start/selective-ssr/tests/app.spec.ts index aea216d506..d6289d5689 100644 --- a/e2e/react-start/selective-ssr/tests/app.spec.ts +++ b/e2e/react-start/selective-ssr/tests/app.spec.ts @@ -4,6 +4,69 @@ import { test } from '@tanstack/router-e2e-utils' const testCount = 7 test.describe('selective ssr', () => { + test('#4614: ssr false child receives context from its parent load generation', async ({ + page, + }) => { + await page.goto('/') + await page.getByTestId('issue-4614-cached-link').hover() + + await expect + .poll(() => + page.evaluate(() => (globalThis as any).__issue4614TargetBeforeLoad), + ) + .not.toBeUndefined() + + const { rootBeforeLoad, targetBeforeLoad } = await page.evaluate(() => { + const rootBeforeLoads = + (globalThis as any).__issue4614RootBeforeLoads ?? [] + return { + rootBeforeLoad: rootBeforeLoads.at(-1), + targetBeforeLoad: (globalThis as any).__issue4614TargetBeforeLoad, + } + }) + + expect(targetBeforeLoad).toMatchObject({ + cause: 'preload', + preload: true, + scenario: 'cached', + }) + expect(targetBeforeLoad.rootContext).toBe(rootBeforeLoad?.root ?? 'server') + expect(targetBeforeLoad.issue4614Context).toBe( + rootBeforeLoad?.issue4614Context ?? 'server:cached', + ) + }) + + test('child receives fresh parent context when loaderDeps force a same-preload reload', async ({ + page, + }) => { + await page.goto('/') + await page.getByTestId('issue-4614-reload-link').hover() + + await expect + .poll(() => + page.evaluate(() => (globalThis as any).__issue4614RootBeforeLoads), + ) + .toEqual([ + { + cause: 'preload', + preload: true, + root: 'client', + issue4614Context: 'client:reload', + }, + ]) + await expect + .poll(() => + page.evaluate(() => (globalThis as any).__issue4614TargetBeforeLoad), + ) + .toEqual({ + cause: 'preload', + preload: true, + rootContext: 'client', + issue4614Context: 'client:reload', + scenario: 'reload', + }) + }) + test('testcount matches', async ({ page }) => { await page.goto('/') diff --git a/packages/react-router/package.json b/packages/react-router/package.json index 9f4bbd6b90..d1b6ddf285 100644 --- a/packages/react-router/package.json +++ b/packages/react-router/package.json @@ -100,6 +100,7 @@ "devDependencies": { "@testing-library/jest-dom": "^6.6.3", "@testing-library/react": "^16.2.0", + "@tanstack/react-query": "catalog:", "@types/node": ">=20", "@vitejs/plugin-react": "^4.3.4", "combinate": "^1.1.11", diff --git a/packages/react-router/tests/issue-2905-root-beforeload-pending.test.tsx b/packages/react-router/tests/issue-2905-root-beforeload-pending.test.tsx new file mode 100644 index 0000000000..2821571c42 --- /dev/null +++ b/packages/react-router/tests/issue-2905-root-beforeload-pending.test.tsx @@ -0,0 +1,59 @@ +import * as React from 'react' +import { act, cleanup, render, screen } from '@testing-library/react' +import { afterEach, expect, test, vi } from 'vitest' +import { + RouterProvider, + createMemoryHistory, + createRootRoute, + createRouter, +} from '../src' + +afterEach(() => { + cleanup() + vi.useRealTimers() +}) + +// https://github.com/TanStack/router/issues/2905 +test('#2905: a root pendingComponent renders while root beforeLoad is pending', async () => { + vi.useFakeTimers() + + const rootRoute = createRootRoute({ + beforeLoad: async () => { + await new Promise((resolve) => setTimeout(resolve, 3_000)) + }, + pendingComponent: () =>
Root pending
, + component: () =>
Root
, + }) + const router = createRouter({ + routeTree: rootRoute, + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render() + await act(async () => { + await vi.advanceTimersByTimeAsync(0) + }) + + await act(async () => { + await vi.advanceTimersByTimeAsync(999) + }) + expect(screen.queryByTestId('root-pending')).not.toBeInTheDocument() + expect(screen.queryByTestId('root-content')).not.toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(1) + }) + expect(screen.getByTestId('root-pending')).toBeInTheDocument() + expect(screen.queryByTestId('root-content')).not.toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(1_999) + }) + expect(screen.getByTestId('root-pending')).toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(1) + }) + expect(screen.queryByTestId('root-pending')).not.toBeInTheDocument() + expect(screen.getByTestId('root-content')).toBeInTheDocument() +}) diff --git a/packages/react-router/tests/issue-4476-react-query-cancellation.test.tsx b/packages/react-router/tests/issue-4476-react-query-cancellation.test.tsx new file mode 100644 index 0000000000..a7d060de6a --- /dev/null +++ b/packages/react-router/tests/issue-4476-react-query-cancellation.test.tsx @@ -0,0 +1,122 @@ +import { + cleanup, + fireEvent, + render, + screen, + waitFor, +} from '@testing-library/react' +import { + QueryClient, + QueryClientProvider, + useQuery, +} from '@tanstack/react-query' +import { afterEach, expect, test, vi } from 'vitest' +import { + Link, + Outlet, + RouterProvider, + createControlledPromise, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +afterEach(cleanup) + +// https://github.com/TanStack/router/issues/4476 +test('#4476: pending navigation does not cancel fetchQuery when it unmounts the last useQuery observer', async () => { + const queryClient = new QueryClient({ + defaultOptions: { queries: { retry: false, staleTime: 0 } }, + }) + const queryGate = createControlledPromise() + const queryKey = ['issue-4476'] as const + const routeError = vi.fn() + const pageTwoBeforeLoad = vi.fn() + let querySignal: AbortSignal | undefined + + const rootRoute = createRootRoute({ + component: () => ( + <> + + Page two + + + + ), + }) + function PageOneComponent() { + const query = useQuery({ + queryKey, + queryFn: () => Promise.resolve(3), + }) + return
Page one: {query.data}
+ } + const pageOneRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: PageOneComponent, + }) + const pageTwoRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page-two', + beforeLoad: async ({ preload }) => { + pageTwoBeforeLoad(preload) + if (preload) { + return + } + const data = await queryClient.fetchQuery({ + queryKey, + queryFn: ({ signal }) => { + querySignal = signal + return queryGate + }, + }) + return { data } + }, + errorComponent: ({ error }) => { + routeError(error) + return
{error.name}
+ }, + component: () => { + const { data } = pageTwoRoute.useRouteContext() + return
Page two: {data}
+ }, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([pageOneRoute, pageTwoRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + defaultPreload: 'intent', + defaultPreloadDelay: 0, + defaultPreloadStaleTime: 0, + defaultPendingMs: 0, + defaultPendingComponent: () =>
Loading page two
, + }) + + try { + render( + + + , + ) + expect(await screen.findByText('Page one: 3')).toBeInTheDocument() + + const link = screen.getByRole('link', { name: 'Page two' }) + fireEvent.mouseOver(link) + await waitFor(() => expect(pageTwoBeforeLoad).toHaveBeenCalledWith(true)) + fireEvent.click(link) + + await waitFor(() => expect(querySignal).toBeDefined()) + // Give the zero-delay pending transition a chance to unmount Page one. + await new Promise((resolve) => setTimeout(resolve, 50)) + expect(querySignal?.aborted).toBe(false) + queryGate.resolve(10) + + expect(await screen.findByText('Page two: 10')).toBeInTheDocument() + expect(routeError).not.toHaveBeenCalled() + expect(screen.queryByTestId('page-two-error')).not.toBeInTheDocument() + } finally { + queryGate.resolve(10) + queryClient.clear() + } +}) diff --git a/packages/react-router/tests/issue-5778-router-provider-context-preload.test.tsx b/packages/react-router/tests/issue-5778-router-provider-context-preload.test.tsx new file mode 100644 index 0000000000..b19aeffb6f --- /dev/null +++ b/packages/react-router/tests/issue-5778-router-provider-context-preload.test.tsx @@ -0,0 +1,102 @@ +import * as React from 'react' +import { + cleanup, + fireEvent, + render, + screen, + waitFor, +} from '@testing-library/react' +import { afterEach, expect, test } from 'vitest' +import { + Link, + Outlet, + RouterProvider, + createMemoryHistory, + createRootRouteWithContext, + createRoute, + createRouter, +} from '../src' + +afterEach(cleanup) + +// https://github.com/TanStack/router/issues/5778 +test('#5778: intent preload sees a RouterProvider context update before the first navigation', async () => { + const seen: Array<{ + route: 'auth' | 'foo' + foo: string + cause: string + preload: boolean + }> = [] + const rootRoute = createRootRouteWithContext<{ foo: string }>()({ + component: () => ( + <> + + Foo + + + + ), + }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
Home
, + }) + const authRoute = createRoute({ + getParentRoute: () => rootRoute, + id: '_authenticated', + beforeLoad: ({ context, cause, preload }) => { + seen.push({ route: 'auth', foo: context.foo, cause, preload }) + }, + component: () => , + }) + const fooRoute = createRoute({ + getParentRoute: () => authRoute, + path: '/foo', + beforeLoad: ({ context, cause, preload }) => { + seen.push({ route: 'foo', foo: context.foo, cause, preload }) + }, + component: () =>
Foo page
, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + authRoute.addChildren([fooRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + context: { foo: null! }, + defaultPreload: 'intent', + defaultPreloadDelay: 0, + }) + + function App() { + const [foo, setFoo] = React.useState('foo') + return ( + <> + + + + ) + } + + render() + expect(await screen.findByText('Home')).toBeInTheDocument() + expect(router.state.matches[0]?.context.foo).toBe('foo') + + fireEvent.click(screen.getByRole('button', { name: 'Update context' })) + await waitFor(() => expect(router.options.context.foo).toBe('baz')) + + seen.length = 0 + fireEvent.mouseOver(screen.getByRole('link', { name: 'Foo' })) + await waitFor(() => expect(seen).toHaveLength(2)) + expect(seen).toEqual([ + { route: 'auth', foo: 'baz', cause: 'preload', preload: true }, + { route: 'foo', foo: 'baz', cause: 'preload', preload: true }, + ]) +}) diff --git a/packages/react-router/tests/issue-6107-lazy-chunk-error-component.test.tsx b/packages/react-router/tests/issue-6107-lazy-chunk-error-component.test.tsx new file mode 100644 index 0000000000..b30446de5c --- /dev/null +++ b/packages/react-router/tests/issue-6107-lazy-chunk-error-component.test.tsx @@ -0,0 +1,84 @@ +import * as React from 'react' +import { + cleanup, + fireEvent, + render, + screen, + waitFor, +} from '@testing-library/react' +import { afterEach, expect, test, vi } from 'vitest' +import { + Link, + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +afterEach(() => { + vi.restoreAllMocks() + cleanup() +}) + +// https://github.com/TanStack/router/issues/6107 +test('#6107: lazy chunk hover failure is non-fatal and navigation renders defaultErrorComponent', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const chunkError = new TypeError( + 'Failed to fetch dynamically imported module: /assets/posts.lazy.js', + ) + let lazyCalls = 0 + + const rootRoute = createRootRoute({ + component: () => ( + <> + + Posts + + + + ), + }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
Index
, + }) + const postsRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + }).lazy(() => { + lazyCalls++ + return Promise.reject(chunkError) + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, postsRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + defaultPreload: 'intent', + defaultPreloadDelay: 0, + defaultErrorComponent: ({ error }) => ( +
{error.message}
+ ), + }) + const preloadRoute = vi.spyOn(router, 'preloadRoute') + + render() + expect(await screen.findByText('Index')).toBeInTheDocument() + + const link = screen.getByRole('link', { name: 'Posts' }) + fireEvent.mouseOver(link) + await waitFor(() => expect(preloadRoute).toHaveBeenCalledTimes(1)) + await preloadRoute.mock.results[0]?.value + expect(lazyCalls).toBeGreaterThanOrEqual(1) + expect(screen.getByText('Index')).toBeInTheDocument() + expect(screen.queryByTestId('default-error')).not.toBeInTheDocument() + + const callsAfterPreload = lazyCalls + fireEvent.click(link) + expect(await screen.findByTestId('default-error')).toHaveTextContent( + chunkError.message, + ) + expect(lazyCalls).toBeGreaterThan(callsAfterPreload) + expect(router.state.location.pathname).toBe('/posts') +}) diff --git a/packages/react-router/tests/loaders.test.tsx b/packages/react-router/tests/loaders.test.tsx index 14518a66f7..307dcbcc66 100644 --- a/packages/react-router/tests/loaders.test.tsx +++ b/packages/react-router/tests/loaders.test.tsx @@ -732,17 +732,20 @@ test('does not show pending UI when loaders finish before their pending delays', test('throw abortError from loader upon initial load with basepath', async () => { window.history.replaceState(null, 'root', '/app') const rootRoute = createRootRoute({}) + const abortError = new DOMException('Aborted', 'AbortError') + const renderedError = vi.fn() const indexRoute = createRoute({ getParentRoute: () => rootRoute, path: '/', loader: async () => { - return Promise.reject(new DOMException('Aborted', 'AbortError')) + return Promise.reject(abortError) }, component: () =>
Index route content
, - errorComponent: () => ( -
indexErrorComponent
- ), + errorComponent: ({ error }) => { + renderedError(error) + return
indexErrorComponent
+ }, }) const routeTree = rootRoute.addChildren([indexRoute]) @@ -750,12 +753,57 @@ 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() + expect(await screen.findByTestId('index-error')).toBeInTheDocument() + expect(screen.queryByText('Index route content')).not.toBeInTheDocument() + expect(renderedError).toHaveBeenCalledWith(abortError) + expect( + router.state.matches.find((match) => match.routeId === indexRoute.id), + ).toMatchObject({ + status: 'error', + error: abortError, + }) expect(window.location.pathname.startsWith('/app')).toBe(true) }) +// https://github.com/TanStack/router/pull/7673 +test('#7673: aborted loader does not render the route component with undefined loaderData', async () => { + const abortError = new DOMException('Aborted', 'AbortError') + const routeComponentRendered = vi.fn() + const renderedError = vi.fn() + const rootRoute = createRootRoute({}) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + loader: (): Promise<{ value: string }> => Promise.reject(abortError), + component: () => { + routeComponentRendered() + const data = indexRoute.useLoaderData() + return
{data.value}
+ }, + errorComponent: ({ error }) => { + renderedError(error) + return
indexErrorComponent
+ }, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history, + }) + + render() + + expect(await screen.findByTestId('index-error')).toBeInTheDocument() + expect(screen.queryByTestId('index-content')).not.toBeInTheDocument() + expect(routeComponentRendered).not.toHaveBeenCalled() + expect(renderedError).toHaveBeenCalledWith(abortError) + expect( + router.state.matches.find((match) => match.routeId === indexRoute.id), + ).toMatchObject({ + status: 'error', + error: abortError, + }) +}) + test('navigating away from a pending route aborts its loader', async () => { function getPendingComponent(onMount: () => void) { const PendingComponent = () => { diff --git a/packages/react-router/tests/issue-7457-redirect-chain-first-load.test.tsx b/packages/react-router/tests/redirect-chain-first-load.test.tsx similarity index 96% rename from packages/react-router/tests/issue-7457-redirect-chain-first-load.test.tsx rename to packages/react-router/tests/redirect-chain-first-load.test.tsx index 3583190d79..b3f4618a28 100644 --- a/packages/react-router/tests/issue-7457-redirect-chain-first-load.test.tsx +++ b/packages/react-router/tests/redirect-chain-first-load.test.tsx @@ -18,12 +18,13 @@ afterEach(() => { 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. +// The production auto-code-splitting reproduction for issue #7457 lives in +// e2e/react-router/issue-7457. test('chained layout beforeLoad redirects on first load render the final target without throwing from MatchInner', async () => { const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}) 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..dcaa50c1cb --- /dev/null +++ b/packages/router-core/tests/issue-3179-preload-cached-cause.test.ts @@ -0,0 +1,57 @@ +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/3179 +test('#3179: preload flags are not inherited from the active match generation', async () => { + const calls: Array<{ + phase: 'beforeLoad' | 'loader' + cause: string + preload: boolean + }> = [] + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + staleTime: 0, + preloadStaleTime: 0, + beforeLoad: ({ cause, preload }) => { + calls.push({ phase: 'beforeLoad', cause, preload }) + }, + loader: ({ cause, preload }) => { + calls.push({ phase: 'loader', cause, preload }) + }, + }) + const aboutRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/about', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, aboutRoute]), + history: createMemoryHistory({ initialEntries: ['/about'] }), + }) + + await router.load() + + // First hover Home from About, then click it. This is the sequence from + // the issue that used to cache the navigation's flags on the match. + await router.preloadRoute({ to: '/' }) + expect(calls).toEqual([ + { phase: 'beforeLoad', cause: 'preload', preload: true }, + { phase: 'loader', cause: 'preload', preload: true }, + ]) + + calls.length = 0 + await router.navigate({ to: '/' }) + expect(calls).toEqual([ + { phase: 'beforeLoad', cause: 'enter', preload: false }, + { phase: 'loader', cause: 'enter', preload: false }, + ]) + + // Hover Home again while it is active. Reusing the active match must not + // rerun callbacks with the cached { cause: 'enter', preload: false } pair. + calls.length = 0 + await router.preloadRoute({ to: '/' }) + expect(calls).toEqual([]) +}) diff --git a/packages/router-core/tests/issue-3293-on-enter-after-loader.test.ts b/packages/router-core/tests/issue-3293-on-enter-after-loader.test.ts new file mode 100644 index 0000000000..c1b6b77f91 --- /dev/null +++ b/packages/router-core/tests/issue-3293-on-enter-after-loader.test.ts @@ -0,0 +1,52 @@ +import { 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/3293 +test('#3293: onEnter runs only after a cold match has completed beforeLoad and loader', async () => { + const beforeLoadGate = createControlledPromise<{ ready: true }>() + const loaderGate = createControlledPromise<{ someData: 42 }>() + const beforeLoad = vi.fn(() => beforeLoadGate) + const loader = vi.fn(() => loaderGate) + const onEnter = vi.fn() + + const rootRoute = new BaseRootRoute({}) + const aboutRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/about', + beforeLoad, + loader, + onEnter, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([aboutRoute]), + history: createMemoryHistory({ initialEntries: ['/about'] }), + }) + + const load = router.load() + await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledTimes(1)) + expect(loader).not.toHaveBeenCalled() + expect(onEnter).not.toHaveBeenCalled() + + beforeLoadGate.resolve({ ready: true }) + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(1)) + expect(loader).toHaveBeenCalledWith( + expect.objectContaining({ + context: expect.objectContaining({ ready: true }), + }), + ) + expect(onEnter).not.toHaveBeenCalled() + + loaderGate.resolve({ someData: 42 }) + await load + + expect(onEnter).toHaveBeenCalledTimes(1) + expect(onEnter).toHaveBeenCalledWith( + expect.objectContaining({ + status: 'success', + context: expect.objectContaining({ ready: true }), + loaderData: { someData: 42 }, + }), + ) +}) 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 index 02c4ffd8aa..7498396172 100644 --- 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 @@ -18,26 +18,45 @@ import { createTestRouter } from './routerTestUtils' test('hover preload does not re-run active ancestors and passes correct flags to new matches', async () => { const rootBeforeLoad = vi.fn() + const indexBeforeLoad = vi.fn() const aboutBeforeLoad = vi.fn() + const bagBeforeLoad = vi.fn() + const nestedBeforeLoad = vi.fn() const rootRoute = new BaseRootRoute({ beforeLoad: rootBeforeLoad }) const indexRoute = new BaseRoute({ getParentRoute: () => rootRoute, path: '/', + beforeLoad: indexBeforeLoad, }) const aboutRoute = new BaseRoute({ getParentRoute: () => rootRoute, path: '/about', beforeLoad: aboutBeforeLoad, }) + const bagRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '_bag', + beforeLoad: bagBeforeLoad, + }) + const nestedRoute = new BaseRoute({ + getParentRoute: () => bagRoute, + path: '/nested', + beforeLoad: nestedBeforeLoad, + }) const router = createTestRouter({ - routeTree: rootRoute.addChildren([indexRoute, aboutRoute]), + routeTree: rootRoute.addChildren([ + indexRoute, + aboutRoute, + bagRoute.addChildren([nestedRoute]), + ]), history: createMemoryHistory({ initialEntries: ['/'] }), }) await router.load() expect(rootBeforeLoad).toHaveBeenCalledTimes(1) + expect(indexBeforeLoad).toHaveBeenCalledTimes(1) expect(rootBeforeLoad).toHaveBeenCalledWith( expect.objectContaining({ cause: 'enter', preload: false }), ) @@ -55,5 +74,35 @@ test('hover preload does not re-run active ancestors and passes correct flags to // Hover the currently active route: everything is borrowed, nothing runs. await router.preloadRoute({ to: '/' } as any) expect(rootBeforeLoad).toHaveBeenCalledTimes(1) + expect(indexBeforeLoad).toHaveBeenCalledTimes(1) expect(aboutBeforeLoad).toHaveBeenCalledTimes(1) + + // The report also covered a pathless parent and its nested active route. + // After navigating there, hovering that same link must not replay any + // ancestor's old enter/stay flags as a preload. + await router.navigate({ to: '/_bag/nested' }) + expect(rootBeforeLoad).toHaveBeenLastCalledWith( + expect.objectContaining({ preload: false }), + ) + expect(bagBeforeLoad).toHaveBeenCalledWith( + expect.objectContaining({ cause: 'enter', preload: false }), + ) + expect(nestedBeforeLoad).toHaveBeenCalledWith( + expect.objectContaining({ cause: 'enter', preload: false }), + ) + expect( + router.state.matches.some((match) => match.routeId === nestedRoute.id), + ).toBe(true) + rootBeforeLoad.mockClear() + indexBeforeLoad.mockClear() + aboutBeforeLoad.mockClear() + bagBeforeLoad.mockClear() + nestedBeforeLoad.mockClear() + + await router.preloadRoute({ to: '/_bag/nested' }) + expect(rootBeforeLoad).not.toHaveBeenCalled() + expect(indexBeforeLoad).not.toHaveBeenCalled() + expect(aboutBeforeLoad).not.toHaveBeenCalled() + expect(bagBeforeLoad).not.toHaveBeenCalled() + expect(nestedBeforeLoad).not.toHaveBeenCalled() }) diff --git a/packages/router-core/tests/issue-4696-parent-context-search-normalization.test.ts b/packages/router-core/tests/issue-4696-parent-context-search-normalization.test.ts new file mode 100644 index 0000000000..02f38c5e80 --- /dev/null +++ b/packages/router-core/tests/issue-4696-parent-context-search-normalization.test.ts @@ -0,0 +1,86 @@ +import { expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +// https://github.com/TanStack/router/issues/4696 +test('#4696: normalized child search preserves parent context across reused matches', async () => { + const rootLoader = vi.fn( + ({ context }: { context: Record }) => context, + ) + const dashboardBeforeLoad = vi.fn( + ({ context }: { context: Record }) => { + if (!context.isAuthenticated) { + throw new Error('Authentication context was lost') + } + }, + ) + const rootRoute = new BaseRootRoute({ + beforeLoad: async () => { + await Promise.resolve() + return { + initialData: { + user: { email: 'mr.user@gmail.com', role: 'user' }, + }, + initializationError: undefined, + isAuthenticated: true, + isAdmin: false, + } + }, + loader: rootLoader, + }) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const dashboardRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/dashboard', + validateSearch: () => ({ page: 0 }), + beforeLoad: dashboardBeforeLoad, + }) + const history = createMemoryHistory({ initialEntries: ['/'] }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, dashboardRoute]), + history, + }) + + await router.load() + router.update({ + history: createMemoryHistory({ + initialEntries: ['/dashboard?page=0'], + }), + }) + await router.load() + expect( + router.state.matches.find((match) => match.routeId === rootRoute.id) + ?.loaderData, + ).toMatchObject({ isAuthenticated: true }) + + dashboardBeforeLoad.mockClear() + router.update({ + history: createMemoryHistory({ initialEntries: ['/dashboard'] }), + }) + await router.load() + + expect(dashboardBeforeLoad).toHaveBeenCalledWith( + expect.objectContaining({ + context: expect.objectContaining({ isAuthenticated: true }), + }), + ) + const rootMatch = router.state.matches.find( + (match) => match.routeId === rootRoute.id, + ) + const dashboardMatch = router.state.matches.find( + (match) => match.routeId === dashboardRoute.id, + ) + expect(rootMatch?.loaderData).toMatchObject({ + isAuthenticated: true, + isAdmin: false, + }) + expect(dashboardMatch).toMatchObject({ + status: 'success', + search: { page: 0 }, + searchError: undefined, + }) +}) 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..19538776b0 --- /dev/null +++ b/packages/router-core/tests/issue-7602-parent-beforeload-context-child-loader.test.ts @@ -0,0 +1,76 @@ +import { 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/7602 +test('#7602: browser Back republishes a cached child with fresh parent beforeLoad context', async () => { + const loaderContextNumbers: Array = [] + const reloadGate = createControlledPromise() + let loaderRuns = 0 + + const rootRoute = new BaseRootRoute({}) + const homeRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const reproRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/repro', + beforeLoad: async () => { + await Promise.resolve() + return { number: 42 } + }, + }) + const reproIndexRoute = new BaseRoute({ + getParentRoute: () => reproRoute, + path: '/', + loader: async ({ context }: { context: { number?: number } }) => { + loaderRuns++ + loaderContextNumbers.push(context.number) + if (loaderRuns === 2) { + await reloadGate + } + return { visit: loaderRuns } + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + homeRoute, + reproRoute.addChildren([reproIndexRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/repro'] }), + }) + const getChildMatch = () => + router.state.matches.find((match) => match.routeId === reproIndexRoute.id) + // RouterProvider's Transitioner installs this subscription in applications. + // It is what turns a browser Back history event into a router load. + const unsubscribe = router.history.subscribe(router.load) + + try { + await router.load() + expect(loaderContextNumbers).toEqual([42]) + + await router.navigate({ to: '/' }) + expect(getChildMatch()).toBeUndefined() + + router.history.back() + await vi.waitFor(() => expect(loaderContextNumbers).toHaveLength(2)) + + // The cached success is visible while its stale loader reloads. It must + // never be published with the parent's context contribution missing. + expect(router.state.location.pathname).toBe('/repro') + expect(getChildMatch()?.status).toBe('success') + expect(getChildMatch()?.context).toMatchObject({ number: 42 }) + expect(loaderContextNumbers).toEqual([42, 42]) + + reloadGate.resolve() + await vi.waitFor(() => + expect(getChildMatch()?.loaderData).toEqual({ visit: 2 }), + ) + expect(getChildMatch()?.context).toMatchObject({ number: 42 }) + } finally { + reloadGate.resolve() + unsubscribe() + } +}) diff --git a/packages/router-core/tests/issue-4476-preload-navigate-abort.test.ts b/packages/router-core/tests/preload-navigation-adoption.test.ts similarity index 79% rename from packages/router-core/tests/issue-4476-preload-navigate-abort.test.ts rename to packages/router-core/tests/preload-navigation-adoption.test.ts index dec4a2a0c0..ab18f703df 100644 --- a/packages/router-core/tests/issue-4476-preload-navigate-abort.test.ts +++ b/packages/router-core/tests/preload-navigation-adoption.test.ts @@ -3,17 +3,11 @@ 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', () => { +// run: it must not abort the preload's loader signal or rerun the loader. This +// is generic router adoption coverage; issue #4476 is covered separately with +// the React Query observer-unmount sequence from its reproduction. +describe('navigation adopting an in-flight preload', () => { test('adopted preload loader runs once and its signal is not aborted', async () => { const loaderGate = createControlledPromise() let capturedSignal: AbortSignal | undefined diff --git a/packages/router-core/tests/server-loader-abort-error.test.ts b/packages/router-core/tests/server-loader-abort-error.test.ts index a6af9a68fc..b3772692ef 100644 --- a/packages/router-core/tests/server-loader-abort-error.test.ts +++ b/packages/router-core/tests/server-loader-abort-error.test.ts @@ -5,12 +5,12 @@ import { createTestRouter, loadServerResponse } 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. + * NOT aborted (e.g. the loader's own fetch timed out) is a route failure. + * Only a router-aborted generation may discard AbortError as cancellation. */ describe('server loader AbortError', () => { - test('settles as non-error with a 200 status when the match signal is not aborted', async () => { + test('settles as an error when the match signal is not aborted', async () => { const rootRoute = new BaseRootRoute({}) const abortingRoute = new BaseRoute({ getParentRoute: () => rootRoute, @@ -30,8 +30,11 @@ describe('server loader AbortError', () => { const match = router.state.matches.find( (item) => item.routeId === abortingRoute.id, ) - expect(response.status).toBe(200) - expect(match?.status).toBe('success') - expect(match?.error).toBeUndefined() + expect(response.status).toBe(500) + expect(match?.status).toBe('error') + expect(match?.error).toMatchObject({ + name: 'AbortError', + message: 'The operation was aborted.', + }) }) }) diff --git a/packages/solid-router/tests/loaders.test.tsx b/packages/solid-router/tests/loaders.test.tsx index 7124411943..c8f13a6a60 100644 --- a/packages/solid-router/tests/loaders.test.tsx +++ b/packages/solid-router/tests/loaders.test.tsx @@ -323,17 +323,20 @@ test('throw error from beforeLoad when navigating to route', async () => { test('throw abortError from loader upon initial load with basepath', async () => { window.history.replaceState(null, 'root', '/app') const rootRoute = createRootRoute({}) + const abortError = new DOMException('Aborted', 'AbortError') + const renderedError = vi.fn() const indexRoute = createRoute({ getParentRoute: () => rootRoute, path: '/', loader: async () => { - return Promise.reject(new DOMException('Aborted', 'AbortError')) + return Promise.reject(abortError) }, component: () =>
Index route content
, - errorComponent: () => ( -
indexErrorComponent
- ), + errorComponent: ({ error }) => { + renderedError(error) + return
indexErrorComponent
+ }, }) const routeTree = rootRoute.addChildren([indexRoute]) @@ -341,12 +344,56 @@ 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() + expect(await screen.findByTestId('index-error')).toBeInTheDocument() + expect(screen.queryByText('Index route content')).not.toBeInTheDocument() + expect(renderedError).toHaveBeenCalledWith(abortError) + expect( + router.state.matches.find((match) => match.routeId === indexRoute.id), + ).toMatchObject({ + status: 'error', + error: abortError, + }) expect(window.location.pathname.startsWith('/app')).toBe(true) }) +// https://github.com/TanStack/router/pull/7673 +test('#7673: aborted loader does not render the route component with undefined loaderData', async () => { + const abortError = new DOMException('Aborted', 'AbortError') + const routeComponentRendered = vi.fn() + const renderedError = vi.fn() + const rootRoute = createRootRoute({}) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + loader: (): Promise<{ value: string }> => Promise.reject(abortError), + component: () => { + routeComponentRendered() + const data = indexRoute.useLoaderData() + return
{data().value}
+ }, + errorComponent: ({ error }) => { + renderedError(error) + return
indexErrorComponent
+ }, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + }) + + render(() => ) + + expect(await screen.findByTestId('index-error')).toBeInTheDocument() + expect(screen.queryByTestId('index-content')).not.toBeInTheDocument() + expect(routeComponentRendered).not.toHaveBeenCalled() + expect(renderedError).toHaveBeenCalledWith(abortError) + expect( + router.state.matches.find((match) => match.routeId === indexRoute.id), + ).toMatchObject({ + status: 'error', + error: abortError, + }) +}) + test('reproducer #4245', async () => { const LOADER_WAIT_TIME = 500 const rootRoute = createRootRoute({}) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a91aaea20f..e658307e76 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1433,6 +1433,43 @@ 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-7457: + dependencies: + '@tanstack/react-query': + specifier: ^5.99.0 + version: 5.99.0(react@19.2.3) + '@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.61.0 + version: 1.61.1 + '@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/view-transitions: dependencies: '@tailwindcss/vite': @@ -12601,6 +12638,9 @@ importers: specifier: ^5.1.22 version: 5.1.28 devDependencies: + '@tanstack/react-query': + specifier: ^5.99.0 + version: 5.99.0(react@19.2.3) '@testing-library/jest-dom': specifier: ^6.6.3 version: 6.6.3 From f54bf4bc411b14248defba947b7bf162e1ab6b49 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Tue, 14 Jul 2026 13:10:50 +0200 Subject: [PATCH 12/59] fix #7673 --- packages/router-core/src/load-client.ts | 6 +--- packages/router-core/src/load-server.ts | 9 ++--- packages/solid-router/tests/loaders.test.tsx | 16 +++++++-- packages/vue-router/tests/loaders.test.tsx | 38 ++++++++++++++++++++ 4 files changed, 55 insertions(+), 14 deletions(-) diff --git a/packages/router-core/src/load-client.ts b/packages/router-core/src/load-client.ts index 465aab6212..a06fe7813c 100644 --- a/packages/router-core/src/load-client.ts +++ b/packages/router-core/src/load-client.ts @@ -165,11 +165,7 @@ function normalize( function normalizeError( route: AnyRoute, cause: unknown, - signal?: AbortSignal, ): LoaderOutcome { - if (signal && (cause as any)?.name === 'AbortError') { - return signal.aborted ? [canceled] : [success, undefined] - } let outcome = normalize(cause, true, route.id) if (outcome[0] !== error) { return outcome @@ -364,7 +360,7 @@ function startFlight( (cause) => controller.signal.aborted ? [canceled] - : normalizeError(route, cause, controller.signal), + : normalizeError(route, cause), ), controller, 1, diff --git a/packages/router-core/src/load-server.ts b/packages/router-core/src/load-server.ts index 341eef28c1..5d267ecd8d 100644 --- a/packages/router-core/src/load-server.ts +++ b/packages/router-core/src/load-server.ts @@ -319,11 +319,6 @@ function startLoader( if (!loader) { outcome = Promise.resolve([success, undefined]) } else { - const failed = (cause: unknown): LoadOutcome => - (cause as any)?.name === 'AbortError' && - !match.abortController.signal.aborted - ? [success, undefined] - : normalizeError(route, cause) let value: unknown let rejected = false try { @@ -337,11 +332,11 @@ function startLoader( outcome = Promise.resolve(value).then( (result) => { const normalized = rejected - ? failed(result) + ? normalizeError(route, result) : normalize(result, false) return stampNotFound(match, normalized) }, - (cause) => stampNotFound(match, failed(cause)), + (cause) => stampNotFound(match, normalizeError(route, cause)), ) } } diff --git a/packages/solid-router/tests/loaders.test.tsx b/packages/solid-router/tests/loaders.test.tsx index c8f13a6a60..e3bb87076d 100644 --- a/packages/solid-router/tests/loaders.test.tsx +++ b/packages/solid-router/tests/loaders.test.tsx @@ -346,7 +346,13 @@ test('throw abortError from loader upon initial load with basepath', async () => expect(await screen.findByTestId('index-error')).toBeInTheDocument() expect(screen.queryByText('Index route content')).not.toBeInTheDocument() - expect(renderedError).toHaveBeenCalledWith(abortError) + // jsdom creates DOMException in another realm, so Solid wraps the error. + expect(renderedError).toHaveBeenCalledWith( + expect.objectContaining({ + message: 'Unknown error', + cause: abortError, + }), + ) expect( router.state.matches.find((match) => match.routeId === indexRoute.id), ).toMatchObject({ @@ -385,7 +391,13 @@ test('#7673: aborted loader does not render the route component with undefined l expect(await screen.findByTestId('index-error')).toBeInTheDocument() expect(screen.queryByTestId('index-content')).not.toBeInTheDocument() expect(routeComponentRendered).not.toHaveBeenCalled() - expect(renderedError).toHaveBeenCalledWith(abortError) + // jsdom creates DOMException in another realm, so Solid wraps the error. + expect(renderedError).toHaveBeenCalledWith( + expect.objectContaining({ + message: 'Unknown error', + cause: abortError, + }), + ) expect( router.state.matches.find((match) => match.routeId === indexRoute.id), ).toMatchObject({ diff --git a/packages/vue-router/tests/loaders.test.tsx b/packages/vue-router/tests/loaders.test.tsx index 4c60731063..a94b1579e3 100644 --- a/packages/vue-router/tests/loaders.test.tsx +++ b/packages/vue-router/tests/loaders.test.tsx @@ -276,6 +276,44 @@ test('throw error from loader upon initial load', async () => { expect(errorElement).toBeInTheDocument() }) +// https://github.com/TanStack/router/pull/7673 +test('#7673: aborted loader does not render the route component with undefined loaderData', async () => { + const abortError = new DOMException('Aborted', 'AbortError') + const routeComponentRendered = vi.fn() + const renderedError = vi.fn() + const rootRoute = createRootRoute({}) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + loader: (): Promise<{ value: string }> => Promise.reject(abortError), + component: () => { + routeComponentRendered() + const data = indexRoute.useLoaderData() + return
{data.value.value}
+ }, + errorComponent: ({ error }) => { + renderedError(error) + return
indexErrorComponent
+ }, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + }) + + render() + + expect(await screen.findByTestId('index-error')).toBeInTheDocument() + expect(screen.queryByTestId('index-content')).not.toBeInTheDocument() + expect(routeComponentRendered).not.toHaveBeenCalled() + expect(renderedError).toHaveBeenCalledWith(abortError) + expect( + router.state.matches.find((match) => match.routeId === indexRoute.id), + ).toMatchObject({ + status: 'error', + error: abortError, + }) +}) + test('throw error from beforeLoad when navigating to route', async () => { const rootRoute = createRootRoute({}) From 7be11499132fcb51d03a9de0c03c12d5f7ec2bf8 Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Tue, 14 Jul 2026 11:12:29 +0000 Subject: [PATCH 13/59] ci: apply automated fixes --- packages/router-core/src/load-client.ts | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/packages/router-core/src/load-client.ts b/packages/router-core/src/load-client.ts index a06fe7813c..3a1f7d73d3 100644 --- a/packages/router-core/src/load-client.ts +++ b/packages/router-core/src/load-client.ts @@ -162,10 +162,7 @@ function normalize( return rejected ? [error, value] : [success, value] } -function normalizeError( - route: AnyRoute, - cause: unknown, -): LoaderOutcome { +function normalizeError(route: AnyRoute, cause: unknown): LoaderOutcome { let outcome = normalize(cause, true, route.id) if (outcome[0] !== error) { return outcome @@ -358,9 +355,7 @@ function startFlight( ? [canceled] : normalize(value, false, route.id), (cause) => - controller.signal.aborted - ? [canceled] - : normalizeError(route, cause), + controller.signal.aborted ? [canceled] : normalizeError(route, cause), ), controller, 1, From 0ed58eafe926749bf7835e1b2e1046f662314b2a Mon Sep 17 00:00:00 2001 From: Sheraff Date: Tue, 14 Jul 2026 13:28:39 +0200 Subject: [PATCH 14/59] rename consts to uppercase --- packages/router-core/src/load-client.ts | 88 ++++++++++++------------- packages/router-core/src/load-server.ts | 70 ++++++++++---------- 2 files changed, 79 insertions(+), 79 deletions(-) diff --git a/packages/router-core/src/load-client.ts b/packages/router-core/src/load-client.ts index 3a1f7d73d3..56f265de19 100644 --- a/packages/router-core/src/load-client.ts +++ b/packages/router-core/src/load-client.ts @@ -34,19 +34,19 @@ type ReducedLane = Lane<'reduced'> export type ProjectedLane = Lane<'projected'> -const success = 0 -const error = 1 -const notFound = 2 +const SUCCESS = 0 +const ERROR = 1 +const NOT_FOUND = 2 // Control outcomes stay contiguous so the hot path can test them together. -const redirected = 3 -const canceled = 4 +const REDIRECTED = 3 +const CANCELED = 4 type LoaderOutcome = - | [typeof success, data: unknown] - | [typeof error, error: unknown] - | [typeof notFound, error: NotFoundError] - | [typeof redirected, redirect: AnyRedirect] - | [typeof canceled] + | [typeof SUCCESS, data: unknown] + | [typeof ERROR, error: unknown] + | [typeof NOT_FOUND, error: NotFoundError] + | [typeof REDIRECTED, redirect: AnyRedirect] + | [typeof CANCELED] type IndexedOutcome = [index: number, outcome: LoaderOutcome] @@ -120,8 +120,8 @@ export type ExecuteLaneOptions = { } type ControlOutcome = - | [typeof redirected, redirect: AnyRedirect] - | [typeof canceled] + | [typeof REDIRECTED, redirect: AnyRedirect] + | [typeof CANCELED] export type LaneResult = ProjectedLane | ControlOutcome @@ -153,18 +153,18 @@ function normalize( routeId?: string, ): LoaderOutcome { if (isRedirect(value)) { - return [redirected, value] + return [REDIRECTED, value] } if (isNotFound(value)) { value.routeId ||= routeId - return [notFound, value] + return [NOT_FOUND, value] } - return rejected ? [error, value] : [success, value] + return rejected ? [ERROR, value] : [SUCCESS, value] } function normalizeError(route: AnyRoute, cause: unknown): LoaderOutcome { let outcome = normalize(cause, true, route.id) - if (outcome[0] !== error) { + if (outcome[0] !== ERROR) { return outcome } try { @@ -275,7 +275,7 @@ async function contextualize( ) match.isFetching = false const outcome = normalize(result, false, route.id) - if (outcome[0] !== success) { + if (outcome[0] !== SUCCESS) { releaseFlight(router as ClientRouter, match) return [index, outcome] } @@ -293,7 +293,7 @@ async function contextualize( } catch (cause) { match.isFetching = false if (cause === options.controller.signal) { - return [index, [canceled]] + return [index, [CANCELED]] } if (cause instanceof Promise) { throw cause @@ -352,10 +352,10 @@ function startFlight( .then( (value) => controller.signal.aborted - ? [canceled] + ? [CANCELED] : normalize(value, false, route.id), (cause) => - controller.signal.aborted ? [canceled] : normalizeError(route, cause), + controller.signal.aborted ? [CANCELED] : normalizeError(route, cause), ), controller, 1, @@ -409,13 +409,13 @@ async function loadResource( signal: AbortSignal, ): Promise { if (signal.aborted) { - return [canceled] + return [CANCELED] } const routeLoader = route.options.loader const loader = typeof routeLoader === 'function' ? routeLoader : routeLoader?.handler if (!loader) { - return [success, undefined] + return [SUCCESS, undefined] } let flight = match._flight @@ -442,13 +442,13 @@ async function loadResource( match.isFetching = 'loader' try { const outcome = await waitFor(flight![0], signal) - if (!joined || outcome[0] === success) { + if (!joined || outcome[0] === SUCCESS) { return outcome } } catch (cause) { if (cause === signal) { releaseFlight(router, match) - return [canceled] + return [CANCELED] } throw cause } @@ -571,7 +571,7 @@ function createTask( const rawOutcome = reloadFailure ? Promise.resolve(reloadFailure) : !loaded || background - ? Promise.resolve([success, match.loaderData]) + ? Promise.resolve([SUCCESS, match.loaderData]) : loadResource( router, workerRouter, @@ -583,7 +583,7 @@ function createTask( options.controller.signal, ) const outcome = rawOutcome.then((result) => { - if (loaded && !background && result[0] === success) { + if (loaded && !background && result[0] === SUCCESS) { applySuccess(match, result[1]) match.preload = preload } @@ -597,7 +597,7 @@ function createTask( (cause): IndexedOutcome => [index, normalizeError(route, cause)], ) const ready = outcome - .then((value) => (value[0] === success ? chunkFailure : undefined)) + .then((value) => (value[0] === SUCCESS ? chunkFailure : undefined)) .then((value) => { options.onReady?.() return value @@ -626,7 +626,7 @@ function createTask( false, options.controller.signal, ).then((result) => { - if (result[0] === success) { + if (result[0] === SUCCESS) { applySuccess(candidate, result[1]) } return result @@ -673,18 +673,18 @@ async function reduceLane( // Background reductions do not compare against the committed lane. const background = !options.base let control = - (serialFailure?.[1][0] ?? 0) >= redirected ? serialFailure : undefined + (serialFailure?.[1][0] ?? 0) >= REDIRECTED ? serialFailure : undefined let loaderFailure: IndexedOutcome | undefined for (let index = 0; index < tasks.length; index++) { const task = tasks[index]! const outcome = await task.outcome const taskIndex = (task as BackgroundTask).index ?? index - if (outcome[0] >= redirected) { + if (outcome[0] >= REDIRECTED) { control = [taskIndex, outcome] break } - if (outcome[0] !== success) { + if (outcome[0] !== SUCCESS) { loaderFailure ||= [taskIndex, outcome] } } @@ -692,17 +692,17 @@ async function reduceLane( let failure = loaderFailure ?? serialFailure if ( - control?.[1][0] === redirected && + control?.[1][0] === REDIRECTED && !control[1][1].options.reloadDocument && (options.redirects ?? 0) >= 20 ) { - failure = [control[0], [error, new Error('Redirect cycle detected')]] + failure = [control[0], [ERROR, new Error('Redirect cycle detected')]] control = undefined } if (!control) { const readinessEnd = failure - ? failure[1][0] === notFound + ? failure[1][0] === NOT_FOUND ? getNotFoundBoundary(router, lane.matches, failure) : failure[0] : lane.matches.length @@ -713,14 +713,14 @@ async function reduceLane( } const chunkFailure = await task.ready if (chunkFailure) { - if (chunkFailure[1][0] === redirected) { + if (chunkFailure[1][0] === REDIRECTED) { if ( !chunkFailure[1][1].options.reloadDocument && (options.redirects ?? 0) >= 20 ) { failure = [ chunkFailure[0], - [error, new Error('Redirect cycle detected')], + [ERROR, new Error('Redirect cycle detected')], ] } else { control = chunkFailure @@ -748,7 +748,7 @@ async function reduceLane( const [index, outcome] = failure const kind = outcome[0] const boundary = - kind === notFound + kind === NOT_FOUND ? getNotFoundBoundary(router, lane.matches, failure) : index let match = lane.matches[boundary]! @@ -760,7 +760,7 @@ async function reduceLane( } const cause = outcome[1] match.globalNotFound = undefined - if (kind === error) { + if (kind === ERROR) { match.status = 'error' } else { ;(cause as NotFoundError).routeId = match.routeId @@ -776,7 +776,7 @@ async function reduceLane( try { await loadRouteChunk( getRoute(router, match), - kind === error ? 'errorComponent' : 'notFoundComponent', + kind === ERROR ? 'errorComponent' : 'notFoundComponent', ) } catch {} trimLane(router, lane, boundary + 1, background) @@ -871,12 +871,12 @@ export async function executeClientLane( const tasks: Array = [] let semanticParent: Promise | undefined let end = failure?.[0] ?? contextualized.matches.length - if (failure?.[1][0] === notFound) { + if (failure?.[1][0] === NOT_FOUND) { end = Math.min( end, getNotFoundBoundary(workerRouter, contextualized.matches, failure) + 1, ) - } else if ((failure?.[1][0] ?? 0) >= redirected) { + } else if ((failure?.[1][0] ?? 0) >= REDIRECTED) { end = 0 } for (let index = 0; index < end; index++) { @@ -1162,7 +1162,7 @@ async function runBackground( if (Array.isArray(reduced)) { discardMatchResources(router, backgroundMatches) if ( - reduced[0] === redirected && + reduced[0] === REDIRECTED && router._tx === tx && router._committedMatches === base ) { @@ -1219,7 +1219,7 @@ async function runClientTransaction( if (Array.isArray(result)) { finishPending(router, tx) discardMatchResources(router, tx.matches) - if (result[0] === redirected && router._tx === tx) { + if (result[0] === REDIRECTED && router._tx === tx) { tx.redirects = (tx.redirects ?? 0) + 1 tx.redirecting = true await router.navigate({ @@ -1497,7 +1497,7 @@ export async function preloadClientRoute( }) if (Array.isArray(result)) { discardMatchResources(router, matches) - if (result[0] === redirected && !result[1].options.reloadDocument) { + if (result[0] === REDIRECTED && !result[1].options.reloadDocument) { return preloadClientRoute( router, { diff --git a/packages/router-core/src/load-server.ts b/packages/router-core/src/load-server.ts index 5d267ecd8d..2a7ebdbbb5 100644 --- a/packages/router-core/src/load-server.ts +++ b/packages/router-core/src/load-server.ts @@ -35,18 +35,18 @@ type ContextualizedLane = ServerLane<'contextualized'> & { type ReducedLane = ServerLane<'reduced'> -const success = 0 -const error = 1 -const notFound = 2 -const redirected = 3 -const skipped = 4 +const SUCCESS = 0 +const ERROR = 1 +const NOT_FOUND = 2 +const REDIRECTED = 3 +const SKIPPED = 4 type LoadOutcome = - | [typeof success, data: unknown] - | [typeof error, error: unknown] - | [typeof notFound, error: NotFoundError] - | [typeof redirected, redirect: AnyRedirect] - | [typeof skipped] + | [typeof SUCCESS, data: unknown] + | [typeof ERROR, error: unknown] + | [typeof NOT_FOUND, error: NotFoundError] + | [typeof REDIRECTED, redirect: AnyRedirect] + | [typeof SKIPPED] type LoaderTask = { index: number @@ -79,17 +79,17 @@ function getRoute(router: ServerWorker, match: AnyRouteMatch): AnyRoute { function normalize(value: unknown, rejected: boolean): LoadOutcome { if (isRedirect(value)) { - return [redirected, value] + return [REDIRECTED, value] } if (isNotFound(value)) { - return [notFound, value] + return [NOT_FOUND, value] } - return rejected ? [error, value] : [success, value] + return rejected ? [ERROR, value] : [SUCCESS, value] } function normalizeError(route: AnyRoute, cause: unknown): LoadOutcome { let outcome = normalize(cause, true) - if (outcome[0] !== error) { + if (outcome[0] !== ERROR) { return outcome } try { @@ -169,7 +169,7 @@ function stampNotFound( match: AnyRouteMatch, outcome: LoadOutcome, ): LoadOutcome { - if (outcome[0] === notFound && !outcome[1].routeId) { + if (outcome[0] === NOT_FOUND && !outcome[1].routeId) { outcome[1].routeId = match.routeId } return outcome @@ -247,7 +247,7 @@ async function contextualize( try { const beforeLoadContext = await route.options.beforeLoad(options) const outcome = stampNotFound(match, normalize(beforeLoadContext, false)) - if (outcome[0] !== success) { + if (outcome[0] !== SUCCESS) { failure = [index, outcome] end = index break @@ -312,12 +312,12 @@ function startLoader( let outcome: Promise if (match.ssr === false) { - outcome = Promise.resolve([skipped]) + outcome = Promise.resolve([SKIPPED]) } else { const option = route.options.loader const loader = typeof option === 'function' ? option : option?.handler if (!loader) { - outcome = Promise.resolve([success, undefined]) + outcome = Promise.resolve([SUCCESS, undefined]) } else { let value: unknown let rejected = false @@ -343,14 +343,14 @@ function startLoader( const parentMatch = outcome.then((result) => { const snapshot = { ...match } - if (result[0] === success) { + if (result[0] === SUCCESS) { snapshot.loaderData = result[1] snapshot.status = 'success' snapshot.error = undefined - } else if (result[0] === error) { + } else if (result[0] === ERROR) { snapshot.status = 'error' snapshot.error = result[1] - } else if (result[0] === notFound) { + } else if (result[0] === NOT_FOUND) { snapshot.status = 'notFound' snapshot.error = result[1] } @@ -406,13 +406,13 @@ function applyFailure( if (boundary >= 0) { abortMatches(lane.matches, boundary + 1) lane.matches.length = boundary + 1 - return { status: 404, boundary, kind: notFound } + return { status: 404, boundary, kind: NOT_FOUND } } return { status: 200 } } const [index, outcome] = indexed - if (outcome[0] === error) { + if (outcome[0] === ERROR) { const match = lane.matches[index]! match.globalNotFound = undefined match.status = 'error' @@ -420,7 +420,7 @@ function applyFailure( match.isFetching = false abortMatches(lane.matches, index + 1) lane.matches.length = index + 1 - return { status: 500, boundary: index, kind: error } + return { status: 500, boundary: index, kind: ERROR } } const boundary = getNotFoundBoundary(router, lane.matches, indexed) @@ -439,7 +439,7 @@ function applyFailure( match.isFetching = false abortMatches(lane.matches, boundary + 1) lane.matches.length = boundary + 1 - return { status: 404, boundary, kind: notFound } + return { status: 404, boundary, kind: NOT_FOUND } } async function loadNormalChunks( @@ -525,9 +525,9 @@ export async function loadServer( const lane = await contextualize(worker, matched, preload) let loaderEnd = lane.end - if (lane.failure?.[1][0] === redirected) { + if (lane.failure?.[1][0] === REDIRECTED) { loaderEnd = 0 - } else if (lane.failure?.[1][0] === notFound) { + } else if (lane.failure?.[1][0] === NOT_FOUND) { loaderEnd = Math.min( loaderEnd, getNotFoundBoundary(worker, lane.matches, lane.failure) + 1, @@ -541,10 +541,10 @@ export async function loadServer( } let loaderFailure: IndexedOutcome | undefined - let control = lane.failure?.[1][0] === redirected ? lane.failure : undefined + let control = lane.failure?.[1][0] === REDIRECTED ? lane.failure : undefined for (const task of tasks) { const outcome = await task.outcome - if (outcome[0] === success) { + if (outcome[0] === SUCCESS) { const match = lane.matches[task.index]! match.loaderData = outcome[1] match.status = 'success' @@ -552,15 +552,15 @@ export async function loadServer( match.invalid = false match.isFetching = false match.updatedAt = Date.now() - } else if (outcome[0] === redirected) { + } else if (outcome[0] === REDIRECTED) { control = [task.index, outcome] break - } else if (outcome[0] !== skipped) { + } else if (outcome[0] !== SKIPPED) { loaderFailure ??= [task.index, outcome] } } - if (control?.[1][0] === redirected) { + if (control?.[1][0] === REDIRECTED) { abortMatches(lane.matches) return resolveServerRedirect(worker, location, control[1][1]) } @@ -570,7 +570,7 @@ export async function loadServer( (match) => match.globalNotFound, ) const readinessEnd = failure - ? failure[1][0] === notFound + ? failure[1][0] === NOT_FOUND ? getNotFoundBoundary(worker, lane.matches, failure) : failure[0] : plannedBoundary < 0 @@ -578,7 +578,7 @@ export async function loadServer( : plannedBoundary const chunkFailure = await loadNormalChunks(worker, lane, readinessEnd) if (chunkFailure) { - if (chunkFailure[1][0] === redirected) { + if (chunkFailure[1][0] === REDIRECTED) { abortMatches(lane.matches) return resolveServerRedirect(worker, location, chunkFailure[1][1]) } @@ -591,7 +591,7 @@ export async function loadServer( if (match.ssr === true) { const route = getRoute(worker, match) try { - if (terminal.kind === error) { + if (terminal.kind === ERROR) { await loadRouteChunk(route, 'errorComponent') } else if (match.globalNotFound) { await Promise.all([ From 4fd731e7879ecd42b7598db000e9445bf101f517 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Tue, 14 Jul 2026 15:30:33 +0200 Subject: [PATCH 15/59] cleanup load-client --- packages/router-core/src/load-client.ts | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/packages/router-core/src/load-client.ts b/packages/router-core/src/load-client.ts index 56f265de19..ca5958dbf5 100644 --- a/packages/router-core/src/load-client.ts +++ b/packages/router-core/src/load-client.ts @@ -23,7 +23,7 @@ type Lane = { readonly [lanePhase]?: TPhase location: ParsedLocation matches: Array - background?: Array + background?: Array } type MatchedLane = Lane<'matched'> @@ -97,13 +97,13 @@ type WorkerRouter = Pick< 'buildLocation' | 'navigate' | 'options' | 'routeTree' | 'routesById' > -type Task = { +type LoaderTask = { outcome: Promise ready: Promise match?: Promise } -type BackgroundTask = Task & { +type BackgroundLoaderTask = LoaderTask & { index: number candidate: WorkMatch } @@ -502,12 +502,12 @@ function applySuccess(match: WorkMatch, data: unknown): void { match.updatedAt = Date.now() } -function createTask( +function createLoaderTask( router: ClientRouter, workerRouter: WorkerRouter, lane: ContextualizedLane, index: number, - tasks: Array, + tasks: Array, semanticParent: Promise | undefined, options: ExecuteLaneOptions, ): Promise { @@ -666,7 +666,7 @@ function getNotFoundBoundary( async function reduceLane( router: WorkerRouter & ClientRouter, lane: ContextualizedLane, - tasks: Array, + tasks: Array, options: ExecuteLaneOptions, serialFailure?: IndexedOutcome, ): Promise { @@ -679,7 +679,7 @@ async function reduceLane( for (let index = 0; index < tasks.length; index++) { const task = tasks[index]! const outcome = await task.outcome - const taskIndex = (task as BackgroundTask).index ?? index + const taskIndex = (task as BackgroundLoaderTask).index ?? index if (outcome[0] >= REDIRECTED) { control = [taskIndex, outcome] break @@ -708,7 +708,7 @@ async function reduceLane( : lane.matches.length for (let index = 0; index < tasks.length; index++) { const task = tasks[index]! - if (((task as BackgroundTask).index ?? index) >= readinessEnd) { + if (((task as BackgroundLoaderTask).index ?? index) >= readinessEnd) { break } const chunkFailure = await task.ready @@ -754,7 +754,7 @@ async function reduceLane( let match = lane.matches[boundary]! if ( background && - !(tasks as Array).some((task) => task.index === boundary) + !(tasks as Array).some((task) => task.index === boundary) ) { match = lane.matches[boundary] = { ...match, _flight: undefined } } @@ -868,7 +868,7 @@ export async function executeClientLane( options.sync = true } const contextualized = matched as ContextualizedLane - const tasks: Array = [] + const tasks: Array = [] let semanticParent: Promise | undefined let end = failure?.[0] ?? contextualized.matches.length if (failure?.[1][0] === NOT_FOUND) { @@ -883,7 +883,7 @@ export async function executeClientLane( if (options.controller.signal.aborted) { break } - semanticParent = createTask( + semanticParent = createLoaderTask( clientRouter, workerRouter, contextualized, @@ -1138,7 +1138,7 @@ async function runBackground( router: CoordinatorRouter, tx: LoadTransaction, base: Array, - tasks: Array, + tasks: Array, ): Promise { const backgroundMatches = tasks.map((task) => task.candidate) const next = base.slice() as Array From acbfba3c39bc7b7d494fcdeeb34a8d72db65189d Mon Sep 17 00:00:00 2001 From: Sheraff Date: Tue, 14 Jul 2026 15:30:53 +0200 Subject: [PATCH 16/59] fix load-client for undefined loaderData --- packages/router-core/src/load-client.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/packages/router-core/src/load-client.ts b/packages/router-core/src/load-client.ts index ca5958dbf5..f0e83c680d 100644 --- a/packages/router-core/src/load-client.ts +++ b/packages/router-core/src/load-client.ts @@ -492,9 +492,7 @@ function shouldReloadMatch( } function applySuccess(match: WorkMatch, data: unknown): void { - if (data !== undefined) { - match.loaderData = data - } + match.loaderData = data match.error = undefined match.status = 'success' match.invalid = false From 8fcf2ebe430fe23d238b60cbad277f6b53d158be Mon Sep 17 00:00:00 2001 From: Sheraff Date: Tue, 14 Jul 2026 15:32:09 +0200 Subject: [PATCH 17/59] cleanup load-server --- packages/router-core/src/load-server.ts | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/packages/router-core/src/load-server.ts b/packages/router-core/src/load-server.ts index 2a7ebdbbb5..51256635ef 100644 --- a/packages/router-core/src/load-server.ts +++ b/packages/router-core/src/load-server.ts @@ -26,7 +26,7 @@ type ServerLane = { type MatchedLane = ServerLane<'matched'> -type IndexedOutcome = [index: number, outcome: LoadOutcome] +type IndexedOutcome = [index: number, outcome: LoaderOutcome] type ContextualizedLane = ServerLane<'contextualized'> & { end: number @@ -41,7 +41,7 @@ const NOT_FOUND = 2 const REDIRECTED = 3 const SKIPPED = 4 -type LoadOutcome = +type LoaderOutcome = | [typeof SUCCESS, data: unknown] | [typeof ERROR, error: unknown] | [typeof NOT_FOUND, error: NotFoundError] @@ -50,7 +50,7 @@ type LoadOutcome = type LoaderTask = { index: number - outcome: Promise + outcome: Promise match: Promise } @@ -77,7 +77,7 @@ function getRoute(router: ServerWorker, match: AnyRouteMatch): AnyRoute { return (router.routesById as Record)[match.routeId]! } -function normalize(value: unknown, rejected: boolean): LoadOutcome { +function normalize(value: unknown, rejected: boolean): LoaderOutcome { if (isRedirect(value)) { return [REDIRECTED, value] } @@ -87,7 +87,7 @@ function normalize(value: unknown, rejected: boolean): LoadOutcome { return rejected ? [ERROR, value] : [SUCCESS, value] } -function normalizeError(route: AnyRoute, cause: unknown): LoadOutcome { +function normalizeError(route: AnyRoute, cause: unknown): LoaderOutcome { let outcome = normalize(cause, true) if (outcome[0] !== ERROR) { return outcome @@ -167,8 +167,8 @@ async function resolveSsr( function stampNotFound( match: AnyRouteMatch, - outcome: LoadOutcome, -): LoadOutcome { + outcome: LoaderOutcome, +): LoaderOutcome { if (outcome[0] === NOT_FOUND && !outcome[1].routeId) { outcome[1].routeId = match.routeId } @@ -309,15 +309,15 @@ function startLoader( ): LoaderTask { const match = lane.matches[index]! const route = getRoute(router, match) - let outcome: Promise + let outcome: Promise if (match.ssr === false) { - outcome = Promise.resolve([SKIPPED]) + outcome = Promise.resolve([SKIPPED]) } else { const option = route.options.loader const loader = typeof option === 'function' ? option : option?.handler if (!loader) { - outcome = Promise.resolve([SUCCESS, undefined]) + outcome = Promise.resolve([SUCCESS, undefined]) } else { let value: unknown let rejected = false From 3ba393ec4b5e4341024339ff8237545e9b45726d Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Tue, 14 Jul 2026 13:41:49 +0000 Subject: [PATCH 18/59] ci: apply automated fixes --- packages/router-core/src/load-client.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/router-core/src/load-client.ts b/packages/router-core/src/load-client.ts index f0e83c680d..1629151a73 100644 --- a/packages/router-core/src/load-client.ts +++ b/packages/router-core/src/load-client.ts @@ -752,7 +752,9 @@ async function reduceLane( let match = lane.matches[boundary]! if ( background && - !(tasks as Array).some((task) => task.index === boundary) + !(tasks as Array).some( + (task) => task.index === boundary, + ) ) { match = lane.matches[boundary] = { ...match, _flight: undefined } } From 3d252e60b51bc73c992ff7a35a69cbd320069080 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Tue, 14 Jul 2026 16:23:53 +0200 Subject: [PATCH 19/59] more cleanup --- packages/router-core/src/load-client.ts | 174 ++++++++++-------------- packages/router-core/src/load-server.ts | 58 ++++---- packages/router-core/src/router.ts | 12 +- 3 files changed, 103 insertions(+), 141 deletions(-) diff --git a/packages/router-core/src/load-client.ts b/packages/router-core/src/load-client.ts index 1629151a73..883f4da14f 100644 --- a/packages/router-core/src/load-client.ts +++ b/packages/router-core/src/load-client.ts @@ -17,9 +17,7 @@ import type { AnyRouter } from './router' declare const lanePhase: unique symbol -type Phase = 'matched' | 'contextualized' | 'reduced' | 'projected' - -type Lane = { +type Lane = { readonly [lanePhase]?: TPhase location: ParsedLocation matches: Array @@ -27,12 +25,9 @@ type Lane = { } type MatchedLane = Lane<'matched'> - type ContextualizedLane = Lane<'contextualized'> - type ReducedLane = Lane<'reduced'> - -export type ProjectedLane = Lane<'projected'> +type ProjectedLane = Lane<'projected'> const SUCCESS = 0 const ERROR = 1 @@ -62,10 +57,6 @@ type WorkMatch = AnyRouteMatch & { _preloadBeforeLoad?: AnyRoute['options']['beforeLoad'] } -type ClientRouter = AnyRouter & { - _flights?: Map -} - export type LoadTransaction = { location: ParsedLocation controller: AbortController @@ -84,18 +75,11 @@ export type PendingSession = { ack?: Promise } -type CoordinatorRouter = ClientRouter & { - _tx?: LoadTransaction - _committedMatches?: Array - _pending?: PendingSession +type CoordinatorRouter = AnyRouter & { /** Cancels reentrant synchronous planning without replacing the current writer. */ _preflight?: AbortController } -type WorkerRouter = Pick< - AnyRouter, - 'buildLocation' | 'navigate' | 'options' | 'routeTree' | 'routesById' -> type LoaderTask = { outcome: Promise @@ -143,7 +127,7 @@ function waitFor( }) } -function getRoute(router: WorkerRouter, match: WorkMatch): AnyRoute { +function getRoute(router: AnyRouter, match: WorkMatch): AnyRoute { return (router.routesById as Record)[match.routeId]! } @@ -175,7 +159,7 @@ function normalizeError(route: AnyRoute, cause: unknown): LoaderOutcome { return outcome } -function navigateFrom(router: WorkerRouter, location: ParsedLocation) { +function navigateFrom(router: AnyRouter, location: ParsedLocation) { return (opts: any) => router.navigate({ ...opts, @@ -184,7 +168,7 @@ function navigateFrom(router: WorkerRouter, location: ParsedLocation) { } async function contextualize( - router: WorkerRouter, + router: AnyRouter, lane: MatchedLane, options: ExecuteLaneOptions, ): Promise { @@ -199,7 +183,7 @@ async function contextualize( const serialError = match.paramsError ?? match.searchError if (serialError !== undefined) { - releaseFlight(router as ClientRouter, match) + releaseFlight(router, match) return [index, normalizeError(route, serialError)] } @@ -276,7 +260,7 @@ async function contextualize( match.isFetching = false const outcome = normalize(result, false, route.id) if (outcome[0] !== SUCCESS) { - releaseFlight(router as ClientRouter, match) + releaseFlight(router, match) return [index, outcome] } match.__beforeLoadContext = result @@ -298,7 +282,7 @@ async function contextualize( if (cause instanceof Promise) { throw cause } - releaseFlight(router as ClientRouter, match) + releaseFlight(router, match) return [index, normalizeError(route, cause)] } } @@ -306,7 +290,7 @@ async function contextualize( return } -function releaseFlight(router: ClientRouter, match: WorkMatch): void { +function releaseFlight(router: AnyRouter, match: WorkMatch): void { const flight = match._flight if (!flight) { return @@ -334,13 +318,13 @@ export function transferMatchResources( ): void { for (const match of previous as Array) { if (!next.includes(match)) { - releaseFlight(router as ClientRouter, match) + releaseFlight(router, match) } } } function startFlight( - router: ClientRouter, + router: AnyRouter, key: string, route: AnyRoute, invoke: (controller: AbortController) => unknown, @@ -364,7 +348,7 @@ function startFlight( return flight } -function closeFlight(router: ClientRouter, match: WorkMatch): void { +function closeFlight(router: AnyRouter, match: WorkMatch): void { const flight = match._flight if (!flight) { return @@ -375,7 +359,7 @@ function closeFlight(router: ClientRouter, match: WorkMatch): void { } function getLoaderContext( - router: WorkerRouter, + router: AnyRouter, lane: ContextualizedLane, match: WorkMatch, route: AnyRoute, @@ -399,8 +383,7 @@ function getLoaderContext( } async function loadResource( - router: ClientRouter, - workerRouter: WorkerRouter, + router: AnyRouter, lane: ContextualizedLane, match: WorkMatch, route: AnyRoute, @@ -426,7 +409,7 @@ async function loadResource( flight = startFlight(router, match.id, route, (controller) => loader( getLoaderContext( - workerRouter, + router, lane, match, route, @@ -459,7 +442,7 @@ async function loadResource( } function shouldReloadMatch( - router: WorkerRouter, + router: AnyRouter, match: WorkMatch, route: AnyRoute, options: ExecuteLaneOptions, @@ -501,8 +484,7 @@ function applySuccess(match: WorkMatch, data: unknown): void { } function createLoaderTask( - router: ClientRouter, - workerRouter: WorkerRouter, + router: AnyRouter, lane: ContextualizedLane, index: number, tasks: Array, @@ -510,7 +492,7 @@ function createLoaderTask( options: ExecuteLaneOptions, ): Promise { const match = lane.matches[index]! - const route = getRoute(workerRouter, match) + const route = getRoute(router, match) const preload = !!options.preload let reload = false let reloadFailure: LoaderOutcome | undefined @@ -524,7 +506,7 @@ function createLoaderTask( if (typeof configured === 'function') { configured = configured( getLoaderContext( - workerRouter, + router, lane, match, route, @@ -536,7 +518,7 @@ function createLoaderTask( } } reload = shouldReloadMatch( - workerRouter, + router, match, route, options, @@ -557,7 +539,7 @@ function createLoaderTask( ((typeof routeLoader === 'function' ? undefined : routeLoader?.staleReloadMode) ?? - workerRouter.options.defaultStaleReloadMode) !== 'blocking' + router.options.defaultStaleReloadMode) !== 'blocking' ) const skippedPreload = preload && route.options.preload === false const loaded = reload && !skippedPreload @@ -572,7 +554,6 @@ function createLoaderTask( ? Promise.resolve([SUCCESS, match.loaderData]) : loadResource( router, - workerRouter, lane, match, route, @@ -616,7 +597,6 @@ function createLoaderTask( } const backgroundOutcome = loadResource( router, - workerRouter, lane, candidate, route, @@ -641,7 +621,7 @@ function createLoaderTask( } function getNotFoundBoundary( - router: WorkerRouter, + router: AnyRouter, matches: Array, indexed: IndexedOutcome, ): number { @@ -662,7 +642,7 @@ function getNotFoundBoundary( } async function reduceLane( - router: WorkerRouter & ClientRouter, + router: AnyRouter, lane: ContextualizedLane, tasks: Array, options: ExecuteLaneOptions, @@ -734,7 +714,7 @@ async function reduceLane( if (control) { if (lane.background) { discardMatchResources( - router as AnyRouter, + router, lane.background.map((task) => task.candidate), ) lane.background = undefined @@ -787,13 +767,13 @@ async function reduceLane( } function trimLane( - router: ClientRouter, + router: AnyRouter, lane: ContextualizedLane, length: number, background: boolean, ): void { if (!background) { - discardMatchResources(router as AnyRouter, lane.matches.slice(length)) + discardMatchResources(router, lane.matches.slice(length)) } lane.matches.length = length if (!lane.background || background) { @@ -804,14 +784,14 @@ function trimLane( if (task.index < length) { lane.background[write++] = task } else { - discardMatchResources(router as AnyRouter, [task.candidate]) + discardMatchResources(router, [task.candidate]) } } lane.background.length = write } async function projectLane( - router: WorkerRouter, + router: AnyRouter, lane: ReducedLane, start = 0, ): Promise { @@ -850,20 +830,18 @@ export async function executeClientLane( matches: Array, options: ExecuteLaneOptions, ): Promise { - const clientRouter = router as ClientRouter - const workerRouter = router as WorkerRouter - const matched = { + const matched: MatchedLane = { location, matches: matches as Array, - } as MatchedLane + } for (const match of matched.matches) { - const flight = clientRouter._flights?.get(match.id) ?? match._flight + const flight = router._flights?.get(match.id) ?? match._flight if (flight) { match._flight = flight flight[2]++ } } - const failure = await contextualize(workerRouter, matched, options) + const failure = await contextualize(router, matched, options) if (failure) { options.sync = true } @@ -874,7 +852,7 @@ export async function executeClientLane( if (failure?.[1][0] === NOT_FOUND) { end = Math.min( end, - getNotFoundBoundary(workerRouter, contextualized.matches, failure) + 1, + getNotFoundBoundary(router, contextualized.matches, failure) + 1, ) } else if ((failure?.[1][0] ?? 0) >= REDIRECTED) { end = 0 @@ -884,8 +862,7 @@ export async function executeClientLane( break } semanticParent = createLoaderTask( - clientRouter, - workerRouter, + router, contextualized, index, tasks, @@ -894,7 +871,7 @@ export async function executeClientLane( ) } const reduced = await reduceLane( - router as WorkerRouter & ClientRouter, + router, contextualized, tasks, options, @@ -904,7 +881,7 @@ export async function executeClientLane( return reduced } return projectLane( - workerRouter, + router, reduced, Math.min(options.resolvedPrefix ?? 0, reduced.matches.length - 1), ) @@ -1154,7 +1131,7 @@ async function runBackground( redirects: tx.redirects, } const reduced = await reduceLane( - router as WorkerRouter & ClientRouter, + router, lane, tasks, options, @@ -1177,7 +1154,7 @@ async function runBackground( } return } - const projected = await projectLane(router as WorkerRouter, reduced) + const projected = await projectLane(router, reduced) if (router._tx !== tx || router._committedMatches !== base) { discardMatchResources(router, backgroundMatches) return @@ -1299,14 +1276,13 @@ async function runClientTransaction( } export async function loadClientRouter( - router: AnyRouter, + router: CoordinatorRouter, opts?: { sync?: boolean /** @internal */ _refreshRouteId?: string }, ): Promise { - const clientRouter = router as CoordinatorRouter const refreshRouteId = process.env.NODE_ENV !== 'production' ? opts?._refreshRouteId : undefined const canReuse = refreshRouteId @@ -1320,14 +1296,14 @@ export async function loadClientRouter( return true } : undefined - const committed = (clientRouter._committedMatches ??= + const committed = (router._committedMatches ??= router.stores.matches.get()) - const previousOwner = clientRouter._tx + const previousOwner = router._tx const resolvedLocation = router.stores.resolvedLocation.get() const previousLocation = resolvedLocation ?? router.stores.location.get() const controller = new AbortController() - clientRouter._preflight?.abort() - clientRouter._preflight = controller + router._preflight?.abort() + router._preflight = controller const location = router.latestLocation let matches: Array @@ -1340,14 +1316,14 @@ export async function loadClientRouter( ) } catch (cause) { const stale = - controller.signal.aborted || clientRouter._tx !== previousOwner + controller.signal.aborted || router._tx !== previousOwner controller.abort() if (stale) { - await awaitCurrent(clientRouter, previousOwner) + await awaitCurrent(router, previousOwner) return } if (!isRedirect(cause)) { - await awaitCurrent(clientRouter) + await awaitCurrent(router) router.commitLocationPromise?.resolve() router.commitLocationPromise = undefined return @@ -1357,16 +1333,16 @@ export async function loadClientRouter( replace: true, ignoreBlocker: true, }) - await awaitCurrent(clientRouter, previousOwner) + await awaitCurrent(router, previousOwner) return } - if (controller.signal.aborted || clientRouter._tx !== previousOwner) { + if (controller.signal.aborted || router._tx !== previousOwner) { controller.abort() - await awaitCurrent(clientRouter, previousOwner) + await awaitCurrent(router, previousOwner) return } - clientRouter._preflight = undefined + router._preflight = undefined const sameHref = previousLocation.href === location.href let resolvedPrefix: number | undefined @@ -1397,24 +1373,24 @@ export async function loadClientRouter( done: Promise.resolve() .then(() => runClientTransaction( - clientRouter, + router, tx, refreshRouteId ? false : sameHref, - refreshRouteId ? undefined : () => offerPending(clientRouter, tx), + refreshRouteId ? undefined : () => offerPending(router, tx), opts?.sync, resolvedPrefix, ), ) .catch(() => { - if (clientRouter._tx === tx) { - finishPending(clientRouter, tx) + if (router._tx === tx) { + finishPending(router, tx) controller.abort() discardMatchResources(router, tx.matches) router.batch(() => { router.stores.status.set('idle') - router.stores.setMatches(clientRouter._committedMatches ?? []) + router.stores.setMatches(router._committedMatches ?? []) }) - if (clientRouter._tx !== tx) { + if (router._tx !== tx) { return } router.commitLocationPromise?.resolve() @@ -1423,7 +1399,7 @@ export async function loadClientRouter( }), redirects: previousOwner?.redirecting ? previousOwner.redirects : undefined, } - clientRouter._tx = tx + router._tx = tx previousOwner?.controller.abort() if (previousOwner) { discardMatchResources(router, previousOwner.matches) @@ -1434,26 +1410,25 @@ export async function loadClientRouter( router.stores.location.set(location) }) if (!refreshRouteId) { - offerPending(clientRouter, tx) + offerPending(router, tx) } try { await tx.done } finally { - await awaitCurrent(clientRouter, tx) + await awaitCurrent(router, tx) } } export function refreshClientRoute( - router: AnyRouter, + router: CoordinatorRouter, routeId: string, ): Promise { - const clientRouter = router as CoordinatorRouter - if (clientRouter._flights) { - for (const flight of clientRouter._flights.values()) { + if (router._flights) { + for (const flight of router._flights.values()) { flight[1].abort() } - clientRouter._flights.clear() + router._flights.clear() } router.clearCache() @@ -1461,17 +1436,16 @@ export function refreshClientRoute( } export async function preloadClientRoute( - router: AnyRouter, + router: CoordinatorRouter, opts: any, redirects = 0, ): Promise | undefined> { if (redirects > 20) { return } - const clientRouter = router as CoordinatorRouter - const owner = clientRouter._tx + const owner = router._tx const location = opts._builtLocation ?? router.buildLocation(opts) - const base = semanticMatches(clientRouter) + const base = semanticMatches(router) const plannedCache = router.stores.cachedMatches.get() const controller = new AbortController() let matches: Array | undefined @@ -1480,7 +1454,7 @@ export async function preloadClientRoute( throwOnError: true, preload: true, _controller: controller, - _isCurrent: () => clientRouter._tx === owner, + _isCurrent: () => router._tx === owner, }) let resolvedPrefix = 0 while ( @@ -1517,7 +1491,7 @@ export async function preloadClientRoute( } const active = new Set( - semanticMatches(clientRouter).map((match) => match.id), + semanticMatches(router).map((match) => match.id), ) const previous = router.stores.cachedMatches.get() const candidates: Array = [] @@ -1529,7 +1503,7 @@ export async function preloadClientRoute( match._preloadBeforeLoad !== getRoute(router, match).options.beforeLoad if (obsoleteContext) { - releaseFlight(clientRouter, match) + releaseFlight(router, match) continue } } @@ -1538,10 +1512,10 @@ export async function preloadClientRoute( previous.find((candidate) => candidate.id === match.id) !== plannedCache.find((candidate) => candidate.id === match.id) ) { - releaseFlight(clientRouter, match) + releaseFlight(router, match) continue } - closeFlight(clientRouter, match) + closeFlight(router, match) candidates.push(match) } const ids = new Set(candidates.map((match) => match.id)) @@ -1551,7 +1525,7 @@ export async function preloadClientRoute( router.stores.setCached(cached) transferMatchResources(router, previous, [ ...cached, - ...semanticMatches(clientRouter), + ...semanticMatches(router), ]) return matches } catch (cause) { @@ -1563,7 +1537,7 @@ export async function preloadClientRoute( } controller.abort() discardMatchResources(router, matches) - if (clientRouter._tx !== owner) { + if (router._tx !== owner) { return } if (isRedirect(cause) && !cause.options.reloadDocument) { diff --git a/packages/router-core/src/load-server.ts b/packages/router-core/src/load-server.ts index 51256635ef..6f7d6351ad 100644 --- a/packages/router-core/src/load-server.ts +++ b/packages/router-core/src/load-server.ts @@ -54,17 +54,6 @@ type LoaderTask = { match: Promise } -type ServerWorker = Pick< - AnyRouter, - | 'buildLocation' - | 'isShell' - | 'navigate' - | 'options' - | 'resolveRedirect' - | 'routeTree' - | 'routesById' -> - export type ServerLoadResult = | { type: 'render' @@ -73,8 +62,8 @@ export type ServerLoadResult = } | { type: 'redirect'; redirect: AnyRedirect } -function getRoute(router: ServerWorker, match: AnyRouteMatch): AnyRoute { - return (router.routesById as Record)[match.routeId]! +function getRoute(router: AnyRouter, match: AnyRouteMatch): AnyRoute { + return router.routesById[match.routeId] } function normalize(value: unknown, rejected: boolean): LoaderOutcome { @@ -110,7 +99,7 @@ function maybe( return { status: 'success', value } } -function navigateFrom(router: ServerWorker, location: ParsedLocation) { +function navigateFrom(router: AnyRouter, location: ParsedLocation) { return (options: any) => router.navigate({ ...options, @@ -119,7 +108,7 @@ function navigateFrom(router: ServerWorker, location: ParsedLocation) { } async function resolveSsr( - router: ServerWorker, + router: AnyRouter, lane: MatchedLane, index: number, ): Promise { @@ -176,7 +165,7 @@ function stampNotFound( } async function contextualize( - router: ServerWorker, + router: AnyRouter, lane: MatchedLane, preload: boolean, ): Promise { @@ -277,7 +266,7 @@ async function contextualize( } function loaderContext( - router: ServerWorker, + router: AnyRouter, lane: ContextualizedLane, match: AnyRouteMatch, route: AnyRoute, @@ -289,7 +278,7 @@ function loaderContext( params: match.params, deps: match.loaderDeps, preload, - parentMatchPromise: tasks[index - 1]?.match as any, + parentMatchPromise: tasks[index - 1]?.match, abortController: match.abortController, context: match.context, location: lane.location, @@ -301,7 +290,7 @@ function loaderContext( } function startLoader( - router: ServerWorker, + router: AnyRouter, lane: ContextualizedLane, index: number, tasks: Array, @@ -361,7 +350,7 @@ function startLoader( } function getNotFoundBoundary( - router: ServerWorker, + router: AnyRouter, matches: Array, indexed: IndexedOutcome, ): number { @@ -388,7 +377,7 @@ function abortMatches(matches: Array, start = 0): void { } function resolveServerRedirect( - router: ServerWorker, + router: AnyRouter, location: ParsedLocation, value: AnyRedirect, ): ServerLoadResult { @@ -397,7 +386,7 @@ function resolveServerRedirect( } function applyFailure( - router: ServerWorker, + router: AnyRouter, lane: ContextualizedLane, indexed: IndexedOutcome | undefined, ): { status: 200 | 404 | 500; boundary?: number; kind?: number } { @@ -443,7 +432,7 @@ function applyFailure( } async function loadNormalChunks( - router: ServerWorker, + router: AnyRouter, lane: ContextualizedLane, end: number, ): Promise { @@ -471,7 +460,7 @@ async function loadNormalChunks( return undefined } -async function project(router: ServerWorker, lane: ReducedLane): Promise { +async function project(router: AnyRouter, lane: ReducedLane): Promise { for (const match of lane.matches) { const routeOptions = getRoute(router, match).options if ( @@ -511,7 +500,6 @@ export async function loadServer( matchedMatches: Array, preload = false, ): Promise { - const worker = router as ServerWorker const matched = { location, matches: matchedMatches.map((match) => ({ @@ -522,7 +510,7 @@ export async function loadServer( abortController: new AbortController(), })), } as MatchedLane - const lane = await contextualize(worker, matched, preload) + const lane = await contextualize(router, matched, preload) let loaderEnd = lane.end if (lane.failure?.[1][0] === REDIRECTED) { @@ -530,13 +518,13 @@ export async function loadServer( } else if (lane.failure?.[1][0] === NOT_FOUND) { loaderEnd = Math.min( loaderEnd, - getNotFoundBoundary(worker, lane.matches, lane.failure) + 1, + getNotFoundBoundary(router, lane.matches, lane.failure) + 1, ) } const tasks: Array = [] for (let index = 0; index < loaderEnd; index++) { - const task = startLoader(worker, lane, index, tasks, preload) + const task = startLoader(router, lane, index, tasks, preload) tasks.push(task) } @@ -562,7 +550,7 @@ export async function loadServer( if (control?.[1][0] === REDIRECTED) { abortMatches(lane.matches) - return resolveServerRedirect(worker, location, control[1][1]) + return resolveServerRedirect(router, location, control[1][1]) } let failure = loaderFailure ?? lane.failure @@ -571,25 +559,25 @@ export async function loadServer( ) const readinessEnd = failure ? failure[1][0] === NOT_FOUND - ? getNotFoundBoundary(worker, lane.matches, failure) + ? getNotFoundBoundary(router, lane.matches, failure) : failure[0] : plannedBoundary < 0 ? lane.matches.length : plannedBoundary - const chunkFailure = await loadNormalChunks(worker, lane, readinessEnd) + const chunkFailure = await loadNormalChunks(router, lane, readinessEnd) if (chunkFailure) { if (chunkFailure[1][0] === REDIRECTED) { abortMatches(lane.matches) - return resolveServerRedirect(worker, location, chunkFailure[1][1]) + return resolveServerRedirect(router, location, chunkFailure[1][1]) } failure = chunkFailure } - const terminal = applyFailure(worker, lane, failure) + const terminal = applyFailure(router, lane, failure) if (terminal.boundary !== undefined) { const match = lane.matches[terminal.boundary]! if (match.ssr === true) { - const route = getRoute(worker, match) + const route = getRoute(router, match) try { if (terminal.kind === ERROR) { await loadRouteChunk(route, 'errorComponent') @@ -605,7 +593,7 @@ export async function loadServer( } } - await project(worker, { + await project(router, { location: lane.location, matches: lane.matches, } as ReducedLane) diff --git a/packages/router-core/src/router.ts b/packages/router-core/src/router.ts index 24250b3aee..15263e35e6 100644 --- a/packages/router-core/src/router.ts +++ b/packages/router-core/src/router.ts @@ -1008,13 +1008,13 @@ export class RouterCore< shouldViewTransition?: boolean | ViewTransitionOptions = undefined isViewTransitionTypesSupported?: boolean = undefined subscribers = new Set>() - _tx?: LoadTransaction - _flights?: Map + declare _tx?: LoadTransaction + declare _flights?: Map /** Terminal semantic lane; pending presentation never becomes a planning base. */ - _committedMatches?: Array - _pending?: PendingSession - _serverResult?: ServerLoadResult - _rendered?: () => void + declare _committedMatches?: Array + declare _pending?: PendingSession + declare _serverResult?: ServerLoadResult + declare _rendered?: () => void declare _refreshRoute: ((routeId: string) => Promise) | undefined // Must build in constructor From 4150cdf073638f64ba30bb2496a2dcb3210ad45e Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Tue, 14 Jul 2026 14:25:53 +0000 Subject: [PATCH 20/59] ci: apply automated fixes --- packages/router-core/src/load-client.ts | 30 +++++++------------------ 1 file changed, 8 insertions(+), 22 deletions(-) diff --git a/packages/router-core/src/load-client.ts b/packages/router-core/src/load-client.ts index 883f4da14f..00cf3bb971 100644 --- a/packages/router-core/src/load-client.ts +++ b/packages/router-core/src/load-client.ts @@ -17,7 +17,9 @@ import type { AnyRouter } from './router' declare const lanePhase: unique symbol -type Lane = { +type Lane< + TPhase extends 'matched' | 'contextualized' | 'reduced' | 'projected', +> = { readonly [lanePhase]?: TPhase location: ParsedLocation matches: Array @@ -80,7 +82,6 @@ type CoordinatorRouter = AnyRouter & { _preflight?: AbortController } - type LoaderTask = { outcome: Promise ready: Promise @@ -517,13 +518,7 @@ function createLoaderTask( ) } } - reload = shouldReloadMatch( - router, - match, - route, - options, - configured, - ) + reload = shouldReloadMatch(router, match, route, options, configured) } } catch (cause) { releaseFlight(router, match) @@ -1130,12 +1125,7 @@ async function runBackground( controller: tx.controller, redirects: tx.redirects, } - const reduced = await reduceLane( - router, - lane, - tasks, - options, - ) + const reduced = await reduceLane(router, lane, tasks, options) if (Array.isArray(reduced)) { discardMatchResources(router, backgroundMatches) if ( @@ -1296,8 +1286,7 @@ export async function loadClientRouter( return true } : undefined - const committed = (router._committedMatches ??= - router.stores.matches.get()) + const committed = (router._committedMatches ??= router.stores.matches.get()) const previousOwner = router._tx const resolvedLocation = router.stores.resolvedLocation.get() const previousLocation = resolvedLocation ?? router.stores.location.get() @@ -1315,8 +1304,7 @@ export async function loadClientRouter( : { _controller: controller }, ) } catch (cause) { - const stale = - controller.signal.aborted || router._tx !== previousOwner + const stale = controller.signal.aborted || router._tx !== previousOwner controller.abort() if (stale) { await awaitCurrent(router, previousOwner) @@ -1490,9 +1478,7 @@ export async function preloadClientRoute( return } - const active = new Set( - semanticMatches(router).map((match) => match.id), - ) + const active = new Set(semanticMatches(router).map((match) => match.id)) const previous = router.stores.cachedMatches.get() const candidates: Array = [] let obsoleteContext = false From 3ecc24bdb188155328903a0265ebb98315948516 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Tue, 14 Jul 2026 20:35:11 +0200 Subject: [PATCH 21/59] update tests --- e2e/react-router/issue-7457/src/main.tsx | 6 +- .../selective-ssr/tests/app.spec.ts | 15 +- e2e/solid-start/selective-ssr/dev-server.ts | 5 + .../selective-ssr/playwright.config.ts | 22 +- .../tests/issue-7283-dev-hydration.spec.ts | 86 +- packages/react-router/tests/Matches.test.tsx | 2 +- ...mponent-preload-retry-pending-min.test.tsx | 19 +- .../tests/component-preload-retry.test.tsx | 9 +- .../tests/errorComponent.test.tsx | 29 +- ...hydration-capped-boundary-pending.test.tsx | 45 +- .../tests/hydration-terminal-lane.test.tsx | 46 +- ...sue-4476-react-query-cancellation.test.tsx | 15 +- .../tests/issue-4759-pending-frame.test.tsx | 61 +- ...8-router-provider-context-preload.test.tsx | 19 +- ...e-6107-lazy-chunk-error-component.test.tsx | 17 +- ...issue-7051-force-pending-suspense.test.tsx | 113 ++- ...-7635-error-head-after-navigation.test.tsx | 100 +++ packages/react-router/tests/loaders.test.tsx | 93 +-- .../on-rendered-same-href-state.test.tsx | 20 +- ...ding-fallback-promise-replacement.test.tsx | 182 ++-- .../tests/preloaded-mount-resolution.test.tsx | 47 +- packages/react-router/tests/redirect.test.tsx | 99 ++- .../tests/root-pending-min.test.tsx | 149 +--- packages/react-router/tests/router.test.tsx | 273 +++--- .../tests/transactional-loading.test.tsx | 41 +- .../transitioner-listener-errors.test.tsx | 6 +- .../tests/transitioner-render-ack.test.tsx | 48 +- .../tests/transitioner-router-swap.test.tsx | 32 +- .../react-router/tests/useNavigate.test.tsx | 4 + .../tests/background-assets-stale.test.ts | 8 +- .../blocked-navigation-current-load.test.ts | 46 +- .../tests/boundary-component-chunk.test.ts | 15 +- .../tests/client-lane-adversarial.test.ts | 13 +- .../tests/fatal-load-rejection.test.ts | 38 +- .../router-core/tests/granular-stores.test.ts | 140 ++++ packages/router-core/tests/hydrate.test.ts | 775 ++++++++---------- .../tests/hydrated-stay-match-data.test.ts | 131 ++- .../hydration-asset-context-order.test.ts | 99 ++- .../tests/hydration-boundary-chunks.test.ts | 200 +++-- .../tests/hydration-currentness.test.ts | 626 ++++++++------ ...ydration-terminal-error-child-head.test.ts | 172 ++++ .../invalidate-pre-rematch-failure.test.ts | 25 +- .../issue-3179-preload-cached-cause.test.ts | 6 +- .../issue-3293-on-enter-after-loader.test.ts | 60 +- .../issue-3928-rapid-reload-abort.test.ts | 180 ++-- ...4078-loader-notfound-root-boundary.test.ts | 102 ++- ...-4444-param-parse-error-lazy-child.test.ts | 17 +- ...4572-preload-root-beforeload-flags.test.ts | 111 ++- ...ssue-4684-head-on-beforeload-error.test.ts | 38 +- ...arent-context-search-normalization.test.ts | 22 +- ...ue-5106-hydrated-notfound-boundary.test.ts | 85 +- .../issue-6107-preload-chunk-failure.test.ts | 78 +- .../issue-6221-head-waits-for-loader.test.ts | 160 ++-- .../issue-6351-fuzzy-notfound-layout.test.ts | 70 +- ...ssue-7379-head-matches-direct-load.test.ts | 16 +- ...nt-beforeload-context-child-loader.test.ts | 53 +- ...e-7635-dehydrated-error-child-head.test.ts | 121 --- packages/router-core/tests/load.test.ts | 266 ++++-- .../tests/preload-adoption.test.ts | 126 ++- ...reload-background-parent-coherence.test.ts | 20 +- .../tests/preload-beforeload-reuse.test.ts | 22 +- .../tests/preload-navigation-adoption.test.ts | 41 +- .../preload-public-cache-behavior.test.ts | 50 +- .../preload-public-signal-lifetime.test.ts | 49 +- .../serial-failure-foreground-prefix.test.ts | 11 +- ...rver-async-headers-decorative-hang.test.ts | 23 +- .../server-chunk-failure-lifecycle.test.ts | 26 +- .../server-concurrent-error-notfound.test.ts | 232 ++++-- .../tests/server-loader-abort-error.test.ts | 5 +- .../tests/server-serial-ssr-notfound.test.ts | 17 +- .../tests/server-ssr-false-assets.test.ts | 58 +- .../tests/server-ssr-option-error.test.ts | 4 + .../tests/stay-match-abort.test.ts | 20 +- .../tests/superseded-load-await.test.ts | 13 +- packages/router-plugin/tests/add-hmr.test.ts | 29 + .../tests/handle-route-update.test.ts | 282 +++++-- packages/solid-router/tests/link.test.tsx | 13 +- packages/solid-router/tests/loaders.test.tsx | 114 ++- .../tests/on-rendered-change-info.test.tsx | 64 -- ...ding-fallback-promise-replacement.test.tsx | 234 +++--- packages/solid-router/tests/redirect.test.tsx | 13 +- packages/solid-router/tests/router.test.tsx | 82 +- .../tests/same-route-pending-blank.test.tsx | 33 +- .../tests/server/errorComponent.test.tsx | 35 +- .../transitioner-listener-errors.test.tsx | 56 +- .../tests/transitioner-remount.test.tsx | 61 +- .../tests/transitioner-render-ack.test.tsx | 272 ++++-- .../use-match-outgoing-transition.test.tsx | 30 +- .../tests/component-preload-retry.test.tsx | 6 +- ...hydration-capped-boundary-pending.test.tsx | 54 +- packages/vue-router/tests/router.test.tsx | 8 +- packages/vue-router/tests/ssr-test-utils.ts | 43 + .../transitioner-listener-errors.test.tsx | 33 +- .../transitioner-remount-rendered.test.tsx | 67 +- 94 files changed, 4671 insertions(+), 2851 deletions(-) create mode 100644 e2e/solid-start/selective-ssr/dev-server.ts create mode 100644 packages/react-router/tests/issue-7635-error-head-after-navigation.test.tsx create mode 100644 packages/router-core/tests/hydration-terminal-error-child-head.test.ts delete mode 100644 packages/router-core/tests/issue-7635-dehydrated-error-child-head.test.ts delete mode 100644 packages/solid-router/tests/on-rendered-change-info.test.tsx create mode 100644 packages/vue-router/tests/ssr-test-utils.ts diff --git a/e2e/react-router/issue-7457/src/main.tsx b/e2e/react-router/issue-7457/src/main.tsx index 70bf4bfacb..1b6805edc0 100644 --- a/e2e/react-router/issue-7457/src/main.tsx +++ b/e2e/react-router/issue-7457/src/main.tsx @@ -1,4 +1,4 @@ -import { StrictMode } from 'react' +import { StrictMode, useEffect } from 'react' import { createRoot } from 'react-dom/client' import { QueryClient } from '@tanstack/react-query' import { RouterProvider, createRouter } from '@tanstack/react-router' @@ -19,7 +19,9 @@ declare module '@tanstack/react-router' { } function DefaultPendingComponent() { - ;(globalThis as any).__pendingSeen = true + useEffect(() => { + ;(globalThis as any).__pendingSeen = true + }, []) return
loading
} diff --git a/e2e/react-start/selective-ssr/tests/app.spec.ts b/e2e/react-start/selective-ssr/tests/app.spec.ts index d6289d5689..3d7053f6fa 100644 --- a/e2e/react-start/selective-ssr/tests/app.spec.ts +++ b/e2e/react-start/selective-ssr/tests/app.spec.ts @@ -16,27 +16,26 @@ test.describe('selective ssr', () => { ) .not.toBeUndefined() - const { rootBeforeLoad, targetBeforeLoad } = await page.evaluate(() => { + const { rootBeforeLoads, targetBeforeLoad } = await page.evaluate(() => { const rootBeforeLoads = (globalThis as any).__issue4614RootBeforeLoads ?? [] return { - rootBeforeLoad: rootBeforeLoads.at(-1), + rootBeforeLoads, targetBeforeLoad: (globalThis as any).__issue4614TargetBeforeLoad, } }) - expect(targetBeforeLoad).toMatchObject({ + expect(rootBeforeLoads).toEqual([]) + expect(targetBeforeLoad).toEqual({ cause: 'preload', preload: true, + rootContext: 'server', + issue4614Context: 'server:cached', scenario: 'cached', }) - expect(targetBeforeLoad.rootContext).toBe(rootBeforeLoad?.root ?? 'server') - expect(targetBeforeLoad.issue4614Context).toBe( - rootBeforeLoad?.issue4614Context ?? 'server:cached', - ) }) - test('child receives fresh parent context when loaderDeps force a same-preload reload', async ({ + test('new loaderDeps match generation propagates fresh parent context to child (control)', async ({ page, }) => { await page.goto('/') diff --git a/e2e/solid-start/selective-ssr/dev-server.ts b/e2e/solid-start/selective-ssr/dev-server.ts new file mode 100644 index 0000000000..519075f261 --- /dev/null +++ b/e2e/solid-start/selective-ssr/dev-server.ts @@ -0,0 +1,5 @@ +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } + +export const devPort = await getTestServerPort(`${packageJson.name}-dev`) +export const devBaseURL = `http://localhost:${devPort}` diff --git a/e2e/solid-start/selective-ssr/playwright.config.ts b/e2e/solid-start/selective-ssr/playwright.config.ts index badd6db0eb..09e5c50410 100644 --- a/e2e/solid-start/selective-ssr/playwright.config.ts +++ b/e2e/solid-start/selective-ssr/playwright.config.ts @@ -1,6 +1,7 @@ import { defineConfig, devices } from '@playwright/test' import { getTestServerPort } from '@tanstack/router-e2e-utils' import packageJson from './package.json' with { type: 'json' } +import { devBaseURL, devPort } from './dev-server' const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` @@ -18,12 +19,21 @@ export default defineConfig({ 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', - }, + 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', + }, + { + command: `NODE_ENV=development VITE_SERVER_PORT=${devPort} pnpm dev:e2e --host localhost --port ${devPort} --strictPort`, + url: devBaseURL, + reuseExistingServer: !process.env.CI, + stdout: 'pipe', + timeout: 90_000, + }, + ], projects: [ { 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 index 817467a0e2..a054a0433a 100644 --- 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 @@ -1,7 +1,5 @@ -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 { devBaseURL } from '../dev-server' import type { Page } from '@playwright/test' // Regression test for https://github.com/TanStack/router/issues/7283 @@ -10,64 +8,8 @@ import type { Page } from '@playwright/test' // `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 - } - } -}) +// route never reaches its loaded component). Playwright therefore owns a +// separate `vite dev` server and drives the app against it. function collectHydrationFailures(page: Page) { const failures: Array = [] @@ -97,13 +39,30 @@ test.describe('dev-mode hydration of selective SSR routes with pendingComponent' await page.goto(`${devBaseURL}/ssr-false-pending-min`) - // The loaded component must eventually replace the pending UI. + // The loaded component is the issue oracle: main never reaches it. await expect(page.getByTestId('ssr-false-target')).toBeVisible({ timeout: 15_000, }) // No dev hydration mismatch may occur along the way. expect(failures).toEqual([]) + + await expect(page.getByTestId('ssr-false-pending')).not.toBeAttached() + + const lifecycleEvents = await page.evaluate(() => + ((globalThis as any).__events ?? []) + .map((event: { type: string }) => event.type) + .filter((type: string) => + ['pending-mounted', 'pending-unmounted', 'target-mounted'].includes( + type, + ), + ), + ) + expect(lifecycleEvents.slice(-3)).toEqual([ + 'pending-mounted', + 'pending-unmounted', + 'target-mounted', + ]) }) test('data-only route with pendingComponent hydrates cleanly and reaches its loaded component (regression vs main)', async ({ @@ -113,6 +72,9 @@ test.describe('dev-mode hydration of selective SSR routes with pendingComponent' await page.goto(`${devBaseURL}/data-only-pending-component`) + await expect( + page.getByTestId('data-only-pending-component-pending'), + ).toBeAttached() await expect( page.getByTestId('data-only-pending-component-ready-label'), ).toHaveText('OK - loader finished', { timeout: 15_000 }) diff --git a/packages/react-router/tests/Matches.test.tsx b/packages/react-router/tests/Matches.test.tsx index 94ed262cc4..f77a939a6a 100644 --- a/packages/react-router/tests/Matches.test.tsx +++ b/packages/react-router/tests/Matches.test.tsx @@ -145,7 +145,7 @@ test('should show pendingComponent of root route', async () => { expect(await rendered.findByTestId('root-content')).toBeInTheDocument() }) -test('a reused legacy notFoundRoute does not retain the previous parent layout', async () => { +test('legacy notFoundRoute drops a stale parent layout after navigation', async () => { const root = createRootRoute({ component: Outlet }) const parent = createRoute({ getParentRoute: () => root, diff --git a/packages/react-router/tests/component-preload-retry-pending-min.test.tsx b/packages/react-router/tests/component-preload-retry-pending-min.test.tsx index 25dee12a4e..b7963c0fa6 100644 --- a/packages/react-router/tests/component-preload-retry-pending-min.test.tsx +++ b/packages/react-router/tests/component-preload-retry-pending-min.test.tsx @@ -22,15 +22,15 @@ afterEach(() => { /** * A component-only route can fail while preloading its code, then retry from * its error UI through invalidate(). The retry is a fresh pending generation: - * it needs a match-local load promise so the rendered pending component can - * attach pendingMinMs to the work that actually owns readiness. + * its fallback must remain visible until the retried component preload is + * ready and pendingMinMs has elapsed. */ -test('component preload retry owns readiness and honors pendingMinMs', async () => { +test('component preload retry remains pending through pendingMinMs', async () => { vi.spyOn(console, 'error').mockImplementation(() => {}) const retryChunk = createControlledPromise() let preloadAttempt = 0 - let retryPromise: Promise | undefined + let retryInvalidation!: Promise let retrySettled = false const Page = Object.assign( @@ -52,8 +52,8 @@ test('component preload retry owns readiness and honors pendingMinMs', async () type="button" onClick={() => { reset() - retryPromise = router.invalidate() - void retryPromise.then(() => { + retryInvalidation = router.invalidate() + void retryInvalidation.then(() => { retrySettled = true }) }} @@ -94,7 +94,11 @@ test('component preload retry owns readiness and honors pendingMinMs', async () await act(async () => { await vi.advanceTimersByTimeAsync(0) }) + expect(Page.preload).toHaveBeenCalledTimes(2) expect(screen.getByTestId('page-pending')).toBeInTheDocument() + expect( + screen.queryByRole('button', { name: 'Retry chunk' }), + ).not.toBeInTheDocument() await act(async () => { retryChunk.resolve() @@ -112,10 +116,9 @@ test('component preload retry owns readiness and honors pendingMinMs', async () await act(async () => { await vi.advanceTimersByTimeAsync(1) - await retryPromise + await retryInvalidation }) - expect(Page.preload).toHaveBeenCalledTimes(2) expect(screen.getByTestId('page-content')).toBeInTheDocument() expect(screen.queryByTestId('page-pending')).not.toBeInTheDocument() }) diff --git a/packages/react-router/tests/component-preload-retry.test.tsx b/packages/react-router/tests/component-preload-retry.test.tsx index 6111a2dd2e..4672228875 100644 --- a/packages/react-router/tests/component-preload-retry.test.tsx +++ b/packages/react-router/tests/component-preload-retry.test.tsx @@ -56,7 +56,14 @@ test('a failed component download is retried from the route error UI', async () render() - fireEvent.click(await screen.findByRole('button', { name: 'Retry' })) + const retryButton = await screen.findByRole('button', { name: 'Retry' }) + expect(importer).toHaveBeenCalledTimes(1) + + fireEvent.click(retryButton) expect(await screen.findByText('Page content')).toBeInTheDocument() + expect(importer).toHaveBeenCalledTimes(2) + expect( + screen.queryByRole('button', { name: 'Retry' }), + ).not.toBeInTheDocument() }) diff --git a/packages/react-router/tests/errorComponent.test.tsx b/packages/react-router/tests/errorComponent.test.tsx index 15dcfbfa8c..4203b2af67 100644 --- a/packages/react-router/tests/errorComponent.test.tsx +++ b/packages/react-router/tests/errorComponent.test.tsx @@ -1,6 +1,5 @@ import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' -import ReactDOMServer from 'react-dom/server' import { Link, @@ -14,6 +13,11 @@ import { createRouter, notFound, } from '../src' +import { + RouterServer, + createRequestHandler, + renderRouterToString, +} from '../src/ssr/server' import type { ErrorComponentProps, RouterHistory } from '../src' function MyErrorComponent(props: ErrorComponentProps) { @@ -314,7 +318,6 @@ test('errorComponent receives primitive errors thrown from beforeLoad', async () }) test('SSR errorComponent receives primitive errors thrown from beforeLoad', async () => { - const history = createMemoryHistory({ initialEntries: ['/about'] }) const rootRoute = createRootRoute({ component: function Root() { return @@ -330,15 +333,25 @@ test('SSR errorComponent receives primitive errors thrown from beforeLoad', asyn errorComponent: ({ error }) =>
Error: {String(error)}
, }) - const router = createRouter({ - routeTree: rootRoute.addChildren([aboutRoute]), - history, + const handler = createRequestHandler({ + request: new Request('http://localhost/about'), + createRouter: () => + createRouter({ + routeTree: rootRoute.addChildren([aboutRoute]), + isServer: true, + }), }) - router.isServer = true - await router.load() + const response = await handler(({ router, responseHeaders }) => + renderRouterToString({ + router, + responseHeaders, + children: , + }), + ) - const html = ReactDOMServer.renderToString() + expect(response.status).toBe(500) + const html = await response.text() expect(html).toContain('Error:') expect(html).toContain('primitive error thrown') }) diff --git a/packages/react-router/tests/hydration-capped-boundary-pending.test.tsx b/packages/react-router/tests/hydration-capped-boundary-pending.test.tsx index b79a5ce751..d4607c946f 100644 --- a/packages/react-router/tests/hydration-capped-boundary-pending.test.tsx +++ b/packages/react-router/tests/hydration-capped-boundary-pending.test.tsx @@ -41,24 +41,35 @@ describe('hydrating a server-capped boundary lane', () => { ] as const)( 'keeps the server-rendered %s %s boundary visible', async (outcome, boundary) => { - const routeFailure = - outcome === 'notFound' ? notFound() : new Error('server route failure') const childLoader = vi.fn(() => 'child data') + const boundaryCommits = vi.fn() + + function BoundaryError() { + React.useEffect(() => { + boundaryCommits() + }, []) + return
Boundary error
+ } + + function BoundaryNotFound() { + React.useEffect(() => { + boundaryCommits() + }, []) + return
Boundary not found
+ } const makeRouteTree = () => { const boundaryOptions = { beforeLoad: () => { - throw routeFailure + throw outcome === 'notFound' + ? notFound() + : new Error('server route failure') }, pendingComponent: () => (
Boundary pending
), - errorComponent: () => ( -
Boundary error
- ), - notFoundComponent: () => ( -
Boundary not found
- ), + errorComponent: BoundaryError, + notFoundComponent: BoundaryNotFound, } const rootRoute = createRootRoute({ component: Outlet, @@ -85,7 +96,6 @@ describe('hydrating a server-capped boundary lane', () => { const serverRouter = createRouter({ ...makeRouteTree(), - ...(boundary === 'root' ? { isShell: true } : {}), history: createMemoryHistory({ initialEntries: ['/parent/child'], }), @@ -110,6 +120,7 @@ describe('hydrating a server-capped boundary lane', () => { expect(serverHtml).toContain( outcome === 'notFound' ? 'Boundary not found' : 'Boundary error', ) + expect(boundaryCommits).not.toHaveBeenCalled() const clientRouter = createRouter({ ...makeRouteTree(), @@ -148,21 +159,19 @@ describe('hydrating a server-capped boundary lane', () => { const consoleError = vi .spyOn(console, 'error') .mockImplementation(() => {}) - const root = hydrateRoot( - container, - , - ) - testCleanups.push(async () => { - await act(() => root.unmount()) - }) - + let root!: ReturnType await act(async () => { + root = hydrateRoot(container, ) + testCleanups.push(async () => { + await act(() => root.unmount()) + }) await Promise.resolve() }) // A shorter dehydrated lane means SPA mode only for an actual shell. // Here it is shorter because the server already rendered a terminal // boundary, so hydration must not replace that boundary with pending UI. + expect(boundaryCommits).toHaveBeenCalledTimes(1) expect(container).toHaveTextContent( outcome === 'notFound' ? 'Boundary not found' : 'Boundary error', ) diff --git a/packages/react-router/tests/hydration-terminal-lane.test.tsx b/packages/react-router/tests/hydration-terminal-lane.test.tsx index d8e64c5944..868f19ab27 100644 --- a/packages/react-router/tests/hydration-terminal-lane.test.tsx +++ b/packages/react-router/tests/hydration-terminal-lane.test.tsx @@ -48,11 +48,13 @@ afterEach(() => { describe('hydration terminal lane', () => { test('keeps server data while loading only the missing client suffix', async () => { + const parentLoader = vi.fn(() => 'client-parent') + const childLoader = vi.fn(() => 'client-child') const rootRoute = createRootRoute({ component: Outlet }) const parentRoute = createRoute({ getParentRoute: () => rootRoute, path: '/parent', - loader: () => 'client-parent', + loader: parentLoader, component: () => ( <>
{parentRoute.useLoaderData()}
@@ -64,7 +66,7 @@ describe('hydration terminal lane', () => { getParentRoute: () => parentRoute, path: '/child', ssr: false, - loader: () => 'client-child', + loader: childLoader, component: () =>
{childRoute.useLoaderData()}
, }) const router = createRouter({ @@ -89,43 +91,7 @@ describe('hydration terminal lane', () => { expect(await screen.findByText('server-parent')).toBeInTheDocument() expect(await screen.findByText('client-child')).toBeInTheDocument() expect(screen.queryByText('client-parent')).not.toBeInTheDocument() - }) - - test('does not render serialized descendants below a server error', async () => { - const rootRoute = createRootRoute({ component: Outlet }) - const parentRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/parent', - errorComponent: ({ error }) =>
Parent failed: {error.message}
, - component: Outlet, - }) - const childRoute = createRoute({ - getParentRoute: () => parentRoute, - path: '/child', - component: () =>
Child must stay omitted
, - }) - const router = createRouter({ - history: createMemoryHistory({ initialEntries: ['/parent/child'] }), - routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), - }) - const matches = router.matchRoutes(router.state.location) - bootstrap([ - { match: matches[0]!, status: 'success', ssr: true }, - { - match: matches[1]!, - status: 'error', - ssr: true, - error: new Error('server boom'), - }, - { match: matches[2]!, status: 'success', ssr: true }, - ]) - - await hydrate(router) - render() - - expect(await screen.findByText('Parent failed: server boom')).toBeVisible() - expect( - screen.queryByText('Child must stay omitted'), - ).not.toBeInTheDocument() + expect(parentLoader).not.toHaveBeenCalled() + expect(childLoader).toHaveBeenCalledTimes(1) }) }) diff --git a/packages/react-router/tests/issue-4476-react-query-cancellation.test.tsx b/packages/react-router/tests/issue-4476-react-query-cancellation.test.tsx index a7d060de6a..080880517d 100644 --- a/packages/react-router/tests/issue-4476-react-query-cancellation.test.tsx +++ b/packages/react-router/tests/issue-4476-react-query-cancellation.test.tsx @@ -25,7 +25,7 @@ import { afterEach(cleanup) // https://github.com/TanStack/router/issues/4476 -test('#4476: pending navigation does not cancel fetchQuery when it unmounts the last useQuery observer', async () => { +test('#4476: pending navigation keeps the query observer mounted and its fetchQuery signal alive', async () => { const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: 0 } }, }) @@ -33,6 +33,7 @@ test('#4476: pending navigation does not cancel fetchQuery when it unmounts the const queryKey = ['issue-4476'] as const const routeError = vi.fn() const pageTwoBeforeLoad = vi.fn() + const pendingComponentRendered = vi.fn() let querySignal: AbortSignal | undefined const rootRoute = createRootRoute({ @@ -90,7 +91,10 @@ test('#4476: pending navigation does not cancel fetchQuery when it unmounts the defaultPreloadDelay: 0, defaultPreloadStaleTime: 0, defaultPendingMs: 0, - defaultPendingComponent: () =>
Loading page two
, + defaultPendingComponent: () => { + pendingComponentRendered() + return
Loading page two
+ }, }) try { @@ -107,14 +111,17 @@ test('#4476: pending navigation does not cancel fetchQuery when it unmounts the fireEvent.click(link) await waitFor(() => expect(querySignal).toBeDefined()) - // Give the zero-delay pending transition a chance to unmount Page one. - await new Promise((resolve) => setTimeout(resolve, 50)) + expect(screen.getByTestId('page-one')).toBeInTheDocument() + expect(screen.queryByTestId('page-two-pending')).not.toBeInTheDocument() expect(querySignal?.aborted).toBe(false) queryGate.resolve(10) expect(await screen.findByText('Page two: 10')).toBeInTheDocument() expect(routeError).not.toHaveBeenCalled() + expect(screen.queryByTestId('page-one')).not.toBeInTheDocument() + expect(screen.queryByTestId('page-two-pending')).not.toBeInTheDocument() expect(screen.queryByTestId('page-two-error')).not.toBeInTheDocument() + expect(router.state.location.pathname).toBe('/page-two') } finally { queryGate.resolve(10) queryClient.clear() diff --git a/packages/react-router/tests/issue-4759-pending-frame.test.tsx b/packages/react-router/tests/issue-4759-pending-frame.test.tsx index 6a6435ee53..5903f2960b 100644 --- a/packages/react-router/tests/issue-4759-pending-frame.test.tsx +++ b/packages/react-router/tests/issue-4759-pending-frame.test.tsx @@ -26,13 +26,12 @@ afterEach(() => { // 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', () => { +// JSDOM cannot observe browser paints. This unit reduction verifies the event +// ordering behind the issue: pending DOM must be published before the first +// macrotask when pendingMs is 0. +describe('issue #4759: pendingMs 0 publishes pending DOM before a macrotask', () => { test('pending fallback is committed on mount without waiting for a macrotask', async () => { + vi.useFakeTimers() let resolveLoader!: (value: string) => void const loaderPromise = new Promise((resolve) => { resolveLoader = resolve @@ -42,9 +41,6 @@ describe('issue #4759: no blank frame before pending UI when pendingMs is 0', () const indexRoute = createRoute({ getParentRoute: () => rootRoute, path: '/', - pendingMs: 0, - pendingMinMs: 0, - pendingComponent: () =>
pending...
, loader: () => loaderPromise, component: () =>
loaded
, }) @@ -53,19 +49,44 @@ describe('issue #4759: no blank frame before pending UI when pendingMs is 0', () routeTree: rootRoute.addChildren([indexRoute]), history, }) + let resolveRendered!: () => void + const rendered = new Promise((resolve) => { + resolveRendered = resolve + }) + const unsubscribe = router.subscribe('onRendered', (event) => { + if (event.toLocation.pathname === '/') { + resolveRendered() + } + }) - render() + try { + render( +
+ ( +
pending...
+ )} + /> +
, + ) - // 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() + // Fake timers keep the first macrotask frozen. An implementation that + // publishes pending state with setTimeout cannot satisfy this assertion. + 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() + // Sanity: the load still completes normally afterwards. + resolveLoader('done') + await act(() => rendered) + expect(screen.getByTestId('loaded')).toBeInTheDocument() + expect(screen.queryByTestId('pending')).not.toBeInTheDocument() + } finally { + unsubscribe() + resolveLoader('done') + vi.useRealTimers() + } }) }) diff --git a/packages/react-router/tests/issue-5778-router-provider-context-preload.test.tsx b/packages/react-router/tests/issue-5778-router-provider-context-preload.test.tsx index b19aeffb6f..e179a1502e 100644 --- a/packages/react-router/tests/issue-5778-router-provider-context-preload.test.tsx +++ b/packages/react-router/tests/issue-5778-router-provider-context-preload.test.tsx @@ -73,6 +73,7 @@ test('#5778: intent preload sees a RouterProvider context update before the firs const [foo, setFoo] = React.useState('foo') return ( <> + {foo} +
@@ -56,9 +65,14 @@ function setup({ failVia }: { failVia: 'render' | 'loader' }) { }, }) - const childLoader = vi.fn(() => { + let childLoaderCalls = 0 + const childLoader = vi.fn(async () => { + childLoaderCalls++ + if (childLoaderCalls === 2) { + await secondChildLoad + } if (failVia === 'loader') { - throw new Error('test error') + throw new Error('loader error') } return 'data' }) @@ -69,7 +83,7 @@ function setup({ failVia }: { failVia: 'render' | 'loader' }) { loader: childLoader, component: function ChildComponent() { if (failVia === 'render') { - throw new Error('test error') + throw new Error('render error') } return
child content
}, @@ -85,7 +99,14 @@ function setup({ failVia }: { failVia: 'render' | 'loader' }) { }, }) - return { router, childLoader, getErrorRenders: () => errorRenders } + return { + router, + childLoader, + parentAction, + secondChildLoad, + getErrorRenders: () => errorRenders, + getInvalidation: () => invalidation, + } } test.each(['render', 'loader'] as const)( @@ -94,37 +115,71 @@ 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 { + router, + childLoader, + parentAction, + secondChildLoad, + getErrorRenders, + getInvalidation, + } = setup({ failVia }) const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}) - const { router, childLoader, getErrorRenders } = setup({ failVia }) - render() + try { + render() - expect(await screen.findByTestId('error-ui')).toBeInTheDocument() - const initialErrorRenders = getErrorRenders() - const initialLoaderCalls = childLoader.mock.calls.length + expect(await screen.findByTestId('error-ui')).toHaveTextContent( + `error: ${failVia} error`, + ) + const initialErrorRenders = getErrorRenders() + expect(childLoader).toHaveBeenCalledTimes(1) + consoleError.mockClear() - fireEvent.click(screen.getByTestId('invalidate')) + fireEvent.click(screen.getByTestId('invalidate')) - // The invalidated reload must actually complete: the loader re-ran ... - await waitFor(() => { - expect(childLoader.mock.calls.length).toBeGreaterThan(initialLoaderCalls) - }) + await waitFor(() => { + expect(childLoader).toHaveBeenCalledTimes(2) + expect(screen.getByTestId('invalidate')).toHaveTextContent('pending') + expect(screen.getByTestId('invalidate')).toBeDisabled() + }) + expect(secondChildLoad.status).toBe('pending') - // ... the error UI is rendered again after the reload ... - await waitFor(() => { - expect(screen.getByTestId('error-ui')).toBeInTheDocument() - expect(getErrorRenders()).toBeGreaterThan(initialErrorRenders) - }) + const invalidation = getInvalidation() + if (!invalidation) { + throw new Error('invalidate action did not return its promise') + } - // 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'), - ), - ) - expect(hooksCrash).toBeUndefined() - // The surrounding route (the issue's "frozen" parent) is still mounted - // and interactive. - expect(screen.getByTestId('invalidate')).toBeInTheDocument() + await act(async () => { + secondChildLoad.resolve() + await invalidation + }) + + await waitFor(() => { + expect(screen.getByTestId('error-ui')).toHaveTextContent( + `error: ${failVia} error`, + ) + expect(getErrorRenders()).toBeGreaterThan(initialErrorRenders) + expect(screen.getByTestId('invalidate')).toHaveTextContent('invalidate') + expect(screen.getByTestId('invalidate')).toBeEnabled() + }) + + fireEvent.click(screen.getByTestId('parent-action')) + expect(parentAction).toHaveBeenCalledTimes(1) + + const hooksCrash = consoleError.mock.calls.find((call) => + call.some((arg) => + String(arg?.message ?? arg).includes('Rendered more hooks'), + ), + ) + expect(hooksCrash).toBeUndefined() + } finally { + if (secondChildLoad.status === 'pending') { + await act(async () => { + secondChildLoad.resolve() + await getInvalidation()?.catch(() => undefined) + }) + } + consoleError.mockRestore() + } }, ) diff --git a/packages/router-core/tests/preload-public-cache-behavior.test.ts b/packages/router-core/tests/preload-public-cache-behavior.test.ts index ce96f77dd1..54e68ef864 100644 --- a/packages/router-core/tests/preload-public-cache-behavior.test.ts +++ b/packages/router-core/tests/preload-public-cache-behavior.test.ts @@ -8,14 +8,15 @@ afterEach(() => { vi.useRealTimers() }) -// Public contract: preloading a descendant must reuse an already accepted -// ancestor generation instead of executing the active layout loader again. -test('preloading children borrows the active ancestor without rerunning it', async () => { +// https://github.com/TanStack/router/issues/2980 +// Repeated child preloads must borrow a stale active parent instead of rerunning +// its loader. +test('#2980: repeated child preloads do not rerun a stale active parent loader', async () => { vi.useFakeTimers() vi.setSystemTime(1_000) const layoutLoader = vi.fn(() => 'layout data') - const childLoader = vi.fn(({ params }: any) => `child ${params.childId}`) + const childLoader = vi.fn((childId: string) => `child ${childId}`) const rootRoute = new BaseRootRoute({}) const layoutRoute = new BaseRoute({ getParentRoute: () => rootRoute, @@ -26,7 +27,7 @@ test('preloading children borrows the active ancestor without rerunning it', asy const childRoute = new BaseRoute({ getParentRoute: () => layoutRoute, path: '$childId', - loader: childLoader, + loader: ({ params }) => childLoader(params.childId), }) const router = createTestRouter({ routeTree: rootRoute.addChildren([layoutRoute.addChildren([childRoute])]), @@ -34,36 +35,24 @@ test('preloading children borrows the active ancestor without rerunning it', asy }) await router.load() + expect(layoutLoader).toHaveBeenCalledTimes(1) vi.setSystemTime(2_000) await router.preloadRoute({ to: '/layout/$childId', params: { childId: 'one' }, - } as any) + }) + expect(layoutLoader).toHaveBeenCalledTimes(1) + expect(childLoader).toHaveBeenNthCalledWith(1, 'one') + await router.preloadRoute({ to: '/layout/$childId', params: { childId: 'two' }, - } as any) - await router.preloadRoute({ - to: '/layout/$childId', - params: { childId: 'one' }, - } as any) + }) expect(layoutLoader).toHaveBeenCalledTimes(1) expect(childLoader).toHaveBeenCalledTimes(2) - - await router.navigate({ - to: '/layout/$childId', - params: { childId: 'one' }, - } as any) - expect(layoutLoader).toHaveBeenCalledTimes(1) - // No preloadStaleTime was configured, so navigation follows the existing - // staleTime policy and reloads the leaf while still borrowing the layout. - expect(childLoader).toHaveBeenCalledTimes(3) - expect( - router.state.matches.find((match) => match.routeId === childRoute.id) - ?.loaderData, - ).toBe('child one') + expect(childLoader).toHaveBeenNthCalledWith(2, 'two') }) // Public contract: the public stale/gc options determine whether user loader diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e658307e76..e602c8f53f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1433,6 +1433,40 @@ 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 + '@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.61.0 + version: 1.61.1 + '@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-query': From ded47d1f43cf6cd49f072498ac76b85e93dc89d7 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Wed, 15 Jul 2026 00:23:09 +0200 Subject: [PATCH 23/59] final fixed issue tests --- .../tests/app.spec.ts | 187 ++++++++++++++++++ .../issue-4467-lazy-route-pending.test.tsx | 80 ++++++++ ...re-navigate-after-initial-redirect.test.ts | 40 ++++ ...27-hydration-root-global-not-found.test.ts | 76 +++++++ ...ue-7759-in-flight-preload-eviction.test.ts | 44 +++++ 5 files changed, 427 insertions(+) create mode 100644 packages/react-router/tests/issue-4467-lazy-route-pending.test.tsx create mode 100644 packages/router-core/tests/issue-3920-on-before-navigate-after-initial-redirect.test.ts create mode 100644 packages/router-core/tests/issue-5427-hydration-root-global-not-found.test.ts create mode 100644 packages/router-core/tests/issue-7759-in-flight-preload-eviction.test.ts diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/tests/app.spec.ts b/e2e/react-router/scroll-restoration-sandbox-vite/tests/app.spec.ts index f72d2d06ab..91846261eb 100644 --- a/e2e/react-router/scroll-restoration-sandbox-vite/tests/app.spec.ts +++ b/e2e/react-router/scroll-restoration-sandbox-vite/tests/app.spec.ts @@ -2,6 +2,21 @@ import { expect, test } from '@playwright/test' import { linkOptions } from '@tanstack/react-router' import { toRuntimePath } from '@tanstack/router-e2e-utils' +type ScrollPaintTestState = { + sourceFrameScrollYs: Array + sourceWasReset: boolean + destinationMounted: boolean + destinationCommitScrollY: number | null + destinationFrameScrollYs: Array + cleanup: () => void +} + +declare global { + interface Window { + __scrollPaintTestState?: ScrollPaintTestState + } +} + test('Smoke - Renders home', async ({ page }) => { await page.goto(toRuntimePath('/')) await expect( @@ -9,6 +24,178 @@ test('Smoke - Renders home', async ({ page }) => { ).toBeVisible() }) +test('PUSH resets scroll before the destination can render a frame (#7815)', async ({ + page, +}) => { + await page.goto(toRuntimePath('/issue-7040-source')) + await expect(page.getByTestId('issue-7040-source-top')).toBeVisible() + + const sourceScrollY = await page.evaluate(async () => { + window.scrollTo(0, 500) + await new Promise((resolve) => requestAnimationFrame(() => resolve())) + return window.scrollY + }) + + expect(sourceScrollY).toBeGreaterThan(0) + + await page.evaluate((expectedSourceScrollY) => { + const root = document.querySelector('#app') + if (!root) { + throw new Error('App root not found') + } + + const geometry = document.createElement('div') + geometry.setAttribute('aria-hidden', 'true') + geometry.style.height = `${window.innerHeight + expectedSourceScrollY + 100}px` + geometry.style.pointerEvents = 'none' + geometry.style.width = '1px' + document.body.append(geometry) + + const state: ScrollPaintTestState = { + sourceFrameScrollYs: [], + sourceWasReset: false, + destinationMounted: false, + destinationCommitScrollY: null, + destinationFrameScrollYs: [], + cleanup: () => {}, + } + + const getDestinationHeading = () => + Array.from(document.querySelectorAll('h3')).find( + (heading) => heading.textContent === 'normal-page', + ) + + const commitObserver = new MutationObserver(() => { + const destinationHeading = getDestinationHeading() + + if (!destinationHeading) { + return + } + + commitObserver.disconnect() + state.destinationMounted = true + state.destinationCommitScrollY = window.scrollY + }) + + commitObserver.observe(root, { childList: true, subtree: true }) + + const handleScroll = () => { + if ( + document.querySelector('[data-testid="issue-7040-source-top"]') && + Math.abs(window.scrollY - expectedSourceScrollY) > 1 + ) { + state.sourceWasReset = true + } + } + window.addEventListener('scroll', handleScroll, { passive: true }) + + const originalScrollTo = window.scrollTo + window.scrollTo = ((...args: Array) => { + const requestedTop = + typeof args[0] === 'number' + ? args[1] + : typeof args[0] === 'object' && args[0] !== null + ? (args[0] as ScrollToOptions).top + : undefined + if ( + typeof requestedTop === 'number' && + Math.abs(requestedTop - expectedSourceScrollY) > 1 && + document.querySelector('[data-testid="issue-7040-source-top"]') + ) { + state.sourceWasReset = true + } + Reflect.apply(originalScrollTo, window, args) + }) as typeof window.scrollTo + + let animationFrameId = 0 + const recordFrame = () => { + if (getDestinationHeading()) { + state.destinationFrameScrollYs.push(window.scrollY) + } else if ( + document.querySelector('[data-testid="issue-7040-source-top"]') + ) { + state.sourceFrameScrollYs.push(window.scrollY) + } + animationFrameId = requestAnimationFrame(recordFrame) + } + animationFrameId = requestAnimationFrame(recordFrame) + + state.cleanup = () => { + commitObserver.disconnect() + cancelAnimationFrame(animationFrameId) + window.removeEventListener('scroll', handleScroll) + window.scrollTo = originalScrollTo + geometry.remove() + delete window.__scrollPaintTestState + } + window.__scrollPaintTestState = state + }, sourceScrollY) + + + await page.evaluate( + () => + new Promise((resolve) => { + requestAnimationFrame(() => resolve()) + }), + ) + expect(await page.evaluate(() => window.scrollY)).toBe(sourceScrollY) + + await page + .getByRole('link', { name: 'Head-/normal-page' }) + .dispatchEvent('click') + + await page.waitForFunction(() => { + const state = window.__scrollPaintTestState + if (!state?.destinationMounted) { + return false + } + + const lastFrames = state.destinationFrameScrollYs.slice(-2) + return ( + lastFrames.length === 2 && + lastFrames.every((scrollY) => Math.abs(scrollY) <= 1) + ) + }) + + const observation = await page.evaluate(() => { + const state = window.__scrollPaintTestState + if (!state) { + throw new Error('Scroll paint observer not found') + } + + return { + sourceFrameScrollYs: state.sourceFrameScrollYs, + sourceWasReset: state.sourceWasReset, + destinationCommitScrollY: state.destinationCommitScrollY, + destinationFrameScrollYs: state.destinationFrameScrollYs, + destinationMaxScrollY: + document.documentElement.scrollHeight - window.innerHeight, + finalScrollY: window.scrollY, + } + }) + + expect(observation.sourceFrameScrollYs.length).toBeGreaterThan(0) + expect( + observation.sourceFrameScrollYs.every( + (scrollY) => Math.abs(scrollY - sourceScrollY) <= 1, + ), + ).toBe(true) + expect(observation.sourceWasReset).toBe(false) + expect(observation.destinationMaxScrollY).toBeGreaterThanOrEqual( + sourceScrollY, + ) + expect(observation.finalScrollY).toBe(0) + expect(observation.destinationFrameScrollYs.length).toBeGreaterThanOrEqual( + 2, + ) + expect( + observation.destinationFrameScrollYs.every( + (scrollY) => Math.abs(scrollY) <= 1, + ), + `Destination paint opportunities: ${observation.destinationFrameScrollYs.join(', ')}, commit: ${observation.destinationCommitScrollY}, final: ${observation.finalScrollY}`, + ).toBe(true) +}) + test('restores the prior scroll position after browser back then forward', async ({ page, }) => { diff --git a/packages/react-router/tests/issue-4467-lazy-route-pending.test.tsx b/packages/react-router/tests/issue-4467-lazy-route-pending.test.tsx new file mode 100644 index 0000000000..5a765c46ea --- /dev/null +++ b/packages/react-router/tests/issue-4467-lazy-route-pending.test.tsx @@ -0,0 +1,80 @@ +import * as React from 'react' +import { act, cleanup, render, screen } from '@testing-library/react' +import { afterEach, expect, test, vi } from 'vitest' + +import { + Outlet, + RouterProvider, + createControlledPromise, + createLazyRoute, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +afterEach(cleanup) + +// https://github.com/TanStack/router/issues/4467 +test('default pending component renders while lazy route options load', async () => { + const rootRoute = createRootRoute({ + component: Outlet, + }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>

Index page

, + }) + const lazyPageOptions = createLazyRoute('/page')({ + component: () =>

Page

, + }) + const lazyOptions = createControlledPromise() + const loadLazyOptions = vi.fn(() => lazyOptions) + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + }).lazy(loadLazyOptions) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, pageRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + defaultPendingMs: 0, + defaultPendingMinMs: 0, + defaultPendingComponent: () =>

Loading page

, + }) + let navigationPromise: Promise | undefined + + try { + render() + + expect( + await screen.findByRole('heading', { name: 'Index page' }), + ).toBeInTheDocument() + + act(() => { + navigationPromise = router.navigate({ to: '/page' }) + }) + + expect(await screen.findByRole('status')).toHaveTextContent('Loading page') + expect( + screen.queryByRole('heading', { name: 'Page' }), + ).not.toBeInTheDocument() + expect(lazyOptions.status).toBe('pending') + expect(loadLazyOptions).toHaveBeenCalledTimes(1) + + await act(async () => { + lazyOptions.resolve(lazyPageOptions) + await navigationPromise + }) + + expect(screen.getByRole('heading', { name: 'Page' })).toBeInTheDocument() + expect(screen.queryByRole('status')).not.toBeInTheDocument() + expect(loadLazyOptions).toHaveBeenCalledTimes(1) + } finally { + await act(async () => { + if (lazyOptions.status === 'pending') { + lazyOptions.resolve(lazyPageOptions) + } + await navigationPromise + }) + } +}) diff --git a/packages/router-core/tests/issue-3920-on-before-navigate-after-initial-redirect.test.ts b/packages/router-core/tests/issue-3920-on-before-navigate-after-initial-redirect.test.ts new file mode 100644 index 0000000000..f0de5df8dd --- /dev/null +++ b/packages/router-core/tests/issue-3920-on-before-navigate-after-initial-redirect.test.ts @@ -0,0 +1,40 @@ +import { createMemoryHistory } from '@tanstack/history' +import { expect, test } from 'vitest' +import { BaseRootRoute, BaseRoute, redirect } from '../src' +import { createTestRouter } from './routerTestUtils' + +// https://github.com/TanStack/router/issues/3920 +test('onBeforeNavigate fires after the initial load redirects', async () => { + const rootRoute = new BaseRootRoute({}) + const sourceRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/source', + beforeLoad: () => { + throw redirect({ to: '/target' }) + }, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const thirdRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/third', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([sourceRoute, targetRoute, thirdRoute]), + history: createMemoryHistory({ initialEntries: ['/source'] }), + }) + + await router.load() + expect(router.state.location.pathname).toBe('/target') + + const navigatedPaths: Array = [] + router.subscribe('onBeforeNavigate', (event) => { + navigatedPaths.push(event.toLocation.pathname) + }) + + await router.navigate({ to: '/third' }) + + expect(navigatedPaths).toEqual(['/third']) +}) diff --git a/packages/router-core/tests/issue-5427-hydration-root-global-not-found.test.ts b/packages/router-core/tests/issue-5427-hydration-root-global-not-found.test.ts new file mode 100644 index 0000000000..21f306249e --- /dev/null +++ b/packages/router-core/tests/issue-5427-hydration-root-global-not-found.test.ts @@ -0,0 +1,76 @@ +import { createMemoryHistory } from '@tanstack/history' +import { describe, expect, test, vi } from 'vitest' +import { BaseRootRoute, BaseRoute } from '../src' +import { hydrate } from '../src/ssr/client' +import { dehydrateMatch } from '../src/ssr/ssr-server' +import { createTestRouter } from './routerTestUtils' +import type { TsrSsrGlobal } from '../src/ssr/types' + +function createRouter(initialEntry: string, isServer: boolean) { + const rootRoute = new BaseRootRoute({ + notFoundComponent: () => 'Root not found', + }) + const notFoundRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/404', + component: () => 'Not found route', + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([notFoundRoute]), + history: createMemoryHistory({ initialEntries: [initialEntry] }), + isServer, + }) + + return { rootRoute, router } +} + +// https://github.com/TanStack/router/issues/5427 +describe('issue #5427: root-only global not-found hydration', () => { + test('resolves the client URL when the dehydrated /404 lane has a child match', async () => { + const { router: bootstrapRouter } = createRouter('/404', true) + await bootstrapRouter.load() + + const dehydratedMatches = bootstrapRouter.state.matches.map(dehydrateMatch) + const lastMatchId = dehydratedMatches.at(-1)?.i + const bootstrap: TsrSsrGlobal = { + router: { + manifest: { routes: {} }, + dehydratedData: {}, + matches: dehydratedMatches, + lastMatchId, + }, + h: () => {}, + e: () => {}, + c: () => {}, + p: () => {}, + buffer: [], + initialized: false, + } + + const hadBootstrap = Object.prototype.hasOwnProperty.call(window, '$_TSR') + const previousBootstrap = window.$_TSR + window.$_TSR = bootstrap + + try { + const { rootRoute, router } = createRouter('/missing', false) + + await hydrate(router) + await vi.waitFor(() => { + expect(router.state.resolvedLocation?.pathname).toBe('/missing') + }) + + expect(router.state.matches).toHaveLength(1) + expect(router.state.matches[0]).toMatchObject({ + routeId: rootRoute.id, + globalNotFound: true, + }) + } finally { + if (hadBootstrap) { + window.$_TSR = previousBootstrap + } else { + delete window.$_TSR + } + } + }) +}) diff --git a/packages/router-core/tests/issue-7759-in-flight-preload-eviction.test.ts b/packages/router-core/tests/issue-7759-in-flight-preload-eviction.test.ts new file mode 100644 index 0000000000..72031499de --- /dev/null +++ b/packages/router-core/tests/issue-7759-in-flight-preload-eviction.test.ts @@ -0,0 +1,44 @@ +import { expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +test('issue #7759: evicting an in-flight preload finishes without an internal error', async () => { + let signalLoaderStarted!: () => void + let resolveLoader!: (value: string) => void + + const loaderStarted = new Promise((resolve) => { + signalLoaderStarted = resolve + }) + const loaderResult = new Promise((resolve) => { + resolveLoader = resolve + }) + + const rootRoute = new BaseRootRoute({}) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + loader: () => { + signalLoaderStarted() + return loaderResult + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([targetRoute]), + history: createMemoryHistory(), + }) + const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}) + + try { + const preload = router.preloadRoute({ to: '/target' }) + await loaderStarted + + router.clearCache() + resolveLoader('loaded') + + await preload + expect(consoleError).not.toHaveBeenCalled() + } finally { + consoleError.mockRestore() + } +}) From 16dfcf94292258e558ac52973176de95da68e390 Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Tue, 14 Jul 2026 22:24:55 +0000 Subject: [PATCH 24/59] ci: apply automated fixes --- .../scroll-restoration-sandbox-vite/tests/app.spec.ts | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/tests/app.spec.ts b/e2e/react-router/scroll-restoration-sandbox-vite/tests/app.spec.ts index 91846261eb..9c2d944dd5 100644 --- a/e2e/react-router/scroll-restoration-sandbox-vite/tests/app.spec.ts +++ b/e2e/react-router/scroll-restoration-sandbox-vite/tests/app.spec.ts @@ -131,7 +131,6 @@ test('PUSH resets scroll before the destination can render a frame (#7815)', asy window.__scrollPaintTestState = state }, sourceScrollY) - await page.evaluate( () => new Promise((resolve) => { @@ -185,9 +184,7 @@ test('PUSH resets scroll before the destination can render a frame (#7815)', asy sourceScrollY, ) expect(observation.finalScrollY).toBe(0) - expect(observation.destinationFrameScrollYs.length).toBeGreaterThanOrEqual( - 2, - ) + expect(observation.destinationFrameScrollYs.length).toBeGreaterThanOrEqual(2) expect( observation.destinationFrameScrollYs.every( (scrollY) => Math.abs(scrollY) <= 1, From ba800532e6532b809866784d52ff75ee54c344c1 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Wed, 15 Jul 2026 13:38:51 +0200 Subject: [PATCH 25/59] minor byte shave in router-core --- packages/router-core/INTERNALS.md | 7 +- packages/router-core/src/hydrate.ts | 1 - packages/router-core/src/load-client.ts | 142 +++++++++++------------- packages/router-core/src/router.ts | 4 +- 4 files changed, 67 insertions(+), 87 deletions(-) diff --git a/packages/router-core/INTERNALS.md b/packages/router-core/INTERNALS.md index cc05ae9555..bf78588df2 100644 --- a/packages/router-core/INTERNALS.md +++ b/packages/router-core/INTERNALS.md @@ -491,7 +491,7 @@ unfinished. ## Pending presentation and renderer acknowledgement Pending UI is a projection of an in-progress transaction, never a semantic lane. -`renderPending` publishes a cloned prefix ending at the selected pending +Pending publication uses a cloned prefix ending at the selected pending boundary. Every visible match is a snapshot with `_flight` removed, and only the terminal snapshot changes status to `pending`. Presentation therefore never shares a mutable match object with the private writer lane. A later failure may @@ -564,9 +564,8 @@ Two facts must remain separate: `closeFlight` removes joinability but does not release the owner's lease. `releaseFlight` removes one lease; only the last release aborts the loader and -removes the registry entry. `transferMatchResources` and -`discardMatchResources` are the bulk ownership operations, based on match object -identity. +removes the registry entry. `transferMatchResources` is the bulk ownership +operations, based on match object identity. The lease intentionally may outlive promise settlement. Once successful data is accepted, closing registry membership prevents new joins while the accepted diff --git a/packages/router-core/src/hydrate.ts b/packages/router-core/src/hydrate.ts index 233c6a30ee..73bcfad837 100644 --- a/packages/router-core/src/hydrate.ts +++ b/packages/router-core/src/hydrate.ts @@ -81,7 +81,6 @@ export async function hydrate(router: AnyRouter): Promise { break } index++ - candidate.id = dehydrated.i candidate.__beforeLoadContext = dehydrated.b candidate.loaderData = dehydrated.l candidate.status = dehydrated.s diff --git a/packages/router-core/src/load-client.ts b/packages/router-core/src/load-client.ts index 00cf3bb971..a7121b4d06 100644 --- a/packages/router-core/src/load-client.ts +++ b/packages/router-core/src/load-client.ts @@ -304,51 +304,22 @@ function releaseFlight(router: AnyRouter, match: WorkMatch): void { } } } - -export function discardMatchResources( - router: AnyRouter, - matches: Array, -): void { - transferMatchResources(router, matches, []) -} - +/** + * Not passing in a `next` ownership recipient + * is equivalent to discarding the match resources + */ export function transferMatchResources( router: AnyRouter, previous: Array, - next: Array, + next?: Array, ): void { for (const match of previous as Array) { - if (!next.includes(match)) { + if (!next?.includes(match)) { releaseFlight(router, match) } } } -function startFlight( - router: AnyRouter, - key: string, - route: AnyRoute, - invoke: (controller: AbortController) => unknown, -): LoaderFlight { - const controller = new AbortController() - const flight: LoaderFlight = [ - Promise.resolve() - .then(() => invoke(controller)) - .then( - (value) => - controller.signal.aborted - ? [CANCELED] - : normalize(value, false, route.id), - (cause) => - controller.signal.aborted ? [CANCELED] : normalizeError(route, cause), - ), - controller, - 1, - ] - ;(router._flights ??= new Map()).set(key, flight) - return flight -} - function closeFlight(router: AnyRouter, match: WorkMatch): void { const flight = match._flight if (!flight) { @@ -407,19 +378,36 @@ async function loadResource( for (;;) { if (!joined) { releaseFlight(router, match) - flight = startFlight(router, match.id, route, (controller) => - loader( - getLoaderContext( - router, - lane, - match, - route, - controller, - parentMatchPromise, - preload, + const controller = new AbortController() + flight = [ + Promise.resolve() + .then(() => + loader( + getLoaderContext( + router, + lane, + match, + route, + controller, + parentMatchPromise, + preload, + ), + ), + ) + .then( + (value) => + controller.signal.aborted + ? [CANCELED] + : normalize(value, false, route.id), + (cause) => + controller.signal.aborted + ? [CANCELED] + : normalizeError(route, cause), ), - ), - ) + controller, + 1, + ] + ;(router._flights ??= new Map()).set(match.id, flight) } match._flight = flight match.abortController = flight![1] @@ -708,7 +696,7 @@ async function reduceLane( if (control) { if (lane.background) { - discardMatchResources( + transferMatchResources( router, lane.background.map((task) => task.candidate), ) @@ -768,7 +756,7 @@ function trimLane( background: boolean, ): void { if (!background) { - discardMatchResources(router, lane.matches.slice(length)) + transferMatchResources(router, lane.matches.slice(length)) } lane.matches.length = length if (!lane.background || background) { @@ -779,7 +767,7 @@ function trimLane( if (task.index < length) { lane.background[write++] = task } else { - discardMatchResources(router, [task.candidate]) + transferMatchResources(router, [task.candidate]) } } lane.background.length = write @@ -920,20 +908,6 @@ function pendingConfig( return undefined } -function renderPending( - router: CoordinatorRouter, - tx: LoadTransaction, - boundary: number, -): Promise { - const offered = tx.matches - .slice(0, boundary + 1) - .map((match) => ({ ...match, _flight: undefined })) - offered[boundary]!.status = 'pending' - return router.startTransition(() => { - router.stores.setMatches(offered) - }) -} - function offerPending(router: CoordinatorRouter, tx: LoadTransaction): void { if (router._tx !== tx) { return @@ -976,12 +950,20 @@ function offerPending(router: CoordinatorRouter, tx: LoadTransaction): void { }, remaining) return } - session.ack = renderPending(router, tx, boundary).then((rendered) => { - if (rendered && router._pending === session) { - session.deadline = Date.now() + min - } - return rendered - }) + const offered = tx.matches + .slice(0, boundary + 1) + .map((match) => ({ ...match, _flight: undefined })) + offered[boundary]!.status = 'pending' + session.ack = router + .startTransition(() => { + router.stores.setMatches(offered) + }) + .then((rendered) => { + if (rendered && router._pending === session) { + session.deadline = Date.now() + min + } + return rendered + }) } function finishPending(router: CoordinatorRouter, tx: LoadTransaction): void { @@ -1127,7 +1109,7 @@ async function runBackground( } const reduced = await reduceLane(router, lane, tasks, options) if (Array.isArray(reduced)) { - discardMatchResources(router, backgroundMatches) + transferMatchResources(router, backgroundMatches) if ( reduced[0] === REDIRECTED && router._tx === tx && @@ -1146,7 +1128,7 @@ async function runBackground( } const projected = await projectLane(router, reduced) if (router._tx !== tx || router._committedMatches !== base) { - discardMatchResources(router, backgroundMatches) + transferMatchResources(router, backgroundMatches) return } router.batch(() => { @@ -1185,7 +1167,7 @@ async function runClientTransaction( if (Array.isArray(result)) { finishPending(router, tx) - discardMatchResources(router, tx.matches) + transferMatchResources(router, tx.matches) if (result[0] === REDIRECTED && router._tx === tx) { tx.redirects = (tx.redirects ?? 0) + 1 tx.redirecting = true @@ -1214,7 +1196,7 @@ async function runClientTransaction( } if (router._tx !== tx) { finishPending(router, tx) - discardMatchResources(router, result.matches) + transferMatchResources(router, result.matches) return } const toLocation = tx.location @@ -1224,7 +1206,7 @@ async function runClientTransaction( ) await router.startViewTransition(async () => { if (router._tx !== tx) { - discardMatchResources(router, result.matches) + transferMatchResources(router, result.matches) return } const commit = () => { @@ -1373,7 +1355,7 @@ export async function loadClientRouter( if (router._tx === tx) { finishPending(router, tx) controller.abort() - discardMatchResources(router, tx.matches) + transferMatchResources(router, tx.matches) router.batch(() => { router.stores.status.set('idle') router.stores.setMatches(router._committedMatches ?? []) @@ -1390,7 +1372,7 @@ export async function loadClientRouter( router._tx = tx previousOwner?.controller.abort() if (previousOwner) { - discardMatchResources(router, previousOwner.matches) + transferMatchResources(router, previousOwner.matches) } router.batch(() => { @@ -1458,7 +1440,7 @@ export async function preloadClientRoute( resolvedPrefix, }) if (Array.isArray(result)) { - discardMatchResources(router, matches) + transferMatchResources(router, matches) if (result[0] === REDIRECTED && !result[1].options.reloadDocument) { return preloadClientRoute( router, @@ -1474,7 +1456,7 @@ export async function preloadClientRoute( matches = result.matches if (matches.some((match) => match.status !== 'success')) { - discardMatchResources(router, matches) + transferMatchResources(router, matches) return } @@ -1522,7 +1504,7 @@ export async function preloadClientRoute( throw cause } controller.abort() - discardMatchResources(router, matches) + transferMatchResources(router, matches) if (router._tx !== owner) { return } diff --git a/packages/router-core/src/router.ts b/packages/router-core/src/router.ts index 15263e35e6..77eccfeeec 100644 --- a/packages/router-core/src/router.ts +++ b/packages/router-core/src/router.ts @@ -40,10 +40,10 @@ import { defaultParseSearch, defaultStringifySearch } from './searchParams' import { rootRouteId } from './root' import { isRedirect } from './redirect' import { - discardMatchResources, loadClientRouter, preloadClientRoute, refreshClientRoute, + transferMatchResources, } from './load-client' import { loadRouteChunk, routeNeedsPreload } from './route-chunks' import { @@ -2604,7 +2604,7 @@ export class RouterCore< if (filter && !filter(match as MakeRouteMatchUnion)) { retained.push(match) } else { - discardMatchResources(this, [match]) + transferMatchResources(this, [match]) } } this.stores.setCached(retained) From 125b13f4fcfbb645c60d03810c06feb2804820e9 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Wed, 15 Jul 2026 13:43:05 +0200 Subject: [PATCH 26/59] minor byte shave in Match --- packages/react-router/src/Match.tsx | 20 +++++++------------- packages/solid-router/src/Matches.tsx | 3 +-- 2 files changed, 8 insertions(+), 15 deletions(-) diff --git a/packages/react-router/src/Match.tsx b/packages/react-router/src/Match.tsx index 8cce99a276..97ce4fb0bb 100644 --- a/packages/react-router/src/Match.tsx +++ b/packages/react-router/src/Match.tsx @@ -87,25 +87,19 @@ export const Match = React.memo(function MatchImpl({ } // 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, - parentRouteId: parentRouteId as string | undefined, - } satisfies MatchViewState - }, [match.routeId, match.ssr, router.routesById]) + const routeId = match.routeId as string + const parentRouteId = (router.routesById[routeId] as AnyRoute).parentRoute?.id return ( ) }) diff --git a/packages/solid-router/src/Matches.tsx b/packages/solid-router/src/Matches.tsx index 63f2a8f4c7..2e3f9ff256 100644 --- a/packages/solid-router/src/Matches.tsx +++ b/packages/solid-router/src/Matches.tsx @@ -66,7 +66,6 @@ function MatchesInner() { const routeId = () => (matchId() ? rootRouteId : undefined) const match = () => routeId() ? router.stores.getRouteMatchStore(rootRouteId).get() : undefined - const resetKey = () => match()?.fetchCount ?? 0 const nearestMatch = { matchId, routeId, @@ -87,7 +86,7 @@ function MatchesInner() { matchComponent() ) : ( resetKey()} + getResetKey={() => match()?.fetchCount ?? 0} errorComponent={ErrorComponent} onCatch={ process.env.NODE_ENV !== 'production' From 2bba8fae502c313b12e53dab623d04a08d49eb78 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Wed, 15 Jul 2026 14:04:49 +0200 Subject: [PATCH 27/59] minor byte shaving --- packages/react-router/src/Match.tsx | 4 +--- packages/react-router/src/Matches.tsx | 3 +-- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/packages/react-router/src/Match.tsx b/packages/react-router/src/Match.tsx index 97ce4fb0bb..44aa3a8633 100644 --- a/packages/react-router/src/Match.tsx +++ b/packages/react-router/src/Match.tsx @@ -25,9 +25,7 @@ type OutletMatchSelection = [ ] const matchViewFieldsEqual = (a: AnyRouteMatch, b: AnyRouteMatch) => - a.routeId === b.routeId && - a.fetchCount === b.fetchCount && - a.status === b.status + a.routeId === b.routeId && a.fetchCount === b.fetchCount const outletMatchSelectionEqual = ( a: OutletMatchSelection, diff --git a/packages/react-router/src/Matches.tsx b/packages/react-router/src/Matches.tsx index bb8b1c962a..79ffc50e2c 100644 --- a/packages/react-router/src/Matches.tsx +++ b/packages/react-router/src/Matches.tsx @@ -79,8 +79,7 @@ export function Matches() { function MatchesInner() { const router = useRouter() - const _isServer = isServer ?? router.isServer - const matches = _isServer + const matches = isServer ?? router.isServer ? router.stores.matches.get() : // eslint-disable-next-line react-hooks/rules-of-hooks useStore(router.stores.matches, (value) => value) From 1f50bd3524f8afdc16fe0272e17981adee13431f Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Wed, 15 Jul 2026 12:06:50 +0000 Subject: [PATCH 28/59] ci: apply automated fixes --- packages/react-router/src/Matches.tsx | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/packages/react-router/src/Matches.tsx b/packages/react-router/src/Matches.tsx index 79ffc50e2c..ecf155f727 100644 --- a/packages/react-router/src/Matches.tsx +++ b/packages/react-router/src/Matches.tsx @@ -79,10 +79,11 @@ export function Matches() { function MatchesInner() { const router = useRouter() - const matches = isServer ?? router.isServer - ? router.stores.matches.get() - : // eslint-disable-next-line react-hooks/rules-of-hooks - useStore(router.stores.matches, (value) => value) + const matches = + (isServer ?? router.isServer) + ? router.stores.matches.get() + : // eslint-disable-next-line react-hooks/rules-of-hooks + useStore(router.stores.matches, (value) => value) const match = matches[0] const matchId = match?.id const resetKey = match ? `${match.id}:${match.fetchCount}` : '' From cf40d59b524197d31525da0aa6b0a364b1a5e3f8 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Wed, 15 Jul 2026 14:47:39 +0200 Subject: [PATCH 29/59] comments and cleanup --- packages/router-core/src/load-client.ts | 6 +++--- packages/router-core/src/router.ts | 25 ++++++++++++++++++++++++- 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/packages/router-core/src/load-client.ts b/packages/router-core/src/load-client.ts index a7121b4d06..f843ec95ba 100644 --- a/packages/router-core/src/load-client.ts +++ b/packages/router-core/src/load-client.ts @@ -93,7 +93,7 @@ type BackgroundLoaderTask = LoaderTask & { candidate: WorkMatch } -export type ExecuteLaneOptions = { +type ExecuteLaneOptions = { preload?: boolean sync?: boolean forceStaleReload?: boolean @@ -108,7 +108,7 @@ type ControlOutcome = | [typeof REDIRECTED, redirect: AnyRedirect] | [typeof CANCELED] -export type LaneResult = ProjectedLane | ControlOutcome +type LaneResult = ProjectedLane | ControlOutcome function waitFor( value: T | PromiseLike, @@ -807,7 +807,7 @@ async function projectLane( return lane as ProjectedLane } -export async function executeClientLane( +async function executeClientLane( router: AnyRouter, location: ParsedLocation, matches: Array, diff --git a/packages/router-core/src/router.ts b/packages/router-core/src/router.ts index 77eccfeeec..a685cd0ba7 100644 --- a/packages/router-core/src/router.ts +++ b/packages/router-core/src/router.ts @@ -639,6 +639,20 @@ export interface MatchRoutesOpts { _canReuse?: (route: AnyRoute) => boolean } +/** + * This function is used to ensure while synchronous `matchRouteInternal` + * is running, if any user-defined function calls `router.navigate(...)` + * we stop the work as we don't have the rights to the `_tx` anymore. + * This includes `router.navigate` calls from: + * - validateSearch + * - loaderDeps + * - params.parse + * - context + * + * If we *trust* our users to never call `router.navigate` from within + * these functions, we could simply delete `assertMatchOwner` and + * remove all its call sites. + */ function assertMatchOwner(opts?: MatchRoutesOpts) { const controller = opts?._controller if ( @@ -1329,7 +1343,9 @@ export class RouterCore< if (listener.eventType === routerEvent.type) { try { listener.fn(routerEvent) - } catch {} + } catch (e) { + console.error(e) + } } }) } @@ -2204,6 +2220,7 @@ export class RouterCore< trimPathRight(this.latestLocation.href) === trimPathRight(next.href) const previousCommitPromise = this.commitLocationPromise + // this is basically `createControlledPromise` but we don't use `createControlledPromise` anymore and this is lighter let resolve!: () => void const commitPromise = new Promise((done) => { resolve = done @@ -2510,6 +2527,7 @@ export class RouterCore< * Invalidate the current matches and optionally force them back into a pending state. * * - Marks all matches that pass the optional `filter` as `invalid: true`. + * * The next load decides when to publish pending UI, so invalidation does not * mutate the currently rendered status. */ @@ -2745,6 +2763,11 @@ export class RouterCore< serverSsrLifecycle?: RouterSsrLifecycle } +/** + * In non-production environments, + * augment the RouterCore class with a `_refreshRoute` method + * dedicated to HMR. + */ if (process.env.NODE_ENV !== 'production') { RouterCore.prototype._refreshRoute = async function (routeId) { this._serverResult = undefined From ec631eb350bce3ca2507a4d152ae92b9c3d9f45d Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Wed, 15 Jul 2026 13:03:33 +0000 Subject: [PATCH 30/59] ci: apply automated fixes --- packages/router-core/src/router.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/router-core/src/router.ts b/packages/router-core/src/router.ts index a685cd0ba7..2fea93f30e 100644 --- a/packages/router-core/src/router.ts +++ b/packages/router-core/src/router.ts @@ -648,7 +648,7 @@ export interface MatchRoutesOpts { * - loaderDeps * - params.parse * - context - * + * * If we *trust* our users to never call `router.navigate` from within * these functions, we could simply delete `assertMatchOwner` and * remove all its call sites. From b56cb51a150453ed4e1092a9e1ebc25f2fe2356d Mon Sep 17 00:00:00 2001 From: Sheraff Date: Wed, 15 Jul 2026 15:13:09 +0200 Subject: [PATCH 31/59] test: does `declare` save any bytes? --- packages/router-core/src/router.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/router-core/src/router.ts b/packages/router-core/src/router.ts index 2fea93f30e..c7e3b45136 100644 --- a/packages/router-core/src/router.ts +++ b/packages/router-core/src/router.ts @@ -1019,8 +1019,8 @@ export class RouterCore< restoration?: boolean reset?: boolean } = { next: true } - shouldViewTransition?: boolean | ViewTransitionOptions = undefined - isViewTransitionTypesSupported?: boolean = undefined + declare shouldViewTransition?: boolean | ViewTransitionOptions + declare isViewTransitionTypesSupported?: boolean = undefined subscribers = new Set>() declare _tx?: LoadTransaction declare _flights?: Map From ef4025957a7b2b4b5ab7bf503e98452e021e247e Mon Sep 17 00:00:00 2001 From: Sheraff Date: Wed, 15 Jul 2026 15:16:07 +0200 Subject: [PATCH 32/59] test again, but i selected everything this time --- packages/router-core/src/router.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/router-core/src/router.ts b/packages/router-core/src/router.ts index c7e3b45136..7852740261 100644 --- a/packages/router-core/src/router.ts +++ b/packages/router-core/src/router.ts @@ -1020,7 +1020,7 @@ export class RouterCore< reset?: boolean } = { next: true } declare shouldViewTransition?: boolean | ViewTransitionOptions - declare isViewTransitionTypesSupported?: boolean = undefined + declare isViewTransitionTypesSupported?: boolean subscribers = new Set>() declare _tx?: LoadTransaction declare _flights?: Map From e1778517587a2cd57ab6f9ebb176648ec5f677eb Mon Sep 17 00:00:00 2001 From: Sheraff Date: Wed, 15 Jul 2026 15:27:59 +0200 Subject: [PATCH 33/59] test: same, but property wasn't even initialized --- packages/router-core/src/router.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/router-core/src/router.ts b/packages/router-core/src/router.ts index 7852740261..9f528db7f2 100644 --- a/packages/router-core/src/router.ts +++ b/packages/router-core/src/router.ts @@ -1052,7 +1052,7 @@ export class RouterCore< latestLocation!: ParsedLocation> pendingBuiltLocation?: ParsedLocation> basepath!: string - routeTree!: TRouteTree + declare routeTree: TRouteTree routesById!: RoutesById routesByPath!: RoutesByPath processedTree!: ProcessedTree From e7322f86da6232cb6e830ced01650de6f3d911d4 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Wed, 15 Jul 2026 15:43:27 +0200 Subject: [PATCH 34/59] simplify Transitioner based on having a unique transitioner per router --- packages/react-router/src/Transitioner.tsx | 33 +++++++++------------- packages/solid-router/src/Transitioner.tsx | 6 ---- packages/vue-router/src/Transitioner.tsx | 4 --- 3 files changed, 13 insertions(+), 30 deletions(-) diff --git a/packages/react-router/src/Transitioner.tsx b/packages/react-router/src/Transitioner.tsx index ead1ca6c57..08700640c8 100644 --- a/packages/react-router/src/Transitioner.tsx +++ b/packages/react-router/src/Transitioner.tsx @@ -10,16 +10,19 @@ export function Transitioner() { const mountLoadForRouter = React.useRef< [typeof router, typeof router.history] | undefined >(undefined) - const acknowledgements = React.useRef void>>( - [], - ).current + /** + * This effect is meant to "polyfill" the fact that React.startTransition + * does not return an awaitable promise. + * + * So we queue `acknowldgements` here, and `` will call + * `router._rendered` whenever it renders a new batch of matches. + */ useLayoutEffect(() => { - const previousTransition = router.startTransition - const previousRendered = router._rendered - const rendered = () => { + const acknowledgements: Array<(rendered: boolean) => void> = [] + const rendered = (done: boolean) => { for (const resolve of acknowledgements.splice(0)) { - resolve(true) + resolve(done) } } const transition = (fn: () => void) => { @@ -28,20 +31,10 @@ export function Transitioner() { React.startTransition(fn) }) } - router._rendered = rendered + router._rendered = () => rendered(true) router.startTransition = transition - return () => { - for (const resolve of acknowledgements.splice(0)) { - resolve(false) - } - if (router._rendered === rendered) { - router._rendered = previousRendered - } - if (router.startTransition === transition) { - router.startTransition = previousTransition - } - } - }, [acknowledgements, router]) + return () => rendered(false) + }, [router]) // Subscribe before canonicalizing so the initial URL has exactly one load. useLayoutEffect(() => { diff --git a/packages/solid-router/src/Transitioner.tsx b/packages/solid-router/src/Transitioner.tsx index 72d5f10300..7a80683971 100644 --- a/packages/solid-router/src/Transitioner.tsx +++ b/packages/solid-router/src/Transitioner.tsx @@ -10,17 +10,11 @@ export function Transitioner() { return null } - const previousTransition = router.startTransition const transition = async (fn: () => void) => { await Solid.startTransition(fn) return true } router.startTransition = transition - Solid.onCleanup(() => { - if (router.startTransition === transition) { - router.startTransition = previousTransition - } - }) // Subscribe to location changes // and try to load the new location diff --git a/packages/vue-router/src/Transitioner.tsx b/packages/vue-router/src/Transitioner.tsx index 6cec279a49..009bd58ebb 100644 --- a/packages/vue-router/src/Transitioner.tsx +++ b/packages/vue-router/src/Transitioner.tsx @@ -9,7 +9,6 @@ export function useTransitionerSetup() { return } - const previousTransition = router.startTransition const transition = async (fn: () => void) => { fn() await Vue.nextTick() @@ -54,9 +53,6 @@ export function useTransitionerSetup() { Vue.onUnmounted(() => { unsubscribe?.() - if (router.startTransition === transition) { - router.startTransition = previousTransition - } }) } From 9810491b7509e5fdbfcb632a42c314cec0438d23 Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Wed, 15 Jul 2026 13:45:38 +0000 Subject: [PATCH 35/59] ci: apply automated fixes --- packages/react-router/src/Transitioner.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/react-router/src/Transitioner.tsx b/packages/react-router/src/Transitioner.tsx index 08700640c8..1d8d7b4762 100644 --- a/packages/react-router/src/Transitioner.tsx +++ b/packages/react-router/src/Transitioner.tsx @@ -14,7 +14,7 @@ export function Transitioner() { /** * This effect is meant to "polyfill" the fact that React.startTransition * does not return an awaitable promise. - * + * * So we queue `acknowldgements` here, and `` will call * `router._rendered` whenever it renders a new batch of matches. */ From 45f77312d10d157cd29fc9d19929ff0a7ddea23d Mon Sep 17 00:00:00 2001 From: Sheraff Date: Wed, 15 Jul 2026 16:01:54 +0200 Subject: [PATCH 36/59] deprecated test --- .../tests/transitioner-router-swap.test.tsx | 112 ------------------ 1 file changed, 112 deletions(-) delete mode 100644 packages/react-router/tests/transitioner-router-swap.test.tsx diff --git a/packages/react-router/tests/transitioner-router-swap.test.tsx b/packages/react-router/tests/transitioner-router-swap.test.tsx deleted file mode 100644 index 9367591324..0000000000 --- a/packages/react-router/tests/transitioner-router-swap.test.tsx +++ /dev/null @@ -1,112 +0,0 @@ -import { act } from 'react' -import { cleanup, render, screen, waitFor } from '@testing-library/react' -import { afterEach, expect, test, vi } from 'vitest' -import { createMemoryHistory } from '@tanstack/history' -import { - Outlet, - RouterProvider, - createRootRoute, - createRoute, - createRouter, -} from '../src' - -const testCleanups: Array<() => void> = [] - -afterEach(() => { - while (testCleanups.length) { - testCleanups.pop()!() - } - cleanup() -}) - -function deferred() { - let resolve!: () => void - const promise = new Promise((r) => { - resolve = r - }) - return { promise, resolve } -} - -test('a load finishing on an old router does not resolve the replacement router', async () => { - const slowLoader = deferred() - const rootA = createRootRoute({ component: () => }) - const indexA = createRoute({ - getParentRoute: () => rootA, - path: '/', - component: () =>
Router A
, - }) - const slowA = createRoute({ - getParentRoute: () => rootA, - path: '/slow', - loader: () => slowLoader.promise, - component: () =>
Slow A
, - }) - const routerA = createRouter({ - routeTree: rootA.addChildren([indexA, slowA]), - history: createMemoryHistory({ initialEntries: ['/'] }), - }) - - const rootB = createRootRoute({ component: () => }) - const indexB = createRoute({ - getParentRoute: () => rootB, - path: '/b', - component: () =>
Router B
, - }) - const routerB = createRouter({ - routeTree: rootB.addChildren([indexB]), - history: createMemoryHistory({ initialEntries: ['/b'] }), - }) - - const view = render() - expect(await screen.findByText('Router A')).toBeInTheDocument() - await waitFor(() => { - expect(routerA.state.status).toBe('idle') - expect(routerA.state.resolvedLocation?.pathname).toBe('/') - }) - - let oldNavigation!: Promise - act(() => { - oldNavigation = routerA.navigate({ to: '/slow' }) - }) - await waitFor(() => expect(routerA.state.isLoading).toBe(true)) - - const onRendered = vi.fn() - const unsubscribeRendered = routerB.subscribe('onRendered', onRendered) - testCleanups.push(unsubscribeRendered) - view.rerender() - expect(await screen.findByText('Router B')).toBeInTheDocument() - await waitFor(() => { - expect(routerB.state.status).toBe('idle') - expect(routerB.state.resolvedLocation?.pathname).toBe('/b') - }) - await waitFor(() => expect(onRendered).toHaveBeenCalledTimes(1)) - expect(onRendered.mock.calls[0]![0].fromLocation).toBeUndefined() - expect(onRendered.mock.calls[0]![0].toLocation.pathname).toBe('/b') - - const onLoad = vi.fn() - const onBeforeRouteMount = vi.fn() - const onResolved = vi.fn() - const unsubscribers = [ - routerB.subscribe('onLoad', onLoad), - routerB.subscribe('onBeforeRouteMount', onBeforeRouteMount), - routerB.subscribe('onResolved', onResolved), - ] - testCleanups.push(...unsubscribers) - - await act(async () => { - slowLoader.resolve() - await oldNavigation - }) - - expect(onLoad).not.toHaveBeenCalled() - expect(onBeforeRouteMount).not.toHaveBeenCalled() - expect(onResolved).not.toHaveBeenCalled() - expect(routerA.state.isLoading).toBe(false) - expect(routerA.state.status).toBe('idle') - expect(routerA.state.resolvedLocation?.pathname).toBe('/slow') - expect(routerA.state.matches.at(-1)?.pathname).toBe('/slow') - expect(screen.getByText('Router B')).toBeInTheDocument() - expect(routerB.state.status).toBe('idle') - expect(routerB.state.resolvedLocation?.pathname).toBe('/b') - expect(onRendered).toHaveBeenCalledTimes(1) -}) From a8d7c8c6dbb0137fd39f448906fe816edb2aad02 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Wed, 15 Jul 2026 16:02:06 +0200 Subject: [PATCH 37/59] no reset key on server --- packages/react-router/src/Matches.tsx | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/packages/react-router/src/Matches.tsx b/packages/react-router/src/Matches.tsx index ecf155f727..b69b9c9275 100644 --- a/packages/react-router/src/Matches.tsx +++ b/packages/react-router/src/Matches.tsx @@ -86,7 +86,6 @@ function MatchesInner() { useStore(router.stores.matches, (value) => value) const match = matches[0] const matchId = match?.id - const resetKey = match ? `${match.id}:${match.fetchCount}` : '' useLayoutEffect(() => { router._rendered?.() @@ -100,7 +99,7 @@ function MatchesInner() { matchComponent ) : ( resetKey} + getResetKey={() => match ? `${matchId}:${match.fetchCount}` : ''} errorComponent={ErrorComponent} onCatch={ process.env.NODE_ENV !== 'production' From f90018f85f710f58e82399cd732d10291672cdc8 Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Wed, 15 Jul 2026 14:04:50 +0000 Subject: [PATCH 38/59] ci: apply automated fixes --- packages/react-router/src/Matches.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/react-router/src/Matches.tsx b/packages/react-router/src/Matches.tsx index b69b9c9275..54422d8b7d 100644 --- a/packages/react-router/src/Matches.tsx +++ b/packages/react-router/src/Matches.tsx @@ -99,7 +99,7 @@ function MatchesInner() { matchComponent ) : ( match ? `${matchId}:${match.fetchCount}` : ''} + getResetKey={() => (match ? `${matchId}:${match.fetchCount}` : '')} errorComponent={ErrorComponent} onCatch={ process.env.NODE_ENV !== 'production' From f7f266b5d5f673586fe5365d77e6874a656e902f Mon Sep 17 00:00:00 2001 From: Sheraff Date: Wed, 15 Jul 2026 16:48:22 +0200 Subject: [PATCH 39/59] some jsdoc --- packages/router-core/src/router.ts | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/packages/router-core/src/router.ts b/packages/router-core/src/router.ts index 9f528db7f2..f1515b5b7a 100644 --- a/packages/router-core/src/router.ts +++ b/packages/router-core/src/router.ts @@ -1022,13 +1022,19 @@ export class RouterCore< declare shouldViewTransition?: boolean | ViewTransitionOptions declare isViewTransitionTypesSupported?: boolean subscribers = new Set>() + /** Current client load transaction and owner of navigation writes. */ declare _tx?: LoadTransaction + /** Shared in-flight route loaders keyed by match ID. */ declare _flights?: Map - /** Terminal semantic lane; pending presentation never becomes a planning base. */ + /** Last terminal matches, excluding temporary pending presentation. */ declare _committedMatches?: Array + /** Pending-boundary reveal and minimum-visible timing state. */ declare _pending?: PendingSession + /** Result of the latest server load, used to render or redirect. */ declare _serverResult?: ServerLoadResult + /** Framework callback that acknowledges the current matches rendered. (used to polyfill when the framework's `startTransition` does not return an awaitable promise) */ declare _rendered?: () => void + /** Development-only HMR reload for a route and its descendants. */ declare _refreshRoute: ((routeId: string) => Promise) | undefined // Must build in constructor @@ -1052,7 +1058,7 @@ export class RouterCore< latestLocation!: ParsedLocation> pendingBuiltLocation?: ParsedLocation> basepath!: string - declare routeTree: TRouteTree + routeTree!: TRouteTree routesById!: RoutesById routesByPath!: RoutesByPath processedTree!: ProcessedTree From 5a8cc8061fd54c843988d9fd2542dca9de75897f Mon Sep 17 00:00:00 2001 From: Sheraff Date: Wed, 15 Jul 2026 17:35:52 +0200 Subject: [PATCH 40/59] simplify getSemanticMatch --- packages/router-core/src/router.ts | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/packages/router-core/src/router.ts b/packages/router-core/src/router.ts index f1515b5b7a..991e7cadab 100644 --- a/packages/router-core/src/router.ts +++ b/packages/router-core/src/router.ts @@ -1490,11 +1490,10 @@ export class RouterCore< } private getSemanticMatch(matchId: string) { - const committed = this._committedMatches - return committed - ? (committed.find((match) => match.id === matchId) ?? - this.stores.cachedMatchStores.get(matchId)?.get()) - : this.stores.matchStores.get(matchId)?.get() + return ( + this._committedMatches?.find((match) => match.id === matchId) ?? + this.stores.cachedMatchStores.get(matchId)?.get() + ) } private matchRoutesInternal( From 1b209334cca5727872d6ee0ae637ad79bab099ec Mon Sep 17 00:00:00 2001 From: Sheraff Date: Wed, 15 Jul 2026 20:11:21 +0200 Subject: [PATCH 41/59] more jsdoc --- packages/router-core/src/load-client.ts | 38 +++++++++++++++++++------ 1 file changed, 30 insertions(+), 8 deletions(-) diff --git a/packages/router-core/src/load-client.ts b/packages/router-core/src/load-client.ts index f843ec95ba..df18baa082 100644 --- a/packages/router-core/src/load-client.ts +++ b/packages/router-core/src/load-client.ts @@ -874,26 +874,31 @@ function semanticMatches(router: CoordinatorRouter): Array { return router._committedMatches ?? router.stores.matches.get() } +/** + * Finds the first route that should show pending UI and its two timing values. + * A fallback already on screen remains selected after its route loads, so we + * do not jump to a child fallback. Matches put back into pending by invalidation + * skip pendingMs, and a route without a usable fallback blocks pending UI for deeper routes. + */ function pendingConfig( router: AnyRouter, matches: Array, -): [delay: number, boundary: number, min: number] | undefined { +): [delay: number, boundary: number, min: number] | undefined | void { const presented = router.stores.matches.get() for (let index = 0; index < matches.length; index++) { const match = matches[index]! + const success = match.status === 'success' const visible = - match.status === 'success' && + success && presented[index]?.id === match.id && presented[index]?.status === 'pending' - if (match.status === 'success' && !visible) { + if (success && !visible) { continue } const route = getRoute(router, match as WorkMatch) - const delay = visible + const delay = visible || match.invalid ? 0 - : match.invalid - ? 0 - : (route.options.pendingMs ?? router.options.defaultPendingMs) + : (route.options.pendingMs ?? router.options.defaultPendingMs) return (route.options.pendingComponent ?? (router.options as any).defaultPendingComponent) && typeof delay === 'number' && @@ -905,9 +910,14 @@ function pendingConfig( ] : undefined } - return undefined } +/** + * Waits for `pendingMs`, then writes the chosen route and its parents to + * `stores.matches`, causing its fallback to render while children stay hidden. + * A replacement load for the same match keeps the timer; choosing a different + * match resets it. `pendingMinMs` starts after the fallback renders. + */ function offerPending(router: CoordinatorRouter, tx: LoadTransaction): void { if (router._tx !== tx) { return @@ -929,6 +939,8 @@ function offerPending(router: CoordinatorRouter, tx: LoadTransaction): void { const [delay, boundary, min] = config const matchId = tx.matches[boundary]!.id if (!session || session.boundary !== boundary || sessionMatchId !== matchId) { + // Hydration and redirects can preserve pending presentation without a session. + // Do not delay it again; conservatively start pendingMinMs from now. clearTimeout(session?.timer) const presented = router.stores.matches.get()[boundary] const visible = presented?.id === matchId && presented.status === 'pending' @@ -966,6 +978,10 @@ function offerPending(router: CoordinatorRouter, tx: LoadTransaction): void { }) } +/** + * Cancels pending UI timing when its load ends. The ownership check prevents + * an older, superseded load from clearing pending UI that a newer load took over. + */ function finishPending(router: CoordinatorRouter, tx: LoadTransaction): void { const session = router._pending if (session?.owner === tx) { @@ -1183,6 +1199,12 @@ async function runClientTransaction( tx.redirects = undefined const pending = router._pending if (pending?.owner === tx) { + /** + * Loading finished, so cancel any pending reveal. If the fallback rendered, + * wait out the rest of `pendingMinMs` before replacing it. If it never + * rendered, there is no minimum wait; if another load took it over, that + * load owns the deadline. + */ clearTimeout(pending.timer) if (pending.ack) { const rendered = await pending.ack From 83fea0f6b8c98b8269b1bc54fa6973619ff9ff9c Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Wed, 15 Jul 2026 18:13:55 +0000 Subject: [PATCH 42/59] ci: apply automated fixes --- packages/router-core/src/load-client.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/router-core/src/load-client.ts b/packages/router-core/src/load-client.ts index df18baa082..7d1eb86ebe 100644 --- a/packages/router-core/src/load-client.ts +++ b/packages/router-core/src/load-client.ts @@ -896,9 +896,10 @@ function pendingConfig( continue } const route = getRoute(router, match as WorkMatch) - const delay = visible || match.invalid - ? 0 - : (route.options.pendingMs ?? router.options.defaultPendingMs) + const delay = + visible || match.invalid + ? 0 + : (route.options.pendingMs ?? router.options.defaultPendingMs) return (route.options.pendingComponent ?? (router.options as any).defaultPendingComponent) && typeof delay === 'number' && From 1f4838d2200f2475347ae671a1f9fa99956bed94 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Thu, 16 Jul 2026 00:21:25 +0200 Subject: [PATCH 43/59] beforeLoad context cleanup on error + naming + misc bugs --- packages/router-core/INTERNALS.md | 10 +- packages/router-core/src/isServer/client.ts | 4 +- .../router-core/src/isServer/development.ts | 2 +- packages/router-core/src/isServer/server.ts | 2 +- packages/router-core/src/load-client.ts | 28 ++-- packages/router-core/src/load-server.ts | 148 +++++++++++++----- packages/router-core/src/router.ts | 68 +------- .../tests/client-lane-adversarial.test.ts | 27 ++++ .../tests/loader-thrown-promise.test.ts | 41 +++++ .../tests/parent-match-promise.test.ts | 94 +++++++++++ .../tests/preload-beforeload-reuse.test.ts | 74 +++++++++ .../server-concurrent-error-notfound.test.ts | 40 ++++- .../tests/server-planning-redirect.test.ts | 29 ++++ .../router-core/tests/server-preload.test.ts | 95 +++++++++++ 14 files changed, 541 insertions(+), 121 deletions(-) create mode 100644 packages/router-core/tests/loader-thrown-promise.test.ts create mode 100644 packages/router-core/tests/parent-match-promise.test.ts create mode 100644 packages/router-core/tests/server-planning-redirect.test.ts create mode 100644 packages/router-core/tests/server-preload.test.ts diff --git a/packages/router-core/INTERNALS.md b/packages/router-core/INTERNALS.md index bf78588df2..9142d542e1 100644 --- a/packages/router-core/INTERNALS.md +++ b/packages/router-core/INTERNALS.md @@ -420,11 +420,11 @@ generation. `RouterCore.load` refreshes `latestLocation` once, uses that same parsed object for the history action and before-navigation events, and delegates to -`loadClientRouter`. The client loader must not parse a second location object; +`loadClientRoute`. The client loader must not parse a second location object; location object identity is also how scroll restoration associates a history action with the later lifecycle event. -`loadClientRouter` first plans under `_preflight`. Only after planning succeeds +`loadClientRoute` first plans under `_preflight`. Only after planning succeeds and both the preflight owner and previous writer are still current does it install a `LoadTransaction` as `_tx`. Installation then: @@ -770,8 +770,10 @@ route's projection group is discarded; projection failure is non-fatal and never overwrites loader semantics. The final result is a closed union: either a render result with status and -matches, or a redirect. `loadServerRouter` is the only publisher of that result -to router stores. +matches, or a redirect. `loadServerRoute` is the only publisher of that result +to router stores. `preloadServerRoute` separately owns the complete speculative +workflow: location building, matching, lane execution, bounded redirect +following, and cache publication. ## Hydration handoff diff --git a/packages/router-core/src/isServer/client.ts b/packages/router-core/src/isServer/client.ts index bd0e6bfe84..9d8164278b 100644 --- a/packages/router-core/src/isServer/client.ts +++ b/packages/router-core/src/isServer/client.ts @@ -1,3 +1,3 @@ export const isServer = false -export const loadServer: never = undefined as never -export const loadServerRouter: never = undefined as never +export const preloadServerRoute: never = undefined as never +export const loadServerRoute: never = undefined as never diff --git a/packages/router-core/src/isServer/development.ts b/packages/router-core/src/isServer/development.ts index 5a19543e21..c76c1b93db 100644 --- a/packages/router-core/src/isServer/development.ts +++ b/packages/router-core/src/isServer/development.ts @@ -1,3 +1,3 @@ // Development/test mode - returns undefined so fallback to router.isServer is used export const isServer: boolean | undefined = undefined -export { loadServer, loadServerRouter } from '../load-server' +export { preloadServerRoute, loadServerRoute } from '../load-server' diff --git a/packages/router-core/src/isServer/server.ts b/packages/router-core/src/isServer/server.ts index e363962e89..9c7e92e2fb 100644 --- a/packages/router-core/src/isServer/server.ts +++ b/packages/router-core/src/isServer/server.ts @@ -1,2 +1,2 @@ export const isServer = process.env.NODE_ENV === 'test' ? undefined : true -export { loadServer, loadServerRouter } from '../load-server' +export { preloadServerRoute, loadServerRoute } from '../load-server' diff --git a/packages/router-core/src/load-client.ts b/packages/router-core/src/load-client.ts index 7d1eb86ebe..addc3778ff 100644 --- a/packages/router-core/src/load-client.ts +++ b/packages/router-core/src/load-client.ts @@ -174,6 +174,7 @@ async function contextualize( options: ExecuteLaneOptions, ): Promise { let reusePreloadContext = !options.preload + const signal = options.controller.signal for ( let index = options.resolvedPrefix ?? 0; index < lane.matches.length; @@ -181,12 +182,6 @@ async function contextualize( ) { const match = lane.matches[index]! const route = getRoute(router, match) - const serialError = match.paramsError ?? match.searchError - - if (serialError !== undefined) { - releaseFlight(router, match) - return [index, normalizeError(route, serialError)] - } // Fresh matches already own this lane's controller; cached matches do not. reusePreloadContext &&= match.abortController !== options.controller @@ -199,11 +194,18 @@ async function contextualize( ...parentContext, ...match.__routeContext, } + match.context = context + const validationError = match.paramsError ?? match.searchError + + if (validationError !== undefined) { + match.__beforeLoadContext = {} + releaseFlight(router, match) + return [index, normalizeError(route, validationError)] + } const beforeLoad = route.options.beforeLoad if (!beforeLoad) { match.__beforeLoadContext = {} - match.context = context continue } @@ -226,6 +228,7 @@ async function contextualize( continue } reusePreloadContext = false + match.__beforeLoadContext = {} const beforeLoadContext: BeforeLoadContextOptions< any, @@ -254,10 +257,7 @@ async function contextualize( try { match.isFetching = 'beforeLoad' - const result = await waitFor( - beforeLoad(beforeLoadContext), - options.controller.signal, - ) + const result = await waitFor(beforeLoad(beforeLoadContext), signal) match.isFetching = false const outcome = normalize(result, false, route.id) if (outcome[0] !== SUCCESS) { @@ -277,7 +277,7 @@ async function contextualize( } } catch (cause) { match.isFetching = false - if (cause === options.controller.signal) { + if (cause === signal && signal.aborted) { return [index, [CANCELED]] } if (cause instanceof Promise) { @@ -1270,7 +1270,7 @@ async function runClientTransaction( }) } -export async function loadClientRouter( +export async function loadClientRoute( router: CoordinatorRouter, opts?: { sync?: boolean @@ -1425,7 +1425,7 @@ export function refreshClientRoute( } router.clearCache() - return loadClientRouter(router, { sync: true, _refreshRouteId: routeId }) + return loadClientRoute(router, { sync: true, _refreshRouteId: routeId }) } export async function preloadClientRoute( diff --git a/packages/router-core/src/load-server.ts b/packages/router-core/src/load-server.ts index 6f7d6351ad..9346c46a6a 100644 --- a/packages/router-core/src/load-server.ts +++ b/packages/router-core/src/load-server.ts @@ -4,6 +4,7 @@ import { isNotFound } from './not-found' import { isRedirect, redirect } from './redirect' import { rootRouteId } from './root' import { loadRouteChunk } from './route-chunks' +import { getLocationChangeInfo } from './router' import type { ParsedLocation } from './location' import type { AnyRouteMatch } from './Matches' import type { NotFoundError } from './not-found' @@ -265,7 +266,7 @@ async function contextualize( } as ContextualizedLane } -function loaderContext( +function getLoaderContext( router: AnyRouter, lane: ContextualizedLane, match: AnyRouteMatch, @@ -289,7 +290,7 @@ function loaderContext( } } -function startLoader( +function createLoaderTask( router: AnyRouter, lane: ContextualizedLane, index: number, @@ -302,31 +303,34 @@ function startLoader( if (match.ssr === false) { outcome = Promise.resolve([SKIPPED]) + } else if (preload && route.options.preload === false) { + match.status = 'success' + match.invalid = true + match.isFetching = false + outcome = Promise.resolve([SKIPPED]) } else { - const option = route.options.loader - const loader = typeof option === 'function' ? option : option?.handler + const routeLoader = route.options.loader + const loader = + typeof routeLoader === 'function' ? routeLoader : routeLoader?.handler if (!loader) { outcome = Promise.resolve([SUCCESS, undefined]) } else { - let value: unknown - let rejected = false - try { - value = loader( - loaderContext(router, lane, match, route, index, tasks, preload), + outcome = Promise.resolve() + .then(() => + loader( + getLoaderContext(router, lane, match, route, index, tasks, preload), + ), + ) + .then( + (result): LoaderOutcome => + match.abortController.signal.aborted + ? [SKIPPED] + : stampNotFound(match, normalize(result, false)), + (cause): LoaderOutcome => + match.abortController.signal.aborted + ? [SKIPPED] + : stampNotFound(match, normalizeError(route, cause)), ) - } catch (cause) { - value = cause - rejected = true - } - outcome = Promise.resolve(value).then( - (result) => { - const normalized = rejected - ? normalizeError(route, result) - : normalize(result, false) - return stampNotFound(match, normalized) - }, - (cause) => stampNotFound(match, normalizeError(route, cause)), - ) } } @@ -336,6 +340,9 @@ function startLoader( snapshot.loaderData = result[1] snapshot.status = 'success' snapshot.error = undefined + snapshot.invalid = false + snapshot.preload = preload + snapshot.isFetching = false } else if (result[0] === ERROR) { snapshot.status = 'error' snapshot.error = result[1] @@ -460,7 +467,10 @@ async function loadNormalChunks( return undefined } -async function project(router: AnyRouter, lane: ReducedLane): Promise { +async function projectLane( + router: AnyRouter, + lane: ReducedLane, +): Promise { for (const match of lane.matches) { const routeOptions = getRoute(router, match).options if ( @@ -494,7 +504,7 @@ async function project(router: AnyRouter, lane: ReducedLane): Promise { } } -export async function loadServer( +async function executeServerLane( router: AnyRouter, location: ParsedLocation, matchedMatches: Array, @@ -524,7 +534,7 @@ export async function loadServer( const tasks: Array = [] for (let index = 0; index < loaderEnd; index++) { - const task = startLoader(router, lane, index, tasks, preload) + const task = createLoaderTask(router, lane, index, tasks, preload) tasks.push(task) } @@ -593,14 +603,86 @@ export async function loadServer( } } - await project(router, { + await projectLane(router, { location: lane.location, matches: lane.matches, } as ReducedLane) return { type: 'render', status: terminal.status, matches: lane.matches } } -export async function loadServerRouter( +export async function preloadServerRoute( + router: AnyRouter, + opts: any, + redirects = 0, +): Promise | undefined> { + if (redirects > 20) { + return + } + const location = opts._builtLocation ?? router.buildLocation(opts) + + try { + const result = await executeServerLane( + router, + location, + router.matchRoutes(location, { + throwOnError: true, + preload: true, + dest: opts, + }), + true, + ) + if (result.type === 'redirect') { + if (result.redirect.options.reloadDocument) { + return + } + return preloadServerRoute( + router, + { + ...result.redirect.options, + _fromLocation: location, + }, + redirects + 1, + ) + } + if (result.matches.some((match) => match.status !== 'success')) { + return + } + + const active = new Set(router.stores.matchesId.get()) + const candidates = result.matches.filter((match) => { + match.preload = !match.invalid + return !active.has(match.id) + }) + const ids = new Set(candidates.map((match) => match.id)) + router.stores.setCached( + router.stores.cachedMatches + .get() + .filter((match) => !ids.has(match.id)) + .concat(candidates), + ) + return result.matches + } catch (cause) { + if (isRedirect(cause)) { + if (cause.options.reloadDocument) { + return + } + return preloadServerRoute( + router, + { + ...cause.options, + _fromLocation: location, + }, + redirects + 1, + ) + } + if (!isNotFound(cause)) { + console.error(cause) + } + return + } +} + +export async function loadServerRoute( router: AnyRouter, _opts?: Parameters[0], ): Promise { @@ -624,21 +706,15 @@ export async function loadServerRouter( } const fromLocation = router.stores.resolvedLocation.get() - const changeInfo = { - fromLocation, - toLocation: next, - pathChanged: fromLocation?.pathname !== next.pathname, - hrefChanged: fromLocation?.href !== next.href, - hashChanged: fromLocation?.hash !== next.hash, - } + const changeInfo = getLocationChangeInfo(next, fromLocation) router.emit({ type: 'onBeforeNavigate', ...changeInfo }) router.emit({ type: 'onBeforeLoad', ...changeInfo }) - result = await loadServer(router, next, router.matchRoutes(next)) + result = await executeServerLane(router, next, router.matchRoutes(next)) } catch (cause) { if (!isRedirect(cause)) { throw cause } - result = { type: 'redirect', redirect: cause } + result = resolveServerRedirect(router, next, cause) } router._serverResult = result diff --git a/packages/router-core/src/router.ts b/packages/router-core/src/router.ts index 991e7cadab..15f4b696e9 100644 --- a/packages/router-core/src/router.ts +++ b/packages/router-core/src/router.ts @@ -1,8 +1,8 @@ import { createBrowserHistory, parseHref } from '@tanstack/history' import { isServer, - loadServer, - loadServerRouter, + loadServerRoute, + preloadServerRoute, } from '@tanstack/router-core/isServer' import { DEFAULT_PROTOCOL_ALLOWLIST, @@ -40,7 +40,7 @@ import { defaultParseSearch, defaultStringifySearch } from './searchParams' import { rootRouteId } from './root' import { isRedirect } from './redirect' import { - loadClientRouter, + loadClientRoute, preloadClientRoute, refreshClientRoute, transferMatchResources, @@ -2455,7 +2455,7 @@ export class RouterCore< load: LoadFn = async (opts): Promise => { if (isServer ?? this.isServer) { - return loadServerRouter(this, opts) + return loadServerRoute(this, opts) } this._serverResult = undefined @@ -2471,7 +2471,7 @@ export class RouterCore< ) this.emit({ type: 'onBeforeNavigate', ...locationChangeInfo }) this.emit({ type: 'onBeforeLoad', ...locationChangeInfo }) - await loadClientRouter(this, opts) + await loadClientRoute(this, opts) } startViewTransition = async (fn: () => Promise) => { @@ -2644,63 +2644,7 @@ export class RouterCore< if (!(isServer ?? this.isServer)) { return preloadClientRoute(this, opts) } - - const next = opts._builtLocation ?? this.buildLocation(opts as any) - - try { - const result = await loadServer( - this, - next, - this.matchRoutes(next, { - throwOnError: true, - preload: true, - dest: opts, - }), - true, - ) - if (result.type === 'redirect') { - if (result.redirect.options.reloadDocument) { - return - } - return this.preloadRoute({ - ...result.redirect.options, - _fromLocation: next, - }) - } - if (result.matches.some((match) => match.status !== 'success')) { - return - } - - const active = new Set(this.stores.matchesId.get()) - const candidates = result.matches.filter((match) => { - match.preload = true - return !active.has(match.id) - }) - const ids = new Set(candidates.map((match) => match.id)) - this.stores.setCached( - this.stores.cachedMatches - .get() - .filter((match) => !ids.has(match.id)) - .concat(candidates), - ) - return result.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 preloadServerRoute(this, opts) } matchRoute: MatchRouteFn< diff --git a/packages/router-core/tests/client-lane-adversarial.test.ts b/packages/router-core/tests/client-lane-adversarial.test.ts index e37f2f2168..85598f43c8 100644 --- a/packages/router-core/tests/client-lane-adversarial.test.ts +++ b/packages/router-core/tests/client-lane-adversarial.test.ts @@ -392,6 +392,33 @@ describe('adversarial client lane ownership', () => { expect(safeLoader).toHaveBeenCalledTimes(1) }) + test('throwing a non-aborted router signal is an error, not cancellation', async () => { + let thrownSignal: AbortSignal | undefined + const rootRoute = new BaseRootRoute({}) + const brokenRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/broken', + beforeLoad: ({ abortController }) => { + thrownSignal = abortController.signal + throw thrownSignal + }, + errorComponent: () => null, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([brokenRoute]), + history: createMemoryHistory({ initialEntries: ['/broken'] }), + }) + + await router.load() + + expect(thrownSignal?.aborted).toBe(false) + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: brokenRoute.id, + status: 'error', + error: thrownSignal, + }) + }) + test('a failed preflight cannot abort and strand the pending lane it attempted to supersede', async () => { const preflightError = new Error('next loaderDeps failed') const pendingGate = createControlledPromise() diff --git a/packages/router-core/tests/loader-thrown-promise.test.ts b/packages/router-core/tests/loader-thrown-promise.test.ts new file mode 100644 index 0000000000..262cbe7eeb --- /dev/null +++ b/packages/router-core/tests/loader-thrown-promise.test.ts @@ -0,0 +1,41 @@ +import { expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter, loadServerResponse } from './routerTestUtils' + +test.each([false, true])( + 'a synchronously thrown loader Promise has the same meaning with isServer=%s', + async (isServer) => { + const thrown = Promise.resolve('not loader data') + const onError = vi.fn() + const rootRoute = new BaseRootRoute({}) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + loader: () => { + throw thrown + }, + onError, + errorComponent: () => null, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([targetRoute]), + history: createMemoryHistory({ initialEntries: ['/target'] }), + isServer, + }) + + if (isServer) { + const response = await loadServerResponse(router, '/target') + expect(response.status).toBe(500) + } else { + await router.load() + } + + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: targetRoute.id, + status: 'error', + error: thrown, + }) + expect(onError).toHaveBeenCalledWith(thrown) + }, +) diff --git a/packages/router-core/tests/parent-match-promise.test.ts b/packages/router-core/tests/parent-match-promise.test.ts new file mode 100644 index 0000000000..ecde4f7a54 --- /dev/null +++ b/packages/router-core/tests/parent-match-promise.test.ts @@ -0,0 +1,94 @@ +import { expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +test.each([false, true])( + 'preload parentMatchPromise exposes successful preload state with isServer=%s', + async (isServer) => { + const seen: Array = [] + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: () => 'parent data', + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: async ({ parentMatchPromise }) => { + seen.push(await parentMatchPromise) + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + isServer, + }) + + await router.preloadRoute({ to: '/parent/child' }) + + expect(seen).toHaveLength(1) + expect(seen[0]).toMatchObject({ + routeId: parentRoute.id, + loaderData: 'parent data', + status: 'success', + invalid: false, + preload: true, + isFetching: false, + }) + }, +) + +test.each([false, true])( + 'preload false parentMatchPromise exposes a successful invalid parent with isServer=%s', + async (isServer) => { + const seen: Array = [] + const parentLoader = vi.fn() + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + preload: false, + loader: parentLoader, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: async ({ parentMatchPromise }) => { + seen.push(await parentMatchPromise) + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + isServer, + }) + + await router.preloadRoute({ to: '/parent/child' }) + + expect(parentLoader).not.toHaveBeenCalled() + expect(seen).toHaveLength(1) + expect(seen[0]).toMatchObject({ + routeId: parentRoute.id, + status: 'success', + invalid: true, + preload: false, + isFetching: false, + }) + }, +) diff --git a/packages/router-core/tests/preload-beforeload-reuse.test.ts b/packages/router-core/tests/preload-beforeload-reuse.test.ts index 51c4493183..34578a6c5c 100644 --- a/packages/router-core/tests/preload-beforeload-reuse.test.ts +++ b/packages/router-core/tests/preload-beforeload-reuse.test.ts @@ -614,4 +614,78 @@ describe('preloaded beforeLoad context reuse', () => { expect(shouldReload).toHaveBeenCalledTimes(1) expect(router.state.matches.at(-1)?.context).toEqual({ guard: 'loaded' }) }) + + test('a beforeLoad failure clears context from the previous generation', async () => { + const failure = new Error('guard failed') + let fail = false + const rootRoute = new BaseRootRoute({}) + const guardedRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/guarded', + context: () => ({ routeContext: true }), + beforeLoad: () => { + if (fail) { + throw failure + } + return { guard: 'accepted' } + }, + errorComponent: () => null, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([guardedRoute]), + history: createMemoryHistory({ initialEntries: ['/guarded'] }), + }) + + await router.load() + expect(router.state.matches.at(-1)?.context).toEqual({ + routeContext: true, + guard: 'accepted', + }) + + fail = true + await router.load() + + const failedMatch = router.state.matches.at(-1) + expect(failedMatch).toMatchObject({ + status: 'error', + error: failure, + }) + expect(failedMatch?.context).toEqual({ routeContext: true }) + }) + + test('a validation failure clears context from the previous generation', async () => { + let fail = false + const rootRoute = new BaseRootRoute({}) + const guardedRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/guarded', + validateSearch: () => { + if (fail) { + throw new Error('invalid search') + } + return {} + }, + context: () => ({ routeContext: true }), + beforeLoad: () => ({ guard: 'accepted' }), + errorComponent: () => null, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([guardedRoute]), + history: createMemoryHistory({ initialEntries: ['/guarded'] }), + }) + + await router.load() + expect(router.state.matches.at(-1)?.context).toEqual({ + routeContext: true, + guard: 'accepted', + }) + fail = true + await router.load() + + const failedMatch = router.state.matches.at(-1) + expect(failedMatch).toMatchObject({ + status: 'error', + }) + expect(failedMatch?.context).toEqual({ routeContext: true }) + }) }) diff --git a/packages/router-core/tests/server-concurrent-error-notfound.test.ts b/packages/router-core/tests/server-concurrent-error-notfound.test.ts index 8315665779..72c46cb97a 100644 --- a/packages/router-core/tests/server-concurrent-error-notfound.test.ts +++ b/packages/router-core/tests/server-concurrent-error-notfound.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, @@ -200,4 +200,42 @@ describe('server concurrent route failure ordering', () => { expect(signals).toHaveLength(2) expect(signals.every((signal) => signal.aborted)).toBe(true) }) + + test('an aborted child does not report its cancellation through onError', async () => { + const childStarted = createControlledPromise() + const childLoader = createControlledPromise() + const cancellation = new Error('discarded request aborted') + const childOnError = vi.fn() + const rootRoute = new BaseRootRoute({ + loader: async () => { + await childStarted + throw redirect({ href: '/target' }) + }, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/child', + loader: ({ abortController }) => { + abortController.signal.addEventListener( + 'abort', + () => childLoader.reject(cancellation), + { once: true }, + ) + childStarted.resolve() + return childLoader + }, + onError: childOnError, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([childRoute]), + history: createMemoryHistory({ initialEntries: ['/child'] }), + isServer: true, + }) + + const response = await loadServerResponse(router, '/child') + await expect(childLoader).rejects.toBe(cancellation) + + expect(response.status).toBe(307) + expect(childOnError).not.toHaveBeenCalled() + }) }) diff --git a/packages/router-core/tests/server-planning-redirect.test.ts b/packages/router-core/tests/server-planning-redirect.test.ts new file mode 100644 index 0000000000..d64730a407 --- /dev/null +++ b/packages/router-core/tests/server-planning-redirect.test.ts @@ -0,0 +1,29 @@ +import { expect, test } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, redirect } from '../src' +import { createTestRouter, loadServerResponse } from './routerTestUtils' + +test('server resolves a redirect thrown while matching', async () => { + const rootRoute = new BaseRootRoute({}) + const sourceRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/source', + context: () => { + throw redirect({ to: '/target' }) + }, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([sourceRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/source'] }), + isServer: true, + }) + + const response = await loadServerResponse(router, '/source') + + expect(response.status).toBe(307) + expect(response.headers.get('Location')).toBe('/target') +}) diff --git a/packages/router-core/tests/server-preload.test.ts b/packages/router-core/tests/server-preload.test.ts new file mode 100644 index 0000000000..685883d305 --- /dev/null +++ b/packages/router-core/tests/server-preload.test.ts @@ -0,0 +1,95 @@ +import { expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, redirect } from '../src' +import { createTestRouter } from './routerTestUtils' + +test('server preload owns matching, execution, and cache publication', async () => { + const loader = vi.fn(({ preload }: { preload: boolean }) => preload) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + isServer: true, + }) + + const matches = await router.preloadRoute({ to: '/target' }) + + expect(loader).toHaveBeenCalledTimes(1) + expect(matches?.at(-1)).toMatchObject({ + routeId: targetRoute.id, + loaderData: true, + preload: true, + }) + expect(router.stores.cachedMatches.get()).toContain(matches?.at(-1)) +}) + +test('server preload false preserves ancestor work but skips its loader', async () => { + const seen: Array = [] + const loader = vi.fn() + const rootLoader = vi.fn(() => 'root data') + const rootRoute = new BaseRootRoute({ loader: rootLoader }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + preload: false, + beforeLoad: ({ preload }) => { + seen.push(preload) + }, + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([targetRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + isServer: true, + }) + + const matches = await router.preloadRoute({ to: '/target' }) + + expect(matches).toHaveLength(2) + expect(seen).toEqual([true]) + expect(rootLoader).toHaveBeenCalledTimes(1) + expect(loader).not.toHaveBeenCalled() + expect(matches?.[0]).toMatchObject({ + routeId: rootRoute.id, + loaderData: 'root data', + preload: true, + invalid: false, + }) + expect(matches?.[1]).toMatchObject({ + routeId: targetRoute.id, + preload: false, + invalid: true, + status: 'success', + }) + expect(router.stores.cachedMatches.get()).toEqual(matches) +}) + +test('server preload stops following a redirect cycle', async () => { + const loader = vi.fn(() => { + throw redirect({ to: '/loop' }) + }) + const rootRoute = new BaseRootRoute({}) + const loopRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/loop', + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([loopRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + isServer: true, + }) + + await router.preloadRoute({ to: '/loop' }) + + expect(loader).toHaveBeenCalledTimes(21) +}) From 47466333b3ea5c33889d3282d26f55cf0cb043b6 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Fri, 17 Jul 2026 07:12:03 +0200 Subject: [PATCH 44/59] server preload is no-op --- packages/router-core/INTERNALS.md | 11 +- packages/router-core/src/isServer/client.ts | 1 - .../router-core/src/isServer/development.ts | 2 +- packages/router-core/src/isServer/server.ts | 2 +- packages/router-core/src/load-server.ts | 98 +---------- packages/router-core/src/router.ts | 9 +- .../tests/client-lane-adversarial.test.ts | 74 ++++++--- .../tests/parent-match-promise.test.ts | 104 ++++++------ .../tests/preload-beforeload-reuse.test.ts | 154 ++++++++++-------- .../server-concurrent-error-notfound.test.ts | 139 ++++++++++------ .../tests/server-loader-abort-error.test.ts | 82 ++++++---- .../tests/server-planning-redirect.test.ts | 57 ++++--- .../router-core/tests/server-preload.test.ts | 95 ----------- 13 files changed, 372 insertions(+), 456 deletions(-) delete mode 100644 packages/router-core/tests/server-preload.test.ts diff --git a/packages/router-core/INTERNALS.md b/packages/router-core/INTERNALS.md index 9142d542e1..89cbca37b1 100644 --- a/packages/router-core/INTERNALS.md +++ b/packages/router-core/INTERNALS.md @@ -631,9 +631,8 @@ removed from the cache; failed, not-found, expired, and loaderless entries without reusable context provenance are discarded. Clearing the cache releases leases before publishing the retained cache entries. -Server `preloadRoute` is different: it runs the request-local server lane and may -cache an all-success result, but it has no client transaction or loader-flight -protocol. +Server `preloadRoute` is a no-op. Server work is owned exclusively by normal +request loading. ## Background stale reloads @@ -770,10 +769,8 @@ route's projection group is discarded; projection failure is non-fatal and never overwrites loader semantics. The final result is a closed union: either a render result with status and -matches, or a redirect. `loadServerRoute` is the only publisher of that result -to router stores. `preloadServerRoute` separately owns the complete speculative -workflow: location building, matching, lane execution, bounded redirect -following, and cache publication. +matches, or a redirect. `loadServerRoute` owns the complete server workflow and +is the only publisher of that result to router stores. ## Hydration handoff diff --git a/packages/router-core/src/isServer/client.ts b/packages/router-core/src/isServer/client.ts index 9d8164278b..e12407f409 100644 --- a/packages/router-core/src/isServer/client.ts +++ b/packages/router-core/src/isServer/client.ts @@ -1,3 +1,2 @@ export const isServer = false -export const preloadServerRoute: never = undefined as never export const loadServerRoute: never = undefined as never diff --git a/packages/router-core/src/isServer/development.ts b/packages/router-core/src/isServer/development.ts index c76c1b93db..e4f13879ad 100644 --- a/packages/router-core/src/isServer/development.ts +++ b/packages/router-core/src/isServer/development.ts @@ -1,3 +1,3 @@ // Development/test mode - returns undefined so fallback to router.isServer is used export const isServer: boolean | undefined = undefined -export { preloadServerRoute, loadServerRoute } from '../load-server' +export { loadServerRoute } from '../load-server' diff --git a/packages/router-core/src/isServer/server.ts b/packages/router-core/src/isServer/server.ts index 9c7e92e2fb..d13401a9e9 100644 --- a/packages/router-core/src/isServer/server.ts +++ b/packages/router-core/src/isServer/server.ts @@ -1,2 +1,2 @@ export const isServer = process.env.NODE_ENV === 'test' ? undefined : true -export { preloadServerRoute, loadServerRoute } from '../load-server' +export { loadServerRoute } from '../load-server' diff --git a/packages/router-core/src/load-server.ts b/packages/router-core/src/load-server.ts index 9346c46a6a..f70c9893ab 100644 --- a/packages/router-core/src/load-server.ts +++ b/packages/router-core/src/load-server.ts @@ -168,7 +168,6 @@ function stampNotFound( async function contextualize( router: AnyRouter, lane: MatchedLane, - preload: boolean, ): Promise { let end = lane.matches.length let failure: IndexedOutcome | undefined @@ -223,12 +222,12 @@ async function contextualize( search: match.search, abortController, params: match.params, - preload, + preload: false, context, location: lane.location, navigate: navigateFrom(router, lane.location), buildLocation: router.buildLocation, - cause: preload ? 'preload' : match.cause, + cause: match.cause, matches: lane.matches, routeId: route.id, ...router.options.additionalContext, @@ -273,18 +272,17 @@ function getLoaderContext( route: AnyRoute, index: number, tasks: Array, - preload: boolean, ): LoaderFnContext { return { params: match.params, deps: match.loaderDeps, - preload, + preload: false, parentMatchPromise: tasks[index - 1]?.match, abortController: match.abortController, context: match.context, location: lane.location, navigate: navigateFrom(router, lane.location), - cause: preload ? 'preload' : match.cause, + cause: match.cause, route, ...router.options.additionalContext, } @@ -295,7 +293,6 @@ function createLoaderTask( lane: ContextualizedLane, index: number, tasks: Array, - preload: boolean, ): LoaderTask { const match = lane.matches[index]! const route = getRoute(router, match) @@ -303,11 +300,6 @@ function createLoaderTask( if (match.ssr === false) { outcome = Promise.resolve([SKIPPED]) - } else if (preload && route.options.preload === false) { - match.status = 'success' - match.invalid = true - match.isFetching = false - outcome = Promise.resolve([SKIPPED]) } else { const routeLoader = route.options.loader const loader = @@ -317,9 +309,7 @@ function createLoaderTask( } else { outcome = Promise.resolve() .then(() => - loader( - getLoaderContext(router, lane, match, route, index, tasks, preload), - ), + loader(getLoaderContext(router, lane, match, route, index, tasks)), ) .then( (result): LoaderOutcome => @@ -341,7 +331,6 @@ function createLoaderTask( snapshot.status = 'success' snapshot.error = undefined snapshot.invalid = false - snapshot.preload = preload snapshot.isFetching = false } else if (result[0] === ERROR) { snapshot.status = 'error' @@ -508,7 +497,6 @@ async function executeServerLane( router: AnyRouter, location: ParsedLocation, matchedMatches: Array, - preload = false, ): Promise { const matched = { location, @@ -520,7 +508,7 @@ async function executeServerLane( abortController: new AbortController(), })), } as MatchedLane - const lane = await contextualize(router, matched, preload) + const lane = await contextualize(router, matched) let loaderEnd = lane.end if (lane.failure?.[1][0] === REDIRECTED) { @@ -534,7 +522,7 @@ async function executeServerLane( const tasks: Array = [] for (let index = 0; index < loaderEnd; index++) { - const task = createLoaderTask(router, lane, index, tasks, preload) + const task = createLoaderTask(router, lane, index, tasks) tasks.push(task) } @@ -610,78 +598,6 @@ async function executeServerLane( return { type: 'render', status: terminal.status, matches: lane.matches } } -export async function preloadServerRoute( - router: AnyRouter, - opts: any, - redirects = 0, -): Promise | undefined> { - if (redirects > 20) { - return - } - const location = opts._builtLocation ?? router.buildLocation(opts) - - try { - const result = await executeServerLane( - router, - location, - router.matchRoutes(location, { - throwOnError: true, - preload: true, - dest: opts, - }), - true, - ) - if (result.type === 'redirect') { - if (result.redirect.options.reloadDocument) { - return - } - return preloadServerRoute( - router, - { - ...result.redirect.options, - _fromLocation: location, - }, - redirects + 1, - ) - } - if (result.matches.some((match) => match.status !== 'success')) { - return - } - - const active = new Set(router.stores.matchesId.get()) - const candidates = result.matches.filter((match) => { - match.preload = !match.invalid - return !active.has(match.id) - }) - const ids = new Set(candidates.map((match) => match.id)) - router.stores.setCached( - router.stores.cachedMatches - .get() - .filter((match) => !ids.has(match.id)) - .concat(candidates), - ) - return result.matches - } catch (cause) { - if (isRedirect(cause)) { - if (cause.options.reloadDocument) { - return - } - return preloadServerRoute( - router, - { - ...cause.options, - _fromLocation: location, - }, - redirects + 1, - ) - } - if (!isNotFound(cause)) { - console.error(cause) - } - return - } -} - export async function loadServerRoute( router: AnyRouter, _opts?: Parameters[0], diff --git a/packages/router-core/src/router.ts b/packages/router-core/src/router.ts index 15f4b696e9..8101228406 100644 --- a/packages/router-core/src/router.ts +++ b/packages/router-core/src/router.ts @@ -1,9 +1,5 @@ import { createBrowserHistory, parseHref } from '@tanstack/history' -import { - isServer, - loadServerRoute, - preloadServerRoute, -} from '@tanstack/router-core/isServer' +import { isServer, loadServerRoute } from '@tanstack/router-core/isServer' import { DEFAULT_PROTOCOL_ALLOWLIST, decodePath, @@ -630,7 +626,6 @@ export type SubscribeFn = ( export interface MatchRoutesOpts { preload?: boolean throwOnError?: boolean - dest?: BuildNextOptions /** @internal */ _controller?: AbortController /** @internal */ @@ -2644,7 +2639,7 @@ export class RouterCore< if (!(isServer ?? this.isServer)) { return preloadClientRoute(this, opts) } - return preloadServerRoute(this, opts) + return undefined } matchRoute: MatchRouteFn< diff --git a/packages/router-core/tests/client-lane-adversarial.test.ts b/packages/router-core/tests/client-lane-adversarial.test.ts index 85598f43c8..05204ce556 100644 --- a/packages/router-core/tests/client-lane-adversarial.test.ts +++ b/packages/router-core/tests/client-lane-adversarial.test.ts @@ -7,7 +7,7 @@ import { notFound, redirect, } from '../src' -import { createTestRouter } from './routerTestUtils' +import { createTestRouter, loadServerResponse } from './routerTestUtils' afterEach(() => { vi.useRealTimers() @@ -392,32 +392,58 @@ describe('adversarial client lane ownership', () => { expect(safeLoader).toHaveBeenCalledTimes(1) }) - test('throwing a non-aborted router signal is an error, not cancellation', async () => { - let thrownSignal: AbortSignal | undefined - const rootRoute = new BaseRootRoute({}) - const brokenRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/broken', - beforeLoad: ({ abortController }) => { - thrownSignal = abortController.signal - throw thrownSignal + test.each( + ([false, true] as const).flatMap((isServer) => [ + { + isServer, + thrownType: 'AbortSignal', + createThrownValue: (signal: AbortSignal) => signal, }, - errorComponent: () => null, - }) - const router = createTestRouter({ - routeTree: rootRoute.addChildren([brokenRoute]), - history: createMemoryHistory({ initialEntries: ['/broken'] }), - }) + { + isServer, + thrownType: 'AbortError', + createThrownValue: () => + new DOMException('The operation was aborted.', 'AbortError'), + }, + ]), + )( + 'treats a user-thrown $thrownType in beforeLoad as an ordinary route error (isServer=$isServer)', + async ({ isServer, createThrownValue }) => { + let matchSignal: AbortSignal | undefined + let thrownValue: unknown + const rootRoute = new BaseRootRoute({}) + const brokenRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/broken', + beforeLoad: ({ abortController }) => { + matchSignal = abortController.signal + thrownValue = createThrownValue(matchSignal) + throw thrownValue + }, + errorComponent: () => null, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([brokenRoute]), + history: createMemoryHistory({ initialEntries: ['/broken'] }), + isServer, + }) - await router.load() + if (isServer) { + const response = await loadServerResponse(router, '/broken') + expect(response.status).toBe(500) + } else { + await router.load() + } - expect(thrownSignal?.aborted).toBe(false) - expect(router.state.matches.at(-1)).toMatchObject({ - routeId: brokenRoute.id, - status: 'error', - error: thrownSignal, - }) - }) + const match = router.state.matches.at(-1) + expect(matchSignal?.aborted).toBe(false) + expect(match).toMatchObject({ + routeId: brokenRoute.id, + status: 'error', + }) + expect(match?.error).toBe(thrownValue) + }, + ) test('a failed preflight cannot abort and strand the pending lane it attempted to supersede', async () => { const preflightError = new Error('next loaderDeps failed') diff --git a/packages/router-core/tests/parent-match-promise.test.ts b/packages/router-core/tests/parent-match-promise.test.ts index ecde4f7a54..eac4fee04c 100644 --- a/packages/router-core/tests/parent-match-promise.test.ts +++ b/packages/router-core/tests/parent-match-promise.test.ts @@ -4,14 +4,10 @@ import { BaseRootRoute, BaseRoute } from '../src' import { createTestRouter } from './routerTestUtils' test.each([false, true])( - 'preload parentMatchPromise exposes successful preload state with isServer=%s', + 'parentMatchPromise exposes successful parent state during loading with isServer=%s', async (isServer) => { const seen: Array = [] const rootRoute = new BaseRootRoute({}) - const indexRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/', - }) const parentRoute = new BaseRoute({ getParentRoute: () => rootRoute, path: '/parent', @@ -25,15 +21,12 @@ test.each([false, true])( }, }) const router = createTestRouter({ - routeTree: rootRoute.addChildren([ - indexRoute, - parentRoute.addChildren([childRoute]), - ]), - history: createMemoryHistory({ initialEntries: ['/'] }), + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), isServer, }) - await router.preloadRoute({ to: '/parent/child' }) + await router.load() expect(seen).toHaveLength(1) expect(seen[0]).toMatchObject({ @@ -41,54 +34,51 @@ test.each([false, true])( loaderData: 'parent data', status: 'success', invalid: false, - preload: true, - isFetching: false, - }) - }, -) - -test.each([false, true])( - 'preload false parentMatchPromise exposes a successful invalid parent with isServer=%s', - async (isServer) => { - const seen: Array = [] - const parentLoader = vi.fn() - const rootRoute = new BaseRootRoute({}) - const indexRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/', - }) - const parentRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/parent', - preload: false, - loader: parentLoader, - }) - const childRoute = new BaseRoute({ - getParentRoute: () => parentRoute, - path: '/child', - loader: async ({ parentMatchPromise }) => { - seen.push(await parentMatchPromise) - }, - }) - const router = createTestRouter({ - routeTree: rootRoute.addChildren([ - indexRoute, - parentRoute.addChildren([childRoute]), - ]), - history: createMemoryHistory({ initialEntries: ['/'] }), - isServer, - }) - - await router.preloadRoute({ to: '/parent/child' }) - - expect(parentLoader).not.toHaveBeenCalled() - expect(seen).toHaveLength(1) - expect(seen[0]).toMatchObject({ - routeId: parentRoute.id, - status: 'success', - invalid: true, preload: false, isFetching: false, }) }, ) + +test('client preload=false parentMatchPromise exposes a successful invalid parent', async () => { + const seen: Array = [] + const parentLoader = vi.fn() + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + preload: false, + loader: parentLoader, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: async ({ parentMatchPromise }) => { + seen.push(await parentMatchPromise) + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + isServer: false, + }) + + await router.preloadRoute({ to: '/parent/child' }) + + expect(parentLoader).not.toHaveBeenCalled() + expect(seen).toHaveLength(1) + expect(seen[0]).toMatchObject({ + routeId: parentRoute.id, + status: 'success', + invalid: true, + preload: false, + isFetching: false, + }) +}) diff --git a/packages/router-core/tests/preload-beforeload-reuse.test.ts b/packages/router-core/tests/preload-beforeload-reuse.test.ts index 34578a6c5c..2cbd3988f5 100644 --- a/packages/router-core/tests/preload-beforeload-reuse.test.ts +++ b/packages/router-core/tests/preload-beforeload-reuse.test.ts @@ -1,7 +1,7 @@ import { afterEach, describe, expect, test, vi } from 'vitest' import { createMemoryHistory } from '@tanstack/history' import { BaseRootRoute, BaseRoute, createControlledPromise } from '../src' -import { createTestRouter } from './routerTestUtils' +import { createTestRouter, loadServerResponse } from './routerTestUtils' afterEach(() => { vi.useRealTimers() @@ -615,77 +615,95 @@ describe('preloaded beforeLoad context reuse', () => { expect(router.state.matches.at(-1)?.context).toEqual({ guard: 'loaded' }) }) - test('a beforeLoad failure clears context from the previous generation', async () => { - const failure = new Error('guard failed') - let fail = false - const rootRoute = new BaseRootRoute({}) - const guardedRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/guarded', - context: () => ({ routeContext: true }), - beforeLoad: () => { - if (fail) { - throw failure - } - return { guard: 'accepted' } - }, - errorComponent: () => null, - }) - const router = createTestRouter({ - routeTree: rootRoute.addChildren([guardedRoute]), - history: createMemoryHistory({ initialEntries: ['/guarded'] }), - }) + test.each([false, true])( + 'a beforeLoad failure clears context from the previous generation with isServer=%s', + async (isServer) => { + const failure = new Error('guard failed') + let fail = false + const rootRoute = new BaseRootRoute({}) + const guardedRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/guarded', + context: () => ({ routeContext: true }), + beforeLoad: () => { + if (fail) { + throw failure + } + return { guard: 'accepted' } + }, + errorComponent: () => null, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([guardedRoute]), + history: createMemoryHistory({ initialEntries: ['/guarded'] }), + isServer, + }) - await router.load() - expect(router.state.matches.at(-1)?.context).toEqual({ - routeContext: true, - guard: 'accepted', - }) + await router.load() + expect(router.state.matches.at(-1)?.context).toEqual({ + routeContext: true, + guard: 'accepted', + }) - fail = true - await router.load() + fail = true + if (isServer) { + const response = await loadServerResponse(router, '/guarded') + expect(response.status).toBe(500) + } else { + await router.load() + } - const failedMatch = router.state.matches.at(-1) - expect(failedMatch).toMatchObject({ - status: 'error', - error: failure, - }) - expect(failedMatch?.context).toEqual({ routeContext: true }) - }) + const failedMatch = router.state.matches.at(-1) + expect(failedMatch).toMatchObject({ + status: 'error', + error: failure, + }) + expect(failedMatch?.context).toEqual({ routeContext: true }) + }, + ) - test('a validation failure clears context from the previous generation', async () => { - let fail = false - const rootRoute = new BaseRootRoute({}) - const guardedRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/guarded', - validateSearch: () => { - if (fail) { - throw new Error('invalid search') - } - return {} - }, - context: () => ({ routeContext: true }), - beforeLoad: () => ({ guard: 'accepted' }), - errorComponent: () => null, - }) - const router = createTestRouter({ - routeTree: rootRoute.addChildren([guardedRoute]), - history: createMemoryHistory({ initialEntries: ['/guarded'] }), - }) + test.each([false, true])( + 'a validation failure clears context from the previous generation with isServer=%s', + async (isServer) => { + let fail = false + const rootRoute = new BaseRootRoute({}) + const guardedRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/guarded', + validateSearch: () => { + if (fail) { + throw new Error('invalid search') + } + return {} + }, + context: () => ({ routeContext: true }), + beforeLoad: () => ({ guard: 'accepted' }), + errorComponent: () => null, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([guardedRoute]), + history: createMemoryHistory({ initialEntries: ['/guarded'] }), + isServer, + }) - await router.load() - expect(router.state.matches.at(-1)?.context).toEqual({ - routeContext: true, - guard: 'accepted', - }) - fail = true - await router.load() + await router.load() + expect(router.state.matches.at(-1)?.context).toEqual({ + routeContext: true, + guard: 'accepted', + }) + fail = true + if (isServer) { + const response = await loadServerResponse(router, '/guarded') + expect(response.status).toBe(500) + } else { + await router.load() + } - const failedMatch = router.state.matches.at(-1) - expect(failedMatch).toMatchObject({ - status: 'error', - }) - expect(failedMatch?.context).toEqual({ routeContext: true }) - }) + const failedMatch = router.state.matches.at(-1) + expect(failedMatch).toMatchObject({ + status: 'error', + }) + expect(failedMatch?.context).toEqual({ routeContext: true }) + }, + ) }) diff --git a/packages/router-core/tests/server-concurrent-error-notfound.test.ts b/packages/router-core/tests/server-concurrent-error-notfound.test.ts index 72c46cb97a..340e6ed624 100644 --- a/packages/router-core/tests/server-concurrent-error-notfound.test.ts +++ b/packages/router-core/tests/server-concurrent-error-notfound.test.ts @@ -9,10 +9,17 @@ import { } from '../src' import { createTestRouter, loadServerResponse } from './routerTestUtils' -describe('server concurrent route failure ordering', () => { - test.each(['parent-first', 'child-first'] as const)( - 'commits the first route-order loader failure and aborts its descendants (%s)', - async (settlementOrder) => { +const concurrentModes = [ + ['parent-first', false], + ['parent-first', true], + ['child-first', false], + ['child-first', true], +] as const + +describe('concurrent route failure ordering', () => { + test.each(concurrentModes)( + 'commits the first route-order loader failure and aborts its descendants (%s, isServer=%s)', + async (settlementOrder, isServer) => { const parentError = new Error('parent loader failed') const parentGate = createControlledPromise() const childGate = createControlledPromise() @@ -56,10 +63,12 @@ describe('server concurrent route failure ordering', () => { parentRoute.addChildren([childRoute]), ]), history: createMemoryHistory({ initialEntries: ['/parent/child'] }), - isServer: true, + isServer, }) - const responsePromise = loadServerResponse(router, '/parent/child') + const responsePromise = isServer + ? loadServerResponse(router, '/parent/child') + : router.load().then(() => undefined) await Promise.all([parentStarted, childStarted]) if (settlementOrder === 'parent-first') { parentGate.resolve() @@ -74,7 +83,9 @@ describe('server concurrent route failure ordering', () => { } const response = await responsePromise - expect(response.status).toBe(500) + if (isServer) { + expect(response?.status).toBe(500) + } expect(settlements).toEqual( settlementOrder === 'parent-first' ? ['parent', 'child'] @@ -93,9 +104,9 @@ describe('server concurrent route failure ordering', () => { }, ) - test.each(['parent-first', 'child-first'] as const)( - 'does not replace an earlier route-order loader notFound with a later error (%s)', - async (settlementOrder) => { + test.each(concurrentModes)( + 'does not replace an earlier route-order loader notFound with a later error (%s, isServer=%s)', + async (settlementOrder, isServer) => { const parentGate = createControlledPromise() const childGate = createControlledPromise() const parentStarted = createControlledPromise() @@ -133,10 +144,12 @@ describe('server concurrent route failure ordering', () => { parentRoute.addChildren([childRoute]), ]), history: createMemoryHistory({ initialEntries: ['/parent/child'] }), - isServer: true, + isServer, }) - const responsePromise = loadServerResponse(router, '/parent/child') + const responsePromise = isServer + ? loadServerResponse(router, '/parent/child') + : router.load().then(() => undefined) await Promise.all([parentStarted, childStarted]) if (settlementOrder === 'parent-first') { parentGate.resolve() @@ -151,7 +164,9 @@ describe('server concurrent route failure ordering', () => { } const response = await responsePromise - expect(response.status).toBe(404) + if (isServer) { + expect(response?.status).toBe(404) + } expect(settlements).toEqual( settlementOrder === 'parent-first' ? ['parent', 'child'] @@ -201,41 +216,69 @@ describe('server concurrent route failure ordering', () => { expect(signals.every((signal) => signal.aborted)).toBe(true) }) - test('an aborted child does not report its cancellation through onError', async () => { - const childStarted = createControlledPromise() - const childLoader = createControlledPromise() - const cancellation = new Error('discarded request aborted') - const childOnError = vi.fn() - const rootRoute = new BaseRootRoute({ - loader: async () => { - await childStarted - throw redirect({ href: '/target' }) - }, - }) - const childRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/child', - loader: ({ abortController }) => { - abortController.signal.addEventListener( - 'abort', - () => childLoader.reject(cancellation), - { once: true }, - ) - childStarted.resolve() - return childLoader - }, - onError: childOnError, - }) - const router = createTestRouter({ - routeTree: rootRoute.addChildren([childRoute]), - history: createMemoryHistory({ initialEntries: ['/child'] }), - isServer: true, - }) + test.each([false, true])( + 'an aborted child does not report its cancellation through onError (isServer=%s)', + async (isServer) => { + const childStarted = createControlledPromise() + const childLoader = createControlledPromise() + const cancellation = new Error('discarded request aborted') + const childOnError = vi.fn() + let childSignal: AbortSignal | undefined + const rootRoute = new BaseRootRoute({}) + const sourceRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/source', + loader: async () => { + await childStarted + throw redirect({ to: '/target' }) + }, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => sourceRoute, + path: '/child', + loader: ({ abortController }) => { + childSignal = abortController.signal + abortController.signal.addEventListener( + 'abort', + () => childLoader.reject(cancellation), + { once: true }, + ) + childStarted.resolve() + return childLoader + }, + onError: childOnError, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + sourceRoute.addChildren([childRoute]), + targetRoute, + ]), + history: createMemoryHistory({ initialEntries: ['/source/child'] }), + isServer, + }) - const response = await loadServerResponse(router, '/child') - await expect(childLoader).rejects.toBe(cancellation) + const childCancellation = expect(childLoader).rejects.toBe(cancellation) + const loadPromise = isServer + ? loadServerResponse(router, '/source/child') + : router.load().then(() => undefined) + const [response] = await Promise.all([loadPromise, childCancellation]) - expect(response.status).toBe(307) - expect(childOnError).not.toHaveBeenCalled() - }) + expect(childSignal?.aborted).toBe(true) + expect(childOnError).not.toHaveBeenCalled() + if (isServer) { + expect(response?.status).toBe(307) + expect(response?.headers.get('Location')).toBe('/target') + } else { + expect(router.state.location.pathname).toBe('/target') + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: targetRoute.id, + status: 'success', + }) + } + }, + ) }) diff --git a/packages/router-core/tests/server-loader-abort-error.test.ts b/packages/router-core/tests/server-loader-abort-error.test.ts index a60fc649fc..811bcae4ce 100644 --- a/packages/router-core/tests/server-loader-abort-error.test.ts +++ b/packages/router-core/tests/server-loader-abort-error.test.ts @@ -3,41 +3,55 @@ import { createMemoryHistory } from '@tanstack/history' import { BaseRootRoute, BaseRoute } from '../src' import { createTestRouter, loadServerResponse } 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 a route failure. - * Only a router-aborted generation may discard AbortError as cancellation. - */ - -describe('server loader AbortError', () => { - test('settles as an error when the match signal is not aborted', async () => { - let loaderSignal: AbortSignal | undefined - const rootRoute = new BaseRootRoute({}) - const abortingRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/aborting', - loader: ({ abortController }) => { - loaderSignal = abortController.signal - throw new DOMException('The operation was aborted.', 'AbortError') +describe('loader user-thrown abort values', () => { + test.each( + ([false, true] as const).flatMap((isServer) => [ + { + isServer, + thrownType: 'AbortSignal', + createThrownValue: (signal: AbortSignal) => signal, }, - }) - const router = createTestRouter({ - routeTree: rootRoute.addChildren([abortingRoute]), - history: createMemoryHistory({ initialEntries: ['/aborting'] }), - isServer: true, - }) + { + isServer, + thrownType: 'AbortError', + createThrownValue: () => + new DOMException('The operation was aborted.', 'AbortError'), + }, + ]), + )( + 'treats a user-thrown $thrownType as an ordinary route error (isServer=$isServer)', + async ({ isServer, createThrownValue }) => { + let matchSignal: AbortSignal | undefined + let thrownValue: unknown + const rootRoute = new BaseRootRoute({}) + const abortingRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/aborting', + loader: ({ abortController }) => { + matchSignal = abortController.signal + thrownValue = createThrownValue(matchSignal) + throw thrownValue + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([abortingRoute]), + history: createMemoryHistory({ initialEntries: ['/aborting'] }), + isServer, + }) - const response = await loadServerResponse(router, '/aborting') + if (isServer) { + const response = await loadServerResponse(router, '/aborting') + expect(response.status).toBe(500) + } else { + await router.load() + } - const match = router.state.matches.find( - (item) => item.routeId === abortingRoute.id, - ) - expect(response.status).toBe(500) - expect(loaderSignal?.aborted).toBe(false) - expect(match?.status).toBe('error') - expect(match?.error).toMatchObject({ - name: 'AbortError', - message: 'The operation was aborted.', - }) - }) + const match = router.state.matches.find( + (item) => item.routeId === abortingRoute.id, + ) + expect(matchSignal?.aborted).toBe(false) + expect(match?.status).toBe('error') + expect(match?.error).toBe(thrownValue) + }, + ) }) diff --git a/packages/router-core/tests/server-planning-redirect.test.ts b/packages/router-core/tests/server-planning-redirect.test.ts index d64730a407..242542a989 100644 --- a/packages/router-core/tests/server-planning-redirect.test.ts +++ b/packages/router-core/tests/server-planning-redirect.test.ts @@ -3,27 +3,40 @@ import { createMemoryHistory } from '@tanstack/history' import { BaseRootRoute, BaseRoute, redirect } from '../src' import { createTestRouter, loadServerResponse } from './routerTestUtils' -test('server resolves a redirect thrown while matching', async () => { - const rootRoute = new BaseRootRoute({}) - const sourceRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/source', - context: () => { - throw redirect({ to: '/target' }) - }, - }) - const targetRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/target', - }) - const router = createTestRouter({ - routeTree: rootRoute.addChildren([sourceRoute, targetRoute]), - history: createMemoryHistory({ initialEntries: ['/source'] }), - isServer: true, - }) +test.each([false, true])( + 'a route-context planning redirect is control with isServer=%s', + async (isServer) => { + const rootRoute = new BaseRootRoute({}) + const sourceRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/source', + context: () => { + throw redirect({ to: '/target' }) + }, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([sourceRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/source'] }), + isServer, + }) - const response = await loadServerResponse(router, '/source') + if (isServer) { + const response = await loadServerResponse(router, '/source') - expect(response.status).toBe(307) - expect(response.headers.get('Location')).toBe('/target') -}) + expect(response.status).toBe(307) + expect(response.headers.get('Location')).toBe('/target') + } else { + await router.load() + + expect(router.state.location.pathname).toBe('/target') + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: targetRoute.id, + status: 'success', + }) + } + }, +) diff --git a/packages/router-core/tests/server-preload.test.ts b/packages/router-core/tests/server-preload.test.ts deleted file mode 100644 index 685883d305..0000000000 --- a/packages/router-core/tests/server-preload.test.ts +++ /dev/null @@ -1,95 +0,0 @@ -import { expect, test, vi } from 'vitest' -import { createMemoryHistory } from '@tanstack/history' -import { BaseRootRoute, BaseRoute, redirect } from '../src' -import { createTestRouter } from './routerTestUtils' - -test('server preload owns matching, execution, and cache publication', async () => { - const loader = vi.fn(({ preload }: { preload: boolean }) => preload) - const rootRoute = new BaseRootRoute({}) - const indexRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/', - }) - const targetRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/target', - loader, - }) - const router = createTestRouter({ - routeTree: rootRoute.addChildren([indexRoute, targetRoute]), - history: createMemoryHistory({ initialEntries: ['/'] }), - isServer: true, - }) - - const matches = await router.preloadRoute({ to: '/target' }) - - expect(loader).toHaveBeenCalledTimes(1) - expect(matches?.at(-1)).toMatchObject({ - routeId: targetRoute.id, - loaderData: true, - preload: true, - }) - expect(router.stores.cachedMatches.get()).toContain(matches?.at(-1)) -}) - -test('server preload false preserves ancestor work but skips its loader', async () => { - const seen: Array = [] - const loader = vi.fn() - const rootLoader = vi.fn(() => 'root data') - const rootRoute = new BaseRootRoute({ loader: rootLoader }) - const targetRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/target', - preload: false, - beforeLoad: ({ preload }) => { - seen.push(preload) - }, - loader, - }) - const router = createTestRouter({ - routeTree: rootRoute.addChildren([targetRoute]), - history: createMemoryHistory({ initialEntries: ['/'] }), - isServer: true, - }) - - const matches = await router.preloadRoute({ to: '/target' }) - - expect(matches).toHaveLength(2) - expect(seen).toEqual([true]) - expect(rootLoader).toHaveBeenCalledTimes(1) - expect(loader).not.toHaveBeenCalled() - expect(matches?.[0]).toMatchObject({ - routeId: rootRoute.id, - loaderData: 'root data', - preload: true, - invalid: false, - }) - expect(matches?.[1]).toMatchObject({ - routeId: targetRoute.id, - preload: false, - invalid: true, - status: 'success', - }) - expect(router.stores.cachedMatches.get()).toEqual(matches) -}) - -test('server preload stops following a redirect cycle', async () => { - const loader = vi.fn(() => { - throw redirect({ to: '/loop' }) - }) - const rootRoute = new BaseRootRoute({}) - const loopRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/loop', - loader, - }) - const router = createTestRouter({ - routeTree: rootRoute.addChildren([loopRoute]), - history: createMemoryHistory({ initialEntries: ['/'] }), - isServer: true, - }) - - await router.preloadRoute({ to: '/loop' }) - - expect(loader).toHaveBeenCalledTimes(21) -}) From 6683863a75a46297765b288957fccd147006ef0c Mon Sep 17 00:00:00 2001 From: Sheraff Date: Fri, 17 Jul 2026 08:08:28 +0200 Subject: [PATCH 45/59] console.error over promise.reject for lifecycle errors --- packages/router-core/src/load-client.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/router-core/src/load-client.ts b/packages/router-core/src/load-client.ts index addc3778ff..578db7f737 100644 --- a/packages/router-core/src/load-client.ts +++ b/packages/router-core/src/load-client.ts @@ -1076,7 +1076,7 @@ function commitMatches( try { getRoute(router, oldMatch as WorkMatch).options.onLeave?.(oldMatch) } catch (cause) { - Promise.reject(cause) + console.error(cause) } } if (match) { @@ -1085,7 +1085,7 @@ function commitMatches( oldMatch?.routeId === match.routeId ? 'onStay' : 'onEnter' ]?.(match) } catch (cause) { - Promise.reject(cause) + console.error(cause) } } } From 3d68db666fb001389382421505f24797701e659a Mon Sep 17 00:00:00 2001 From: Sheraff Date: Fri, 17 Jul 2026 10:13:47 +0200 Subject: [PATCH 46/59] INTERNALS update --- packages/router-core/INTERNALS.md | 446 ++++++++++++++++++++---------- 1 file changed, 301 insertions(+), 145 deletions(-) diff --git a/packages/router-core/INTERNALS.md b/packages/router-core/INTERNALS.md index 89cbca37b1..3275325b44 100644 --- a/packages/router-core/INTERNALS.md +++ b/packages/router-core/INTERNALS.md @@ -4,6 +4,11 @@ This document describes the match-loading architecture shared by router core and the React, Solid, and Vue adapters. It is intended for maintainers changing navigation, preloading, pending UI, SSR, hydration, route chunks, or route HMR. +Its scope ends at route-match publication and the immediate framework handoff. +The request handler, manifest reduction, Seroval stream protocol, backpressure, +and HTTP response cleanup in `src/ssr/` are separate concerns except where they +determine the server-to-client match handoff described here. + The implementation is deliberately a small ownership and publication protocol, not a second match-status state machine. TypeScript brands constrain phase-specific call sites, and closed outcome unions make control results @@ -19,11 +24,11 @@ The loader is built around these rules: 1. A foreground navigation builds a private lane. Only the current transaction may commit it, and presentation remains separate from accepted semantics. -2. Context is materialized serially from parent to child. Independent loader and - chunk work starts concurrently, while each parallel phase consumes results in - structural route order. -3. Shared work never grants publication authority. Losing work releases its - resources and cannot publish after it becomes stale. +2. Context is materialized serially from parent to child. Client loader and chunk + work start concurrently; server chunks start after concurrent loader + selection. Each parallel phase consumes results in structural route order. +3. Shared work never grants semantic publication authority. Losing work releases + its resources and cannot commit a stale lane. 4. Runtime state exists only for a real ownership, publication, or completion boundary. Phase naming and impossible local transitions belong in TypeScript. @@ -60,31 +65,39 @@ The location and match references intentionally advance at different moments: | Transaction installed | new | old | old lane | old lane or new pending prefix | `pending` | | Terminal commit, before acknowledgement | new | old | new lane | new lane | `pending` | | Transition acknowledgement settled | new | new | new lane | new lane | `idle` | +| Installed transaction rolls back | new | old | old lane | old lane | `idle` | `latestLocation` is the parsed history input captured before planning. It is not another published phase. In particular, `stores.location` advancing does not -mean that destination matches have committed or rendered. +mean that destination matches have committed or rendered. After an unexpected +post-install orchestration failure, `idle` likewise does not imply that +`stores.location` and `stores.resolvedLocation` are equal. ## File map -- `src/router.ts` matches locations, owns the router-level authorities, and - starts client or server loads. -- `src/load-client.ts` contains client lanes, foreground transactions, loader - flights, preloads, pending presentation, background reloads, and atomic - commits. -- `src/load-server.ts` contains the request-local server lane and SSR selection. -- `src/hydrate.ts` reconstructs the server-resolved prefix and hands unresolved - work to the ordinary client loader. -- `src/route-chunks.ts` owns lazy-route option installation and component - preloading. -- `src/stores.ts` projects matches into fine-grained framework stores. These - stores are reactive presentation/indexing machinery, not another loading - authority. -- `src/ssr/` serializes and streams server results. +Paths in this section are repository-relative. + +- `packages/router-core/src/router.ts` matches locations, owns router-level + authorities, and starts client or server loads. +- `packages/router-core/src/load-client.ts` contains client lanes, foreground + transactions, loader flights, preloads, pending presentation, background + reloads, and atomic commits. +- `packages/router-core/src/load-server.ts` contains the request-local server + lane and SSR selection. +- `packages/router-core/src/hydrate.ts` reconstructs the server-resolved prefix + and hands unresolved work to the ordinary client loader. +- `packages/router-core/src/route-chunks.ts` owns lazy-route option installation + and component preloading. +- `packages/router-core/src/stores.ts` owns the common active/cache pool topology + and reconciliation algorithm. Adapter `routerStores.ts` files provide the + reactive or non-reactive primitives and optional derived indexes. +- `packages/router-core/src/ssr/` serializes server results and coordinates the + stream and response lifecycle, which is mostly outside this document's scope. - `packages/{react,solid,vue}-router/src/Transitioner.*` connect history and renderer transitions to router core. -- `packages/{react,solid,vue}-router/src/Match.*` render pending, error, - not-found, selective-SSR, and client-only boundaries. +- Adapter `Matches.*` files own aggregate/root rendering and React's render + acknowledgement. Adapter `Match.*` and `ClientOnly.*` files own per-route + pending, error, not-found, selective-SSR, and client-only boundaries. - `packages/router-plugin/src/core/hmr/handle-route-update.ts` installs route updates and asks core for a development-only refresh. @@ -127,7 +140,7 @@ flight may be joined; a lease means a particular match owns that generation and its `AbortSignal`. **Projection** computes non-loader route output such as head metadata, scripts, -styles, and server headers after semantic outcomes have been reduced. +styles, and, on the server, headers after semantic outcomes have been reduced. **Authority** is an identity or state comparison whose equality permits a publication or resource mutation. A boolean that merely restates an authority is @@ -141,13 +154,13 @@ There are intentionally few independent authorities: | -------------------------- | -------------------------------------------------------------- | -------------------------------------- | | `router._tx` | Latest foreground transaction; equality authorizes publication | A loading boolean; use `stores.status` | | `router._committedMatches` | Accepted active semantic generation | The currently rendered lane | -| `stores.matches` | Current presentation | A semantic planning base | +| `stores.matches` | Presentation offered to the renderer | A semantic planning base | | `stores.cachedMatches` | Off-screen semantic cache | Active routes or in-progress work | | `stores.status` | Public loading-state projection | Foreground writer identity | | `stores.location` | Requested location | Proof that loading finished | | `stores.resolvedLocation` | Last location whose load/hydration settled | The requested location | | `router._pending` | One pending reveal/minimum-duration session | A second navigation transaction | -| `router._preflight` | Owner of synchronous foreground planning | A second writer | +| `router._preflight` | Latest synchronous foreground planning controller | A second writer | | `router._flights` | Joinable loader work by match id | Ownership of every flight | | `route._lazy` | Current lazy-route import owner or loaded marker | A component-module cache | @@ -163,7 +176,14 @@ stores.matches -> renderer presentation, including pending prefixes Pending presentation can remove hidden suffix entries from the reactive match pool. Planning from it would therefore forget valid committed matches and make presentation timing affect loader semantics. Once `_committedMatches` is -initialized, all semantic lookups use it and the terminal cache. +initialized, full lane planning and semantic reuse use it and the terminal +cache. Lightweight matching for `buildLocation` may still consult the active +presentation pool only to reuse already-parsed params; it is not loader planning. + +The active and cached pools remain separate, so the same match id may exist in +both. Reconciliation preserves existing per-id stores, suppresses exact +same-object writes, and updates each pool's id order only when that order changes. +These are framework-notification and indexing rules, not loading authority. ### Completion scopes @@ -175,11 +195,15 @@ Promises also have deliberately narrow ownership: | `tx.done` | One private foreground transaction | | Pending/transition ack | Settlement and render confirmation for one publication | | `commitLocationPromise` | History/navigation completion | -| `parentMatchPromise` | One loader's view of its semantic parent result | +| `parentMatchPromise` | One loader's view after its parent's loader settles | These scopes are not interchangeable. A new “latest load” promise usually duplicates transaction or history-completion authority and makes supersession -ambiguous. +ambiguous. On the client, a successful parent has already received its loader +data when `parentMatchPromise` resolves; parent error/not-found reduction may not +yet have run. The server instead resolves the promise to a snapshot with the raw +loader outcome applied, not the final reduced lane or selected not-found +boundary. ## Planning a lane @@ -189,10 +213,12 @@ The first pass: 1. validates and accumulates search, 2. computes `loaderDeps`, -3. interpolates and parses params, -4. derives the match id, -5. reuses a committed or cached semantic match when allowed, and -6. creates a fresh work match otherwise. +3. interpolates the raw path params, +4. derives the match id from route id, interpolated path, and serialized loader + dependencies, +5. looks up an allowed committed or cached semantic match, and +6. parses strict params only for a fresh match, then creates or clones the work + match. The second pass finalizes params and runs route `context` functions for fresh matches in parent-first order. @@ -217,7 +243,9 @@ itself as writer. until a replacement has finished matching successfully. Folding preflight into `_tx` would require publishing a partially constructed transaction and then rolling it back if matching throws. The small preflight controller represents a -real synchronous ownership boundary and avoids that invalid partial state. +real synchronous ownership boundary and avoids that invalid partial state. Its +presence alone does not prove planning is active: a failed current plan may leave +an aborted controller installed until the next plan replaces it. Client preloads do not replace `_preflight`. They use a local controller and a snapshot of `_tx`, because speculative work may be canceled by foreground @@ -269,13 +297,25 @@ success(data) | error(error) | notFound(error) | redirected(redirect) | canceled ``` The server counterpart uses `skipped` for an `ssr: false` loader instead of -`canceled`. +`canceled`. It also uses `skipped` when a server loader settles after that +match's controller has been aborted; the server has no lane-level cancellation +outcome. The compact numeric representation is internal. The union matters because cancellation and redirects are control outcomes, not match states, while errors and not-found results become terminal match semantics at the reducer's selected cutoff. Resolved and thrown redirects/not-found values normalize to the same outcomes. `onError` may transform an ordinary error by throwing a control value. +Lane waiting and `beforeLoad` recognize cancellation only from the exact aborted +lane signal; an arbitrary `AbortError` or user-thrown signal is an ordinary +error. A loader flight instead normalizes either settlement branch to canceled +whenever its own controller is already aborted, regardless of the settled value. + +A native `Promise` used as the thrown value or rejection reason of `beforeLoad` +is a deliberate exception: contextualization rethrows that value to the lane +owner instead of reducing it into route error state. An ordinary rejected +`beforeLoad` promise is still a route error, and a promise thrown by a loader is +normalized like any other loader error. The client phase driver, `executeClientLane`, performs: @@ -287,7 +327,10 @@ adopt flight leases -> project assets ``` -No phase publishes router state. +No phase publishes the terminal semantic lane. Foreground task readiness may +offer pending presentation through its `onReady` callback. Background lanes +reuse the phases with mixed ownership; their current projection caveat is +documented below. ## Contextualization and concurrent work @@ -316,6 +359,11 @@ Execution then makes two independent decisions: freshness, navigation cause/forced reload, and blocking versus background reload mode. Reusing a match therefore does not imply reusing its loader data. +Age-based staleness alone does not reload every successful stay match. Unless +the match is invalid or `shouldReload` says otherwise, the stale-time branch also +requires a forced stale reload, an entering match, or another active id for the +same route. + An accepted `beforeLoad` donor may have run with `preload: true`. Navigation intentionally reuses that context without rerunning the hook merely to call it with `preload: false`. Pending or failed `beforeLoad` work is never donated. A @@ -338,15 +386,17 @@ therefore run concurrently. Each client task exposes three related milestones: Separating `outcome` from `ready` is essential. A redirect or error can win without waiting for irrelevant successful descendant chunks, while a successful -lane cannot commit before the chunks it needs to render are ready. +lane cannot commit before the chunks it needs to render are ready. The client +`match` promise resolves after the loader outcome settles; successful data has +already been applied, but error/not-found state is selected later by reduction. `resolvedPrefix` skips repeated contextualization and loader work while preserving the task chain needed for parent promises and chunk readiness. A client preload derives it from the contiguous active successful same-id prefix. -The initial hydration handoff instead adopts its entire committed prefix or none -of it, under the href/key/id/currentness checks described below. Joinable work -already attached to an adopted prefix is still accounted for, and projection may -restart at its retained terminal match. +The subsequent unresolved-suffix transaction after hydration instead adopts the +entire committed prefix or none of it, under the href/key/id/currentness checks +described below. Joinable work already attached to an adopted prefix is still +accounted for, and projection may restart at its retained terminal match. ## Phase-local reduction and failure boundaries @@ -368,12 +418,16 @@ same small reduction policy: first relevant chunk failure replaces the selected failure; if that failure is a redirect, it becomes control flow. 5. Core applies the result once, trims once, and attempts the selected terminal - component once. Terminal-component preload is best-effort: rejection is - swallowed, does not call route `onError`, and does not restart selection. + component once. In ordinary client/server lane reduction, terminal-component + preload is best-effort: rejection is swallowed, does not call route `onError`, + and does not restart selection. Hydration readiness is stricter, as described + below. 6. Projection runs after semantic reduction and cannot replace its result. -An ordinary serial failure still permits loaders above its effective boundary to -run, so the terminal render keeps the ancestor data it is allowed to expose. A +An ordinary serial error still permits loaders strictly above the throwing route +to run. A serial not-found permits work through its effective not-found boundary, +but never past the throwing route: an ancestor boundary's loader runs, while the +throwing route's loader does not run when that route is itself the boundary. A serial redirect/cancel starts no loader work. “First” inside a concurrent phase means structural route order, not promise @@ -390,9 +444,9 @@ therefore differ. A global root not-found remains a successful root match marked `globalNotFound`, because the root shell still renders while presenting the global not-found result. -The server uses redirect control flow and `skipped` for `ssr: false`; the client -also has cancellation control flow. Those representation differences do not -change the failure-selection policy. +The server uses redirect control flow and `skipped` for omitted or aborted work; +the client also has cancellation control flow. Those representation differences +do not change the failure-selection policy. A `globalNotFound` assigned while matching is planned presentation metadata, not a thrown lane outcome. The client retains the planned lane and the framework @@ -401,28 +455,35 @@ request-local lane at that boundary before rendering the 404. Do not feed this case into the thrown-outcome reducer merely to make the two storage shapes look identical. -Redirect and cancellation outcomes never become committed match states. Internal -redirects are followed by a replacement navigation. Redirect depth is inherited -one hop at a time across the whole redirect-produced replacement chain and is -capped at 20. The current transaction's `redirecting` marker authorizes only its -redirect successor to inherit the count; an unrelated superseding navigation -must not inherit it. The count clears when a semantic lane completes without -redirecting. +Redirect and cancellation outcomes never become committed match states. +Installed foreground and background client-lane redirects are followed by +replacement navigation. Their depth is inherited one hop at a time, and the 21st +non-document redirect is reduced to `Redirect cycle detected`. The current +transaction's `redirecting` boolean is the inheritance condition; it is not an +identity binding to a particular destination. Redirects thrown during +synchronous foreground planning are followed before transaction installation and +do not participate in that counter. Client preloads recursively preload a +redirect target under a separate limit and stop quietly beyond it; a preload +planning redirect remains the caller's planning error. The server returns a +redirect result to its request layer. -Projection runs only after reduction, so head/scripts/headers see the final lane -and loader data. Projection hooks for one route start together. Their results are -applied only if that group resolves; a rejection is logged and swallowed without -replacing the semantic result. Discarding a failed group means applying no new -projection output; reused matches may retain output from their previous -generation. +Ordinary client/server projection runs only after reduction, so hooks see the +final lane and loader data. Client projection starts `head` and `scripts` +together; server projection also starts `headers`. Results for one route are +applied only if the whole group resolves. A rejection is logged and swallowed +without replacing the semantic result. Reused matches may therefore retain +projection output from their previous generation. Hydration uses a different, +serial projection policy described below. ## Foreground transaction lifecycle -`RouterCore.load` refreshes `latestLocation` once, uses that same parsed object -for the history action and before-navigation events, and delegates to -`loadClientRoute`. The client loader must not parse a second location object; -location object identity is also how scroll restoration associates a history -action with the later lifecycle event. +`RouterCore.load` refreshes `latestLocation` and captures that object for +`onBeforeNavigate` and `onBeforeLoad`. It then delegates to `loadClientRoute`, +which reads the current `latestLocation` after those synchronous listeners have +run. A reentrant listener can therefore replace the location that the outer call +would otherwise plan; preflight and transaction currentness decide which load +wins. Scroll restoration consumes lifecycle location values and `_scroll` state, +not parsed-location object identity. `loadClientRoute` first plans under `_preflight`. Only after planning succeeds and both the preflight owner and previous writer are still current does it install @@ -486,7 +547,9 @@ the pre-mount lifecycle: a route callback suppresses stale `onLoad`, and an `onLoad` listener that supersedes the writer suppresses stale `onBeforeRouteMount` and later completion publication. Listener exceptions are isolated and do not stop later listeners or leave acknowledgement cleanup -unfinished. +unfinished. There is currently no currentness recheck between `onResolved` and +`onRendered`; a synchronous navigation started by an `onResolved` listener can +therefore coexist with the acknowledged transaction's `onRendered` event. ## Pending presentation and renderer acknowledgement @@ -564,8 +627,8 @@ Two facts must remain separate: `closeFlight` removes joinability but does not release the owner's lease. `releaseFlight` removes one lease; only the last release aborts the loader and -removes the registry entry. `transferMatchResources` is the bulk ownership -operations, based on match object identity. +removes the registry entry. `transferMatchResources` performs bulk ownership +transfers based on match object identity. The lease intentionally may outlive promise settlement. Once successful data is accepted, closing registry membership prevents new joins while the accepted @@ -583,6 +646,10 @@ the joining lane closes/releases that flight and runs its own loader. This lets work be shared without allowing a preload's control outcome or failure context to govern a navigation. +When a lane adopts leases, the registry's current joinable flight takes +precedence over a copied, closed `_flight`. An accepted old generation therefore +cannot hide newer joinable work for the same match id. + Transaction cancellation races the shared promise through `waitFor`. Losing the race releases that lane's lease; it does not abort work still leased elsewhere. The flight also checks its own controller after both loader resolution and @@ -624,12 +691,20 @@ adding a version counter. Development refreshes also reject context produced by `beforeLoad` function that is no longer installed, together with the descendant suffix that depended on it. +The compare-and-swap is per match id, not a global cache epoch. `clearCache()` +releases entries present at that moment, but a still-running preload planned +against an absent entry may later publish whenever the entry is also absent at +publication. The slot need not have remained continuously empty between those +two snapshots. + Foreground commits retain successful exiting matches only when they have either fresh loader-backed data within the applicable normal/preload GC window or reusable preloaded `beforeLoad` context within `preloadGcTime`. Active ids are removed from the cache; failed, not-found, expired, and loaderless entries without reusable context provenance are discarded. Clearing the cache releases -leases before publishing the retained cache entries. +leases before publishing the retained cache entries. GC is opportunistic: +foreground commits apply these age checks; there is no eviction timer, and +preload publication does not sweep unrelated entries by age. Server `preloadRoute` is a no-op. Server work is owned exclusively by normal request loading. @@ -669,6 +744,14 @@ the guarded publication succeeds. Trimming a background lane likewise leaves shared suffix resources alone. The final transfer or discard of the background batch is the single resource authority. +The two guards above protect final lane publication, not every pre-commit effect. +`projectLane` currently runs user `head`/`scripts` hooks before those guards over +the mixed lane, and it can write projection fields onto an untouched shared base +match even if the final compare-and-swap loses. This is a current sharp edge, not +an authority to copy. Strengthening stale-publication isolation requires +detached projection output or resource-aware, flight-free clones; an ordinary +clone must not accidentally duplicate a flight lease. + Background publication replaces an already-resolved presentation directly. It does not enter the pending/renderer-acknowledgement protocol, change `stores.status` or `resolvedLocation`, or emit foreground navigation lifecycle @@ -695,15 +778,19 @@ background-specific cancellation flag. ## Route chunks -Normal successful readiness loads the route component and pending component. -Error and not-found component preloads are requested only for the semantic -terminal match selected by reduction. A framework may still bubble an ordinary -error to a visibly different ancestor catch boundary. Terminal-component -preloading is best-effort; failure is swallowed because semantic selection has -already finished. Client chunk work begins alongside loader work, but a normal -chunk failure is semantically considered only when its loader outcome succeeds. +On the client, normal component and pending-component preload starts +speculatively for every created task alongside loader work. Its failure is +semantically considered only when that loader succeeds and the task lies before +the selected cutoff. On the server, normal chunk work starts after loader +selection for the retained `ssr: true` prefix. -`route._lazy` has three compact states: +Error and not-found component preloads are requested only for the semantic +terminal match selected by ordinary lane reduction. A framework may still bubble +an ordinary error to a visibly different ancestor catch boundary. These terminal +preloads are best-effort because semantic selection has already finished; +hydration chunk readiness, including terminal boundary chunks, is required. + +The current `route._lazy` encoding has three compact states: ```text undefined = no current owner @@ -731,29 +818,40 @@ uses a separate typed lane with the same high-level ordering: match -> resolve SSR + contextualize serially -> run loaders concurrently -> select serial/loader result -> load normal chunks before its cutoff -> apply and trim once -> preload terminal component once - -> project -> render or redirect + -> project -> publish a render descriptor or redirect ``` SSR policy is resolved parent-first before each route's `beforeLoad`: -- `ssr: true` runs `beforeLoad`, loads data and render chunks, and projects - assets. +- `ssr: true` runs `beforeLoad`, loads data and render chunks, and runs route + projection hooks. - `ssr: 'data-only'` loads data but does not render that route's component or - project its assets on the server. Its `beforeLoad` still runs. -- `ssr: false` skips server `beforeLoad`, loader, chunks, and assets for that - route. Its synchronous route context was already created during matching. + run its route projection hooks on the server. Its `beforeLoad` still runs. +- `ssr: false` skips server `beforeLoad`, loader, route chunks, and route + projection hooks. Its synchronous route context and params/search validation + still run, so matching validation may still produce a server error or 404. - A `false` parent forces descendants to `false`; a `data-only` parent caps any `true` descendant at `data-only`, whether explicit, computed, or inherited. -- Shell mode renders only the root route. +- Shell mode forces the root to `true` and every descendant to `false`. The + server presentation lane may retain those client-only descendants and render + their first applicable pending fallback, while dehydration retains only the + root semantic match. + +These bullets concern route-hook output. Bundler-manifest CSS, preloads, or +scripts may still be emitted for matched client-only routes so that the browser +can load them. If an `ssr` callback throws, the server normalizes it through that route's `onError`, records it as the serial failure for the route, and stops serial -descent just like a `beforeLoad` failure. +descent just like a `beforeLoad` failure. The callback receives wrapped +search/params results and parent-first match summaries; `undefined` falls back to +`defaultSsr` before the parent restriction is applied. Shell mode bypasses route +SSR callbacks. Hydration adopts the semantic work produced by `true` and `data-only`; `data-only` still requires client rendering, while `false` begins the unresolved -client suffix. Prefix adoption is governed by exact location and match identity, -not stale-time rules. The handoff rules are detailed below. +client suffix. Initial reconstruction and the later unresolved-suffix handoff use +different identity checks, detailed below. Loaders start concurrently and retain parent match promises. The request-local lane consumes their outcomes in route order, keeping redirect as control flow and @@ -769,25 +867,37 @@ route's projection group is discarded; projection failure is non-fatal and never overwrites loader semantics. The final result is a closed union: either a render result with status and -matches, or a redirect. `loadServerRoute` owns the complete server workflow and -is the only publisher of that result to router stores. +matches, or a redirect. `loadServerRoute` owns matching, loading, reduction, +projection, and publication of that route result to router stores. The request +handler and framework adapter separately own dehydration, HTTP response +construction, rendering/streaming, redirect responses, and request cleanup. + +Before matching, server loading canonicalizes `publicHref`; a mismatch becomes a +redirect before lifecycle events are emitted. On the canonical path it emits +`onBeforeNavigate` and `onBeforeLoad`, but not the client mount/render lifecycle +events. ## Hydration handoff Hydration reconstructs what the server actually resolved; it does not rerun a -parallel hydration loader. +parallel hydration loader. Before matching, it installs serialization adapters +and flushes buffered bootstrap scripts when adapters are configured, marks the +bootstrap initialized, installs the dehydrated manifest/CSP nonce, and awaits the +application's custom hydration hook. For the current location, `hydrate`: -1. matches a fresh candidate lane, -2. walks the serialized server matches while ids agree, +1. publishes the current requested location and matches a fresh candidate lane, +2. walks candidates while serialized match ids agree, 3. copies serialized loader/before-load/error/SSR data into a local resolved prefix, -4. loads the chunks needed to hydrate that prefix, -5. rebuilds complete route contexts before running any head/script hook, -6. rebuilds client head/script projection and derives the presentation frontier, - and -7. after all asynchronous work and currentness checks, installs +4. makes the server's effective SSR decisions visible to immediate client + rendering/planning, +5. loads the chunks needed to hydrate that prefix, +6. rebuilds complete route contexts before running any head/script hook, +7. rebuilds client head then script projection and derives the presentation + frontier, and +8. after all asynchronous work and currentness checks, installs `_committedMatches` and publishes the presentation frontier. The presentation frontier is the candidate prefix initially shown to the @@ -798,6 +908,12 @@ for `data-only`. For the initial handoff, committed `beforeLoad` and loader work is authoritative and does not rerun; hydration rebuilds route context, chunks, and client head/script output as required. +The initial serialized payload carries match ids but no server href/history key. +Bootstrap reconstruction therefore matches the browser's current location and +adopts only the contiguous serialized same-id prefix; it tolerates an unused +serialized suffix. Exact href/key comparison applies to the subsequent ordinary +client transaction, not this initial reconstruction. + If the whole location was resolved, hydration sets `resolvedLocation`. Otherwise the framework Transitioner observes the unresolved location and starts an ordinary client transaction. That transaction adopts the whole committed prefix @@ -805,23 +921,35 @@ or none of it. Adoption requires the same canonical href and history key, exact match ids at every committed index, and no invalidated match or development refresh. A terminal adopted prefix also caps the candidate lane, so descendants omitted below a server error/not-found boundary cannot execute on the client. -These checks derive `resolvedPrefix` from existing authorities; there is no -hydration-specific scheduler, flag, or completion authority. +These checks derive `resolvedPrefix` from existing authorities; core adds no +second authority for deciding whether that transaction may adopt the committed +hydration prefix. Bootstrap and framework layers do have their own initialization +and hydration-completion state. Candidate matching may already have invoked route `context`. After lazy options are installed, hydration deliberately rebuilds context parent-first for the accepted prefix and awaits each result before projection. Context functions must therefore tolerate this hydration re-entry. Hydration also copies each serialized SSR decision onto the route options so later client planning and framework -rendering observe the server's resolved mode. +rendering observe the server's resolved mode; that mutation is the current +mechanism, not a required representation. -Unlike ordinary decorative projection, a non-not-found head/script failure -during hydration rejects hydration. A not-found is logged and attached to its -match. Preserve this call-site-specific policy. +Hydration chunk and context readiness is required. A chunk failure is suppressed +when hydration became stale and otherwise rejects; a rejected context rebuild +propagates directly, with currentness checked only after successful context work. +Projection is deliberately serial within each route: `head` is awaited before +`scripts`, and hydration does not rerun `headers`. A current non-not-found +projection failure is logged, attached, and rethrown; a current not-found is +logged and attached without rejecting, while stale projection failures are +suppressed. Preserve these call-site-specific policies. -Hydration snapshots `_tx` and checks it after asynchronous user/chunk work. A -navigation that starts during hydration wins; stale hydration does not overwrite -it. +Hydration snapshots `_tx` and checks it after successful custom hydration, +chunk, context, and projection steps. Candidate matching and rejected custom or +context work can still throw after ownership changed, but stale hydration cannot +reach the final committed-lane/presentation publication. Hydration does set +`stores.location` and copy SSR decisions before its final guard, so this +currentness guarantee is specifically about semantic match publication, not +complete side-effect or failure isolation. Framework `Match` implementations combine the SSR mode with match presentation. `ssr: false` and `data-only` content is behind `ClientOnly`, with the pending @@ -870,19 +998,21 @@ not be mistaken for an already-rendered mount. React additionally guards the router/history pair across Strict Mode effect replay and refreshes `latestLocation` from history before canonicalization. -Swapping routers or histories still installs the correct subscription and initial -load. Listener errors must not prevent cleanup or leave transition -acknowledgements unresolved. +In React, swapping routers or histories installs the correct subscription and +initial load; Solid and Vue capture their router during setup and currently cover +unmount/remount catch-up instead. Listener errors must not prevent cleanup or +leave transition acknowledgements unresolved. ## Invariants to preserve When modifying this system, keep these invariants explicit: -1. `stores.matches` never becomes a semantic planning base after +1. `stores.matches` never becomes a full-lane semantic planning base after `_committedMatches` exists. -2. Only the current `_tx` may redirect foreground client navigation, commit its - lane, or publish its completion; only the current `PendingSession` owner may - finish that session. +2. Only the current `_tx` may redirect from an installed foreground lane, commit + that lane, or publish its completion; planning redirects require the current + preflight and unchanged previous writer. Only the current `PendingSession` + owner may finish that session. 3. `_preflight` can invalidate synchronous foreground planning but cannot publish; preload planning uses its local controller and foreground-owner snapshot. @@ -902,11 +1032,12 @@ When modifying this system, keep these invariants explicit: authority. 12. Preloaded `beforeLoad` provenance is independent from loader-data provenance, and its reuse is prefix-closed. -13. Background publication requires both current-writer identity and exact-base - identity. -14. Hydration builds its resolved prefix privately, publishes it only after - currentness checks, and delegates the remainder to the normal client - transaction. +13. Final background lane publication requires both current-writer identity and + exact-base identity. Untouched matches are currently shared during + pre-publication projection, as noted above. +14. Hydration builds its committed resolved prefix privately, publishes that + prefix only after currentness checks, and delegates the remainder to the + normal client transaction. 15. Planning cancellation is not a lane failure; a current preload planning error remains the caller's error. 16. Invalidation replaces semantic generation identity and reloads through the @@ -930,36 +1061,61 @@ and the absence of broader/default boundary output. A generic `/Not Found/` or Useful category-level suites include: -- `packages/router-core/tests/client-lane-adversarial.test.ts` and - `preflight-reentrant-context.test.ts` for ordering and reentrancy; plus - `fatal-load-rejection.test.ts`, `blocked-navigation-current-load.test.ts`, and - `superseded-load-await.test.ts` for planning, rollback, and waiter ownership, -- `preload-adoption.test.ts`, `preload-public-cache-behavior.test.ts`, and - `preload-background-parent-coherence.test.ts` for shared work and cache - publication, and `preload-beforeload-reuse.test.ts` for serial context - donation, -- `background-assets-stale.test.ts`, `background-trim-abort.test.ts`, and - `invalidate-pre-rematch-failure.test.ts` for identity-CAS publication, -- `preload-public-signal-lifetime.test.ts` and `stay-match-abort.test.ts` for - flight lease and accepted-generation signal lifetime, -- `hydration-currentness.test.ts`, `hydration-boundary-chunks.test.ts`, and the - framework hydration suites for the server/client frontier, -- `server-concurrent-error-notfound.test.ts`, - `server-chunk-failure-lifecycle.test.ts`, and the selective-SSR E2E suites for - server reduction, -- framework `store-updates-during-navigation.test.*`, pending-min, transitioner - acknowledgement, and transactional-loading suites for rendered behavior. +Unless a path is shown, core filenames below are relative to +`packages/router-core/tests/`: -Framework coverage should include canonicalization, exact href/key reuse, -same-href new-key navigation, unmounted catch-up, remount/Strict Mode, -router/history swaps, transition acknowledgement, and listener failures. The -relevant suites follow the `transitioner-*`, `on-rendered-*`, -`preloaded-mount-*`, and listener-error naming patterns. +- `client-lane-adversarial.test.ts` and `preflight-reentrant-context.test.ts` for + ordering and reentrancy; `fatal-load-rejection.test.ts`, + `blocked-navigation-current-load.test.ts`, and `superseded-load-await.test.ts` + for planning, rollback, and waiter ownership, +- `preload-adoption.test.ts`, `preload-navigation-adoption.test.ts`, + `preload-public-cache-behavior.test.ts`, and + `preload-background-parent-coherence.test.ts` for shared work and cache + publication; `preload-beforeload-reuse.test.ts` for serial context donation, +- `background-assets-stale.test.ts` and `background-trim-abort.test.ts` for + background projection, trimming, ownership, and writer supersession; + `invalidate-pre-rematch-failure.test.ts` for generation replacement across a + failed plan, +- `preload-public-signal-lifetime.test.ts`, `stay-match-abort.test.ts`, and + `issue-7759-in-flight-preload-eviction.test.ts` for leases, accepted-generation + signal lifetime, and cache clearing, +- `granular-stores.test.ts` for active/cached pool identity and notification; + `parent-match-promise.test.ts` and `loader-thrown-promise.test.ts` for promise + boundaries, +- `chunk-failure-lifecycle.test.ts`, `boundary-component-chunk.test.ts`, and + `load-route-chunk.test.ts` for normal, terminal, and lazy-option chunk behavior, +- `hydration-currentness.test.ts`, `hydration-boundary-chunks.test.ts`, + `hydration-asset-context-order.test.ts`, + `hydration-terminal-error-child-head.test.ts`, and + `issue-5427-hydration-root-global-not-found.test.ts` for bootstrap + reconstruction and the server/client frontier, +- `server-concurrent-error-notfound.test.ts`, + `server-chunk-failure-lifecycle.test.ts`, `server-ssr-option-error.test.ts`, + `server-ssr-false-assets.test.ts`, and the selective-SSR E2E suites for server + reduction and policy, +- `transformStreamWithRouter.test.ts`, `ssr-server-manifest.test.ts`, and + `ssr-server-cleanup.test.ts` when changing the adjacent streaming/serialization + system outside this document's primary scope, +- framework `store-updates-during-navigation.test.*`, pending-min, transitioner + acknowledgement, and transactional-loading tests for rendered behavior, and +- `packages/router-plugin/tests/handle-route-update.test.ts`, + `packages/router-plugin/tests/add-hmr.test.ts`, and the React Start HMR E2E + suite for development refresh. + +Framework coverage is distributed unevenly and equivalent tests do not always +share filenames. Shared bootstrap changes should cover canonicalization, exact +href/key reuse, same-href new-key navigation, unmounted catch-up, remount, +transition acknowledgement, and listener failures in every affected adapter. +React additionally needs Strict Mode and live router/history-swap coverage. Do +not infer cross-framework coverage from the presence of one `transitioner-*`, +`on-rendered-*`, or pending-min file. Run category suites while developing, then the affected core/framework unit and -type suites. Changes to client runtime paths must also run the production bundle -benchmarks. Development-only helpers, diagnostics, and HMR paths must be verified -as absent from production output. +type suites. Changes to client runtime paths must also run +`CI=1 NX_DAEMON=false pnpm nx run @benchmarks/bundle-size:build --outputStyle=stream --skipRemoteCache --skipNxCache`. +For development-only helpers, diagnostics, and HMR paths, inspect the emitted +production output to verify that they are absent; package `test:build` is not a +bundle-size or dead-code-elimination check. If a regression appears to require another flag, counter, copied deadline, or completion authority, stop and identify which existing authority is ambiguous. From 423f905df8799ddd206a2532b696a96fde28e513 Mon Sep 17 00:00:00 2001 From: Flo Date: Mon, 20 Jul 2026 18:52:47 +0200 Subject: [PATCH 47/59] fix(router-core): complete lane match loader rewrite (#7858) * fix(router-core): complete lane match loader rewrite * fix(router-core): harden match loading lifecycle * fix(router-core): preserve hydrated context handoff * bench(memory): accept expected abort errors * perf(ssr): reduce request cancellation overhead (#7862) --- .../scenarios/aborted-requests/shared.ts | 4 +- docs/router/api/router/RouteMatchType.md | 15 +- docs/router/api/router/RouteOptionsType.md | 16 +- docs/router/api/router/RouterOptionsType.md | 4 +- docs/router/api/router/RouterStateType.md | 29 +- docs/router/api/router/RouterType.md | 47 +- docs/router/api/router/useChildMatchesHook.md | 5 +- docs/router/api/router/useMatchesHook.md | 2 +- .../router/api/router/useParentMatchesHook.md | 5 +- docs/router/guide/data-loading.md | 15 +- docs/router/guide/path-params.md | 3 + docs/router/guide/preloading.md | 37 +- docs/router/how-to/debug-router-issues.md | 11 +- .../selective-ssr/tests/app.spec.ts | 15 +- packages/react-router/src/CatchBoundary.tsx | 10 +- packages/react-router/src/Match.tsx | 332 +-- packages/react-router/src/Matches.tsx | 55 +- packages/react-router/src/RouterProvider.tsx | 4 +- packages/react-router/src/Scripts.tsx | 72 +- packages/react-router/src/Transitioner.tsx | 93 +- .../react-router/src/headContentUtils.tsx | 229 +- .../react-router/src/lazyRouteComponent.tsx | 48 +- .../react-router/src/ssr/RouterClient.tsx | 11 +- .../src/ssr/renderRouterToStream.tsx | 7 +- packages/react-router/src/useMatch.tsx | 24 +- packages/react-router/src/utils.ts | 5 +- packages/react-router/tests/Matches.test.tsx | 20 +- packages/react-router/tests/Scripts.test.tsx | 137 +- ...ancestor-loader-child-pending-min.test.tsx | 62 + ...mponent-preload-retry-pending-min.test.tsx | 26 + .../tests/component-preload-retry.test.tsx | 32 + .../tests/errorComponent.test.tsx | 290 +++ ...hydration-capped-boundary-pending.test.tsx | 103 +- .../tests/hydration-terminal-lane.test.tsx | 3 +- .../issue-4467-lazy-route-pending.test.tsx | 66 + ...sue-4476-react-query-cancellation.test.tsx | 2 +- .../react-router/tests/not-found.test.tsx | 182 +- .../tests/preloaded-mount-resolution.test.tsx | 55 +- ...public-presentation-lane-contract.test.tsx | 244 ++ .../tests/renderRouterToStream.test.tsx | 34 +- .../tests/root-pending-min.test.tsx | 70 +- .../react-router/tests/routeContext.test.tsx | 32 +- .../router-client-stream-cleanup.test.tsx | 55 + packages/react-router/tests/router.test.tsx | 3 + .../store-updates-during-navigation.test.tsx | 4 +- .../tests/transactional-loading.test.tsx | 91 + .../tests/transitioner-render-ack.test.tsx | 93 +- packages/react-router/tests/useMatch.test.tsx | 153 +- .../react-start-client/src/hydrateStart.ts | 7 +- .../src/tests/hydrateStart.test.ts | 33 + packages/router-core/INTERNALS.md | 2179 +++++++++-------- packages/router-core/src/Matches.ts | 7 +- packages/router-core/src/await-signal.ts | 27 + packages/router-core/src/hydrate.ts | 448 ++-- packages/router-core/src/index.ts | 4 +- packages/router-core/src/load-client.ts | 2002 ++++++++------- packages/router-core/src/load-server.ts | 467 ++-- packages/router-core/src/rendered-matches.ts | 12 + packages/router-core/src/route-chunks.ts | 32 +- packages/router-core/src/router.ts | 622 ++--- .../src/ssr/createRequestHandler.ts | 129 +- .../router-core/src/ssr/handlerCallback.ts | 71 +- packages/router-core/src/ssr/server.ts | 5 +- packages/router-core/src/ssr/ssr-match-id.ts | 13 +- packages/router-core/src/ssr/ssr-server.ts | 13 +- .../src/ssr/transformStreamWithRouter.ts | 38 +- packages/router-core/src/ssr/types.ts | 1 - packages/router-core/src/stores.ts | 206 +- .../tests/background-trim-abort.test.ts | 48 +- .../blocked-navigation-current-load.test.ts | 6 +- .../tests/boundary-component-chunk.test.ts | 99 +- .../tests/client-lane-adversarial.test.ts | 135 +- .../router-core/tests/granular-stores.test.ts | 236 +- packages/router-core/tests/hydrate.test.ts | 318 ++- .../tests/hydration-boundary-chunks.test.ts | 7 +- .../tests/hydration-currentness.test.ts | 536 ++-- ...ydration-terminal-error-child-head.test.ts | 9 +- .../invalidate-pre-rematch-failure.test.ts | 14 +- .../issue-3179-preload-cached-cause.test.ts | 8 +- ...4078-loader-notfound-root-boundary.test.ts | 8 +- ...-4444-param-parse-error-lazy-child.test.ts | 9 +- ...4572-preload-root-beforeload-flags.test.ts | 40 +- ...ue-5106-hydrated-notfound-boundary.test.ts | 19 +- ...27-hydration-root-global-not-found.test.ts | 97 +- .../issue-6351-fuzzy-notfound-layout.test.ts | 14 +- .../tests/load-client-wait-for.test.ts | 209 ++ packages/router-core/tests/load.test.ts | 80 +- .../loader-architecture-regressions.test.ts | 900 +++++++ .../tests/loader-self-abort.test.ts | 73 + .../tests/loader-thrown-promise.test.ts | 32 +- .../tests/parent-match-promise.test.ts | 43 +- .../tests/preflight-reentrant-context.test.ts | 50 - .../tests/preload-adoption.test.ts | 121 +- ...reload-background-parent-coherence.test.ts | 27 +- .../tests/preload-beforeload-reuse.test.ts | 183 +- .../tests/preload-navigation-adoption.test.ts | 115 +- .../preload-public-cache-behavior.test.ts | 204 ++ .../public-client-loading-contract.test.ts | 538 ++++ .../tests/public-hydration-contract.test.ts | 1485 +++++++++++ .../public-preload-lane-contract.test.ts | 1151 +++++++++ .../server-beforeload-preload-flag.test.ts | 65 +- .../server-chunk-failure-lifecycle.test.ts | 2 +- .../server-concurrent-error-notfound.test.ts | 116 +- .../tests/server-loader-abort-error.test.ts | 238 +- .../tests/server-planning-redirect.test.ts | 39 +- .../tests/server-route-lifecycle.test.ts | 76 + .../tests/server-serial-ssr-notfound.test.ts | 13 +- .../tests/server-ssr-false-assets.test.ts | 42 + .../tests/server-ssr-option-error.test.ts | 158 +- .../router-core/tests/ssr-match-id.bench.ts | 53 + .../router-core/tests/ssr-match-id.test.ts | 18 +- .../tests/ssr-server-cleanup.test.ts | 200 +- .../tests/ssr-server-manifest.test.ts | 52 + .../tests/transformStreamWithRouter.test.ts | 32 + .../src/BaseTanStackRouterDevtoolsPanel.tsx | 38 +- .../router-devtools-core/src/useStyles.tsx | 3 +- packages/router-devtools-core/src/utils.tsx | 1 - .../src/core/hmr/handle-route-update.ts | 7 +- packages/router-plugin/tests/add-hmr.test.ts | 6 +- .../snapshots/react/arrow-function@true.tsx | 4 +- .../react/arrow-function@webpack-hot.tsx | 4 +- .../createRootRoute-inline-component@true.tsx | 4 +- .../snapshots/react/createRootRoute@true.tsx | 4 +- ...ateRootRouteWithContext-type-args@true.tsx | 4 +- .../explicit-undefined-component@true.tsx | 4 +- .../react/function-declaration@true.tsx | 4 +- .../snapshots/react/multi-component@true.tsx | 4 +- .../react/string-literal-keys@true.tsx | 4 +- .../snapshots/solid/arrow-function@true.tsx | 4 +- .../tests/handle-route-update.test.ts | 30 +- packages/solid-router/src/CatchBoundary.tsx | 2 +- packages/solid-router/src/Match.tsx | 471 ++-- packages/solid-router/src/Matches.tsx | 25 +- packages/solid-router/src/Scripts.tsx | 105 +- packages/solid-router/src/Transitioner.tsx | 46 +- .../solid-router/src/headContentUtils.tsx | 205 +- packages/solid-router/src/matchContext.tsx | 2 - packages/solid-router/src/routerStores.ts | 45 +- .../solid-router/src/ssr/RouterClient.tsx | 13 +- .../src/ssr/renderRouterToStream.tsx | 2 +- packages/solid-router/src/useMatch.tsx | 2 +- packages/solid-router/tests/Scripts.test.tsx | 54 + .../tests/errorComponent.test.tsx | 47 + packages/solid-router/tests/loaders.test.tsx | 9 +- .../tests/renderRouterToStream.test.tsx | 3 +- .../solid-router/tests/routeContext.test.tsx | 32 +- .../router-client-stream-cleanup.test.tsx | 39 + .../store-updates-during-navigation.test.tsx | 14 +- .../tests/transitioner-remount.test.tsx | 109 - .../tests/transitioner-render-ack.test.tsx | 5 +- packages/solid-router/tests/useMatch.test.tsx | 153 +- .../solid-start-client/src/hydrateStart.ts | 7 +- .../src/tests/hydrateStart.test.ts | 33 + .../src/client/hydrateStart.ts | 2 +- .../src/vite/dev-server-plugin/plugin.ts | 6 +- .../src/createStartHandler.ts | 211 +- .../tests/createStartHandler.test.ts | 483 +++- packages/vue-router/src/CatchBoundary.tsx | 6 +- packages/vue-router/src/Match.tsx | 278 +-- packages/vue-router/src/Matches.tsx | 77 +- packages/vue-router/src/Scripts.tsx | 72 +- packages/vue-router/src/Transitioner.tsx | 7 +- packages/vue-router/src/headContentUtils.tsx | 239 +- packages/vue-router/src/matchContext.tsx | 8 +- packages/vue-router/src/routerStores.ts | 27 +- packages/vue-router/src/ssr/RouterClient.tsx | 17 +- .../src/ssr/renderRouterToStream.tsx | 2 +- packages/vue-router/src/useMatch.tsx | 11 +- .../tests/disableGlobalCatchBoundary.test.tsx | 26 + .../vue-router/tests/errorComponent.test.tsx | 47 + ...hydration-capped-boundary-pending.test.tsx | 6 +- packages/vue-router/tests/loaders.test.tsx | 12 +- packages/vue-router/tests/redirect.test.tsx | 18 +- .../tests/renderRouterToStream.test.tsx | 3 +- .../router-client-stream-cleanup.test.tsx | 46 + .../store-updates-during-navigation.test.tsx | 14 +- .../transitioner-remount-rendered.test.tsx | 89 - packages/vue-router/tests/useMatch.test.tsx | 163 +- .../vue-start-client/src/hydrateStart.test.ts | 23 + packages/vue-start-client/src/hydrateStart.ts | 16 +- 180 files changed, 14404 insertions(+), 6142 deletions(-) create mode 100644 packages/react-router/tests/public-presentation-lane-contract.test.tsx create mode 100644 packages/react-router/tests/router-client-stream-cleanup.test.tsx create mode 100644 packages/react-start-client/src/tests/hydrateStart.test.ts create mode 100644 packages/router-core/src/await-signal.ts create mode 100644 packages/router-core/src/rendered-matches.ts create mode 100644 packages/router-core/tests/load-client-wait-for.test.ts create mode 100644 packages/router-core/tests/loader-architecture-regressions.test.ts create mode 100644 packages/router-core/tests/loader-self-abort.test.ts create mode 100644 packages/router-core/tests/public-client-loading-contract.test.ts create mode 100644 packages/router-core/tests/public-hydration-contract.test.ts create mode 100644 packages/router-core/tests/public-preload-lane-contract.test.ts create mode 100644 packages/router-core/tests/server-route-lifecycle.test.ts create mode 100644 packages/router-core/tests/ssr-match-id.bench.ts create mode 100644 packages/solid-router/tests/router-client-stream-cleanup.test.tsx delete mode 100644 packages/solid-router/tests/transitioner-remount.test.tsx create mode 100644 packages/solid-start-client/src/tests/hydrateStart.test.ts create mode 100644 packages/vue-router/tests/router-client-stream-cleanup.test.tsx create mode 100644 packages/vue-start-client/src/hydrateStart.test.ts diff --git a/benchmarks/memory/server/scenarios/aborted-requests/shared.ts b/benchmarks/memory/server/scenarios/aborted-requests/shared.ts index f7f63c17e6..c98f462538 100644 --- a/benchmarks/memory/server/scenarios/aborted-requests/shared.ts +++ b/benchmarks/memory/server/scenarios/aborted-requests/shared.ts @@ -27,11 +27,11 @@ const textDecoder = new TextDecoder() const abortedRequestModes: Record = { react: { readMode: 'first-chunk', - cancelMode: 'plain', + cancelMode: 'swallow-abort-error', }, solid: { readMode: 'first-chunk', - cancelMode: 'plain', + cancelMode: 'swallow-abort-error', }, vue: { readMode: 'shell-before-deferred', diff --git a/docs/router/api/router/RouteMatchType.md b/docs/router/api/router/RouteMatchType.md index 251c2c031e..b5009ebe68 100644 --- a/docs/router/api/router/RouteMatchType.md +++ b/docs/router/api/router/RouteMatchType.md @@ -11,9 +11,8 @@ 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 paramsError: unknown searchError: unknown @@ -21,9 +20,17 @@ interface RouteMatch { loaderData?: Route['loaderData'] context: Route['allContext'] search: Route['fullSearchSchema'] - fetchedAt: number abortController: AbortController - cause: 'enter' | 'stay' + cause: 'preload' | 'enter' | 'stay' ssr?: boolean | 'data-only' } ``` + +`status` describes the match's render state. `isFetching` independently exposes +active `beforeLoad` or loader work. In particular, a successful match can report +`isFetching: 'loader'` while stale data remains visible during a background +reload. + +The router state can contain matches below the pending, error, or not-found +boundary. Those matches remain observable as part of the structurally matched +lane even though the route renderer stops at the boundary. diff --git a/docs/router/api/router/RouteOptionsType.md b/docs/router/api/router/RouteOptionsType.md index 1fb4c4eb30..a1c0cb42aa 100644 --- a/docs/router/api/router/RouteOptionsType.md +++ b/docs/router/api/router/RouteOptionsType.md @@ -56,6 +56,7 @@ The `RouteOptions` type accepts an object with the following properties: - Type: `(rawSearchParams: unknown) => TSearchSchema` - Optional - A function that will be called when this route is matched and passed the raw search params from the current location and return valid parsed search params. If this function throws, the route will be put into an error state and the error will be thrown during render. If this function does not throw, its return value will be used as the route's search params and the return type will be inferred into the rest of the router. +- This is a planning callback. It must be deterministic and side-effect-free for the same input; do not navigate or mutate application/router state from it. - Optionally, the parameter type can be tagged with the `SearchSchemaInput` type like this: `(searchParams: TSearchSchemaInput & SearchSchemaInput) => TSearchSchema`. If this tag is present, `TSearchSchemaInput` will be used to type the `search` property of `` and `navigate()` **instead of** `TSearchSchema`. The difference between `TSearchSchemaInput` and `TSearchSchema` can be useful, for example, to express optional search parameters. ### `search.middlewares` property @@ -70,6 +71,7 @@ The `RouteOptions` type accepts an object with the following properties: - Type: `(rawParams: Record) => TParams` - Optional - A function that will be called when this route is matched and passed the raw params from the current location and return valid parsed params. If this function throws, the route will be put into an error state and the error will be thrown during render. If this function does not throw, its return value will be used as the route's params and the return type will be inferred into the rest of the router. +- This is a planning callback. It must be deterministic and side-effect-free for the same input. ### `stringifyParams` method (⚠️ deprecated, use `params.stringify` instead) @@ -82,6 +84,7 @@ The `RouteOptions` type accepts an object with the following properties: - Type: `(rawParams: Record) => TParams | false` - Optional - A function that will be called when this route is matched and passed the raw params from the current location and return valid parsed params. If this function throws, the route will be put into an error state and the error will be thrown during render. If this function returns parsed params, its return value will be used as the route's params and the return type will be inferred into the rest of the router. +- This is a planning callback. It must be deterministic and side-effect-free for the same input. - Experimental: returning `false` during incoming route matching skips this route and allows matching to continue to another candidate route. ### `params.priority` property @@ -176,6 +179,7 @@ type loaderDeps = (opts: { search: TFullSearchSchema }) => Record - Optional - A function that will be called before this route is matched to provide additional unique identification to the route match and serve as a dependency tracker for when the match should be reloaded. It should return any serializable value that can uniquely identify the route match from navigation to navigation. +- This is a planning callback and cache-key function. It must be deterministic and side-effect-free for the same validated search input. The returned value and any serialization methods on it, such as `toJSON`, must also be side-effect-free. - By default, path params are already used to uniquely identify a route match, so it's unnecessary to return these here. - If your route match relies on search params for unique identification, it's required that you return them here so they can be made available in the `loader`'s `deps` argument. @@ -191,14 +195,14 @@ type loaderDeps = (opts: { search: TFullSearchSchema }) => Record - Type: `number` - Optional - Defaults to `routerOptions.defaultPreloadStaleTime`, which defaults to `30_000` ms (30 seconds) -- The amount of time in milliseconds that a route match's loader data will be considered fresh when preloading. If a route match is preloaded again within this time frame, its loader data will not be reloaded. If a route match is loaded (for navigation) within this time frame, the normal `staleTime` is used instead. +- The amount of time in milliseconds that loader data produced by a preload is considered fresh. Another preload or the first navigation can reuse it within this interval. After navigation accepts the generation, subsequent freshness uses `staleTime`. ### `gcTime` property - Type: `number` - Optional -- Defaults to `routerOptions.defaultGcTime`, which defaults to 30 minutes. -- The amount of time in milliseconds that a route match's loader data will be kept in memory after a preload or it is no longer in use. +- Defaults to `routerOptions.defaultGcTime`, which defaults to 5 minutes. +- The amount of time in milliseconds that loader data from an ordinary load will be kept in memory after it is no longer in use. ### `shouldReload` property @@ -234,12 +238,12 @@ type loaderDeps = (opts: { search: TFullSearchSchema }) => Record - Defaults to `routerOptions.defaultPendingMinMs` which defaults to `500` - The minimum amount of time in milliseconds that the pending component will be shown for if it is shown. This is useful to prevent the pending component from flashing on the screen for a split second. -### `preloadMaxAge` property +### `preloadGcTime` property - Type: `number` - Optional -- Defaults to `30_000` ms (30 seconds) -- The maximum amount of time in milliseconds that a route's preloaded route data will be cached for. If a route is not matched within this time frame, its loader data will be discarded. +- Defaults to `routerOptions.defaultPreloadGcTime`, which defaults to 5 minutes. +- The amount of time in milliseconds that loader data produced by a preload can remain in memory while it is not in use. This controls retention; use `preloadStaleTime` to control whether retained data is fresh enough to reuse without reloading. ### `preSearchFilters` property (⚠️ deprecated, use `search.middlewares` instead) diff --git a/docs/router/api/router/RouterOptionsType.md b/docs/router/api/router/RouterOptionsType.md index 7127e1191e..91f13e0e50 100644 --- a/docs/router/api/router/RouterOptionsType.md +++ b/docs/router/api/router/RouterOptionsType.md @@ -129,14 +129,14 @@ The `RouterOptions` type accepts an object with the following properties and met - Type: `number` - Optional -- Defaults to `routerOptions.defaultGcTime`, which defaults to 30 minutes. +- Defaults to 5 minutes. - The default `preloadGcTime` a route should use if no preloadGcTime is provided. ### `defaultGcTime` property - Type: `number` - Optional -- Defaults to 30 minutes. +- Defaults to 5 minutes. - The default `gcTime` a route should use if no gcTime is provided. ### `defaultOnCatch` property diff --git a/docs/router/api/router/RouterStateType.md b/docs/router/api/router/RouterStateType.md index a77f4e775f..4da9cd9bb6 100644 --- a/docs/router/api/router/RouterStateType.md +++ b/docs/router/api/router/RouterStateType.md @@ -3,16 +3,17 @@ id: RouterStateType title: RouterState type --- -The `RouterState` type represents shape of the internal state of the router. The Router's internal state is useful, if you need to access certain internals of the router, such as any pending matches, is the router in its loading state, etc. +The `RouterState` type represents the observable state of the router, including +the requested and resolved locations, match presentation, and foreground loading +status. ```tsx type RouterState = { status: 'pending' | 'idle' isLoading: boolean - isTransitioning: boolean matches: Array location: ParsedLocation - resolvedLocation: ParsedLocation + resolvedLocation?: ParsedLocation } ``` @@ -23,22 +24,24 @@ The `RouterState` type contains all of the properties that are available on the ### `status` property - Type: `'pending' | 'idle'` -- The current status of the router. If the router is pending, it means that it is currently loading a route or the router is still transitioning to the new route. +- The current foreground status of the router. `pending` means the requested route is still loading or waiting for its framework transition to settle. ### `isLoading` property - 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. +- `true` when `status` is `pending`. +- Background loader refreshes do not change this value. Inspect each match's `isFetching` field to observe foreground `beforeLoad`/loader work and background loader work. ### `matches` property - Type: [`Array`](./RouteMatchType.md) -- An array of all of the route matches that have been resolved and are currently active. +- The match presentation currently exposed to the application. +- A navigation can keep the previous presentation visible until pending UI is + published. Once the destination is presented, this contains its complete + structurally matched lane, including descendants that are still loading. +- Error and not-found results also preserve the complete structurally matched + lane. Rendering stops at the selected pending or terminal boundary; it does + not truncate this array. ### `location` property @@ -47,5 +50,5 @@ The `RouterState` type contains all of the properties that are available on the ### `resolvedLocation` property -- Type: [`ParsedLocation`](./ParsedLocationType.md) -- The location that the router has resolved and loaded. +- Type: [`ParsedLocation`](./ParsedLocationType.md) | `undefined` +- The location whose load and framework transition have settled. It is `undefined` before the initial location resolves. diff --git a/docs/router/api/router/RouterType.md b/docs/router/api/router/RouterType.md index 757a6098ca..0252eb5b80 100644 --- a/docs/router/api/router/RouterType.md +++ b/docs/router/api/router/RouterType.md @@ -35,16 +35,6 @@ 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. - ### `.buildLocation` method Builds a new parsed location object that can be used later to navigate to a new location. @@ -138,23 +128,27 @@ Navigates to a new location. ### `.invalidate` method -Invalidates route matches by forcing their `beforeLoad` and `load` functions to be called again. +Invalidates selected route-match generations, reruns their loading lifecycle, +reruns `beforeLoad`, and reloads their loaders through the normal loading +protocol. - Type: `(opts?: {filter?: (d: MakeRouteMatchUnion) => boolean, sync?: boolean, forcePending?: boolean }) => Promise` - This is useful any time your loader data might be out of date or stale. For example, if you have a route that displays a list of posts, and you have a loader function that fetches the list of posts from an API, you might want to invalidate the route matches for that route any time a new post is created so that the list of posts is always up-to-date. -- if `filter` is not supplied, all matches will be invalidated -- if `filter` is supplied, only matches for which `filter` returns `true` will be invalidated. -- if `sync` is true, the promise returned by this function will only resolve once all loaders have finished. -- if `forcePending` is true, the invalidated matches will be put into `'pending'` state regardless whether they are in `'error'` state or not. +- If `filter` is not supplied, all committed and cached match generations are invalidated. +- If `filter` is supplied, it is evaluated against committed and cached matches. Selecting one generation invalidates every committed or cached generation with the same match ID. +- Invalidation reruns `beforeLoad`; reusable loader data is marked stale and reloads through the normal loading protocol. Route-level `context` remains reusable while the match ID is unchanged. +- If `sync` is `true`, stale loader work is blocking and the returned promise resolves after it finishes instead of leaving a background refresh detached. +- If `forcePending` is `true`, selected routes that need loading enter the normal pending protocol even when successful data was already available. - You might also want to invalidate the Router if you imperatively `reset` the router's `CatchBoundary` to trigger loaders again. ### `.clearCache` method -Remove cached route matches. +Remove cached route matches and matching active preloads. - Type: `(opts?: {filter?: (d: MakeRouteMatchUnion) => boolean}) => void` -- if `filter` is not supplied, all cached matches will be removed -- if `filter` is supplied, only matches for which `filter` returns `true` will be removed. +- If `filter` is not supplied, all cached matches and active preload lanes are removed. +- If `filter` is supplied, matching cached matches are removed. An active preload lane is canceled when any match in that lane passes the filter. +- Current committed and presented matches are not removed. ### `.load` method @@ -170,16 +164,25 @@ Loads all of the currently matched route matches and resolves when they are all Preloads all of the matches that match the provided `NavigateOptions`. -> ⚠️⚠️⚠️ **Preloaded route matches are not stored long-term in the router state. They are only stored until the next attempted navigation action.** +An active preload is speculative and is not published as the current match +presentation. Successful loader data can enter the normal in-memory route cache +and remain reusable according to `preloadStaleTime` and `preloadGcTime`. -- Type: `(opts?: NavigateOptions) => Promise` +Completed preload `beforeLoad` context is not cached. A later navigation reruns +`beforeLoad` unless it adopts an identical whole-route preload that is still +active. Adoption also requires unchanged router context, additional context, +and user-supplied location state. + +- Type: `(opts: NavigateOptions) => Promise` - Properties - `opts` - Type: `NavigateOptions` - - Optional, defaults to the current location. + - Required. - The options that will be used to determine which route matches to preload. - Returns - - A promise that resolves with an array of all of the route matches that were preloaded. + - A promise that resolves with the speculative route-match lane. An ordinary error or not-found is represented by a terminal match array rather than a rejected promise. + - It resolves with `undefined` when cancellation or control flow does not produce a reusable lane. + - The method is also available on server router instances. It remains speculative and does not change the request's current location or presented matches. ### `.loadRouteChunk` method diff --git a/docs/router/api/router/useChildMatchesHook.md b/docs/router/api/router/useChildMatchesHook.md index d6de892192..13212e61e0 100644 --- a/docs/router/api/router/useChildMatchesHook.md +++ b/docs/router/api/router/useChildMatchesHook.md @@ -5,8 +5,9 @@ title: useChildMatches hook The `useChildMatches` hook returns all of the child [`RouteMatch`](./RouteMatchType.md) objects from the closest match down to the leaf-most match. **It does not include the current match, which can be obtained using the `useMatch` hook.** -> [!IMPORTANT] -> If the router has pending matches and they are showing their pending component fallbacks, pending matches are used instead of active matches. +The result is derived from the router's current match presentation. It can +include still-loading descendants and descendants below the current render +boundary. ## useChildMatches options diff --git a/docs/router/api/router/useMatchesHook.md b/docs/router/api/router/useMatchesHook.md index d7a1be8dc3..e57c6c2c7e 100644 --- a/docs/router/api/router/useMatchesHook.md +++ b/docs/router/api/router/useMatchesHook.md @@ -3,7 +3,7 @@ id: useMatchesHook title: useMatches hook --- -The `useMatches` hook returns all of the [`RouteMatch`](./RouteMatchType.md) objects from the router **regardless of its callers position in the React component tree**. +The `useMatches` hook returns the router's complete presented array of [`RouteMatch`](./RouteMatchType.md) objects **regardless of its caller's position in the component tree**. The array can include still-loading descendants or matches below a pending/error/not-found render boundary. > [!TIP] > If you only want the parent or child matches, then you can use the [`useParentMatches`](./useParentMatchesHook.md) or the [`useChildMatches`](./useChildMatchesHook.md) based on the selection you need. diff --git a/docs/router/api/router/useParentMatchesHook.md b/docs/router/api/router/useParentMatchesHook.md index 7afc5585a6..a0ce985411 100644 --- a/docs/router/api/router/useParentMatchesHook.md +++ b/docs/router/api/router/useParentMatchesHook.md @@ -5,8 +5,9 @@ title: useParentMatches hook The `useParentMatches` hook returns all of the parent [`RouteMatch`](./RouteMatchType.md) objects from the root down to the immediate parent of the current match in context. **It does not include the current match, which can be obtained using the `useMatch` hook.** -> [!IMPORTANT] -> If the router has pending matches and they are showing their pending component fallbacks, pending matches are used instead of active matches. +The result is derived from the router's current match presentation. During a +navigation that may still be the previous presentation; after pending UI is +published it is the destination's complete structurally matched lane. ## useParentMatches options diff --git a/docs/router/guide/data-loading.md b/docs/router/guide/data-loading.md index 2ecdf443ad..dad97b1e39 100644 --- a/docs/router/guide/data-loading.md +++ b/docs/router/guide/data-loading.md @@ -150,7 +150,7 @@ Using these dependencies as keys, TanStack Router will cache the data returned f To control router dependencies and "freshness", TanStack Router provides a plethora of options to control the keying and caching behavior of your route loaders. Let's take a look at them in the order that you are most likely to use them: - `routeOptions.loaderDeps` - - A function that supplies you the search params for a router and returns an object of dependencies for use in your `loader` function. When these deps changed from navigation to navigation, it will cause the route to reload regardless of `staleTime`s. The deps are compared using a deep equality check. + - A deterministic, side-effect-free function that supplies you the validated search params for a router and returns a serializable object of dependencies for use in your `loader` function. When these deps change from navigation to navigation, it will cause the route to reload regardless of `staleTime`s. The deps are compared using a deep equality check. - `routeOptions.staleTime` - `routerOptions.defaultStaleTime` - The number of milliseconds that a route's data should be considered fresh when attempting to load. @@ -170,7 +170,7 @@ To control router dependencies and "freshness", TanStack Router provides a pleth - By default, the `staleTime` is set to `0`, meaning that the route's data is immediately considered stale. Stale matches are reloaded in the background when the route is entered again, when its loader key changes (path params used by the route or `loaderDeps`), or when `router.load()` is called explicitly. - By default, a previously preloaded route is considered fresh for **30 seconds**. This means if a route is preloaded, then preloaded again within 30 seconds, the second preload will be ignored. This prevents unnecessary preloads from happening too frequently. **When a route is loaded normally, the standard `staleTime` is used.** -- By default, the `gcTime` is set to **30 minutes**, meaning that any route data that has not been accessed in 30 minutes will be garbage collected and removed from the cache. +- By default, `gcTime` and `preloadGcTime` are **5 minutes**, meaning unused loader data is removed from the in-memory cache after 5 minutes. They can be configured independently. - By default, `staleReloadMode` is `'background'`, so stale successful matches keep rendering with their existing `loaderData` while the loader revalidates in the background. - `router.invalidate()` will force all active routes to reload their loaders immediately and mark every cached route's data as stale. @@ -180,6 +180,11 @@ Imagine a `/posts` route supports some pagination via search params `offset` and Once we have these deps in place, the route will always reload when the deps change. +`loaderDeps` defines a cache key during route planning. For the same validated +search input it must return the same value without navigating or mutating state. +The returned value and custom serialization methods such as `toJSON` must also +be side-effect-free. + ```tsx // /routes/posts.tsx export const Route = createFileRoute('/posts')({ @@ -302,7 +307,11 @@ export const Route = createFileRoute('/posts')({ ### Opting out of caching while still preloading -Even though you may opt-out of short-term caching for your route data, you can still get the benefits of preloading! With the above configuration, preloading will still "just work" with the default `preloadGcTime`. This means that if a route is preloaded, then navigated to, the route's data will be considered fresh and will not be reloaded. +Even though you may opt out of retaining ordinary route data, you can still get +the benefits of preloading. Preloaded results use `preloadGcTime` for retention +and `preloadStaleTime` for freshness, so the default settings keep a recent +preload in memory and let the first navigation reuse it without another loader +call. To opt out of preloading, don't turn it on via the `routerOptions.defaultPreload` or `routeOptions.preload` options. diff --git a/docs/router/guide/path-params.md b/docs/router/guide/path-params.md index b1ae4f5d2f..d9d6d753b6 100644 --- a/docs/router/guide/path-params.md +++ b/docs/router/guide/path-params.md @@ -137,6 +137,9 @@ When multiple dynamic, optional, or wildcard routes can match the same URL, rout Higher `params.priority` values are tried first. The default priority is `0`, and if a higher-priority route's `params.parse` returns `false`, matching continues to the next candidate route. +`params.parse` runs during route planning and may be evaluated more than once. +It must be deterministic and side-effect-free for the same raw params. + ```tsx title="src/routes/posts.$postId.tsx" export const Route = createFileRoute('/posts/$postId')({ params: { diff --git a/docs/router/guide/preloading.md b/docs/router/guide/preloading.md index 092a869685..9498880ff8 100644 --- a/docs/router/guide/preloading.md +++ b/docs/router/guide/preloading.md @@ -18,10 +18,17 @@ Preloading in TanStack Router is a way to load a route before the user actually ## How long does preloaded data stay in memory? -Preloaded route matches are temporarily cached in memory with a few important caveats: +Successful preloaded loader results can enter the router's in-memory cache with +two independent lifetimes: -- **Unused preloaded data is removed after 30 seconds by default.** This can be configured by setting the `defaultPreloadMaxAge` option on your router. -- **Obviously, when a route is loaded, its preloaded version is promoted to the router's normal pending matches state.** +- **Freshness defaults to 30 seconds.** Configure it with + `defaultPreloadStaleTime` or a route's `preloadStaleTime`. +- **Unused retention defaults to 5 minutes.** Configure it with + `defaultPreloadGcTime` or a route's `preloadGcTime`. +- **The speculative lane is never promoted into router state.** Navigation + creates its own presentation and can reuse cached loader data. It reruns + `beforeLoad` unless it adopts the same whole lane while that preload is still + active. If you need more control over preloading, caching and/or garbage collection of preloaded data, you should use an external caching library like [TanStack Query](https://tanstack.com/query). @@ -87,9 +94,15 @@ const router = createRouter({ You can also set the `preloadDelay` prop on individual `` components to override the default behavior on a per-link basis. -## Built-in Preloading & `preloadStaleTime` +## Built-in Preloading, Freshness, and Retention -If you're using the built-in loaders, you can control how long preloaded data is considered fresh until another preload is triggered by setting either `routerOptions.defaultPreloadStaleTime` or `routeOptions.preloadStaleTime` to a number of milliseconds. **By default, preloaded data is considered fresh for 30 seconds.**. +If you're using the built-in loaders, you can control how long preloaded data is considered fresh by setting either `routerOptions.defaultPreloadStaleTime` or `routeOptions.preloadStaleTime` to a number of milliseconds. **By default, preloaded data is considered fresh for 30 seconds.** + +Freshness and retention are separate. `preloadStaleTime` controls whether the +retained loader result can be reused without another loader call. +`preloadGcTime` (or `defaultPreloadGcTime`) controls how long an unused preload +result can remain in the in-memory cache. Both preload GC options default to 5 +minutes. To change this, you can set the `defaultPreloadStaleTime` option on your router: @@ -125,12 +138,16 @@ Or, you can use the `routeOptions.preloadStaleTime` option on individual routes: // src/routes/posts.$postId.tsx export const Route = createFileRoute('/posts/$postId')({ loader: async ({ params }) => fetchPost(params.postId), - // Preload the route again if the preload cache is older than 10 seconds + // Reload preloaded data when it is more than 10 seconds old preloadStaleTime: 10_000, }) ``` -Client-side preloading also runs each new route's `beforeLoad` with `preload: true`. When a completed successful preload is still fresh under the built-in freshness and invalidation policy used for preloaded loader data, the client router can reuse the context returned by that invocation instead of calling `beforeLoad` again with `preload: false`. Reuse follows route match identity, including `loaderDeps`, and requires a reusable parent context. The `shouldReload` option remains loader-only. Pending, failed, invalidated, or stale preloads do not donate their `beforeLoad` context to a client navigation. +Client-side preloading also runs each new route's `beforeLoad` with `preload: true`. A completed preload never caches the context returned by `beforeLoad`; a later navigation calls `beforeLoad` again with `preload: false`, even when it reuses the preload's cached loader data. + +There is one exception: if navigation starts while an identical whole-route preload is still running, it can adopt that active work. Compatibility includes the complete ordered route lane, params, search, router context, additional context, and user-supplied location state. In that case navigation can use the active preload's `beforeLoad` result, or follow its redirect, without calling `beforeLoad` again. A completed, failed, not-found, or canceled preload does not donate `beforeLoad` context to a later navigation. The `shouldReload` option remains loader-only. + +If any route in the lane has `preload: false`, navigation does not adopt the active preload. It reruns the `beforeLoad` chain and performs the loader work that speculation skipped. ## Preloading with External Libraries @@ -170,7 +187,11 @@ This would then allow you, for instance, to use an option like React Query's `st ## Preloading Manually -If you need to manually preload a route, you can use the router's `preloadRoute` method. It accepts a standard TanStack `NavigateOptions` object and returns a promise that resolves when the route is preloaded. +If you need to manually preload a route, use the router's `preloadRoute` method. +It accepts a standard TanStack `NavigateOptions` object and returns the +speculative match lane. An ordinary error or not-found is represented in that +returned lane; cancellation or control flow that produces no reusable lane can +return `undefined`. diff --git a/docs/router/how-to/debug-router-issues.md b/docs/router/how-to/debug-router-issues.md index b4d20ec72f..27dadd361f 100644 --- a/docs/router/how-to/debug-router-issues.md +++ b/docs/router/how-to/debug-router-issues.md @@ -322,11 +322,16 @@ const route = createRoute({ ```tsx function DataLoadingDebug() { - const location = useLocation() + const state = useRouterState() console.log('Route status:', { - isLoading: location.isLoading, - isTransitioning: location.isTransitioning, + status: state.status, + isLoading: state.isLoading, + matches: state.matches.map((match) => ({ + routeId: match.routeId, + status: match.status, + isFetching: match.isFetching, + })), }) return null diff --git a/e2e/react-start/selective-ssr/tests/app.spec.ts b/e2e/react-start/selective-ssr/tests/app.spec.ts index 3d7053f6fa..89eff32cae 100644 --- a/e2e/react-start/selective-ssr/tests/app.spec.ts +++ b/e2e/react-start/selective-ssr/tests/app.spec.ts @@ -4,7 +4,7 @@ import { test } from '@tanstack/router-e2e-utils' const testCount = 7 test.describe('selective ssr', () => { - test('#4614: ssr false child receives context from its parent load generation', async ({ + test('#4614: cached parent loader data does not cache its beforeLoad context', async ({ page, }) => { await page.goto('/') @@ -25,12 +25,19 @@ test.describe('selective ssr', () => { } }) - expect(rootBeforeLoads).toEqual([]) + expect(rootBeforeLoads).toEqual([ + { + cause: 'preload', + preload: true, + root: 'client', + issue4614Context: 'client:cached', + }, + ]) expect(targetBeforeLoad).toEqual({ cause: 'preload', preload: true, - rootContext: 'server', - issue4614Context: 'server:cached', + rootContext: 'client', + issue4614Context: 'client:cached', scenario: 'cached', }) }) diff --git a/packages/react-router/src/CatchBoundary.tsx b/packages/react-router/src/CatchBoundary.tsx index 98743f9447..79afb87934 100644 --- a/packages/react-router/src/CatchBoundary.tsx +++ b/packages/react-router/src/CatchBoundary.tsx @@ -5,7 +5,7 @@ import type { ErrorRouteComponent } from './route' import type { ErrorInfo } from 'react' export function CatchBoundary(props: { - getResetKey: () => number | string + getResetKey: () => unknown children: React.ReactNode errorComponent?: ErrorRouteComponent onCatch?: (error: Error, errorInfo: ErrorInfo) => void @@ -31,18 +31,18 @@ export function CatchBoundary(props: { } class CatchBoundaryImpl extends React.Component<{ - getResetKey: () => number | string + getResetKey: () => unknown children: (props: { error: Error | null reset: () => void }) => React.ReactNode onCatch?: (error: Error, errorInfo: ErrorInfo) => void }> { - state = { error: null } as { error: Error | null; resetKey?: string | number } + state = { error: null } as { error: Error | null; resetKey?: unknown } static getDerivedStateFromProps( - props: { getResetKey: () => string | number }, - state: { resetKey?: string | number; error: Error | null }, + props: { getResetKey: () => unknown }, + state: { resetKey?: unknown; error: Error | null }, ) { const resetKey = props.getResetKey() diff --git a/packages/react-router/src/Match.tsx b/packages/react-router/src/Match.tsx index 44aa3a8633..99028c173e 100644 --- a/packages/react-router/src/Match.tsx +++ b/packages/react-router/src/Match.tsx @@ -2,7 +2,7 @@ import * as React from 'react' import { useStore } from '@tanstack/react-store' -import { invariant, isNotFound, rootRouteId } from '@tanstack/router-core' +import { isNotFound, rootRouteId } from '@tanstack/router-core' import { isServer } from '@tanstack/router-core/isServer' import { CatchBoundary, ErrorComponent } from './CatchBoundary' import { useRouter } from './useRouter' @@ -18,113 +18,58 @@ import type { RootRouteOptions, } from '@tanstack/router-core' +export function renderPending( + router: ReturnType, + route?: AnyRoute, +) { + const PendingComponent = + route?.options.pendingComponent ?? router.options.defaultPendingComponent + return PendingComponent ? : null +} + type OutletMatchSelection = [ - routeId: string | undefined, parentGlobalNotFound: boolean, parentNotFoundError: unknown, ] -const matchViewFieldsEqual = (a: AnyRouteMatch, b: AnyRouteMatch) => - a.routeId === b.routeId && a.fetchCount === b.fetchCount +const matchViewFieldsEqual = ( + a: AnyRouteMatch | undefined, + b: AnyRouteMatch | undefined, +) => a?.abortController === b?.abortController && a?.status === b?.status const outletMatchSelectionEqual = ( a: OutletMatchSelection, b: OutletMatchSelection, -) => a[0] === b[0] && a[1] === b[1] && a[2] === b[2] +) => a[0] === b[0] && a[1] === b[1] export const Match = React.memo(function MatchImpl({ - matchId, + routeId, }: { - matchId: string + routeId: string }) { const router = useRouter() if (isServer ?? router.isServer) { - const match = router.stores.matchStores.get(matchId)?.get() - if (!match) { - if (process.env.NODE_ENV !== 'production') { - throw new Error( - `Invariant failed: Could not find match for matchId "${matchId}". Please file an issue!`, - ) - } - - invariant() - } - - const routeId = match.routeId as string - const parentRouteId = (router.routesById[routeId] as AnyRoute).parentRoute - ?.id - - return ( - - ) + const match = router.stores.byRoute.get(routeId)!.get()! + 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( - `Invariant failed: Could not find match for matchId "${matchId}". Please file an issue!`, - ) - } - - invariant() - } + const matchStore = router.stores.getMatchStore(routeId) // eslint-disable-next-line react-hooks/rules-of-hooks const match = useStore(matchStore, (value) => value, matchViewFieldsEqual) - const routeId = match.routeId as string - const parentRouteId = (router.routesById[routeId] as AnyRoute).parentRoute?.id - - return ( - - ) + return }) -type MatchViewState = { - routeId: string - ssr: boolean | 'data-only' | 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 route: AnyRoute = router.routesById[match.routeId] - const PendingComponent = - route.options.pendingComponent ?? router.options.defaultPendingComponent - - const pendingElement = PendingComponent ? : null + const pendingElement = renderPending(router, route) const routeErrorComponent = route.options.errorComponent ?? router.options.defaultErrorComponent @@ -132,16 +77,15 @@ function MatchView({ const routeOnCatch = route.options.onCatch ?? router.options.defaultOnCatch const routeNotFoundComponent = route.isRoot - ? // If it's the root route, use the globalNotFound option, with fallback to the notFoundRoute's component + ? // If it's the root route, use the _notFound option, with fallback to the notFoundRoute's component (route.options.notFoundComponent ?? 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 = (route.options.wrapInSuspense ?? - PendingComponent ?? + pendingElement ?? ((route.options.errorComponent as any)?.preload || resolvedNoSsr)) ? React.Suspense : SafeFragment @@ -159,146 +103,68 @@ function MatchView({ : SafeFragment return ( - + `${matchId}:${resetKey}`} - errorComponent={routeErrorComponent || ErrorComponent} + getResetKey={() => match.abortController} + errorComponent={routeErrorComponent as any} 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 ??= match.routeId throw error } if (process.env.NODE_ENV !== 'production') { - console.warn(`Warning: Error in route match: ${matchId}`) + console.warn(`Warning: Error in route match: ${match.id}`) } routeOnCatch?.(error, errorInfo) }} > { - error.routeId ??= matchState.routeId as any + error.routeId ??= match.routeId - // 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 && !route.isRoot) - ) + if (error.routeId !== match.routeId) { throw error + } - return React.createElement(routeNotFoundComponent, error as any) + return React.createElement( + routeNotFoundComponent!, + error as any, + ) }} > {resolvedNoSsr ? ( - + ) : ( - + )} - {matchState.parentRouteId === rootRouteId ? ( - router.options.scrollRestoration && (isServer ?? router.isServer) ? ( - - ) : null + {(isServer ?? router.isServer) && + route.parentRoute?.id === rootRouteId && + router.options.scrollRestoration ? ( + ) : null} ) } export const MatchInner = React.memo(function MatchInnerImpl({ - matchId, + match, }: { - matchId: string + match: AnyRouteMatch }): any { const router = useRouter() - - if (isServer ?? router.isServer) { - const match = router.stores.matchStores.get(matchId)?.get() - if (!match) { - if (process.env.NODE_ENV !== 'production') { - throw new Error( - `Invariant failed: Could not find match for matchId "${matchId}". Please file an issue!`, - ) - } - - invariant() - } - - const routeId = match.routeId as string - const route = router.routesById[routeId] as AnyRoute - const remountFn = - (router.routesById[routeId] as AnyRoute).options.remountDeps ?? - router.options.defaultRemountDeps - const remountDeps = remountFn?.({ - routeId, - loaderDeps: match.loaderDeps, - params: match._strictParams, - search: match._strictSearch, - }) - const key = remountDeps ? JSON.stringify(remountDeps) : undefined - const Comp = route.options.component ?? router.options.defaultComponent - const out = Comp ? : - - if (match.status === 'pending') { - invariant() - } - - if (match.status === 'notFound') { - if (!isNotFound(match.error)) { - if (process.env.NODE_ENV !== 'production') { - throw new Error('Invariant failed: Expected a notFound error') - } - - invariant() - } - return renderRouteNotFound(router, route, match.error) - } - - if (match.status === 'error') { - const RouteErrorComponent = - (route.options.errorComponent ?? - router.options.defaultErrorComponent) || - ErrorComponent - return ( - - ) - } - - return out - } - - const matchStore = router.stores.matchStores.get(matchId) - if (!matchStore) { - if (process.env.NODE_ENV !== 'production') { - throw new Error( - `Invariant failed: Could not find match for matchId "${matchId}". Please file an issue!`, - ) - } - - invariant() - } - // eslint-disable-next-line react-hooks/rules-of-hooks - const match = useStore(matchStore, (value) => value) - const routeId = match.routeId as string + const routeId = match.routeId const route = router.routesById[routeId] as AnyRoute - // 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 + route.options.remountDeps ?? router.options.defaultRemountDeps const remountDeps = remountFn?.({ routeId, loaderDeps: match.loaderDeps, @@ -311,42 +177,26 @@ export const MatchInner = React.memo(function MatchInnerImpl({ match.loaderDeps, match._strictParams, match._strictSearch, + route.options.remountDeps, router.options.defaultRemountDeps, - router.routesById, ]) - - // 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 + return Comp ? : }, [key, route.options.component, router.options.defaultComponent]) if (match.status === 'pending') { - const PendingComponent = - route.options.pendingComponent ?? router.options.defaultPendingComponent - return PendingComponent ? : null + if (router._tx) { + throw router._tx[5] + } + return renderPending(router, route) } if (match.status === 'notFound') { - if (!isNotFound(match.error)) { - if (process.env.NODE_ENV !== 'production') { - throw new Error('Invariant failed: Expected a notFound error') - } - - invariant() - } return renderRouteNotFound(router, route, match.error) } 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 ?? @@ -362,7 +212,6 @@ export const MatchInner = React.memo(function MatchInnerImpl({ /> ) } - throw match.error } @@ -377,77 +226,54 @@ export const MatchInner = React.memo(function MatchInnerImpl({ */ export const Outlet = React.memo(function OutletImpl() { const router = useRouter() - const matchId = React.useContext(matchContext) + const routeId = React.useContext(matchContext)! - let routeId: string | undefined - let parentGlobalNotFound = false + let parentGlobalNotFound: boolean let parentNotFoundError: unknown - let childMatchId: string | undefined + let childRouteId: string | undefined if (isServer ?? router.isServer) { const matches = router.stores.matches.get() - const parentIndex = matchId - ? matches.findIndex((match) => match.id === matchId) - : -1 - const parentMatch = parentIndex >= 0 ? matches[parentIndex] : undefined - routeId = parentMatch?.routeId as string | undefined - parentGlobalNotFound = parentMatch?.globalNotFound ?? false - parentNotFoundError = parentMatch?.error - childMatchId = - parentIndex >= 0 ? (matches[parentIndex + 1]?.id as string) : undefined + const parentIndex = matches.findIndex((match) => match.routeId === routeId) + const parentMatch = matches[parentIndex]! + parentGlobalNotFound = !!parentMatch._notFound + parentNotFoundError = parentMatch.error + childRouteId = matches[parentIndex + 1]?.routeId } else { - // Subscribe directly to the match store from the pool instead of - // the two-level byId → matchStore pattern. - const parentMatchStore = matchId - ? router.stores.matchStores.get(matchId) - : undefined + const parentMatchStore = router.stores.getMatchStore(routeId) // eslint-disable-next-line react-hooks/rules-of-hooks - ;[routeId, parentGlobalNotFound, parentNotFoundError] = useStore( + ;[parentGlobalNotFound, parentNotFoundError] = useStore( parentMatchStore, - (match): OutletMatchSelection => [ - match?.routeId as string | undefined, - match?.globalNotFound ?? false, - match?.error, - ], + (match): OutletMatchSelection => [!!match!._notFound, match!.error], outletMatchSelectionEqual, ) // eslint-disable-next-line react-hooks/rules-of-hooks - childMatchId = useStore(router.stores.matchesId, (ids) => { - const index = ids.findIndex((id) => id === matchId) - return ids[index + 1] + childRouteId = useStore(router.stores.ids, (ids) => { + return ids[ids.indexOf(routeId) + 1] }) } - const route = routeId ? router.routesById[routeId] : undefined - - const pendingElement = router.options.defaultPendingComponent ? ( - - ) : 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, parentNotFoundError) + return renderRouteNotFound( + router, + router.routesById[routeId], + parentNotFoundError, + ) } - if (!childMatchId) { + if (!childRouteId) { return null } - const nextMatch = + const nextMatch = if (routeId === rootRouteId) { return ( - {nextMatch} + + {nextMatch} + ) } diff --git a/packages/react-router/src/Matches.tsx b/packages/react-router/src/Matches.tsx index 54422d8b7d..0c4c936c77 100644 --- a/packages/react-router/src/Matches.tsx +++ b/packages/react-router/src/Matches.tsx @@ -4,13 +4,13 @@ import * as React from 'react' import { useStore } from '@tanstack/react-store' import { rootRouteId } from '@tanstack/router-core' import { isServer } from '@tanstack/router-core/isServer' -import { CatchBoundary, ErrorComponent } from './CatchBoundary' +import { CatchBoundary } from './CatchBoundary' import { useRouter } from './useRouter' import { useStructuralSharing } from './useMatch' import { useLayoutEffect } from './utils' import { Transitioner } from './Transitioner' import { matchContext } from './matchContext' -import { Match } from './Match' +import { Match, renderPending } from './Match' import { SafeFragment } from './SafeFragment' import type { StructuralSharingOption, @@ -49,17 +49,11 @@ export function Matches() { const router = useRouter() const rootRoute: AnyRoute = router.routesById[rootRouteId] - const PendingComponent = - rootRoute.options.pendingComponent ?? router.options.defaultPendingComponent - - const pendingElement = PendingComponent ? : null + const pendingElement = renderPending(router, rootRoute) // Do not render a root Suspense during SSR or hydrating from SSR const ResolvedSuspense = - (isServer ?? router.isServer) || - (typeof document !== 'undefined' && router.ssr) - ? SafeFragment - : React.Suspense + (isServer ?? router.isServer) || router.ssr ? SafeFragment : React.Suspense const inner = ( <> @@ -85,22 +79,21 @@ function MatchesInner() { : // eslint-disable-next-line react-hooks/rules-of-hooks useStore(router.stores.matches, (value) => value) const match = matches[0] - const matchId = match?.id + const routeId = match?.routeId useLayoutEffect(() => { - router._rendered?.() + router._rendered!(matches) }, [matches, router]) - const matchComponent = matchId ? : null + const matchComponent = routeId ? : null return ( - + {router.options.disableGlobalCatchBoundary ? ( matchComponent ) : ( (match ? `${matchId}:${match.fetchCount}` : '')} - errorComponent={ErrorComponent} + getResetKey={() => match} onCatch={ process.env.NODE_ENV !== 'production' ? (error) => { @@ -148,7 +141,7 @@ export function useMatchRoute() { if (!(isServer ?? router.isServer)) { // eslint-disable-next-line react-hooks/rules-of-hooks - useStore(router.stores.matchRouteDeps, (d) => d) + useStore(router.stores.loadDeps, (d) => d) } return React.useCallback( @@ -260,20 +253,8 @@ export function useMatches< } /** - * Read the full array of active route matches or select a derived subset. - * - * Useful for debugging, breadcrumbs, or aggregating metadata across matches. - * - * @returns The array of matches (or the selected value). - * @link https://tanstack.com/router/latest/docs/framework/react/api/router/useMatchesHook - */ - -/** - * Read the full array of active route matches or select a derived subset. - * - * Useful for debugging, breadcrumbs, or aggregating metadata across matches. - * - * @link https://tanstack.com/router/latest/docs/framework/react/api/router/useMatchesHook + * Read the presented route matches above the current match, or select a + * derived value from them. */ export function useParentMatches< TRouter extends AnyRouter = RegisteredRouter, @@ -283,13 +264,13 @@ export function useParentMatches< opts?: UseMatchesBaseOptions & StructuralSharingOption, ): UseMatchesResult { - const contextMatchId = React.useContext(matchContext) + const contextRouteId = React.useContext(matchContext) return useMatches({ select: (matches: Array>) => { matches = matches.slice( 0, - matches.findIndex((d) => d.id === contextMatchId), + matches.findIndex((d) => d.routeId === contextRouteId), ) return opts?.select ? opts.select(matches) : matches }, @@ -298,8 +279,8 @@ export function useParentMatches< } /** - * Read the array of active route matches that are children of the current - * match (or selected parent) in the match tree. + * Read the presented route matches below the current match, or select a + * derived value from them. */ export function useChildMatches< TRouter extends AnyRouter = RegisteredRouter, @@ -309,12 +290,12 @@ export function useChildMatches< opts?: UseMatchesBaseOptions & StructuralSharingOption, ): UseMatchesResult { - const contextMatchId = React.useContext(matchContext) + const contextRouteId = React.useContext(matchContext) return useMatches({ select: (matches: Array>) => { matches = matches.slice( - matches.findIndex((d) => d.id === contextMatchId) + 1, + matches.findIndex((d) => d.routeId === contextRouteId) + 1, ) return opts?.select ? opts.select(matches) : matches }, diff --git a/packages/react-router/src/RouterProvider.tsx b/packages/react-router/src/RouterProvider.tsx index 4846ab17fc..81c3fb4ece 100644 --- a/packages/react-router/src/RouterProvider.tsx +++ b/packages/react-router/src/RouterProvider.tsx @@ -50,8 +50,8 @@ export function RouterContextProvider< } /** - * Top-level component that renders the active route matches and provides the - * router to the React tree via context. + * Renders the current match presentation and provides the router to the React + * tree via context. * * Accepts the same options as `createRouter` via props to update the router * instance after creation. diff --git a/packages/react-router/src/Scripts.tsx b/packages/react-router/src/Scripts.tsx index 5285fbd8db..33f4961c2a 100644 --- a/packages/react-router/src/Scripts.tsx +++ b/packages/react-router/src/Scripts.tsx @@ -1,5 +1,5 @@ import { useStore } from '@tanstack/react-store' -import { deepEqual } from '@tanstack/router-core' +import { _getRenderedMatches, deepEqual } from '@tanstack/router-core' import { isServer } from '@tanstack/router-core/isServer' import { Asset } from './Asset' import { useRouter } from './useRouter' @@ -17,23 +17,38 @@ export const Scripts = () => { const router = useRouter() const nonce = router.options.ssr?.nonce - const getAssetScripts = (matches: Array) => { - const assetScripts: Array = [] + const getScripts = (matches: Array) => { + matches = _getRenderedMatches(matches) + const scripts = matches + .flatMap((match) => match.scripts ?? []) + .filter(Boolean) + .map( + ({ children, ...script }) => + ({ + tag: 'script', + attrs: { + ...script, + suppressHydrationWarning: true, + nonce, + }, + children, + }) satisfies RouterManagedTag, + ) as Array const manifest = router.ssr?.manifest if (!manifest) { - return [] + return scripts } for (const match of matches) { - const scripts = manifest.routes[match.routeId]?.scripts + const manifestScripts = manifest.routes[match.routeId]?.scripts - if (!scripts) { + if (!manifestScripts) { continue } - for (const asset of scripts) { - assetScripts.push({ + for (const asset of manifestScripts) { + scripts.push({ tag: 'script', attrs: { ...asset.attrs, nonce }, children: asset.children, @@ -44,64 +59,35 @@ export const Scripts = () => { } } - return assetScripts + return scripts } - const getScripts = (matches: Array): Array => - ( - matches - .map((match) => match.scripts!) - .flat(1) - .filter(Boolean) as Array - ).map( - ({ children, ...script }) => - ({ - tag: 'script', - attrs: { - ...script, - suppressHydrationWarning: true, - nonce, - }, - children, - }) satisfies RouterManagedTag, - ) - if (isServer ?? router.isServer) { const activeMatches = router.stores.matches.get() - const assetScripts = getAssetScripts(activeMatches) const scripts = getScripts(activeMatches) - return renderScripts(router, scripts, assetScripts) + return renderScripts(router, scripts) } - // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static - const assetScripts = useStore( - router.stores.matches, - getAssetScripts, - deepEqual, - ) // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static const scripts = useStore(router.stores.matches, getScripts, deepEqual) - return renderScripts(router, scripts, assetScripts) + return renderScripts(router, scripts) } function renderScripts( router: ReturnType, - scripts: Array, - assetScripts: Array, + scripts: Array, ) { - const allScripts = [...scripts, ...assetScripts] as Array - if ((isServer ?? router.isServer) && router.serverSsr) { const serverBufferedScript = router.serverSsr.takeBufferedScripts() if (serverBufferedScript) { - allScripts.unshift(serverBufferedScript) + scripts.unshift(serverBufferedScript) } } return ( <> - {allScripts.map((asset, i) => ( + {scripts.map((asset, i) => ( ))} diff --git a/packages/react-router/src/Transitioner.tsx b/packages/react-router/src/Transitioner.tsx index 1d8d7b4762..9f494595ae 100644 --- a/packages/react-router/src/Transitioner.tsx +++ b/packages/react-router/src/Transitioner.tsx @@ -4,47 +4,57 @@ import * as React from 'react' import { getLocationChangeInfo, trimPathRight } from '@tanstack/router-core' import { useLayoutEffect } from './utils' import { useRouter } from './useRouter' +import type { AnyRouteMatch } from '@tanstack/router-core' export function Transitioner() { const router = useRouter() - const mountLoadForRouter = React.useRef< - [typeof router, typeof router.history] | undefined + const acknowledgement = React.useRef< + [Array, (rendered: boolean) => void] | undefined >(undefined) + const mounted = + process.env.NODE_ENV !== 'production' + ? // eslint-disable-next-line react-hooks/rules-of-hooks + React.useRef(false) + : undefined - /** - * This effect is meant to "polyfill" the fact that React.startTransition - * does not return an awaitable promise. - * - * So we queue `acknowldgements` here, and `` will call - * `router._rendered` whenever it renders a new batch of matches. - */ - useLayoutEffect(() => { - const acknowledgements: Array<(rendered: boolean) => void> = [] - const rendered = (done: boolean) => { - for (const resolve of acknowledgements.splice(0)) { - resolve(done) - } + // `` precedes ``, so install the render + // acknowledgement before the latter can publish a rendered lane. + router._rendered = (matches) => { + const current = acknowledgement.current + if ( + current?.[0].length === matches.length && + current[0].every( + (match, index) => + match.id === matches[index]!.id && + match.abortController === matches[index]!.abortController && + match.status === matches[index]!.status, + ) + ) { + acknowledgement.current = undefined + current[1](true) } - const transition = (fn: () => void) => { - return new Promise((resolve) => { - acknowledgements.push(resolve) + } + router.startTransition = (fn, expected, urgent) => + new Promise((resolve) => { + acknowledgement.current?.[1](false) + acknowledgement.current = [expected, resolve] + if (urgent) { + fn() + } else { React.startTransition(fn) - }) - } - router._rendered = () => rendered(true) - router.startTransition = transition - return () => rendered(false) - }, [router]) + } + }) // Subscribe before canonicalizing so the initial URL has exactly one load. useLayoutEffect(() => { const unsub = router.history.subscribe(router.load) - const mounted = mountLoadForRouter.current - if (mounted?.[0] === router && mounted[1] === router.history) { - return unsub + if (mounted?.current) { + return process.env.NODE_ENV !== 'production' ? unsub : undefined + } + if (mounted) { + mounted.current = true } - mountLoadForRouter.current = [router, router.history] router.updateLatestLocation() const location = router.latestLocation @@ -58,14 +68,14 @@ export function Transitioner() { }) // Check if the current URL matches the canonical form. - // Compare publicHref (browser-facing URL) for consistency with - // the server-side redirect check in router.beforeLoad. + // Compare publicHref (browser-facing URL) consistently with server + // canonicalization. if ( trimPathRight(location.publicHref) !== trimPathRight(nextLocation.publicHref) ) { router.commitLocation({ ...nextLocation, replace: true }) - return unsub + return process.env.NODE_ENV !== 'production' ? unsub : undefined } const resolvedLocation = router.stores.resolvedLocation.get() @@ -73,15 +83,24 @@ export function Transitioner() { resolvedLocation?.href === location.href && resolvedLocation.state.__TSR_key === location.state.__TSR_key ) { - router.emit({ - type: 'onRendered', - ...getLocationChangeInfo(resolvedLocation, resolvedLocation), - }) - } else { + acknowledgement.current = [ + router.stores.matches.get(), + (rendered) => { + if (rendered) { + router.emit({ + type: 'onRendered', + ...getLocationChangeInfo(resolvedLocation, resolvedLocation), + }) + } + }, + ] + } else if (!router._tx) { router.load().catch(console.error) } - return unsub + return process.env.NODE_ENV !== 'production' ? unsub : undefined + // `mounted` exists only in development and is a stable ref when present. + // eslint-disable-next-line react-hooks/exhaustive-deps }, [router, router.history]) return null diff --git a/packages/react-router/src/headContentUtils.tsx b/packages/react-router/src/headContentUtils.tsx index 5ed35bd1ce..49dd47caad 100644 --- a/packages/react-router/src/headContentUtils.tsx +++ b/packages/react-router/src/headContentUtils.tsx @@ -1,6 +1,7 @@ import * as React from 'react' import { useStore } from '@tanstack/react-store' import { + _getRenderedMatches, appendUniqueUserTags, deepEqual, escapeHtml, @@ -22,6 +23,7 @@ function buildTagsFromMatches( matches: Array, assetCrossOrigin?: AssetCrossOriginConfig, ): Array { + matches = _getRenderedMatches(matches) const routeMeta = matches .map((match) => match.meta) .filter((meta) => meta !== undefined) @@ -187,7 +189,7 @@ function buildTagsFromMatches( } /** - * Build the list of head/link/meta/script tags to render for active matches. + * Build the head/link/meta/script tags from the renderable presented prefix. * Used internally by `HeadContent`. */ export const useTags = (assetCrossOrigin?: AssetCrossOriginConfig) => { @@ -204,226 +206,11 @@ export const useTags = (assetCrossOrigin?: AssetCrossOriginConfig) => { } // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static - const routeMeta = useStore( - router.stores.matches, - (matches) => { - return matches - .map((match) => match.meta) - .filter((meta) => meta !== undefined) - }, - deepEqual, + const selectTags = React.useCallback( + (matches: Array) => + buildTagsFromMatches(router, nonce, matches, assetCrossOrigin), + [assetCrossOrigin, nonce, router], ) - // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static - const meta: Array = React.useMemo(() => { - const resultMeta: Array = [] - const metaByAttribute: Record = {} - let title: RouterManagedTag | undefined - for (let i = routeMeta.length - 1; i >= 0; i--) { - const metas = routeMeta[i]! - for (let j = metas.length - 1; j >= 0; j--) { - const m = metas[j] - if (!m) continue - - if (m.title) { - if (!title) { - title = { - tag: 'title', - children: m.title, - } - } - } else if ('script:ld+json' in m) { - // Handle JSON-LD structured data - // Content is HTML-escaped to prevent XSS when injected via dangerouslySetInnerHTML - try { - const json = JSON.stringify(m['script:ld+json']) - resultMeta.push({ - tag: 'script', - attrs: { - type: 'application/ld+json', - }, - children: escapeHtml(json), - }) - } catch { - // Skip invalid JSON-LD objects - } - } else { - const attribute = m.name ?? m.property - if (attribute) { - if (metaByAttribute[attribute]) { - continue - } else { - metaByAttribute[attribute] = true - } - } - - resultMeta.push({ - tag: 'meta', - attrs: { - ...m, - nonce, - }, - }) - } - } - } - - if (title) { - resultMeta.push(title) - } - - if (nonce) { - resultMeta.push({ - tag: 'meta', - attrs: { - property: 'csp-nonce', - content: nonce, - }, - }) - } - resultMeta.reverse() - - return resultMeta - }, [routeMeta, nonce]) - - // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static - const links = useStore( - router.stores.matches, - (matches) => { - const constructed = matches - .flatMap((match) => match.links ?? []) - .filter((link) => link !== undefined) - .map((link) => ({ - tag: 'link', - attrs: { - ...link, - nonce, - }, - })) satisfies Array - - return constructed - }, - deepEqual, - ) - - // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static - const manifestCssTags = useStore( - router.stores.matches, - (matches) => { - const manifest = router.ssr?.manifest - const tags: Array = [] - - if (!manifest) { - return tags - } - - matches.forEach((match) => { - manifest.routes[match.routeId]?.css?.forEach((link) => { - const resolvedLink = resolveManifestCssLink(link) - tags.push({ - tag: 'link', - attrs: { - rel: 'stylesheet', - ...resolvedLink, - crossOrigin: - getAssetCrossOrigin(assetCrossOrigin, 'stylesheet') ?? - resolvedLink.crossOrigin, - suppressHydrationWarning: true, - nonce, - }, - }) - }) - }) - - if (manifest.inlineStyle) { - tags.push({ - tag: 'style', - attrs: { - ...manifest.inlineStyle.attrs, - nonce, - }, - children: manifest.inlineStyle.children, - inlineCss: true, - }) - } - - return tags - }, - deepEqual, - ) - - // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static - const preloadLinks = useStore( - router.stores.matches, - (matches) => { - const preloadLinks: Array = [] - const manifest = router.ssr?.manifest - - if (!manifest) { - return preloadLinks - } - - matches.forEach((match) => { - manifest.routes[match.routeId]?.preloads?.forEach((preload) => { - preloadLinks.push({ - tag: 'link', - attrs: { - ...getScriptPreloadAttrs(manifest, preload, assetCrossOrigin), - nonce, - }, - }) - }) - }) - - return preloadLinks - }, - deepEqual, - ) - - // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static - const styles = useStore( - router.stores.matches, - (matches) => { - return matches - .flatMap((match) => match.styles ?? []) - .filter((style) => style !== undefined) - .map(({ children, ...attrs }) => ({ - tag: 'style', - attrs: { - ...attrs, - nonce, - }, - children: children as string | undefined, - })) satisfies Array - }, - deepEqual, - ) - - // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static - const headScripts: Array = useStore( - router.stores.matches, - (matches) => { - return matches - .flatMap((match) => match.headScripts ?? []) - .filter((script) => script !== undefined) - .map(({ children, ...script }) => ({ - tag: 'script', - attrs: { - ...script, - nonce, - }, - children: children as string | undefined, - })) satisfies Array - }, - deepEqual, - ) - - const tags: Array = [] - appendUniqueUserTags(tags, meta) - tags.push(...preloadLinks) - appendUniqueUserTags(tags, links) - tags.push(...manifestCssTags) - appendUniqueUserTags(tags, styles) - appendUniqueUserTags(tags, headScripts) - return tags + return useStore(router.stores.matches, selectTags, deepEqual) } diff --git a/packages/react-router/src/lazyRouteComponent.tsx b/packages/react-router/src/lazyRouteComponent.tsx index f918b55ea4..7b228ea632 100644 --- a/packages/react-router/src/lazyRouteComponent.tsx +++ b/packages/react-router/src/lazyRouteComponent.tsx @@ -1,5 +1,6 @@ import * as React from 'react' import { isModuleNotFoundError } from '@tanstack/router-core' +import { isServer } from '@tanstack/router-core/isServer' import { reactUse } from './utils' import type { AsyncRouteComponent } from './route' @@ -24,7 +25,6 @@ export function lazyRouteComponent< let loadPromise: Promise | undefined let comp: T[TKey] | T['default'] let error: any - let reload: boolean const load = () => { if (!loadPromise) { @@ -40,28 +40,6 @@ export function lazyRouteComponent< // there's nothing we want to do about module not found during preload. // Record the error, the rest is handled during the render path. error = err - // If the load fails due to module not found, it may mean a new version of - // the build was deployed and the user's browser is still using an old version. - // If this happens, the old version in the user's browser would have an outdated - // URL to the lazy module. - // In that case, we want to attempt one window refresh to get the latest. - if (isModuleNotFoundError(error)) { - if ( - error instanceof Error && - typeof window !== 'undefined' && - typeof sessionStorage !== 'undefined' - ) { - // Again, we want to reload one time on module not found error and not enter - // a reload loop if there is some other issue besides an old deploy. - // That's why we store our reload attempt in sessionStorage. - // Use error.message as key because it contains the module path that failed. - const storageKey = `tanstack_router_reload:${error.message}` - if (!sessionStorage.getItem(storageKey)) { - sessionStorage.setItem(storageKey, '1') - reload = true - } - } - } }) } @@ -69,15 +47,23 @@ export function lazyRouteComponent< } const lazyComp = function Lazy(props: any) { - // Now that we're out of preload and into actual render path, - if (reload) { - // If it was a module loading error, - // throw eternal suspense while we wait for window to reload - window.location.reload() - throw new Promise(() => {}) - } if (error) { - // Otherwise, just throw the error + // A missing module can mean that a newer deployment replaced the URL. + // Reload only for the error that is still current at render time, so a + // successful retry cannot leave a stale reload request armed. + if ( + isModuleNotFoundError(error) && + !(isServer ?? typeof window === 'undefined') && + typeof sessionStorage !== 'undefined' + ) { + const storageKey = `tanstack_router_reload:${error.message}` + if (!sessionStorage.getItem(storageKey)) { + sessionStorage.setItem(storageKey, '1') + window.location.reload() + // Suspend forever while the document reloads. + throw new Promise(() => {}) + } + } throw error } diff --git a/packages/react-router/src/ssr/RouterClient.tsx b/packages/react-router/src/ssr/RouterClient.tsx index 3271dcd63f..69abc97f0b 100644 --- a/packages/react-router/src/ssr/RouterClient.tsx +++ b/packages/react-router/src/ssr/RouterClient.tsx @@ -3,16 +3,11 @@ import { Await } from '../awaited' import { RouterProvider } from '../RouterProvider' import type { AnyRouter } from '@tanstack/router-core' -let hydrationPromise: Promise>> | undefined +let hydrationPromise: Promise | undefined export function RouterClient(props: { router: AnyRouter }) { - if (!hydrationPromise) { - if (!props.router.stores.matchesId.get().length) { - hydrationPromise = hydrate(props.router) - } else { - hydrationPromise = Promise.resolve() - } - } + hydrationPromise ??= hydrate(props.router).finally(() => window.$_TSR!.h()) + return ( stream.cancel().catch(() => {}) }, + { + signal: request.signal, + onAbort: () => stream.cancel().catch(() => {}), + }, ) return createSsrStreamResponse( router, @@ -180,7 +183,7 @@ export const renderRouterToStream = async ({ const responseStream = transformPipeableStreamWithRouter( router, reactAppPassthrough, - { onAbort: abortPipeable }, + { signal: request.signal, onAbort: abortPipeable }, ) responseAttached = true diff --git a/packages/react-router/src/useMatch.tsx b/packages/react-router/src/useMatch.tsx index 6c1d03421d..35d6673962 100644 --- a/packages/react-router/src/useMatch.tsx +++ b/packages/react-router/src/useMatch.tsx @@ -20,12 +20,7 @@ import type { ThrowOrOptional, } from '@tanstack/router-core' -const dummyStore = { - get() {}, - subscribe() { - return { unsubscribe() {} } - }, -} as any +const dummyMatch = {} export function useStructuralSharing< TRouter extends AnyRouter, @@ -147,16 +142,15 @@ export function useMatch< >, ): ThrowOrOptional, TThrow> { const router = useRouter() - const nearestMatchId = React.useContext( + const nearestRouteId = React.useContext( opts.from ? dummyMatchContext : matchContext, ) - const matchStore = opts.from - ? router.stores.getRouteMatchStore(opts.from) - : router.stores.matchStores.get(nearestMatchId!) + const routeId = opts.from ?? nearestRouteId + const matchStore = router.stores.getMatchStore(routeId!) if (isServer ?? router.isServer) { - const match = matchStore?.get() + const match = matchStore.get() if (!match) { if (opts.shouldThrow ?? true) { if (process.env.NODE_ENV !== 'production') { @@ -179,12 +173,12 @@ export function useMatch< useStructuralSharing(opts, router) // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static - const matchSelection = useStore(matchStore ?? dummyStore, (match) => - match ? selector(match as any) : dummyStore, + const matchSelection = useStore(matchStore, (match) => + match ? selector(match as any) : dummyMatch, ) - if (matchSelection !== dummyStore) { - return matchSelection + if (matchSelection !== dummyMatch) { + return matchSelection as any } if (opts.shouldThrow ?? true) { diff --git a/packages/react-router/src/utils.ts b/packages/react-router/src/utils.ts index f3cbf54613..ca0653e350 100644 --- a/packages/react-router/src/utils.ts +++ b/packages/react-router/src/utils.ts @@ -1,5 +1,6 @@ 'use client' import * as React from 'react' +import { isServer } from '@tanstack/router-core/isServer' // Safe version of React.use() that will not cause compilation errors against // React 18 with Webpack, which statically analyzes imports and fails when it @@ -27,7 +28,9 @@ export function useStableCallback) => any>( } export const useLayoutEffect = - typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect + (isServer ?? typeof window === 'undefined') + ? React.useEffect + : React.useLayoutEffect /** * Taken from https://www.developerway.com/posts/implementing-advanced-use-previous-hook#part3 diff --git a/packages/react-router/tests/Matches.test.tsx b/packages/react-router/tests/Matches.test.tsx index f77a939a6a..f98e840f27 100644 --- a/packages/react-router/tests/Matches.test.tsx +++ b/packages/react-router/tests/Matches.test.tsx @@ -146,6 +146,7 @@ test('should show pendingComponent of root route', async () => { }) test('legacy notFoundRoute drops a stale parent layout after navigation', async () => { + let legacyLoads = 0 const root = createRootRoute({ component: Outlet }) const parent = createRoute({ getParentRoute: () => root, @@ -161,21 +162,19 @@ test('legacy notFoundRoute drops a stale parent layout after navigation', async getParentRoute: () => parent, path: '/known', }) - const home = createRoute({ - getParentRoute: () => root, - path: '/home', - component: () =>
Home
, - }) const legacyNotFound = createRoute({ getParentRoute: () => root, path: '/404', - loader: () => 'not found', + loader: () => { + legacyLoads++ + return 'not found' + }, component: () =>
Legacy not found
, staleTime: Infinity, gcTime: Infinity, }) const router = createRouter({ - routeTree: root.addChildren([parent.addChildren([known]), home]), + routeTree: root.addChildren([parent.addChildren([known])]), history: createMemoryHistory({ initialEntries: ['/parent/missing'] }), notFoundRoute: legacyNotFound, }) @@ -183,11 +182,7 @@ test('legacy notFoundRoute drops a stale parent layout after navigation', async const rendered = render() expect(await rendered.findByText('Parent layout')).toBeInTheDocument() expect(await rendered.findByText('Legacy not found')).toBeInTheDocument() - - await act(async () => { - await router.navigate({ to: '/home' }) - }) - expect(await rendered.findByText('Home')).toBeInTheDocument() + expect(legacyLoads).toBe(1) await act(async () => { await router.navigate({ to: '/missing' } as any) @@ -195,6 +190,7 @@ test('legacy notFoundRoute drops a stale parent layout after navigation', async expect(rendered.queryByText('Parent layout')).not.toBeInTheDocument() expect(await rendered.findByText('Legacy not found')).toBeInTheDocument() + expect(legacyLoads).toBe(1) rendered.unmount() }) diff --git a/packages/react-router/tests/Scripts.test.tsx b/packages/react-router/tests/Scripts.test.tsx index b7605c9402..0a3cfd4aef 100644 --- a/packages/react-router/tests/Scripts.test.tsx +++ b/packages/react-router/tests/Scripts.test.tsx @@ -158,15 +158,12 @@ describe('ssr scripts', () => { { src: 'script3.js' }, ]) - const { container } = await act(() => - render(), - ) - expect(await screen.findByTestId('root')).toBeInTheDocument() - expect(await screen.findByTestId('index')).toBeInTheDocument() - - expect(container.innerHTML).toEqual( - `
root
index
`, + const html = ReactDOMServer.renderToString( + , ) + expect(html).toContain('') + expect(html).toContain('') + expect(html).not.toContain('script2.js') }) }) @@ -839,6 +836,130 @@ describe('ssr HeadContent', () => { ), ).toHaveLength(1) }) + + test('does not render retained descendant assets past a terminal parent boundary', async () => { + let failParent = false + const childHeadScript = '{"source":"child-head"}' + const childBodyScript = '{"source":"child-body"}' + const childManifestScript = '{"source":"child-manifest"}' + const childPreload = '/terminal-child-preload.js' + const childHeadLink = '/terminal-child-head-link.js' + const rootRoute = createRootRoute({ + component: () => ( + <> + {createPortal(, document.head)} + + + + ), + }) + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + shouldReload: true, + loader: () => { + if (failParent) { + throw new Error('parent failed') + } + }, + component: Outlet, + errorComponent: () =>
Parent error
, + }) + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + head: () => ({ + meta: [{ name: 'terminal-child', content: 'visible' }], + links: [{ rel: 'preload', href: childHeadLink }], + styles: [{ children: '.terminal-child { color: red }' }], + scripts: [{ type: 'application/ld+json', children: childHeadScript }], + }), + scripts: () => [ + { type: 'application/ld+json', children: childBodyScript }, + ], + component: () =>
Child content
, + }) + const router = createRouter({ + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + }) + router.ssr = { + manifest: { + routes: { + [childRoute.id]: { + preloads: [childPreload], + scripts: [ + { + attrs: { type: 'application/ld+json' }, + children: childManifestScript, + }, + ], + }, + }, + }, + } + + await router.load() + await act(() => render()) + + await waitFor(() => { + expect( + document.head.querySelector('meta[name="terminal-child"]'), + ).not.toBeNull() + expect( + document.head.querySelector(`link[href="${childPreload}"]`), + ).not.toBeNull() + expect( + document.head.querySelector(`link[href="${childHeadLink}"]`), + ).not.toBeNull() + expect(document.head.textContent).toContain( + '.terminal-child { color: red }', + ) + expect(document.documentElement.textContent).toContain(childHeadScript) + expect(document.documentElement.textContent).toContain(childBodyScript) + expect(document.documentElement.textContent).toContain( + childManifestScript, + ) + }) + + failParent = true + await act(() => router.invalidate()) + await screen.findByText('Parent error') + + expect(router.state.matches).toHaveLength(3) + expect(router.state.matches[1]).toMatchObject({ + routeId: parentRoute.id, + status: 'error', + }) + expect(router.state.matches[2]).toMatchObject({ + routeId: childRoute.id, + meta: [{ name: 'terminal-child', content: 'visible' }], + scripts: [{ type: 'application/ld+json', children: childBodyScript }], + }) + await waitFor(() => { + expect( + document.head.querySelector('meta[name="terminal-child"]'), + ).toBeNull() + expect( + document.head.querySelector(`link[href="${childPreload}"]`), + ).toBeNull() + expect( + document.head.querySelector(`link[href="${childHeadLink}"]`), + ).toBeNull() + expect(document.head.textContent).not.toContain( + '.terminal-child { color: red }', + ) + expect(document.documentElement.textContent).not.toContain( + childHeadScript, + ) + expect(document.documentElement.textContent).not.toContain( + childBodyScript, + ) + expect(document.documentElement.textContent).not.toContain( + childManifestScript, + ) + }) + }) }) describe('data script rendering', () => { diff --git a/packages/react-router/tests/ancestor-loader-child-pending-min.test.tsx b/packages/react-router/tests/ancestor-loader-child-pending-min.test.tsx index a4d587e2f3..09945bb9af 100644 --- a/packages/react-router/tests/ancestor-loader-child-pending-min.test.tsx +++ b/packages/react-router/tests/ancestor-loader-child-pending-min.test.tsx @@ -93,3 +93,65 @@ test('a child fallback revealed after a fresh ancestor loader keeps its own pend expect(screen.queryByText('Child pending')).not.toBeInTheDocument() expect(screen.getByText('Child content')).toBeInTheDocument() }) + +test('advancing from a parent loader to a parallel child loader does not restart pendingMs', async () => { + vi.useFakeTimers() + + const parentLoader = createControlledPromise() + const childLoader = createControlledPromise() + const rootRoute = createRootRoute({ component: Outlet }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
Index
, + }) + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: () => parentLoader, + component: Outlet, + }) + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + pendingMs: 1_000, + pendingMinMs: 0, + pendingComponent: () =>
Child pending
, + loader: () => childLoader, + component: () =>
Child content
, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + render() + + let navigation!: Promise + await act(async () => { + navigation = router.navigate({ to: '/parent/child' }) + await vi.advanceTimersByTimeAsync(900) + }) + expect(screen.queryByText('Child pending')).not.toBeInTheDocument() + + await act(async () => { + parentLoader.resolve() + await vi.advanceTimersByTimeAsync(99) + }) + expect(screen.queryByText('Child pending')).not.toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(1) + }) + expect(screen.getByText('Child pending')).toBeInTheDocument() + + await act(async () => { + childLoader.resolve() + await navigation + }) + expect(screen.getByText('Child content')).toBeInTheDocument() +}) diff --git a/packages/react-router/tests/component-preload-retry-pending-min.test.tsx b/packages/react-router/tests/component-preload-retry-pending-min.test.tsx index b7963c0fa6..dcdd94af67 100644 --- a/packages/react-router/tests/component-preload-retry-pending-min.test.tsx +++ b/packages/react-router/tests/component-preload-retry-pending-min.test.tsx @@ -19,6 +19,32 @@ afterEach(() => { cleanup() }) +test('delayed component preload reveals pending UI', async () => { + const componentGate = createControlledPromise() + const Page = Object.assign(() =>
Page content
, { + preload: () => componentGate, + }) + const rootRoute = createRootRoute({}) + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + component: Page, + pendingMs: 10, + pendingComponent: () =>
Loading page...
, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + render() + + expect(await screen.findByText('Loading page...')).toBeInTheDocument() + componentGate.resolve() + expect(await screen.findByText('Page content')).toBeInTheDocument() + expect(screen.queryByText('Loading page...')).not.toBeInTheDocument() +}) + /** * A component-only route can fail while preloading its code, then retry from * its error UI through invalidate(). The retry is a fresh pending generation: diff --git a/packages/react-router/tests/component-preload-retry.test.tsx b/packages/react-router/tests/component-preload-retry.test.tsx index 4672228875..034276b2fb 100644 --- a/packages/react-router/tests/component-preload-retry.test.tsx +++ b/packages/react-router/tests/component-preload-retry.test.tsx @@ -15,6 +15,7 @@ import type { ErrorComponentProps } from '../src' afterEach(() => { cleanup() vi.restoreAllMocks() + sessionStorage.clear() }) test('a failed component download is retried from the route error UI', async () => { @@ -67,3 +68,34 @@ test('a failed component download is retried from the route error UI', async () screen.queryByRole('button', { name: 'Retry' }), ).not.toBeInTheDocument() }) + +test('renders after retrying a module download that failed during preload', async () => { + const PageContent = () =>
Page content
+ const importer = vi + .fn<() => Promise<{ default: typeof PageContent }>>() + .mockRejectedValueOnce( + new TypeError( + 'Failed to fetch dynamically imported module: /assets/page.js', + ), + ) + .mockResolvedValue({ default: PageContent }) + const Page = lazyRouteComponent(importer) + + await Page.preload?.() + + const rootRoute = createRootRoute() + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + component: Page, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + render() + + expect(await screen.findByText('Page content')).toBeInTheDocument() + expect(importer).toHaveBeenCalledTimes(2) +}) diff --git a/packages/react-router/tests/errorComponent.test.tsx b/packages/react-router/tests/errorComponent.test.tsx index 560b1b5bfa..8f408c380d 100644 --- a/packages/react-router/tests/errorComponent.test.tsx +++ b/packages/react-router/tests/errorComponent.test.tsx @@ -7,6 +7,7 @@ import { Outlet, RouterProvider, createBrowserHistory, + createControlledPromise, createLazyRoute, createMemoryHistory, createRootRoute, @@ -272,6 +273,52 @@ describe.each([true, false])( }, ) +test('global catch boundary resets when a background child generation recovers', async () => { + const refresh = createControlledPromise() + let loaderCalls = 0 + const rootRoute = createRootRoute({ component: Outlet }) + const childRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + loader: { + staleReloadMode: 'background', + handler: () => (++loaderCalls === 1 ? 1 : refresh), + }, + component: () => { + const revision = childRoute.useLoaderData() + if (revision === 1) { + throw new Error('stale child render failed') + } + return
Recovered child revision {revision}
+ }, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([childRoute]), + history, + }) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + vi.spyOn(console, 'error').mockImplementation(() => {}) + + render() + expect( + await screen.findByText('stale child render failed'), + ).toBeInTheDocument() + + const invalidation = router.invalidate() + await vi.waitFor(() => expect(loaderCalls).toBe(2)) + expect(screen.getByText('stale child render failed')).toBeInTheDocument() + expect(screen.queryByText(/Recovered child revision/)).not.toBeInTheDocument() + refresh.resolve(2) + await invalidation + + expect( + await screen.findByText('Recovered child revision 2'), + ).toBeInTheDocument() + expect( + screen.queryByText('stale child render failed'), + ).not.toBeInTheDocument() +}) + test('errorComponent receives primitive errors thrown from beforeLoad', async () => { const rootRoute = createRootRoute() const indexRoute = createRoute({ @@ -318,6 +365,46 @@ test('errorComponent receives primitive errors thrown from beforeLoad', async () expect(screen.queryByText('About route content')).not.toBeInTheDocument() }) +test.each(['beforeLoad', 'loader'] as const)( + 'a Promise synchronously thrown from %s renders the route error UI', + async (hook) => { + const thrown = Promise.resolve('not route data') + const rootRoute = createRootRoute() + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + beforeLoad: + hook === 'beforeLoad' + ? () => { + throw thrown + } + : undefined, + loader: + hook === 'loader' + ? () => { + throw thrown + } + : undefined, + errorComponent: ({ error }) => ( +
+ {error instanceof Error && error.cause === thrown + ? 'Promise route error' + : 'Wrong route error'} +
+ ), + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render() + + expect(await screen.findByText('Promise route error')).toBeInTheDocument() + expect(screen.queryByText('Wrong route error')).not.toBeInTheDocument() + }, +) + test('SSR errorComponent receives primitive errors thrown from beforeLoad', async () => { const rootRoute = createRootRoute({ component: function Root() { @@ -357,6 +444,209 @@ test('SSR errorComponent receives primitive errors thrown from beforeLoad', asyn expect(html).toContain('primitive error thrown') }) +test('a later ancestor loader failure does not hide the first child error', async () => { + const parentStarted = createControlledPromise() + const childStarted = createControlledPromise() + const parentGate = createControlledPromise() + const childGate = createControlledPromise() + const childSettled = createControlledPromise() + const rootRoute = createRootRoute({ component: Outlet }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
Home
, + }) + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + component: Outlet, + loader: async () => { + parentStarted.resolve() + await parentGate + throw new Error('later parent failure') + }, + errorComponent: () =>
Parent error boundary
, + }) + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: async () => { + childStarted.resolve() + await childGate + childSettled.resolve() + throw new Error('first child failure') + }, + errorComponent: () =>
Child error boundary
, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + render() + + let navigation!: Promise + await act(async () => { + navigation = router.navigate({ to: '/parent/child' }) + await Promise.all([parentStarted, childStarted]) + }) + await act(async () => { + childGate.resolve() + await childSettled + parentGate.resolve() + await navigation + }) + + expect(screen.getByText('Child error boundary')).toBeInTheDocument() + expect(screen.queryByText('Parent error boundary')).not.toBeInTheDocument() +}) + +test('a losing ancestor loader still waits for its lazy component before rendering the child error', async () => { + const parentStarted = createControlledPromise() + const childStarted = createControlledPromise() + const parentGate = createControlledPromise() + const childGate = createControlledPromise() + const childSettled = createControlledPromise() + const lazyParentOptions = createLazyRoute('/parent')({ + component: () => ( + <> +
Lazy parent shell
+ + + ), + }) + const parentChunk = createControlledPromise() + const rootRoute = createRootRoute({ component: Outlet }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
Home
, + }) + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: async () => { + parentStarted.resolve() + await parentGate + throw new Error('later parent failure') + }, + errorComponent: () =>
Parent error boundary
, + }).lazy(() => parentChunk) + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: async () => { + childStarted.resolve() + await childGate + childSettled.resolve() + throw new Error('first child failure') + }, + errorComponent: () =>
Child error boundary
, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + render() + + let navigation: Promise | undefined + try { + await act(async () => { + navigation = router.navigate({ to: '/parent/child' }) + await Promise.all([parentStarted, childStarted]) + }) + await act(async () => { + childGate.resolve() + await childSettled + parentGate.resolve() + await Promise.resolve() + }) + + expect(parentChunk.status).toBe('pending') + expect(screen.getByText('Home')).toBeInTheDocument() + expect(screen.queryByText('Child error boundary')).not.toBeInTheDocument() + } finally { + await act(async () => { + childGate.resolve() + parentGate.resolve() + parentChunk.resolve(lazyParentOptions) + await navigation + }) + } + + expect(screen.getByText('Lazy parent shell')).toBeInTheDocument() + expect(screen.getByText('Child error boundary')).toBeInTheDocument() + expect(screen.queryByText('Parent error boundary')).not.toBeInTheDocument() +}) + +test('SSR renders the first child loader error after a later ancestor failure', async () => { + const parentStarted = createControlledPromise() + const childStarted = createControlledPromise() + const parentGate = createControlledPromise() + const childGate = createControlledPromise() + const childSettled = createControlledPromise() + const rootRoute = createRootRoute({ component: Outlet }) + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + component: Outlet, + loader: async () => { + parentStarted.resolve() + await parentGate + throw new Error('later parent failure') + }, + errorComponent: () =>
Parent error boundary
, + }) + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: async () => { + childStarted.resolve() + await childGate + childSettled.resolve() + throw new Error('first child failure') + }, + errorComponent: () =>
Child error boundary
, + }) + const handler = createRequestHandler({ + request: new Request('http://localhost/parent/child'), + createRouter: () => + createRouter({ + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([childRoute]), + ]), + isServer: true, + }), + }) + + const responsePromise = handler(({ router, responseHeaders }) => + renderRouterToString({ + router, + responseHeaders, + children: , + }), + ) + await Promise.all([parentStarted, childStarted]) + childGate.resolve() + await childSettled + parentGate.resolve() + const response = await responsePromise + const html = await response.text() + + expect(response.status).toBe(500) + expect(html).toContain('Child error boundary') + expect(html).not.toContain('Parent error boundary') +}) + // https://github.com/TanStack/router/issues/4684 test('#4684: SSR renders head content when beforeLoad throws', async () => { const rootRoute = createRootRoute({ diff --git a/packages/react-router/tests/hydration-capped-boundary-pending.test.tsx b/packages/react-router/tests/hydration-capped-boundary-pending.test.tsx index d4607c946f..57d99c8af5 100644 --- a/packages/react-router/tests/hydration-capped-boundary-pending.test.tsx +++ b/packages/react-router/tests/hydration-capped-boundary-pending.test.tsx @@ -4,6 +4,7 @@ import { hydrateRoot } from 'react-dom/client' import { renderToString } from 'react-dom/server' import { afterEach, describe, expect, test, vi } from 'vitest' import { createMemoryHistory } from '@tanstack/history' +import { dehydrateSsrMatchId } from '../../router-core/src/ssr/ssr-match-id' import { hydrate } from '../src/ssr/client' import { Outlet, @@ -33,6 +34,82 @@ afterEach(async () => { }) describe('hydrating a server-capped boundary lane', () => { + test('recovers a /404 payload against a missing browser URL', async () => { + function MissingPage() { + return
Missing page
+ } + + const makeRouteTree = () => { + const rootRoute = createRootRoute({ + component: Outlet, + notFoundComponent: MissingPage, + }) + const notFoundRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/404', + component: MissingPage, + }) + return rootRoute.addChildren([notFoundRoute]) + } + + const serverRouter = createRouter({ + routeTree: makeRouteTree(), + history: createMemoryHistory({ initialEntries: ['/404'] }), + }) + serverRouter.isServer = true + await serverRouter.load() + const serverMatches = serverRouter.stores.matches.get() + const serverHtml = renderToString() + expect(serverHtml).toContain('Missing page') + + const clientRouter = createRouter({ + routeTree: makeRouteTree(), + history: createMemoryHistory({ initialEntries: ['/missing'] }), + }) + window.$_TSR = { + router: { + manifest: { routes: {} }, + dehydratedData: {}, + matches: serverMatches.map((match) => ({ + i: dehydrateSsrMatchId(match.id), + u: match.updatedAt, + s: match.status, + l: match.loaderData, + e: match.error, + ssr: match.ssr, + ...(match._notFound ? { g: true } : {}), + })), + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + initialized: false, + } + + await hydrate(clientRouter) + + const container = document.createElement('div') + container.innerHTML = serverHtml + document.body.appendChild(container) + let root!: ReturnType + await act(async () => { + root = hydrateRoot(container, , { + onRecoverableError: () => {}, + }) + testCleanups.push(async () => { + await act(() => root.unmount()) + }) + await Promise.resolve() + }) + + expect(container).toHaveTextContent('Missing page') + expect(clientRouter.state.resolvedLocation?.pathname).toBe('/missing') + expect(clientRouter.state.matches).toHaveLength(1) + expect(clientRouter.state.matches[0]).toMatchObject({ _notFound: true }) + }) + test.each([ ['error', 'parent'], ['notFound', 'parent'], @@ -104,12 +181,12 @@ describe('hydrating a server-capped boundary lane', () => { await serverRouter.load() const serverMatches = serverRouter.stores.matches.get() - expect(serverMatches).toHaveLength(boundary === 'root' ? 1 : 2) - const serverBoundary = serverMatches.at(-1)! + expect(serverMatches).toHaveLength(3) + const serverBoundary = serverMatches[boundary === 'root' ? 0 : 1]! if (outcome === 'notFound' && boundary === 'root') { expect(serverBoundary).toMatchObject({ status: 'success', - globalNotFound: true, + _notFound: true, }) } else { expect(serverBoundary.status).toBe(outcome) @@ -133,15 +210,17 @@ describe('hydrating a server-capped boundary lane', () => { router: { manifest: { routes: {} }, dehydratedData: {}, - matches: serverMatches.map((match) => ({ - i: match.id, - u: match.updatedAt, - s: match.status, - l: match.loaderData, - e: match.error, - ssr: match.ssr, - ...(match.globalNotFound ? { g: true } : {}), - })), + matches: serverMatches + .slice(0, boundary === 'root' ? 1 : 2) + .map((match) => ({ + i: dehydrateSsrMatchId(match.id), + u: match.updatedAt, + s: match.status, + l: match.loaderData, + e: match.error, + ssr: match.ssr, + ...(match._notFound ? { g: true } : {}), + })), }, h: vi.fn(), e: vi.fn(), diff --git a/packages/react-router/tests/hydration-terminal-lane.test.tsx b/packages/react-router/tests/hydration-terminal-lane.test.tsx index 868f19ab27..35784ea916 100644 --- a/packages/react-router/tests/hydration-terminal-lane.test.tsx +++ b/packages/react-router/tests/hydration-terminal-lane.test.tsx @@ -1,6 +1,7 @@ import { cleanup, render, screen } from '@testing-library/react' import { afterEach, describe, expect, test, vi } from 'vitest' import { hydrate } from '@tanstack/router-core/ssr/client' +import { dehydrateSsrMatchId } from '../../router-core/src/ssr/ssr-match-id' import { Outlet, RouterProvider, @@ -25,7 +26,7 @@ function bootstrap( router: { manifest: undefined, matches: matches.map(({ match, status, ssr, data, error }) => ({ - i: match.id, + i: dehydrateSsrMatchId(match.id), l: data, e: error, s: status, diff --git a/packages/react-router/tests/issue-4467-lazy-route-pending.test.tsx b/packages/react-router/tests/issue-4467-lazy-route-pending.test.tsx index 5a765c46ea..e05d2ee792 100644 --- a/packages/react-router/tests/issue-4467-lazy-route-pending.test.tsx +++ b/packages/react-router/tests/issue-4467-lazy-route-pending.test.tsx @@ -78,3 +78,69 @@ test('default pending component renders while lazy route options load', async () }) } }) + +test('a lazy pending component is offered while the eager loader is still pending', async () => { + const rootRoute = createRootRoute({ component: Outlet }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>

Index page

, + }) + const loader = createControlledPromise() + const lazyPageOptions = createLazyRoute('/page')({ + pendingComponent: () =>

Loading lazy page

, + component: () =>

Page

, + }) + const lazyOptions = createControlledPromise() + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + loader: () => loader, + }).lazy(() => lazyOptions) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, pageRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + defaultPendingMs: 0, + defaultPendingMinMs: 0, + defaultPendingComponent: () =>

Loading default

, + }) + let navigation: Promise | undefined + + try { + render() + expect( + await screen.findByRole('heading', { name: 'Index page' }), + ).toBeInTheDocument() + + act(() => { + navigation = router.navigate({ to: '/page' }) + }) + expect(await screen.findByRole('status')).toHaveTextContent( + 'Loading default', + ) + + await act(async () => { + lazyOptions.resolve(lazyPageOptions) + }) + + expect(await screen.findByRole('status')).toHaveTextContent( + 'Loading lazy page', + ) + expect( + screen.queryByRole('heading', { name: 'Page' }), + ).not.toBeInTheDocument() + + await act(async () => { + loader.resolve() + await navigation + }) + + expect(screen.getByRole('heading', { name: 'Page' })).toBeInTheDocument() + } finally { + await act(async () => { + lazyOptions.resolve(lazyPageOptions) + loader.resolve() + await navigation + }) + } +}) diff --git a/packages/react-router/tests/issue-4476-react-query-cancellation.test.tsx b/packages/react-router/tests/issue-4476-react-query-cancellation.test.tsx index 080880517d..3bffbed1ac 100644 --- a/packages/react-router/tests/issue-4476-react-query-cancellation.test.tsx +++ b/packages/react-router/tests/issue-4476-react-query-cancellation.test.tsx @@ -112,7 +112,7 @@ test('#4476: pending navigation keeps the query observer mounted and its fetchQu await waitFor(() => expect(querySignal).toBeDefined()) expect(screen.getByTestId('page-one')).toBeInTheDocument() - expect(screen.queryByTestId('page-two-pending')).not.toBeInTheDocument() + expect(screen.getByTestId('page-two-pending')).toBeInTheDocument() expect(querySignal?.aborted).toBe(false) queryGate.resolve(10) diff --git a/packages/react-router/tests/not-found.test.tsx b/packages/react-router/tests/not-found.test.tsx index 3754785d35..f27057c7ab 100644 --- a/packages/react-router/tests/not-found.test.tsx +++ b/packages/react-router/tests/not-found.test.tsx @@ -1,17 +1,24 @@ import { afterEach, beforeEach, expect, test } from 'vitest' -import { cleanup, render, screen } from '@testing-library/react' +import { act, cleanup, render, screen } from '@testing-library/react' import { Link, Outlet, RouterProvider, createBrowserHistory, + createControlledPromise, + createLazyRoute, createRootRoute, createRoute, createRouter, notFound, rootRouteId, } from '../src' +import { + RouterServer, + createRequestHandler, + renderRouterToString, +} from '../src/ssr/server' import type { NotFoundRouteProps, RouterHistory } from '../src' let history: RouterHistory @@ -27,6 +34,179 @@ afterEach(() => { cleanup() }) +test('navigating to an actively preloaded missing URL renders the global not-found boundary', async () => { + const missingLoaderStarted = createControlledPromise() + const missingLoader = createControlledPromise() + const rootRoute = createRootRoute({ + component: Outlet, + notFoundComponent: () =>
Missing URL boundary
, + loader: ({ location }) => { + if (location.pathname === '/missing') { + missingLoaderStarted.resolve() + return missingLoader + } + return + }, + shouldReload: true, + }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
Home
, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history, + }) + + render() + expect(await screen.findByText('Home')).toBeInTheDocument() + + const preload = router.preloadRoute({ to: '/missing' } as any) + await missingLoaderStarted + const navigation = router.navigate({ to: '/missing' } as any) + missingLoader.resolve() + await act(() => Promise.all([preload, navigation])) + + expect(screen.getByText('Missing URL boundary')).toBeInTheDocument() + expect(screen.queryByText('Home')).not.toBeInTheDocument() +}) + +test('a lazy route notFoundComponent handles an eager beforeLoad failure', async () => { + const rootRoute = createRootRoute({ + component: Outlet, + notFoundComponent: () =>
Root not found
, + }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
Home
, + }) + const failingRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/lazy-not-found', + beforeLoad: () => { + throw notFound() + }, + }).lazy(() => + Promise.resolve( + createLazyRoute('/lazy-not-found')({ + notFoundComponent: () =>
Lazy route not found
, + }), + ), + ) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, failingRoute]), + history, + }) + + render() + expect(await screen.findByText('Home')).toBeInTheDocument() + + await act(() => router.navigate({ to: '/lazy-not-found' })) + + expect(screen.getByText('Lazy route not found')).toBeInTheDocument() + expect(screen.queryByText('Root not found')).not.toBeInTheDocument() +}) + +test('SSR uses a lazy route notFoundComponent for an eager beforeLoad failure', async () => { + const rootRoute = createRootRoute({ + component: Outlet, + notFoundComponent: () =>
Root not found
, + }) + const failingRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/lazy-not-found', + beforeLoad: () => { + throw notFound() + }, + }).lazy(() => + Promise.resolve( + createLazyRoute('/lazy-not-found')({ + notFoundComponent: () =>
Lazy route not found
, + }), + ), + ) + const handler = createRequestHandler({ + request: new Request('http://localhost/lazy-not-found'), + createRouter: () => + createRouter({ + routeTree: rootRoute.addChildren([failingRoute]), + isServer: true, + }), + }) + + const response = await handler(({ router, responseHeaders }) => + renderRouterToString({ + router, + responseHeaders, + children: , + }), + ) + + expect(response.status).toBe(404) + const html = await response.text() + expect(html).toContain('Lazy route not found') + expect(html).not.toContain('Root not found') +}) + +test.each(['client', 'server'] as const)( + 'a lazy child boundary handles a fuzzy URL miss on the %s', + async (environment) => { + const rootRoute = createRootRoute({ + component: Outlet, + notFoundComponent: () =>
Root fuzzy boundary
, + }) + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + component: Outlet, + notFoundComponent: () =>
Parent fuzzy boundary
, + }) + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + }).lazy(() => + Promise.resolve( + createLazyRoute('/parent/child')({ + notFoundComponent: () =>
Lazy child fuzzy boundary
, + }), + ), + ) + const routeTree = rootRoute.addChildren([ + parentRoute.addChildren([childRoute]), + ]) + + if (environment === 'client') { + const router = createRouter({ routeTree, history }) + render() + await act(() => router.navigate({ to: '/parent/child/missing' as any })) + + expect(screen.getByText('Lazy child fuzzy boundary')).toBeInTheDocument() + expect( + screen.queryByText('Parent fuzzy boundary'), + ).not.toBeInTheDocument() + return + } + + const response = await createRequestHandler({ + request: new Request('http://localhost/parent/child/missing'), + createRouter: () => createRouter({ routeTree, isServer: true }), + })(({ router, responseHeaders }) => + renderRouterToString({ + router, + responseHeaders, + children: , + }), + ) + + expect(response.status).toBe(404) + const html = await response.text() + expect(html).toContain('Lazy child fuzzy boundary') + expect(html).not.toContain('Parent fuzzy boundary') + }, +) + test.each([ { notFoundMode: 'fuzzy' as const, diff --git a/packages/react-router/tests/preloaded-mount-resolution.test.tsx b/packages/react-router/tests/preloaded-mount-resolution.test.tsx index 3b5fd0d173..b7527beb3e 100644 --- a/packages/react-router/tests/preloaded-mount-resolution.test.tsx +++ b/packages/react-router/tests/preloaded-mount-resolution.test.tsx @@ -5,6 +5,7 @@ import { createMemoryHistory } from '@tanstack/history' import { Outlet, RouterProvider, + createControlledPromise, createRootRoute, createRoute, createRouter, @@ -38,6 +39,13 @@ afterEach(() => { }) test('mounting after a settled load still resolves status and fires onRendered', async () => { + const lifecycle: Array<'layout' | 'rendered'> = [] + const Home = () => { + React.useLayoutEffect(() => { + lifecycle.push('layout') + }, []) + return
Home
+ } const rootRoute = createRootRoute({ component: () => , }) @@ -45,7 +53,7 @@ test('mounting after a settled load still resolves status and fires onRendered', getParentRoute: () => rootRoute, path: '/', loader: () => 'home data', - component: () =>
Home
, + component: Home, }) const router = createRouter({ routeTree: rootRoute.addChildren([indexRoute]), @@ -56,7 +64,10 @@ test('mounting after a settled load still resolves status and fires onRendered', const rendered = new Promise((resolve) => { resolveRendered = resolve }) - const onRendered = vi.fn(() => resolveRendered()) + const onRendered = vi.fn(() => { + lifecycle.push('rendered') + resolveRendered() + }) const onResolved = vi.fn() const onLoad = vi.fn() const unsubscribers = [ @@ -92,6 +103,7 @@ test('mounting after a settled load still resolves status and fires onRendered', expect(container.querySelector('[data-testid="home"]')).not.toBeNull() expect(onRendered).toHaveBeenCalledTimes(1) + expect(lifecycle).toEqual(['layout', 'rendered']) expect(router.state.status).toBe('idle') expect(router.state.resolvedLocation?.pathname).toBe('/') } finally { @@ -101,3 +113,42 @@ test('mounting after a settled load still resolves status and fires onRendered', container.remove() } }) + +test('mounting during a load keeps the existing generation', async () => { + const gate = createControlledPromise() + const beforeLoad = vi.fn() + const loader = vi.fn(() => gate) + const rootRoute = createRootRoute({ component: () => }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + beforeLoad, + loader, + component: () =>
Home
, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + const load = router.load() + await vi.waitFor(() => expect(loader).toHaveBeenCalledOnce()) + + const container = document.createElement('div') + document.body.appendChild(container) + const reactRoot = createRoot(container) + try { + reactRoot.render() + await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledOnce()) + gate.resolve() + await load + await vi.waitFor(() => { + expect(container.querySelector('[data-testid="home"]')).not.toBeNull() + }) + + expect(beforeLoad).toHaveBeenCalledOnce() + expect(loader).toHaveBeenCalledOnce() + } finally { + reactRoot.unmount() + container.remove() + } +}) diff --git a/packages/react-router/tests/public-presentation-lane-contract.test.tsx b/packages/react-router/tests/public-presentation-lane-contract.test.tsx new file mode 100644 index 0000000000..862fffc93f --- /dev/null +++ b/packages/react-router/tests/public-presentation-lane-contract.test.tsx @@ -0,0 +1,244 @@ +import { act, cleanup, render, screen, waitFor } from '@testing-library/react' +import { afterEach, describe, expect, test, vi } from 'vitest' +import { createControlledPromise } from '@tanstack/router-core' +import { + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +afterEach(() => { + cleanup() + vi.useRealTimers() +}) + +describe('public presentation lane contracts', () => { + test('visible pending UI publishes every matched route and its loading state', async () => { + const parentGate = createControlledPromise() + + const rootRoute = createRootRoute({ component: Outlet }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
Home
, + }) + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + pendingMs: 0, + pendingComponent: () =>
Loading parent
, + loader: () => parentGate, + component: Outlet, + }) + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: () => 'child data', + component: () =>
Child content
, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render() + expect(await screen.findByText('Home')).toBeInTheDocument() + await waitFor(() => expect(router.state.status).toBe('idle')) + + let navigation!: Promise + await act(async () => { + navigation = router.navigate({ to: '/parent/child' }) + await Promise.resolve() + }) + + expect(await screen.findByText('Loading parent')).toBeInTheDocument() + expect(screen.queryByText('Child content')).not.toBeInTheDocument() + + expect(router.state.matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + parentRoute.id, + childRoute.id, + ]) + expect( + router.state.matches.find((match) => match.routeId === parentRoute.id), + ).toMatchObject({ status: 'pending', isFetching: 'loader' }) + + await act(async () => { + parentGate.resolve('parent data') + await navigation + }) + + expect(screen.getByText('Child content')).toBeInTheDocument() + expect(router.state.status).toBe('idle') + }) + + test('same-boundary takeover republishes successor search without restarting pendingMinMs', async () => { + const firstGate = createControlledPromise() + const secondGate = createControlledPromise() + + const rootRoute = createRootRoute({ component: Outlet }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
Home
, + }) + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + validateSearch: (search: Record) => ({ + revision: Number(search.revision), + }), + pendingMs: 0, + pendingMinMs: 100, + pendingComponent: () =>
Loading page
, + beforeLoad: ({ search }) => + search.revision === 1 ? firstGate : secondGate, + component: () => { + const search = pageRoute.useSearch() + return
Page revision {search.revision}
+ }, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, pageRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render() + expect(await screen.findByText('Home')).toBeInTheDocument() + await waitFor(() => expect(router.state.status).toBe('idle')) + + vi.useFakeTimers() + vi.setSystemTime(0) + + let successorSettled = false + let settledAtOriginalDeadline = false + let renderedAtOriginalDeadline = false + try { + await act(async () => { + void router.navigate({ + to: '/page', + search: { revision: 1 }, + }) + await vi.advanceTimersByTimeAsync(0) + }) + expect(screen.getByText('Loading page')).toBeInTheDocument() + expect(router.state.matches.at(-1)?.search).toMatchObject({ revision: 1 }) + + await act(async () => { + await vi.advanceTimersByTimeAsync(25) + }) + + let secondNavigation!: Promise + await act(async () => { + secondNavigation = router.navigate({ + to: '/page', + search: { revision: 2 }, + }) + await vi.advanceTimersByTimeAsync(0) + }) + + expect(screen.getByText('Loading page')).toBeInTheDocument() + expect(router.state.location.search).toMatchObject({ revision: 2 }) + expect(router.state.matches.at(-1)?.search).toMatchObject({ revision: 2 }) + + void secondNavigation.then(() => { + successorSettled = true + }) + await act(async () => { + secondGate.resolve() + await Promise.resolve() + }) + + await act(async () => { + await vi.advanceTimersByTimeAsync(74) + }) + expect(successorSettled).toBe(false) + expect(screen.getByText('Loading page')).toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(1) + await Promise.resolve() + }) + + settledAtOriginalDeadline = successorSettled + renderedAtOriginalDeadline = + screen.queryByText('Page revision 2') !== null + } finally { + // Finish a faulty implementation too, so a deadline assertion cannot + // strand this router and contaminate the following test. + firstGate.resolve() + secondGate.resolve() + await act(async () => { + await vi.advanceTimersByTimeAsync(1_000) + await Promise.resolve() + }) + } + + expect({ + settled: settledAtOriginalDeadline, + rendered: renderedAtOriginalDeadline, + }).toEqual({ settled: true, rendered: true }) + expect(screen.getByText('Page revision 2')).toBeInTheDocument() + expect(screen.queryByText('Loading page')).not.toBeInTheDocument() + }) + + test('a reentrant navigation from onResolved suppresses the stale onRendered event', async () => { + const rootRoute = createRootRoute({ component: Outlet }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
Home
, + }) + const firstRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/first', + component: () =>
First
, + }) + const secondRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/second', + component: () =>
Second
, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, firstRoute, secondRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render() + expect(await screen.findByText('Home')).toBeInTheDocument() + await waitFor(() => expect(router.state.status).toBe('idle')) + + const renderedPaths: Array = [] + let successor: Promise | undefined + const unsubscribeResolved = router.subscribe('onResolved', (event) => { + if (event.toLocation.pathname === '/first') { + successor = router.navigate({ to: '/second' }) + } + }) + const unsubscribeRendered = router.subscribe('onRendered', (event) => { + if (event.toLocation.pathname !== '/') { + renderedPaths.push(event.toLocation.pathname) + } + }) + + try { + await act(() => router.navigate({ to: '/first' })) + await act(async () => { + await successor + }) + + expect(screen.getByText('Second')).toBeInTheDocument() + expect(screen.queryByText('First')).not.toBeInTheDocument() + expect(renderedPaths).toEqual(['/second']) + } finally { + unsubscribeResolved() + unsubscribeRendered() + } + }) +}) diff --git a/packages/react-router/tests/renderRouterToStream.test.tsx b/packages/react-router/tests/renderRouterToStream.test.tsx index 74e180a552..b7bc885a91 100644 --- a/packages/react-router/tests/renderRouterToStream.test.tsx +++ b/packages/react-router/tests/renderRouterToStream.test.tsx @@ -52,6 +52,35 @@ function unwrapResponse( } describe('renderRouterToStream - pipeable sync errors', () => { + test('request abort cancels readable rendering without consuming the response body', async () => { + const cancel = vi.fn() + const stream = Object.assign(new ReadableStream({ cancel }), { + allReady: Promise.resolve(), + }) + reactDomServerMocks.renderToReadableStream = vi.fn(() => stream) + + const router = await buildRouter() + const controller = new AbortController() + try { + const response = unwrapResponse( + await renderRouterToStream({ + request: new Request('http://localhost/', { + signal: controller.signal, + }), + router, + responseHeaders: new Headers(), + children: null, + }), + ) + + expect(response.body).not.toBeNull() + controller.abort(new Error('request-gone')) + await vi.waitFor(() => expect(cancel).toHaveBeenCalledOnce()) + } finally { + router.serverSsr?.cleanup() + } + }) + test('sync onError before pipeable is assigned still aborts pipeable', async () => { const abort = vi.fn() reactDomServerMocks.renderToPipeableStream.mockImplementationOnce( @@ -197,7 +226,7 @@ describe('renderRouterToStream - pipeable sync errors', () => { } }) - test('request abort aborts pipeable and errors body', async () => { + test('request abort cancels pipeable rendering before the response body is consumed', async () => { const abort = vi.fn() reactDomServerMocks.renderToPipeableStream.mockImplementationOnce( (_children, opts) => { @@ -220,13 +249,14 @@ describe('renderRouterToStream - pipeable sync errors', () => { }), ) + expect(response.body).not.toBeNull() controller.abort(new Error('request-gone')) + await vi.waitFor(() => expect(abort).toHaveBeenCalledOnce()) const terminated = await Promise.race([ expectBodyRejects(response, 'request-gone').then(() => true), new Promise((resolve) => setTimeout(() => resolve(false), 2000)), ]) expect(terminated).toBe(true) - expect(abort).toHaveBeenCalledOnce() } finally { router.serverSsr?.cleanup() } diff --git a/packages/react-router/tests/root-pending-min.test.tsx b/packages/react-router/tests/root-pending-min.test.tsx index 636f871274..0216ae4fec 100644 --- a/packages/react-router/tests/root-pending-min.test.tsx +++ b/packages/react-router/tests/root-pending-min.test.tsx @@ -3,14 +3,13 @@ import { act, cleanup, render, screen } from '@testing-library/react' import { hydrateRoot } from 'react-dom/client' import { renderToString } from 'react-dom/server' import { afterEach, expect, test, vi } from 'vitest' +import { dehydrateSsrMatchId } from '../../router-core/src/ssr/ssr-match-id' import { hydrate } from '../src/ssr/client' import { - Outlet, RouterProvider, createControlledPromise, createMemoryHistory, createRootRoute, - createRoute, createRouter, } from '../src' @@ -44,7 +43,6 @@ test('a post-hydration root reload keeps its fallback through pendingMinMs', asy history: createMemoryHistory({ initialEntries: ['/'] }), }) const rootMatch = router.matchRoutes(router.latestLocation)[0]! - // This is the same public bootstrap shape produced by the server. Calling // hydrate() ensures router.ssr and the active match are established through // the real client hydration path rather than by mutating router stores. @@ -54,7 +52,7 @@ test('a post-hydration root reload keeps its fallback through pendingMinMs', asy dehydratedData: {}, matches: [ { - i: rootMatch.id, + i: dehydrateSsrMatchId(rootMatch.id), s: 'success', ssr: true, l: { generation: 1 }, @@ -87,7 +85,7 @@ test('a post-hydration root reload keeps its fallback through pendingMinMs', asy expect(rootLoader).toHaveBeenCalledTimes(1) expect(screen.getByTestId('root-pending')).toBeInTheDocument() - expect(screen.queryByTestId('root-content')).not.toBeInTheDocument() + expect(screen.getByTestId('root-content')).not.toBeVisible() await act(async () => { reloadGate.resolve() @@ -98,7 +96,6 @@ test('a post-hydration root reload keeps its fallback through pendingMinMs', asy await vi.advanceTimersByTimeAsync(99) }) expect(screen.getByTestId('root-pending')).toBeInTheDocument() - expect(screen.queryByTestId('root-content')).not.toBeInTheDocument() await act(async () => { await vi.advanceTimersByTimeAsync(1) @@ -187,64 +184,3 @@ test('server rendering uses the root pending boundary for route component suspen // can wait for the same boundary instead. expect(html).toContain('Server root pending') }) - -test('Transitioner remount loads hydrated history changes made while unmounted', async () => { - const rootRoute = createRootRoute({ component: Outlet }) - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: () =>
Index route
, - }) - const nextRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/next', - component: () =>
Next route
, - }) - const history = createMemoryHistory({ initialEntries: ['/'] }) - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute, nextRoute]), - history, - }) - const matches = router.matchRoutes(router.latestLocation) - const now = Date.now() - - window.$_TSR = { - router: { - manifest: { routes: {} }, - dehydratedData: {}, - matches: matches.map((match) => ({ - i: match.id, - s: 'success' as const, - ssr: true, - u: now, - })), - }, - h: vi.fn(), - e: vi.fn(), - c: vi.fn(), - p: vi.fn(), - buffer: [], - initialized: false, - } - - await hydrate(router) - const firstRender = render() - expect(screen.getByText('Index route')).toBeInTheDocument() - - firstRender.unmount() - history.push('/next') - - const secondRender = render() - expect(await screen.findByText('Next route')).toBeInTheDocument() - expect(router.state.location.pathname).toBe('/next') - - secondRender.unmount() - history.push('/next', { marker: 'new history entry' }) - - render() - await vi.waitFor(() => { - expect((router.state.location.state as any).marker).toBe( - 'new history entry', - ) - }) -}) diff --git a/packages/react-router/tests/routeContext.test.tsx b/packages/react-router/tests/routeContext.test.tsx index d11f86420e..e00228e280 100644 --- a/packages/react-router/tests/routeContext.test.tsx +++ b/packages/react-router/tests/routeContext.test.tsx @@ -141,7 +141,7 @@ describe('context function', () => { }) test('when loader deps change', async () => { - const mockContextFn = vi.fn() + let generation = 0 const rootRoute = createRootRoute() const indexRoute = createRoute({ @@ -153,14 +153,21 @@ describe('context function', () => { path: '/', loaderDeps: ({ search }) => ({ foo: search.foo }), context: ({ deps }) => { - mockContextFn(deps) + return { + generation: ++generation, + deps: JSON.stringify(deps), + } }, component: () => { const navigate = indexRoute.useNavigate() + const context = indexRoute.useRouteContext() return (

Index page

search: {JSON.stringify(indexRoute.useSearch())}

+

+ context: {context.generation}:{context.deps} +

+ + Destination + + + ), + }) + const aRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/a', + }) + const bRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/b', + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([aRoute, bRoute]), + history, + }) + + render(() => ) + + const link = await screen.findByTestId('dynamic-link') + expect(link).toHaveAttribute('href', '/a') + + fireEvent.click( + screen.getByRole('button', { name: 'Change destination' }), + ) + + await waitFor(() => { + expect(link).toHaveAttribute('href', '/b') + }) + }) + test('updates exact and fuzzy active state before the next route renders', async () => { const postLoader = createControlledPromise() diff --git a/packages/start-server-core/src/createStartHandler.ts b/packages/start-server-core/src/createStartHandler.ts index 81e71197cc..20c4763137 100644 --- a/packages/start-server-core/src/createStartHandler.ts +++ b/packages/start-server-core/src/createStartHandler.ts @@ -214,7 +214,7 @@ function handleCtxResult(result: TODO) { function disposeLateResponse(result: TODO, signal: AbortSignal): void { const response = handleCtxResult(result)?.response - if (isSsrResponse(response) && response.serverSsrCleanup === 'stream') { + if (isSsrResponse(response) || isSpecialResponse(response)) { disposeSsrResponseDetached(response, signal.reason) } } @@ -235,6 +235,13 @@ async function executeMiddleware( let streamResponse: | Extract | undefined + let retiredStreamIdentities: WeakSet | undefined + + const isResponseAlias = (candidate: unknown, response: Response) => + candidate === response || + (candidate instanceof Response && + response.body !== null && + candidate.body === response.body) const setResponse = (response: TODO) => { if (isSsrResponse(response)) { @@ -255,18 +262,37 @@ async function executeMiddleware( } streamResponse = undefined + retiredStreamIdentities ??= new WeakSet() + retiredStreamIdentities.add(response.response) + if (response.response.body) { + retiredStreamIdentities.add(response.response.body) + } const currentResponse = ctx.response - if ( - currentResponse === response.response || - (currentResponse instanceof Response && - response.response.body !== null && - currentResponse.body === response.response.body) - ) { + if (isResponseAlias(currentResponse, response.response)) { ctx.response = undefined } await response.dispose(reason) } + const disposeAbandonedResult = (result: TODO) => { + const exposed = handleCtxResult(result)?.response + const response = isSsrResponse(exposed) ? exposed.response : exposed + if (streamResponse && isResponseAlias(response, streamResponse.response)) { + void disposeStreamResponse(signal.reason).catch(console.error) + return + } + if ( + response instanceof Response && + retiredStreamIdentities && + (retiredStreamIdentities.has(response) || + (response.body !== null && retiredStreamIdentities.has(response.body))) + ) { + return + } + + disposeLateResponse(result, signal) + } + const getFinalResponse = async (): Promise => { const response = ctx.response if (!response) { @@ -332,13 +358,11 @@ async function executeMiddleware( nextPromise = undefined result = await pending if (isSignalAborted(signal)) { - disposeLateResponse(result, signal) + disposeAbandonedResult(result) throw signal.reason } } else { - result = await waitForRequest(pending, signal, (late) => - disposeLateResponse(late, signal), - ) + result = await waitForRequest(pending, signal, disposeAbandonedResult) } } catch (err) { if (isSignalAborted(signal)) { @@ -366,10 +390,13 @@ async function executeMiddleware( try { await runNext() - const response = await waitForRequest(getFinalResponse(), signal, (late) => - disposeLateResponse(late, signal), + const response = await waitForRequest( + getFinalResponse(), + signal, + disposeAbandonedResult, ) if (signal.aborted) { + disposeAbandonedResult(response) throw signal.reason } return { ctx, response } diff --git a/packages/start-server-core/tests/createStartHandler.test.ts b/packages/start-server-core/tests/createStartHandler.test.ts index a97d9cf670..a4c8dc16f6 100644 --- a/packages/start-server-core/tests/createStartHandler.test.ts +++ b/packages/start-server-core/tests/createStartHandler.test.ts @@ -467,6 +467,81 @@ describe('createStartHandler request cancellation', () => { expect(router.serverSsr).toBeUndefined() }) + it('cancels a plain response resolved by the render callback later', async () => { + const router = makeRouter() + startMocks.router = router + const requestController = new AbortController() + let notifyRenderStarted!: () => void + const renderStarted = new Promise((resolve) => { + notifyRenderStarted = resolve + }) + let resolveRender!: (value: Response) => void + const renderResult = new Promise((resolve) => { + resolveRender = resolve + }) + const cancel = vi.fn((_reason: unknown) => new Promise(() => {})) + const handler = createStartHandler(() => { + notifyRenderStarted() + return renderResult + }) + const response = handler( + new Request('http://localhost/', { + signal: requestController.signal, + }), + {}, + ) + + await renderStarted + const cancellation = new Error('request disconnected') + requestController.abort(cancellation) + + expect((await response).status).toBe(500) + resolveRender(new Response(new ReadableStream({ cancel }))) + await vi.waitFor(() => { + expect(cancel).toHaveBeenCalledTimes(1) + expect(cancel).toHaveBeenCalledWith(cancellation) + }) + }) + + it('cancels a plain response resolved by request middleware later', async () => { + const router = makeRouter() + startMocks.router = router + const requestController = new AbortController() + let notifyMiddlewareStarted!: () => void + const middlewareStarted = new Promise((resolve) => { + notifyMiddlewareStarted = resolve + }) + let resolveMiddleware!: (value: Response) => void + const middlewareResult = new Promise((resolve) => { + resolveMiddleware = resolve + }) + const cancel = vi.fn((_reason: unknown) => new Promise(() => {})) + startMocks.requestMiddleware = [ + createMiddleware().server(() => { + notifyMiddlewareStarted() + return middlewareResult + }), + ] + const handler = createStartHandler(() => new Response('must not render')) + const response = handler( + new Request('http://localhost/', { + signal: requestController.signal, + }), + {}, + ) + + await middlewareStarted + const cancellation = new Error('request disconnected') + requestController.abort(cancellation) + + expect((await response).status).toBe(500) + resolveMiddleware(new Response(new ReadableStream({ cancel }))) + await vi.waitFor(() => { + expect(cancel).toHaveBeenCalledTimes(1) + expect(cancel).toHaveBeenCalledWith(cancellation) + }) + }) + it.each(['throw', 'reject'] as const)( 'reports a %s from disposal of a late render response', async (failureMode) => { @@ -766,6 +841,7 @@ describe('createStartHandler request cancellation', () => { const afterNext = vi.fn() const ssrResponse = makeStreamResponse(router) const dispose = vi.spyOn(ssrResponse as any, 'dispose') + const cancel = vi.spyOn(ssrResponse.response.body!, 'cancel') startMocks.requestMiddleware = [ createMiddleware().server(async ({ next }) => { try { @@ -798,10 +874,118 @@ describe('createStartHandler request cancellation', () => { expect(response.status).toBe(500) await vi.waitFor(() => expect(observedErrors).toEqual([reason])) - await vi.waitFor(() => expect(dispose).toHaveBeenCalledWith(reason)) + await vi.waitFor(() => { + expect(dispose).toHaveBeenCalledOnce() + expect(dispose).toHaveBeenCalledWith(reason) + expect(cancel).toHaveBeenCalledOnce() + expect(cancel).toHaveBeenCalledWith(reason) + }) expect(afterNext).not.toHaveBeenCalled() expect(render).not.toHaveBeenCalled() }) + + it('disposes a tagged final response once when abort wins handoff', async () => { + const router = makeRouter() + startMocks.router = router + const requestController = new AbortController() + const reason = new Error('request disconnected') + const ssrResponse = makeStreamResponse(router) + const dispose = vi.spyOn(ssrResponse as any, 'dispose') + const cancel = vi.spyOn(ssrResponse.response.body!, 'cancel') + startMocks.requestMiddleware = [ + createMiddleware().server(() => { + queueMicrotask(() => { + queueMicrotask(() => requestController.abort(reason)) + }) + return ssrResponse as any + }), + ] + const render = vi.fn(() => new Response('must not render')) + const handler = createStartHandler(render) + + const response = await handler( + new Request('http://localhost/', { + signal: requestController.signal, + }), + {}, + ) + + expect(response.status).toBe(500) + await vi.waitFor(() => { + expect(dispose).toHaveBeenCalledOnce() + expect(dispose).toHaveBeenCalledWith(reason) + expect(cancel).toHaveBeenCalledOnce() + expect(cancel).toHaveBeenCalledWith(reason) + }) + expect(router.serverSsr).toBeUndefined() + expect(render).not.toHaveBeenCalled() + }) + + it('ignores a late same-body alias after catch disposes its owner', async () => { + const router = makeRouter() + startMocks.router = router + const requestController = new AbortController() + const reason = new Error('request disconnected') + let notifyResponseCaptured!: () => void + const responseCaptured = new Promise((resolve) => { + notifyResponseCaptured = resolve + }) + let releaseMiddleware!: () => void + const middlewareRelease = new Promise((resolve) => { + releaseMiddleware = resolve + }) + let notifyLateResultDelivered!: () => void + const lateResultDelivered = new Promise((resolve) => { + notifyLateResultDelivered = resolve + }) + startMocks.requestMiddleware = [ + createMiddleware().server(async ({ next }) => { + const result = await next() + const wrapped = new Response(result.response.body, result.response) + notifyResponseCaptured() + await middlewareRelease + queueMicrotask(() => { + queueMicrotask(notifyLateResultDelivered) + }) + return wrapped + }), + ] + const response = new Response( + new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode('stream')) + }, + }), + ) + const cancel = vi.spyOn(response.body!, 'cancel') + let ssrResponse!: ReturnType + const render = vi.fn(({ router: requestRouter }) => { + ssrResponse = createSsrStreamResponse(requestRouter, response) + return ssrResponse + }) + const handler = createStartHandler(render) + const result = handler( + new Request('http://localhost/', { + signal: requestController.signal, + }), + {}, + ) + + await responseCaptured + const dispose = vi.spyOn(ssrResponse as any, 'dispose') + requestController.abort(reason) + + expect((await result).status).toBe(500) + releaseMiddleware() + await lateResultDelivered + await vi.waitFor(() => { + expect(dispose).toHaveBeenCalledOnce() + expect(dispose).toHaveBeenCalledWith(reason) + expect(cancel).toHaveBeenCalledOnce() + expect(cancel).toHaveBeenCalledWith(reason) + }) + expect(router.serverSsr).toBeUndefined() + }) }) describe('createStartHandler inlineCss option', () => { diff --git a/packages/vue-router/src/CatchBoundary.tsx b/packages/vue-router/src/CatchBoundary.tsx index 50c2563c25..e912445158 100644 --- a/packages/vue-router/src/CatchBoundary.tsx +++ b/packages/vue-router/src/CatchBoundary.tsx @@ -1,11 +1,6 @@ import * as Vue from 'vue' import type { ErrorRouteComponent } from './route' -interface ErrorComponentProps { - error: Error - reset: () => void -} - type CatchBoundaryProps = { getResetKey: () => unknown children: Vue.VNode @@ -18,11 +13,11 @@ const VueErrorBoundary = Vue.defineComponent({ props: { onError: Function, resetKey: [String, Number, Object], + children: null, + errorComponent: null, }, - emits: ['catch'], - setup(props, { slots }) { + setup(props) { const error = Vue.ref(null) - const resetFn = Vue.ref<(() => void) | null>(null) const reset = () => { error.value = null @@ -46,7 +41,6 @@ const VueErrorBoundary = Vue.defineComponent({ } error.value = err - resetFn.value = reset if (props.onError) { props.onError(err) @@ -55,56 +49,26 @@ const VueErrorBoundary = Vue.defineComponent({ return false }) - return () => { - if (error.value && slots.fallback) { - const fallbackContent = slots.fallback({ - error: error.value, - reset, - }) - return Array.isArray(fallbackContent) && fallbackContent.length === 1 - ? fallbackContent[0] - : fallbackContent - } - - const defaultContent = slots.default && slots.default() - return Array.isArray(defaultContent) && defaultContent.length === 1 - ? defaultContent[0] - : defaultContent - } - }, -}) - -const CatchBoundaryWrapper = Vue.defineComponent({ - name: 'CatchBoundary', - inheritAttrs: false, - props: ['getResetKey', 'children', 'errorComponent', 'onCatch'] as any, - setup(props: CatchBoundaryProps) { - const resetKey = Vue.computed(() => props.getResetKey()) - - return () => { - return Vue.h( - VueErrorBoundary, - { - resetKey: resetKey.value as any, - onError: props.onCatch, - }, - { - default: () => props.children, - fallback: ({ error, reset }: ErrorComponentProps) => { - if (props.errorComponent) { - return Vue.h(props.errorComponent, { error, reset }) - } - return Vue.h(ErrorComponent, { error, reset }) - }, - }, - ) - } + return () => + error.value + ? Vue.h(props.errorComponent ?? ErrorComponent, { + error: error.value, + reset, + }) + : (props.children as Vue.VNode) }, }) export function CatchBoundary(props: CatchBoundaryProps) { - return Vue.h(CatchBoundaryWrapper, props as any) + return Vue.h(VueErrorBoundary, { + resetKey: props.getResetKey() as any, + onError: props.onCatch, + children: props.children, + errorComponent: props.errorComponent, + }) } +CatchBoundary.inheritAttrs = false +CatchBoundary.props = ['getResetKey', 'children', 'errorComponent', 'onCatch'] export const ErrorComponent = Vue.defineComponent({ name: 'ErrorComponent', diff --git a/packages/vue-router/src/Match.tsx b/packages/vue-router/src/Match.tsx index 2734c95d87..9fc4ed6c8d 100644 --- a/packages/vue-router/src/Match.tsx +++ b/packages/vue-router/src/Match.tsx @@ -28,29 +28,15 @@ export const Match = Vue.defineComponent({ const activeMatch = useStore( router.stores.getMatchStore(routeId), (value) => value, + { equal: Object.is }, ) - const matchData = Vue.computed(() => { - const match = activeMatch.value - if (!match) { - return null - } - - return { - matchId: match.id, - routeId, - abortController: match.abortController, - ssr: match.ssr, - } - }) // Provide routeId context (stable string) for children. // MatchInner, Outlet, and useMatch all consume this. Vue.provide(routeIdContext, routeId) return (): VNode => { - const data = matchData.value - const route = data - ? (router.routesById[data.routeId] as AnyRoute) - : undefined + const match = activeMatch.value + const route = match ? (router.routesById[routeId] as AnyRoute) : undefined const PendingComponent = route?.options.pendingComponent ?? router.options.defaultPendingComponent @@ -68,7 +54,7 @@ export const Match = Vue.defineComponent({ const ShellComponent = route?.isRoot ? ((route.options as RootRouteOptions).shellComponent as any) : undefined - const resolvedNoSsr = data?.ssr === false || data?.ssr === 'data-only' + const resolvedNoSsr = match?.ssr === false || match?.ssr === 'data-only' const renderMatchContent = (): VNode => { const matchInner = Vue.h(MatchInner) @@ -89,9 +75,9 @@ export const Match = Vue.defineComponent({ if (routeNotFoundComponent) { content = Vue.h(CatchNotFound, { fallback: (error: any) => { - error.routeId ??= data!.routeId + error.routeId ??= routeId - if (error.routeId !== data!.routeId) { + if (error.routeId !== routeId) { throw error } @@ -104,16 +90,16 @@ export const Match = Vue.defineComponent({ // Wrap in error boundary if needed if (routeErrorComponent) { content = CatchBoundary({ - getResetKey: () => data?.abortController, + getResetKey: () => activeMatch.value, errorComponent: routeErrorComponent, onCatch: (error: Error) => { // Forward not found errors (we don't want to show the error component for these) if (isNotFound(error)) { - error.routeId ??= data?.routeId + error.routeId ??= routeId throw error } if (process.env.NODE_ENV !== 'production') { - console.warn(`Warning: Error in route match: ${data?.matchId}`) + console.warn(`Warning: Error in route match: ${match?.id}`) } routeOnCatch?.(error) }, @@ -121,25 +107,18 @@ export const Match = Vue.defineComponent({ }) } - // Add scroll restoration if needed - const withScrollRestoration: Array = [ - content, - route?.parentRoute?.id === rootRouteId - ? Vue.h(Vue.Fragment, null, [ - router.options.scrollRestoration && - (isServer ?? router.isServer) - ? Vue.h(ScrollRestoration) - : null, - ]) - : null, - ].filter(Boolean) as Array - - // Return single child directly to avoid Fragment wrapper that causes hydration mismatch - if (withScrollRestoration.length === 1) { - return withScrollRestoration[0]! + if (route?.parentRoute?.id !== rootRouteId) { + return content } - return Vue.h(Vue.Fragment, null, withScrollRestoration) + return Vue.h(Vue.Fragment, null, [ + content, + Vue.h(Vue.Fragment, null, [ + (isServer ?? router.isServer) && router.options.scrollRestoration + ? Vue.h(ScrollRestoration) + : null, + ]), + ]) } if (!ShellComponent) { @@ -163,10 +142,7 @@ export const MatchInner = Vue.defineComponent({ // Use routeId from context (provided by parent Match) — stable string. const routeId = Vue.inject(routeIdContext)! - const activeMatch = useStore( - router.stores.getMatchStore(routeId), - (value) => value, - ) + const activeMatch = useStore(router.stores.getMatchStore(routeId)) // Combined selector for match state AND remount key // This ensures both are computed in the same selector call with consistent data @@ -184,18 +160,19 @@ export const MatchInner = Vue.defineComponent({ (router.routesById[matchRouteId] as AnyRoute).options.remountDeps ?? router.options.defaultRemountDeps - let remountKey: string | undefined - if (remountFn) { - const remountDeps = remountFn({ - routeId: matchRouteId, - loaderDeps: match.loaderDeps, - params: match._strictParams, - search: match._strictSearch, - }) - remountKey = remountDeps ? JSON.stringify(remountDeps) : undefined - } + const remountDeps = remountFn + ? remountFn({ + routeId: matchRouteId, + loaderDeps: match.loaderDeps, + params: match._strictParams, + search: match._strictSearch, + }) + : undefined - return [match, remountKey] as const + return [ + match, + remountDeps ? JSON.stringify(remountDeps) : undefined, + ] as const }) return (): VNode | null => { @@ -275,51 +252,39 @@ export const Outlet = Vue.defineComponent({ const router = useRouter() const parentRouteId = Vue.inject(routeIdContext)! - const parentMatch = useStore( - router.stores.getMatchStore(parentRouteId), - (v) => v, - ) + const parentMatch = useStore(router.stores.getMatchStore(parentRouteId)) const route = router.routesById[parentRouteId]! - const parentGlobalNotFound = Vue.computed( - () => parentMatch.value?._notFound ?? false, - ) - const childMatch = useStore(router.stores.matches, (matches) => { const index = matches.findIndex( (match) => match.routeId === parentRouteId, ) - return matches[index + 1] + const child = matches[index + 1] + return child + ? ([ + child.routeId, + child.routeId + JSON.stringify(child._strictParams), + ] as const) + : undefined }) - const childMatchData = Vue.computed(() => { + return (): VNode | null => { + if (parentMatch.value?._notFound) { + return renderRouteNotFound(router, route, parentMatch.value.error) + } + const child = childMatch.value if (!child) { return null } - return { - routeId: child.routeId, + const nextMatch = Vue.h(Match, { + routeId: child[0], // Key based on routeId + params only (not loaderDeps) // This ensures component recreates when params change, // but NOT when only loaderDeps change - paramsKey: child.routeId + JSON.stringify(child._strictParams), - } - }) - - return (): VNode | null => { - if (parentGlobalNotFound.value) { - return renderRouteNotFound(router, route, parentMatch.value!.error) - } - - if (!childMatchData.value) { - return null - } - - const nextMatch = Vue.h(Match, { - routeId: childMatchData.value.routeId, - key: childMatchData.value.paramsKey, + key: child[1], }) // Note: We intentionally do NOT wrap in Suspense here. diff --git a/packages/vue-router/src/Matches.tsx b/packages/vue-router/src/Matches.tsx index 121dd1f702..15799d2a5b 100644 --- a/packages/vue-router/src/Matches.tsx +++ b/packages/vue-router/src/Matches.tsx @@ -126,7 +126,12 @@ export type UseMatchRouteOptions< export function useMatchRoute() { const router = useRouter() - const routerState = useStore(router.stores.loadDeps, (value) => value) + const location = useStore(router.stores.location, (value) => value.href) + const resolvedLocation = useStore( + router.stores.resolvedLocation, + (value) => value?.href, + ) + const status = useStore(router.stores.status) return < const TFrom extends string = string, @@ -138,12 +143,11 @@ export function useMatchRoute() { ): Vue.Ref< false | ResolveRoute['types']['allParams'] > => { - const { pending, caseSensitive, fuzzy, includeSearch, ...rest } = opts - const matchRoute = Vue.computed(() => { - // Access routerState to establish dependency - - routerState.value + location.value + resolvedLocation.value + status.value + const { pending, caseSensitive, fuzzy, includeSearch, ...rest } = opts return router.matchRoute(rest as any, { pending, caseSensitive, @@ -222,24 +226,20 @@ export const MatchRoute = Vue.defineComponent({ }, }, setup(props, { slots }) { - const router = useRouter() - const status = useStore(router.stores.loadDeps, (value) => value[2]) + const params = useMatchRoute()(props) return () => { - if (!status.value) return null - - const matchRoute = useMatchRoute() - const params = matchRoute(props).value as boolean + const match = params.value as boolean // Create a component that renders the slot in a reactive manner - if (!params || !slots.default) { + if (!match || !slots.default) { return null } // For function slots, pass the params if (typeof slots.default === 'function') { // Use h to create a wrapper component that will call the slot function - return Vue.h(Vue.Fragment, null, slots.default(params)) + return Vue.h(Vue.Fragment, null, slots.default(match)) } // For normal slots, just render them diff --git a/packages/vue-router/src/Transitioner.tsx b/packages/vue-router/src/Transitioner.tsx index 7b9f6aab9f..6b7e92eb5e 100644 --- a/packages/vue-router/src/Transitioner.tsx +++ b/packages/vue-router/src/Transitioner.tsx @@ -45,7 +45,7 @@ export function useTransitionerSetup() { type: 'onRendered', ...getLocationChangeInfo(resolvedLocation, resolvedLocation), }) - } else { + } else if (!router._tx) { router.load().catch(console.error) } }) diff --git a/packages/vue-router/src/not-found.tsx b/packages/vue-router/src/not-found.tsx index f676c66e99..f0ebf678ea 100644 --- a/packages/vue-router/src/not-found.tsx +++ b/packages/vue-router/src/not-found.tsx @@ -16,7 +16,7 @@ export function CatchNotFound(props: { router.stores.location, (location) => location.pathname, ) - const status = useStore(router.stores.status, (value) => value) + const status = useStore(router.stores.status) // Create a function that returns a VNode to match the SyncRouteComponent signature const errorComponentFn = (componentProps: ErrorComponentProps) => { diff --git a/packages/vue-router/src/useMatch.tsx b/packages/vue-router/src/useMatch.tsx index 70095e4552..495d87d5fc 100644 --- a/packages/vue-router/src/useMatch.tsx +++ b/packages/vue-router/src/useMatch.tsx @@ -117,16 +117,13 @@ export function useMatch< if (opts.from) { // routeId case: subscribe to the stable per-route presentation atom. const matchStore = router.stores.getMatchStore(opts.from) - match = useStore(matchStore, (value) => value) + match = useStore(matchStore) } else { // Nearest-match case: use the routeId from context for stable lookup. // The routeId is provided by the nearest Match component and doesn't // change for the component's lifetime, so the store is stable. if (nearestRouteId) { - match = useStore( - router.stores.getMatchStore(nearestRouteId), - (value) => value, - ) + match = useStore(router.stores.getMatchStore(nearestRouteId)) } else { // No route context — will fall through to error handling below match = Vue.ref(undefined) as Readonly> diff --git a/packages/vue-router/tests/Matches.test.tsx b/packages/vue-router/tests/Matches.test.tsx index b398fd98c7..314cbfba2b 100644 --- a/packages/vue-router/tests/Matches.test.tsx +++ b/packages/vue-router/tests/Matches.test.tsx @@ -1,4 +1,5 @@ import { afterEach, describe, expect, test } from 'vitest' +import * as Vue from 'vue' import { cleanup, fireEvent, @@ -7,6 +8,7 @@ import { waitFor, } from '@testing-library/vue' import { createMemoryHistory } from '@tanstack/history' +import { createControlledPromise } from '@tanstack/router-core' import { Link, Outlet, @@ -158,6 +160,78 @@ test('should show pendingComponent of root route', async () => { expect(await rendered.findByTestId('root-content')).toBeInTheDocument() }) +test('useMatchRoute follows superseding pending locations', async () => { + const aGate = createControlledPromise() + const bGate = createControlledPromise() + + const Layout = Vue.defineComponent({ + setup() { + const matchRoute = useMatchRoute() + const pendingA = matchRoute({ to: '/a', pending: true }) + const pendingB = matchRoute({ to: '/b', pending: true }) + const resolvedB = matchRoute({ to: '/b', pending: false }) + return () => ( +
+ {String(Boolean(pendingA.value))} + {String(Boolean(pendingB.value))} + + {String(Boolean(resolvedB.value))} + + +
+ ) + }, + }) + + const root = createRootRoute({ component: Layout }) + const index = createRoute({ + getParentRoute: () => root, + path: '/', + }) + const a = createRoute({ + getParentRoute: () => root, + path: '/a', + loader: () => aGate, + }) + const b = createRoute({ + getParentRoute: () => root, + path: '/b', + loader: () => bGate, + }) + const router = createRouter({ + routeTree: root.addChildren([index, a, b]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + render() + + await waitFor(() => { + expect(screen.getByTestId('pending-a')).toHaveTextContent('false') + expect(router.stores.status.get()).toBe('idle') + expect(router.stores.resolvedLocation.get()?.pathname).toBe('/') + }) + + const navigationA = router.navigate({ to: '/a' }) + await waitFor(() => { + expect(screen.getByTestId('pending-a')).toHaveTextContent('true') + expect(screen.getByTestId('resolved-b')).toHaveTextContent('false') + }) + + const navigationB = router.navigate({ to: '/b' }) + await waitFor(() => { + expect(screen.getByTestId('pending-a')).toHaveTextContent('false') + expect(screen.getByTestId('pending-b')).toHaveTextContent('true') + expect(screen.getByTestId('resolved-b')).toHaveTextContent('false') + }) + + aGate.resolve() + bGate.resolve() + await Promise.allSettled([navigationA, navigationB]) + await waitFor(() => { + expect(screen.getByTestId('pending-b')).toHaveTextContent('false') + expect(screen.getByTestId('resolved-b')).toHaveTextContent('true') + }) +}) + describe('matching on different param types', () => { const testCases = [ { diff --git a/packages/vue-router/tests/Transitioner.test.tsx b/packages/vue-router/tests/Transitioner.test.tsx index 5d463c9dc8..2422df93d4 100644 --- a/packages/vue-router/tests/Transitioner.test.tsx +++ b/packages/vue-router/tests/Transitioner.test.tsx @@ -1,12 +1,17 @@ -import { describe, expect, it, vi } from 'vitest' -import { render, waitFor } from '@testing-library/vue' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { cleanup, render, waitFor } from '@testing-library/vue' import { + RouterProvider, + createControlledPromise, createMemoryHistory, createRootRoute, createRoute, createRouter, } from '../src' -import { RouterProvider } from '../src/RouterProvider' + +afterEach(() => { + cleanup() +}) describe('Transitioner', () => { it('loads the initial route when the provider mounts', async () => { @@ -34,4 +39,38 @@ describe('Transitioner', () => { expect(view.getByText('Index')).toBeInTheDocument() }) }) + + it('reuses a public load already in progress when the provider mounts', async () => { + const loaderGate = createControlledPromise() + const beforeLoad = vi.fn() + const loader = vi.fn(() => loaderGate) + const rootRoute = createRootRoute() + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + beforeLoad, + loader, + component: () =>
Index
, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + const load = router.load() + try { + await waitFor(() => expect(loader).toHaveBeenCalledTimes(1)) + + const view = render() + loaderGate.resolve() + await load + + expect(await view.findByText('Index')).toBeInTheDocument() + expect(beforeLoad).toHaveBeenCalledTimes(1) + expect(loader).toHaveBeenCalledTimes(1) + } finally { + loaderGate.resolve() + await Promise.allSettled([load]) + } + }) }) diff --git a/packages/vue-router/tests/errorComponent.test.tsx b/packages/vue-router/tests/errorComponent.test.tsx index a149a880ff..92fab168e6 100644 --- a/packages/vue-router/tests/errorComponent.test.tsx +++ b/packages/vue-router/tests/errorComponent.test.tsx @@ -207,3 +207,59 @@ test('global catch boundary resets when a background child generation recovers', screen.queryByText('stale child render failed'), ).not.toBeInTheDocument() }) + +test('ancestor route errorComponent resets when a background child generation recovers', async () => { + const refresh = createControlledPromise() + let loaderCalls = 0 + const rootRoute = createRootRoute({ + component: Outlet, + errorComponent: ({ error }) =>
Ancestor error: {error.message}
, + }) + const childRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + loader: { + staleReloadMode: 'background', + handler: () => (++loaderCalls === 1 ? 1 : refresh), + }, + component: () => { + const revision = childRoute.useLoaderData() + if (revision.value === 1) { + throw new Error('stale child render failed') + } + return
Recovered child revision {revision.value}
+ }, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([childRoute]), + }) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + vi.spyOn(console, 'error').mockImplementation(() => {}) + + let invalidation: Promise | undefined + try { + render() + expect( + await screen.findByText('Ancestor error: stale child render failed'), + ).toBeInTheDocument() + + invalidation = router.invalidate({ + filter: (match) => match.routeId === childRoute.id, + }) + await vi.waitFor(() => expect(loaderCalls).toBe(2)) + expect( + screen.getByText('Ancestor error: stale child render failed'), + ).toBeInTheDocument() + refresh.resolve(2) + await invalidation + + expect( + await screen.findByText('Recovered child revision 2'), + ).toBeInTheDocument() + } finally { + refresh.resolve(2) + if (invalidation) { + await Promise.allSettled([invalidation]) + } + } +}) From 03a1fde26123f66a314213897abf6bcb4c99c258 Mon Sep 17 00:00:00 2001 From: Flo Date: Wed, 22 Jul 2026 08:56:43 +0200 Subject: [PATCH 49/59] perf(router): reduce SSR lane loading overhead (#7875) * perf(router): reduce SSR lane loading overhead * ci: apply automated fixes --------- Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com> --- .../react-router/src/lazyRouteComponent.tsx | 5 ++- .../tests/component-preload-retry.test.tsx | 13 +++++++ packages/router-core/src/load-server.ts | 36 +++++++++++++------ packages/solid-router/src/Match.tsx | 14 +++++--- .../solid-router/src/lazyRouteComponent.tsx | 6 +++- .../tests/component-preload-retry.test.tsx | 25 +++++++++++++ 6 files changed, 81 insertions(+), 18 deletions(-) diff --git a/packages/react-router/src/lazyRouteComponent.tsx b/packages/react-router/src/lazyRouteComponent.tsx index 7b228ea632..7c387e0e31 100644 --- a/packages/react-router/src/lazyRouteComponent.tsx +++ b/packages/react-router/src/lazyRouteComponent.tsx @@ -31,7 +31,10 @@ export function lazyRouteComponent< error = undefined loadPromise = importer() .then((res) => { - loadPromise = undefined + // Keep browser preload behavior unchanged; SSR can reuse the import. + if (!(isServer ?? typeof window === 'undefined')) { + loadPromise = undefined + } comp = res[exportName ?? 'default'] }) .catch((err) => { diff --git a/packages/react-router/tests/component-preload-retry.test.tsx b/packages/react-router/tests/component-preload-retry.test.tsx index 034276b2fb..2ce819f1bb 100644 --- a/packages/react-router/tests/component-preload-retry.test.tsx +++ b/packages/react-router/tests/component-preload-retry.test.tsx @@ -15,9 +15,22 @@ import type { ErrorComponentProps } from '../src' afterEach(() => { cleanup() vi.restoreAllMocks() + vi.unstubAllGlobals() sessionStorage.clear() }) +test('a successful server component download is reused', async () => { + vi.stubGlobal('window', undefined) + const importer = vi.fn().mockResolvedValue({ default: () => null }) + const Page = lazyRouteComponent(importer) + + const preload = Page.preload?.() + await preload + + expect(Page.preload?.()).toBe(preload) + expect(importer).toHaveBeenCalledTimes(1) +}) + test('a failed component download is retried from the route error UI', async () => { vi.spyOn(console, 'error').mockImplementation(() => {}) diff --git a/packages/router-core/src/load-server.ts b/packages/router-core/src/load-server.ts index 3524312f72..4257697fd0 100644 --- a/packages/router-core/src/load-server.ts +++ b/packages/router-core/src/load-server.ts @@ -511,25 +511,39 @@ async function loadNormalChunks( end: number, signal?: AbortSignal, ): Promise { - const chunks = lane.matches.map(async (match, index) => { + const chunks: Array> = [] + for (let index = 0; index < lane.matches.length; index++) { + const match = lane.matches[index]! if (index >= end || match.ssr !== true || match.status !== 'success') { - return undefined + continue } const route = getRoute(router, match) try { - await loadRouteChunk(route) + const loading = loadRouteChunk(route) + if (loading) { + chunks.push( + loading.then( + () => { + signal?.throwIfAborted() + return undefined + }, + (cause) => { + signal?.throwIfAborted() + return [ + index, + stampNotFound(match, normalizeError(route, cause)), + ] as IndexedOutcome + }, + ), + ) + } } catch (cause) { signal?.throwIfAborted() - return [ - index, - stampNotFound(match, normalizeError(route, cause)), - ] as IndexedOutcome + chunks.push([index, stampNotFound(match, normalizeError(route, cause))]) } - signal?.throwIfAborted() - return undefined - }) + } for (const chunk of chunks) { - const indexed = await chunk + const indexed = Array.isArray(chunk) ? chunk : await chunk if (indexed) { return indexed } diff --git a/packages/solid-router/src/Match.tsx b/packages/solid-router/src/Match.tsx index 28d51d6502..8a400a8580 100644 --- a/packages/solid-router/src/Match.tsx +++ b/packages/solid-router/src/Match.tsx @@ -41,11 +41,15 @@ export const Match = (props: { routeId: string }) => { const route: AnyRoute = router.routesById[props.routeId] - // Lazy route option mutations become observable with the next match publication. - const routeOptions = () => { - currentMatch() - return route.options - } + // Lazy route option mutations become observable with the next client match + // publication. Server stores are non-reactive and options load before render. + const routeOptions = + (isServer ?? router.isServer) + ? () => route.options + : () => { + currentMatch() + return route.options + } const resolvePendingComponent = () => routeOptions().pendingComponent ?? router.options.defaultPendingComponent diff --git a/packages/solid-router/src/lazyRouteComponent.tsx b/packages/solid-router/src/lazyRouteComponent.tsx index 4c842bbe61..64bf129337 100644 --- a/packages/solid-router/src/lazyRouteComponent.tsx +++ b/packages/solid-router/src/lazyRouteComponent.tsx @@ -1,6 +1,7 @@ import { Dynamic } from 'solid-js/web' import { createResource } from 'solid-js' import { isModuleNotFoundError } from '@tanstack/router-core' +import { isServer } from '@tanstack/router-core/isServer' import type { AsyncRouteComponent } from './route' export function lazyRouteComponent< @@ -21,7 +22,10 @@ export function lazyRouteComponent< error = undefined loadPromise = importer() .then((res) => { - loadPromise = undefined + // Keep browser preload behavior unchanged; SSR can reuse the import. + if (!(isServer ?? typeof window === 'undefined')) { + loadPromise = undefined + } comp = res[exportName ?? 'default'] return comp }) diff --git a/packages/solid-router/tests/component-preload-retry.test.tsx b/packages/solid-router/tests/component-preload-retry.test.tsx index 41ec6bbc1a..0a26f0af26 100644 --- a/packages/solid-router/tests/component-preload-retry.test.tsx +++ b/packages/solid-router/tests/component-preload-retry.test.tsx @@ -14,6 +14,31 @@ import type { ErrorComponentProps } from '../src' afterEach(() => { cleanup() vi.restoreAllMocks() + vi.unstubAllGlobals() +}) + +test('a successful server component download is reused', async () => { + vi.stubGlobal('window', undefined) + const importer = vi.fn().mockResolvedValue({ default: () => null }) + const Page = lazyRouteComponent(importer) + + const preload = Page.preload?.() + await preload + + expect(Page.preload?.()).toBe(preload) + expect(importer).toHaveBeenCalledTimes(1) +}) + +test('a component loads when rendered before preload', async () => { + const importer = vi.fn().mockResolvedValue({ + default: () =>
Page content
, + }) + const Page = lazyRouteComponent(importer) + + render(() => ) + + expect(await screen.findByText('Page content')).toBeInTheDocument() + expect(importer).toHaveBeenCalledTimes(1) }) test('a failed component download is retried from the route error UI', async () => { From da82a47081677b84f110dd5ba8c56ef12e48e6b3 Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Wed, 22 Jul 2026 07:29:01 +0000 Subject: [PATCH 50/59] ci: apply automated fixes --- docs/router/guide/internationalization-i18n.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/router/guide/internationalization-i18n.md b/docs/router/guide/internationalization-i18n.md index d5147ba6bf..6b09c66280 100644 --- a/docs/router/guide/internationalization-i18n.md +++ b/docs/router/guide/internationalization-i18n.md @@ -188,7 +188,7 @@ export default { ```tsx import { getLocale } from '../paraglide/runtime' - +; ``` --- From f84d087783853e42a7708647ac5cb535ddb68f70 Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Wed, 22 Jul 2026 07:31:02 +0000 Subject: [PATCH 51/59] ci: apply automated fixes (attempt 2/3) --- docs/router/guide/internationalization-i18n.md | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/router/guide/internationalization-i18n.md b/docs/router/guide/internationalization-i18n.md index 6b09c66280..f6fd04087e 100644 --- a/docs/router/guide/internationalization-i18n.md +++ b/docs/router/guide/internationalization-i18n.md @@ -187,7 +187,6 @@ export default { ```tsx import { getLocale } from '../paraglide/runtime' - ; ``` From 90a7f3923ca7f22dd479d09d297d78bd0a1a3664 Mon Sep 17 00:00:00 2001 From: Flo Date: Thu, 23 Jul 2026 09:57:37 +0200 Subject: [PATCH 52/59] fix(router): address lane loader regressions (#7880) * fix(router): address lane loader regressions * perf(router-core): shave asset-prefix bookkeeping bytes - rename the internal `_dataOnlyAssetEnd` match field to `_assetEnd`: property keys survive minification, so the shorter internal name saves bytes at every site in every bundle - reduce the `_getAssetMatches` guard to a presence check: the field is only ever set on hydration presentation clones that already satisfy the pending/data-only/error-free/not-not-found conditions, and commits clear it (invariant documented at the guard) - clone-then-patch the hydration handoff splice instead of spreading a conditional object per element, and drop the unreachable zero guard in `_getAssetMatches` Measured (gzip, vs PR tip): react-router.full -43 B, vue-router.full -35 B, react-router.minimal -8 B. All unit suites green. Co-Authored-By: Claude Fable 5 * test(router-devtools): preload lazy panel --------- Co-authored-by: Claude Fable 5 --- packages/react-router/src/Scripts.tsx | 4 +- packages/react-router/src/Transitioner.tsx | 57 ++- .../react-router/src/headContentUtils.tsx | 4 +- packages/react-router/tests/Scripts.test.tsx | 119 ++++- ...earch-default-normalization-abort.test.tsx | 42 ++ packages/router-core/src/Matches.ts | 2 + packages/router-core/src/hydrate.ts | 63 ++- packages/router-core/src/index.ts | 2 +- packages/router-core/src/load-client.ts | 255 +++++++++- packages/router-core/src/load-server.ts | 29 +- packages/router-core/src/rendered-matches.ts | 23 + packages/router-core/src/router.ts | 8 +- .../tests/hmr-refresh-lifecycle.test.ts | 462 ++++++++++++++++++ packages/router-core/tests/hydrate.test.ts | 74 ++- .../tests/hydration-currentness.test.ts | 225 ++++++++- .../tests/rendered-matches.test.ts | 30 ++ packages/router-core/tests/routerTestUtils.ts | 8 +- .../server-chunk-failure-lifecycle.test.ts | 61 +++ packages/router-devtools-core/package.json | 4 +- .../src/BaseTanStackRouterDevtoolsPanel.tsx | 22 +- .../tests/cache-replacement.test.ts | 100 ++++ packages/router-devtools-core/tsconfig.json | 2 +- packages/router-devtools-core/vite.config.ts | 14 + packages/solid-router/src/Scripts.tsx | 4 +- packages/solid-router/src/Transitioner.tsx | 6 +- .../solid-router/src/headContentUtils.tsx | 4 +- packages/solid-router/tests/Scripts.test.tsx | 104 +++- packages/vue-router/src/Scripts.tsx | 4 +- packages/vue-router/src/Transitioner.tsx | 6 +- packages/vue-router/src/headContentUtils.tsx | 4 +- packages/vue-router/src/useMatch.tsx | 9 +- packages/vue-router/tests/Scripts.test.tsx | 98 +++- packages/vue-router/tests/useMatch.test.tsx | 38 ++ pnpm-lock.yaml | 3 + 34 files changed, 1797 insertions(+), 93 deletions(-) create mode 100644 packages/router-core/tests/hmr-refresh-lifecycle.test.ts create mode 100644 packages/router-core/tests/rendered-matches.test.ts create mode 100644 packages/router-devtools-core/tests/cache-replacement.test.ts diff --git a/packages/react-router/src/Scripts.tsx b/packages/react-router/src/Scripts.tsx index 33f4961c2a..a1b189d4c6 100644 --- a/packages/react-router/src/Scripts.tsx +++ b/packages/react-router/src/Scripts.tsx @@ -1,5 +1,5 @@ import { useStore } from '@tanstack/react-store' -import { _getRenderedMatches, deepEqual } from '@tanstack/router-core' +import { _getAssetMatches, deepEqual } from '@tanstack/router-core' import { isServer } from '@tanstack/router-core/isServer' import { Asset } from './Asset' import { useRouter } from './useRouter' @@ -18,7 +18,7 @@ export const Scripts = () => { const nonce = router.options.ssr?.nonce const getScripts = (matches: Array) => { - matches = _getRenderedMatches(matches) + matches = _getAssetMatches(matches) const scripts = matches .flatMap((match) => match.scripts ?? []) .filter(Boolean) diff --git a/packages/react-router/src/Transitioner.tsx b/packages/react-router/src/Transitioner.tsx index 9f494595ae..ccf1373c0e 100644 --- a/packages/react-router/src/Transitioner.tsx +++ b/packages/react-router/src/Transitioner.tsx @@ -34,16 +34,47 @@ export function Transitioner() { current[1](true) } } - router.startTransition = (fn, expected, urgent) => - new Promise((resolve) => { - acknowledgement.current?.[1](false) - acknowledgement.current = [expected, resolve] - if (urgent) { - fn() - } else { - React.startTransition(fn) - } - }) + if (process.env.NODE_ENV === 'production') { + router.startTransition = (fn, expected, urgent) => + new Promise((resolve) => { + acknowledgement.current?.[1](false) + acknowledgement.current = [expected, resolve] + if (urgent) { + fn() + } else { + React.startTransition(fn) + } + }) + } else { + router.startTransition = (fn, expected, urgent) => + new Promise((resolve, reject) => { + acknowledgement.current?.[1](false) + const next: NonNullable = [ + expected, + resolve, + ] + acknowledgement.current = next + try { + if (urgent) { + fn() + } else { + React.startTransition(fn) + } + } catch (cause) { + if (acknowledgement.current === next) { + acknowledgement.current = undefined + } + reject(cause) + } + }) + ;( + router as typeof router & { _cancelTransition?: () => void } + )._cancelTransition = () => { + const current = acknowledgement.current + acknowledgement.current = undefined + current?.[1](false) + } + } // Subscribe before canonicalizing so the initial URL has exactly one load. useLayoutEffect(() => { @@ -74,7 +105,11 @@ export function Transitioner() { trimPathRight(location.publicHref) !== trimPathRight(nextLocation.publicHref) ) { - router.commitLocation({ ...nextLocation, replace: true }) + router.commitLocation({ + ...nextLocation, + replace: true, + ignoreBlocker: true, + }) return process.env.NODE_ENV !== 'production' ? unsub : undefined } diff --git a/packages/react-router/src/headContentUtils.tsx b/packages/react-router/src/headContentUtils.tsx index 49dd47caad..d61ca829db 100644 --- a/packages/react-router/src/headContentUtils.tsx +++ b/packages/react-router/src/headContentUtils.tsx @@ -1,7 +1,7 @@ import * as React from 'react' import { useStore } from '@tanstack/react-store' import { - _getRenderedMatches, + _getAssetMatches, appendUniqueUserTags, deepEqual, escapeHtml, @@ -23,7 +23,7 @@ function buildTagsFromMatches( matches: Array, assetCrossOrigin?: AssetCrossOriginConfig, ): Array { - matches = _getRenderedMatches(matches) + matches = _getAssetMatches(matches) const routeMeta = matches .map((match) => match.meta) .filter((meta) => meta !== undefined) diff --git a/packages/react-router/tests/Scripts.test.tsx b/packages/react-router/tests/Scripts.test.tsx index 0a3cfd4aef..893cef01bc 100644 --- a/packages/react-router/tests/Scripts.test.tsx +++ b/packages/react-router/tests/Scripts.test.tsx @@ -1,4 +1,4 @@ -import { afterEach, describe, expect, test } from 'vitest' +import { afterEach, describe, expect, test, vi } from 'vitest' import { act, cleanup, @@ -9,11 +9,14 @@ import { } from '@testing-library/react' import { createPortal } from 'react-dom' import ReactDOMServer from 'react-dom/server' +import { hydrate } from '@tanstack/router-core/ssr/client' +import { dehydrateSsrMatchId } from '../../router-core/src/ssr/ssr-match-id' import { HeadContent, Link, Outlet, + RouterContextProvider, RouterProvider, createBrowserHistory, createMemoryHistory, @@ -57,6 +60,7 @@ afterEach(() => { cleanup() browserHistories.splice(0).forEach((history) => history.destroy()) window.history.replaceState(null, 'root', '/') + delete window.$_TSR }) describe('ssr scripts', () => { @@ -334,6 +338,119 @@ describe('scripts with async/defer attributes', () => { }) describe('ssr HeadContent', () => { + test('renders descendant assets during a data-only hydration handoff', async () => { + const rootRoute = createRootRoute({}) + const dataOnlyRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/report', + ssr: 'data-only', + loader: () => 'report', + }) + const childRoute = createRoute({ + getParentRoute: () => dataOnlyRoute, + path: '/details', + loader: () => 'details', + head: () => ({ + meta: [{ name: 'data-only-child', content: 'visible' }], + links: [{ rel: 'preload', href: '/data-only-head-link.js' }], + styles: [ + { + id: 'data-only-route-style', + children: '.data-only-child { color: green }', + }, + ], + scripts: [ + { + id: 'data-only-head-script', + type: 'application/json', + children: '{"source":"head"}', + }, + ], + }), + scripts: () => [ + { + id: 'data-only-body-script', + type: 'application/json', + children: '{"source":"body"}', + }, + ], + }) + const router = createRouter({ + history: createMemoryHistory({ + initialEntries: ['/report/details'], + }), + routeTree: rootRoute.addChildren([ + dataOnlyRoute.addChildren([childRoute]), + ]), + }) + const matches = router.matchRoutes(router.latestLocation) + window.$_TSR = { + router: { + dehydratedData: {}, + manifest: { + routes: { + [childRoute.id]: { + css: ['/data-only-manifest.css'], + preloads: ['/data-only-manifest.js'], + scripts: [ + { + attrs: { + id: 'data-only-manifest-script', + type: 'application/json', + }, + children: '{"source":"manifest"}', + }, + ], + }, + }, + }, + matches: matches.map((match, index) => ({ + i: dehydrateSsrMatchId(match.id), + s: 'success', + ssr: index === 1 ? 'data-only' : true, + l: index ? (index === 1 ? 'report' : 'details') : undefined, + u: Date.now(), + })), + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + } + + await hydrate(router) + + expect(router.state.matches.map((match) => match.status)).toEqual([ + 'success', + 'pending', + 'success', + ]) + render( + + + + , + ) + + expect( + document.querySelector('meta[name="data-only-child"]'), + ).not.toBeNull() + expect( + document.querySelector('link[href="/data-only-head-link.js"]'), + ).not.toBeNull() + expect(document.querySelector('#data-only-route-style')).not.toBeNull() + expect(document.querySelector('#data-only-head-script')).not.toBeNull() + expect(document.querySelector('#data-only-body-script')).not.toBeNull() + expect( + document.querySelector('link[href="/data-only-manifest.css"]'), + ).not.toBeNull() + expect( + document.querySelector('link[href="/data-only-manifest.js"]'), + ).not.toBeNull() + expect(document.querySelector('#data-only-manifest-script')).not.toBeNull() + }) + test('derives title, dedupes meta, and allows non-loader HeadContent', async () => { const rootRoute = createRootRoute({ loader: () => diff --git a/packages/react-router/tests/issue-6371-search-default-normalization-abort.test.tsx b/packages/react-router/tests/issue-6371-search-default-normalization-abort.test.tsx index 2c29748040..811447a89a 100644 --- a/packages/react-router/tests/issue-6371-search-default-normalization-abort.test.tsx +++ b/packages/react-router/tests/issue-6371-search-default-normalization-abort.test.tsx @@ -127,3 +127,45 @@ test('#6371: initial search defaults produce one live canonical loader', async ( }) } }) + +test('initial canonicalization bypasses existing navigation blockers', async () => { + const loader = vi.fn( + ({ location }: { location: { href: string } }) => location.href, + ) + const rootRoute = createRootRoute({ + component: () => , + }) + const aboutRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/about', + validateSearch: (search: Record) => ({ + page: typeof search.page === 'number' ? search.page : 1, + }), + loader, + component: () =>
{aboutRoute.useLoaderData()}
, + }) + const history = createMemoryHistory({ initialEntries: ['/about'] }) + const blockerFn = vi.fn(() => true) + const unblock = history.block({ + blockerFn, + enableBeforeUnload: false, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([aboutRoute]), + history, + }) + + try { + render() + + expect(await screen.findByText('/about?page=1')).toBeInTheDocument() + expect(loader).toHaveBeenCalledTimes(1) + expect(history.location.href).toBe('/about?page=1') + expect(router.latestLocation.href).toBe('/about?page=1') + expect(router.state.location.href).toBe('/about?page=1') + expect(router.state.resolvedLocation?.href).toBe('/about?page=1') + expect(blockerFn).not.toHaveBeenCalled() + } finally { + unblock() + } +}) diff --git a/packages/router-core/src/Matches.ts b/packages/router-core/src/Matches.ts index 1ac8d9c1b9..41fd4018b5 100644 --- a/packages/router-core/src/Matches.ts +++ b/packages/router-core/src/Matches.ts @@ -138,6 +138,8 @@ export interface RouteMatch< searchError: unknown updatedAt: number loaderData?: TLoaderData + /** @internal Exclusive end of the SSR-verified asset prefix. */ + _assetEnd?: number /** @internal */ _ctx?: Record /** @internal */ diff --git a/packages/router-core/src/hydrate.ts b/packages/router-core/src/hydrate.ts index 53977d9055..f8b67cfafe 100644 --- a/packages/router-core/src/hydrate.ts +++ b/packages/router-core/src/hydrate.ts @@ -104,7 +104,10 @@ export async function hydrate(router: AnyRouter): Promise { } const committed: Array = [] let pendingBoundary: number | undefined + let verifiedAssetEnd = 0 const retryFrom = (index: number) => { + // The failing route's identity is still verified, but no descendant is. + verifiedAssetEnd = Math.min(verifiedAssetEnd, index + 1) const removed = committed.splice(index) for (const match of removed) { if ( @@ -145,12 +148,19 @@ export async function hydrate(router: AnyRouter): Promise { pendingBoundary ??= index break } - if ('l' in dehydrated) { + verifiedAssetEnd = index + 1 + const route = getRoute(router, candidate) + if ( + 'l' in dehydrated || + (dehydrated.s === 'success' && + dehydrated.e === undefined && + route.options.loader) + ) { candidate.loaderData = dehydrated.l } candidate.status = dehydrated.s candidate.ssr = dehydrated.ssr - getRoute(router, candidate).options.ssr = candidate.ssr + route.options.ssr = candidate.ssr candidate.updatedAt = dehydrated.u candidate.error = dehydrated.e candidate._notFound ||= dehydrated.g @@ -176,6 +186,7 @@ export async function hydrate(router: AnyRouter): Promise { pendingBoundary ??= index } } + let verifiedContextEnd = verifiedAssetEnd if ( !isTerminal && @@ -226,15 +237,18 @@ export async function hydrate(router: AnyRouter): Promise { return } if (chunkFailure < committed.length) { + verifiedContextEnd = Math.min(verifiedContextEnd, chunkFailure) retryFrom(chunkFailure) } // The first pending match is already visible, so prepare its route context // without granting its beforeLoad or loader any hydration authority. - const contextEnd = + const contextEnd = Math.max( pendingBoundary === committed.length ? committed.length + 1 - : committed.length + : committed.length, + verifiedContextEnd, + ) for (let index = 0; index < contextEnd; index++) { const match = candidates[index]! const route = getRoute(router, match) @@ -286,7 +300,7 @@ export async function hydrate(router: AnyRouter): Promise { [location, candidates] as any, controller.signal, 0, - committed.length, + verifiedAssetEnd, ) if (!isCurrent()) { return @@ -296,13 +310,23 @@ export async function hydrate(router: AnyRouter): Promise { const committedMatches = isTerminal && committed.length === shared ? candidates : committed let presented = needsClientLoad ? candidates : committedMatches + let dataOnlyAssetEnd: number | undefined if (needsClientLoad && pendingBoundary !== undefined) { + const boundary = presented[pendingBoundary]! + dataOnlyAssetEnd = + boundary.status === 'success' && + boundary.ssr === 'data-only' && + boundary.error === undefined && + !boundary._notFound && + verifiedAssetEnd > pendingBoundary + 1 + ? verifiedAssetEnd + : undefined presented = presented.slice() presented[pendingBoundary] = { - ...presented[pendingBoundary]!, + ...boundary, status: 'pending', - ssr: - presented[pendingBoundary]!.ssr === 'data-only' ? 'data-only' : false, + ssr: boundary.ssr === 'data-only' ? 'data-only' : false, + _assetEnd: dataOnlyAssetEnd, } } @@ -332,14 +356,21 @@ export async function hydrate(router: AnyRouter): Promise { controller.abort() return } - transferMatchResources( - router, - matches.splice( - 0, - prefix, - ...committedMatches.map((match) => ({ ...match })), - ), - ) + let handoffAssetEnd = dataOnlyAssetEnd + if (handoffAssetEnd !== undefined) { + for (let index = prefix; index < handoffAssetEnd; index++) { + if (candidates[index]?.id !== matches[index]?.id) { + handoffAssetEnd = + index > (pendingBoundary ?? -1) + 1 ? index : undefined + break + } + } + } + const clones = committedMatches.map((match) => ({ ...match })) + if (handoffAssetEnd !== undefined) { + clones[pendingBoundary!]!._assetEnd = handoffAssetEnd + } + transferMatchResources(router, matches.splice(0, prefix, ...clones)) for (let index = prefix; index < matches.length; index++) { const match = matches[index]! const hydrated = candidates[index] diff --git a/packages/router-core/src/index.ts b/packages/router-core/src/index.ts index 7ec095147c..946f18b6ca 100644 --- a/packages/router-core/src/index.ts +++ b/packages/router-core/src/index.ts @@ -103,7 +103,7 @@ export { resolveManifestCssLink, } from './manifest' export { isMatch } from './Matches' -export { _getRenderedMatches } from './rendered-matches' +export { _getAssetMatches, _getRenderedMatches } from './rendered-matches' export type { AnyMatchAndValue, FindValueByIndex, diff --git a/packages/router-core/src/load-client.ts b/packages/router-core/src/load-client.ts index acb10f280c..8b5e28ca43 100644 --- a/packages/router-core/src/load-client.ts +++ b/packages/router-core/src/load-client.ts @@ -97,6 +97,9 @@ export type LoadTransaction = [ matches: Array, startedAt: number, done: Promise, + refresh?: true, + refreshPresentation?: Array, + refreshHandoff?: NonNullable, ] export type PendingSession = [ @@ -112,6 +115,17 @@ export type PendingSession = [ type CoordinatorRouter = AnyRouter & { /** Whole speculative lanes that a matching navigation may adopt. */ _preloads?: Map + _refreshNextLoad?: boolean + _rollbackRefresh?: () => void + _cancelTransition?: () => void +} + +type PublicationCheckpoint = { + previousMatches: Array + previousPresentation: Array + previousCache: Map + commitPromise: CoordinatorRouter['_commitPromise'] + published: boolean } type LoaderTask = [ @@ -1331,11 +1345,15 @@ function commitMatches( router: CoordinatorRouter, tx: LoadTransaction, matches: Array, + resolvedPrefix?: number, ): void { const previous = router._committed const previousCached = router._cache for (const match of matches) { match.preload = false + if (resolvedPrefix) { + match._assetEnd = undefined + } } const rendered = _getRenderedMatches(matches) const cached = new Map() @@ -1384,6 +1402,155 @@ function commitMatches( runRouteLifecycle(router, previous, matches, () => router._tx === tx) } +function commitRefreshMatches( + router: CoordinatorRouter, + tx: LoadTransaction, + matches: Array, + checkpoint: PublicationCheckpoint, +): void { + const previous = router._committed + const previousCached = router._cache + for (const match of matches) { + match.preload = false + } + const cached = new Map() + // Delay releasing the previous owners until the HMR render is acknowledged. + // Old generations must not become reusable cache entries after refresh. + tx[3] = [] + router._cache = cached + checkpoint.previousMatches = previous + checkpoint.previousCache = previousCached + checkpoint.published = true + publishMatches(router, matches) + if (!checkpoint.published || router._tx !== tx) { + return + } + runRouteLifecycle(router, previous, matches, () => router._tx === tx) +} + +function settlePublication( + router: CoordinatorRouter, + checkpoint: PublicationCheckpoint, +): void { + if (!checkpoint.published) { + return + } + checkpoint.published = false + transferMatchResources( + router, + [...checkpoint.previousCache.values(), ...checkpoint.previousMatches], + [...router._cache.values(), ...router._committed], + ) +} + +function rollbackPublication( + router: CoordinatorRouter, + tx: LoadTransaction, + lane: ProjectedLane, + checkpoint: PublicationCheckpoint, +): boolean { + if ( + !checkpoint.published || + router._tx !== tx || + router._committed !== lane[1] + ) { + settlePublication(router, checkpoint) + return false + } + + const discarded = [...router._cache.values(), ...router._committed] + const restored = [ + ...checkpoint.previousCache.values(), + ...checkpoint.previousMatches, + ] + router._cache = checkpoint.previousCache + router._committed = checkpoint.previousMatches + checkpoint.published = false + + for (const match of discarded as Array) { + if ( + !restored.includes(match) && + match._flight && + router._flights?.get(match.id) === match._flight + ) { + router._flights.delete(match.id) + } + } + + finishPending(router, tx) + router.batch(() => { + router.stores.status.set('idle') + router.stores.setMatches(checkpoint.previousPresentation) + }) + tx[0].abort() + transferMatchResources(router, discarded, restored) + discardBackground(router, lane) + if (router._tx === tx && router._commitPromise === checkpoint.commitPromise) { + router._commitPromise?.resolve() + router._commitPromise = undefined + } + return true +} + +async function transitionRefresh( + router: CoordinatorRouter, + tx: LoadTransaction, + lane: ProjectedLane, + changeInfo: ReturnType, +): Promise { + const checkpoint: PublicationCheckpoint = { + previousMatches: router._committed, + previousPresentation: tx[7] ?? router.stores.matches.get(), + previousCache: router._cache, + commitPromise: router._commitPromise, + published: false, + } + const commit = () => { + finishPending(router, tx) + router._rollbackRefresh = rollback + commitRefreshMatches(router, tx, lane[1], checkpoint) + if (!checkpoint.published || router._tx !== tx) { + return + } + router.emit({ type: 'onLoad', ...changeInfo }) + if (router._tx === tx) { + router.emit({ type: 'onBeforeRouteMount', ...changeInfo }) + } + } + const rollback = () => { + if (router._rollbackRefresh === rollback) { + router._rollbackRefresh = undefined + } + const restored = rollbackPublication(router, tx, lane, checkpoint) + router._cancelTransition?.() + return restored + } + try { + const rendered = await router.startTransition(commit, lane[1]) + if (router._rollbackRefresh === rollback) { + router._rollbackRefresh = undefined + } + if (checkpoint.published) { + const handoff = tx[8] + if (handoff && router._handoff === handoff) { + handoff[1]() + } + if (router._tx === tx) { + tx[6] = undefined + tx[7] = undefined + tx[8] = undefined + } + } + settlePublication(router, checkpoint) + return rendered + } catch (cause) { + if (rollback()) { + return + } + throw cause + } +} + async function awaitCurrent( router: CoordinatorRouter, owner?: LoadTransaction, @@ -1543,6 +1710,9 @@ async function runClientTransaction( transferMatchResources(router, tx[3]) tx[3] = [] if (router._tx === tx) { + if (process.env.NODE_ENV !== 'production' && tx[6]) { + router._refreshNextLoad = true + } await followRedirect(router, tx, result[1]) } } else { @@ -1603,7 +1773,7 @@ async function runClientTransaction( } const commit = () => { finishPending(router, tx) - commitMatches(router, tx, result[1]) + commitMatches(router, tx, result[1], resolvedPrefix) if (router._tx !== tx) { return } @@ -1612,7 +1782,17 @@ async function runClientTransaction( router.emit({ type: 'onBeforeRouteMount', ...changeInfo }) } } - const rendered = await router.startTransition(commit, result[1]) + const rendered = + process.env.NODE_ENV !== 'production' && tx[6] + ? await transitionRefresh(router, tx, result, changeInfo) + : await router.startTransition(commit, result[1]) + if ( + process.env.NODE_ENV !== 'production' && + tx[6] && + rendered === undefined + ) { + return + } if (router._tx !== tx) { discardBackground(router, result) return @@ -1647,6 +1827,14 @@ export async function loadClientRoute( router: CoordinatorRouter, opts?: { sync?: boolean }, ): Promise { + let rematerialize = false + if (process.env.NODE_ENV !== 'production') { + router._rollbackRefresh?.() + rematerialize = !!router._refreshNextLoad || !!router._tx?.[6] + } + const refreshPresentation = rematerialize + ? router.stores.matches.get() + : undefined const previousOwner = router._tx const resolvedLocation = router.stores.resolvedLocation.get() const previousLocation = resolvedLocation ?? router.stores.location.get() @@ -1659,11 +1847,11 @@ export async function loadClientRoute( ? (pendingLocation._redirects ?? 0) : 0 const handoff = router._handoff - const hydrationController = handoff?.[0]() + const hydrationController = rematerialize ? undefined : handoff?.[0]() const preflight = new AbortController() const previousPreflight = router._preflight router._preflight = preflight - if (!hydrationController) { + if (!rematerialize && !hydrationController) { handoff?.[1]() } previousPreflight?.abort() @@ -1685,6 +1873,16 @@ export async function loadClientRoute( const sameHref = previousLocation.href === location.href let adopted = router._preloads?.get(location.href) let retained: ActivePreload | undefined + if (rematerialize && adopted) { + router._preloads!.delete(location.href) + discardPreload(router, adopted) + adopted = undefined + if (preflight.signal.aborted || router._tx !== previousOwner) { + preflight.abort() + await awaitCurrent(router, previousOwner) + return + } + } if ( adopted && (hydrationController || @@ -1710,7 +1908,13 @@ export async function loadClientRoute( router._preloads!.delete(location.href) } else { try { - matches = router.matchRoutes(location, { _controller: preflight }) + matches = + process.env.NODE_ENV !== 'production' && rematerialize + ? router.matchRoutes(location, { + _controller: preflight, + _rematerialize: true, + }) + : router.matchRoutes(location, { _controller: preflight }) acquireMatchResources(matches) } catch (cause) { preflight.abort() @@ -1718,6 +1922,9 @@ export async function loadClientRoute( discardPreload(router, retained) } if (!isRedirect(cause)) { + if (process.env.NODE_ENV !== 'production' && rematerialize) { + router._refreshNextLoad = undefined + } await awaitCurrent(router) router._commitPromise?.resolve() router._commitPromise = undefined @@ -1771,8 +1978,14 @@ export async function loadClientRoute( } }), ] + if (process.env.NODE_ENV !== 'production' && rematerialize) { + tx[6] = true + tx[7] = refreshPresentation + tx[8] = handoff + router._refreshNextLoad = undefined + } router._tx = tx - if (router._handoff === handoff) { + if (!rematerialize && router._handoff === handoff) { router._handoff = undefined } if (previousOwner) { @@ -1806,20 +2019,22 @@ export async function loadClientRoute( } } -export function refreshClientRoute(router: CoordinatorRouter): Promise { - if (router._flights) { - const flights = [...router._flights.values()] - router._flights.clear() - for (const flight of flights) { - flight[1].abort() +export async function refreshClientRoute( + router: CoordinatorRouter, +): Promise { + router._rollbackRefresh?.() + const pending = router._tx + if (pending && !pending[6] && router.stores.status.get() === 'pending') { + await pending[5] + if (router._tx !== pending) { + await awaitCurrent(router, pending) } } - const committed = router._committed - router._committed = [] + // Existing owners remain alive for rollback but cannot donate stale work. + router._flights?.clear() router.clearCache() - transferMatchResources(router, committed) - - return router.load({ sync: true }) + router._refreshNextLoad = true + await loadClientRoute(router, { sync: true }) } function followPreloadRedirect( @@ -1855,6 +2070,12 @@ export async function preloadClientRoute( return } const owner = router._tx + if ( + process.env.NODE_ENV !== 'production' && + (router._refreshNextLoad || owner?.[6]) + ) { + return + } const location = opts._builtLocation ?? router.buildLocation(opts) const base = router._committed const controller = new AbortController() diff --git a/packages/router-core/src/load-server.ts b/packages/router-core/src/load-server.ts index 4257697fd0..cc2a796b98 100644 --- a/packages/router-core/src/load-server.ts +++ b/packages/router-core/src/load-server.ts @@ -521,21 +521,22 @@ async function loadNormalChunks( try { const loading = loadRouteChunk(route) if (loading) { - chunks.push( - loading.then( - () => { - signal?.throwIfAborted() - return undefined - }, - (cause) => { - signal?.throwIfAborted() - return [ - index, - stampNotFound(match, normalizeError(route, cause)), - ] as IndexedOutcome - }, - ), + const chunk = loading.then( + () => { + signal?.throwIfAborted() + return undefined + }, + (cause) => { + signal?.throwIfAborted() + return [ + index, + stampNotFound(match, normalizeError(route, cause)), + ] as IndexedOutcome + }, ) + // Route-order reduction can return before later chunks settle. + void chunk.catch(() => {}) + chunks.push(chunk) } } catch (cause) { signal?.throwIfAborted() diff --git a/packages/router-core/src/rendered-matches.ts b/packages/router-core/src/rendered-matches.ts index 8ce8c0803f..3534279312 100644 --- a/packages/router-core/src/rendered-matches.ts +++ b/packages/router-core/src/rendered-matches.ts @@ -10,3 +10,26 @@ export function _getRenderedMatches( ) + 1 return end && end < matches.length ? matches.slice(0, end) : matches } + +/** Return the lane whose document assets belong to the current presentation. */ +export function _getAssetMatches( + matches: Array, +): Array { + let end = matches.length + for (let index = 0; index < end; index++) { + const match = matches[index]! + // `_assetEnd` is only ever set on hydration presentation clones that are + // `status: 'pending'`, `ssr: 'data-only'`, error-free, and not not-found + // (see hydrate.ts), and commits clear it — so its presence alone is the guard. + if (match._assetEnd !== undefined) { + end = Math.min(end, Math.max(index + 1, match._assetEnd)) + continue + } + if (match.status !== 'success' || match._notFound) { + end = index + 1 + break + } + } + // `end` only ever shrinks to `index + 1 >= 1`, so no zero guard is needed. + return end < matches.length ? matches.slice(0, end) : matches +} diff --git a/packages/router-core/src/router.ts b/packages/router-core/src/router.ts index 1183407b7c..4d26bd7173 100644 --- a/packages/router-core/src/router.ts +++ b/packages/router-core/src/router.ts @@ -626,6 +626,8 @@ export interface MatchRoutesOpts { throwOnError?: boolean /** @internal */ _controller?: AbortController + /** @internal */ + _rematerialize?: boolean } function routeNeedsLoad(route: AnyRoute): unknown { @@ -1629,8 +1631,10 @@ export class RouterCore< const previousMatch = previousAt(route, index) const existingMatch = - this._cache.get(matchId) ?? - (previousMatch?.id === matchId ? previousMatch : undefined) + process.env.NODE_ENV !== 'production' && opts?._rematerialize + ? undefined + : (this._cache.get(matchId) ?? + (previousMatch?.id === matchId ? previousMatch : undefined)) const strictParams = existingMatch?._strictParams ?? usedParams diff --git a/packages/router-core/tests/hmr-refresh-lifecycle.test.ts b/packages/router-core/tests/hmr-refresh-lifecycle.test.ts new file mode 100644 index 0000000000..2807c05951 --- /dev/null +++ b/packages/router-core/tests/hmr-refresh-lifecycle.test.ts @@ -0,0 +1,462 @@ +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { + BaseRootRoute, + BaseRoute, + createControlledPromise, + redirect, +} from '../src' +import { createTestRouter } from './routerTestUtils' + +beforeEach(() => { + vi.spyOn(window, 'scrollTo').mockImplementation(() => {}) +}) + +afterEach(() => { + vi.restoreAllMocks() +}) + +describe('HMR route refresh', () => { + test('reloads retained routes with onStay lifecycle semantics', async () => { + let generation = 1 + const loader = vi.fn(() => generation) + const onEnter = vi.fn() + const onLeave = vi.fn() + const order: Array = [] + const onStay = vi.fn(() => order.push('onStay')) + const rootRoute = new BaseRootRoute({}) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + loader, + onEnter, + onLeave, + onStay, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + await router.load() + const unsubLoad = router.subscribe('onLoad', () => order.push('onLoad')) + const unsubMount = router.subscribe('onBeforeRouteMount', () => + order.push('onBeforeRouteMount'), + ) + generation = 2 + await router._refreshRoute!() + + expect(loader).toHaveBeenCalledTimes(2) + expect(router.state.matches.at(-1)?.loaderData).toBe(2) + expect(onEnter).toHaveBeenCalledTimes(1) + expect(onLeave).not.toHaveBeenCalled() + expect(onStay).toHaveBeenCalledTimes(1) + expect(order).toEqual(['onStay', 'onLoad', 'onBeforeRouteMount']) + unsubLoad() + unsubMount() + }) + + test('retires refresh mode after an acknowledged publication', async () => { + const otherLoader = vi.fn(() => 'other data') + const rootRoute = new BaseRootRoute({}) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + }) + const otherRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/other', + loader: otherLoader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute, otherRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + await router.load() + await router._refreshRoute!() + await router.preloadRoute({ to: '/other' }) + + expect(router._tx?.[6]).toBeUndefined() + expect(otherLoader).toHaveBeenCalledOnce() + }) + + test('passes rematerialization to a reentrant preflight load', async () => { + let generation = 1 + const loader = vi.fn(() => generation) + const rootRoute = new BaseRootRoute({}) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + staleTime: Infinity, + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + await router.load() + generation = 2 + let reenter = true + let reentrantLoad: Promise | undefined + const unsubscribe = router.subscribe('onBeforeNavigate', () => { + if (reenter) { + reenter = false + reentrantLoad = router.load({ sync: true }) + } + }) + try { + await router._refreshRoute!() + await reentrantLoad + } finally { + unsubscribe() + } + + expect(loader).toHaveBeenCalledTimes(2) + expect(router.state.matches.at(-1)?.loaderData).toBe(2) + }) + + test('passes rematerialization to a load that supersedes refresh work', async () => { + let generation = 1 + let reenter = false + let reentrantLoad: Promise | undefined + let router!: ReturnType + const loader = vi.fn(() => { + if (reenter) { + reenter = false + reentrantLoad = router.load({ sync: true }) + } + return generation + }) + const rootRoute = new BaseRootRoute({}) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + staleTime: Infinity, + loader, + }) + router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + await router.load() + generation = 2 + reenter = true + await router._refreshRoute!() + await reentrantLoad + + expect(loader).toHaveBeenCalledTimes(3) + expect(router.state.matches.at(-1)?.loaderData).toBe(2) + }) + + test('passes rematerialization through a refresh redirect', async () => { + let generation = 1 + let shouldRedirect = false + const rootLoader = vi.fn(() => generation) + const rootRoute = new BaseRootRoute({ + staleTime: Infinity, + loader: rootLoader, + }) + const sourceRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/source', + beforeLoad: () => { + if (shouldRedirect) { + throw redirect({ to: '/target' }) + } + }, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([sourceRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/source'] }), + }) + + await router.load() + generation = 2 + shouldRedirect = true + await router._refreshRoute!() + + expect(router.state.location.pathname).toBe('/target') + expect(rootLoader).toHaveBeenCalledTimes(2) + expect(router.state.matches[0]?.loaderData).toBe(2) + }) + + test('restores the committed presentation when publication fails', async () => { + let generation = 1 + const rootRoute = new BaseRootRoute({}) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + loader: () => generation, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + await router.load() + const previousMatches = router.state.matches + generation = 2 + const startTransition = router.startTransition + router.startTransition = async (fn) => { + fn() + router.clearCache() + throw new Error('render failed') + } + + await router._refreshRoute!() + + expect(router.state.status).toBe('idle') + expect(router.state.matches).toHaveLength(previousMatches.length) + expect(router.state.matches.at(-1)?.loaderData).toBe(1) + + router.startTransition = startTransition + generation = 3 + await router._refreshRoute!() + expect(router.state.matches.at(-1)?.loaderData).toBe(3) + }) + + test('keeps the rendered generation alive until refresh is acknowledged', async () => { + let generation = 1 + const signals: Array = [] + const rootRoute = new BaseRootRoute({}) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + loader: ({ abortController }) => { + signals.push(abortController.signal) + return generation + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + await router.load() + const renderedSignal = signals[0]! + generation = 2 + const startTransition = router.startTransition + router.startTransition = async (fn) => { + fn() + throw new Error('render failed') + } + + await router._refreshRoute!() + + expect(renderedSignal.aborted).toBe(false) + expect(signals[1]?.aborted).toBe(true) + expect(router.state.matches.at(-1)?.loaderData).toBe(1) + + router.startTransition = startTransition + generation = 3 + await router._refreshRoute!() + expect(renderedSignal.aborted).toBe(true) + expect(router.state.matches.at(-1)?.loaderData).toBe(3) + }) + + test('rolls overlapping refreshes back to the last acknowledged generation', async () => { + let generation = 1 + const rootRoute = new BaseRootRoute({}) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + loader: () => generation, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + await router.load() + let transitionCount = 0 + let supersedeFirst!: () => void + router.startTransition = (fn) => { + transitionCount++ + fn() + if (transitionCount === 1) { + return new Promise((resolve) => { + supersedeFirst = () => resolve(false) + }) + } + return Promise.reject(new Error('replacement render failed')) + } + ;( + router as typeof router & { _cancelTransition?: () => void } + )._cancelTransition = () => supersedeFirst() + + generation = 2 + const firstRefresh = router._refreshRoute!() + await vi.waitFor(() => expect(transitionCount).toBe(1)) + + generation = 3 + const secondRefresh = router._refreshRoute!() + await Promise.all([firstRefresh, secondRefresh]) + + expect(router.state.status).toBe('idle') + expect(router.state.matches.at(-1)?.loaderData).toBe(1) + }) + + test('does not resolve a superseding navigation promise during rollback', async () => { + let generation = 1 + const destinationGate = createControlledPromise() + const rootRoute = new BaseRootRoute({}) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + loader: () => generation, + }) + const destinationRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/destination', + loader: () => destinationGate, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute, destinationRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + await router.load() + let transitionCount = 0 + let cancelRefresh!: () => void + router.startTransition = (fn) => { + transitionCount++ + fn() + if (transitionCount === 1) { + return new Promise((resolve) => { + cancelRefresh = () => resolve(false) + }) + } + return Promise.resolve(true) + } + ;( + router as typeof router & { _cancelTransition?: () => void } + )._cancelTransition = () => cancelRefresh() + + generation = 2 + const refresh = router._refreshRoute!() + await vi.waitFor(() => expect(transitionCount).toBe(1)) + + const navigationSettled = vi.fn() + const navigation = router + .navigate({ to: '/destination' }) + .then(navigationSettled) + await vi.waitFor(() => + expect(router.state.location.pathname).toBe('/destination'), + ) + expect(navigationSettled).not.toHaveBeenCalled() + + destinationGate.resolve() + await Promise.all([refresh, navigation]) + expect(navigationSettled).toHaveBeenCalledOnce() + expect(router.state.matches.at(-1)?.routeId).toBe(destinationRoute.id) + }) + + test('waits for an ordinary pending navigation before refreshing', async () => { + const destinationGate = createControlledPromise() + const rootRoute = new BaseRootRoute({}) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + }) + const destinationRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/destination', + pendingMs: 0, + pendingMinMs: 0, + pendingComponent: () => null, + loader: () => destinationGate, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute, destinationRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + await router.load() + const navigation = router.navigate({ to: '/destination' }) + await vi.waitFor(() => { + expect(router.state.status).toBe('pending') + expect(router.state.matches.at(-1)?.routeId).toBe(destinationRoute.id) + }) + destinationRoute.options.onStay = () => { + throw new Error('refreshed destination failed') + } + const refreshSettled = vi.fn() + const refresh = router._refreshRoute!().then(refreshSettled) + await Promise.resolve() + expect(refreshSettled).not.toHaveBeenCalled() + + destinationGate.resolve() + await Promise.all([navigation, refresh]) + + expect(router.state.status).toBe('idle') + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: destinationRoute.id, + status: 'success', + }) + expect(refreshSettled).toHaveBeenCalledOnce() + }) + + test('rolls back when an HMR lifecycle callback throws', async () => { + let generation = 1 + const rootRoute = new BaseRootRoute({}) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + loader: () => generation, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + await router.load() + generation = 2 + pageRoute.options.onStay = () => { + throw new Error('lifecycle failed') + } + + await router._refreshRoute!() + + expect(router.state.status).toBe('idle') + expect(router.state.matches.at(-1)?.loaderData).toBe(1) + + pageRoute.options.onStay = undefined + generation = 3 + await router._refreshRoute!() + expect(router.state.matches.at(-1)?.loaderData).toBe(3) + }) + + test('does not adopt a preload created by HMR preflight hooks', async () => { + let generation = 1 + const rootRoute = new BaseRootRoute({}) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + loader: () => generation, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + await router.load() + generation = 2 + const unsubscribe = router.subscribe('onBeforeLoad', () => { + void router.preloadRoute({ to: '/page' }) + }) + try { + await router._refreshRoute!() + } finally { + unsubscribe() + } + + expect(router.state.matches.at(-1)?.loaderData).toBe(2) + }) +}) diff --git a/packages/router-core/tests/hydrate.test.ts b/packages/router-core/tests/hydrate.test.ts index 1ceabfd309..7ecec4a4e5 100644 --- a/packages/router-core/tests/hydrate.test.ts +++ b/packages/router-core/tests/hydrate.test.ts @@ -4,6 +4,7 @@ import { createMemoryHistory } from '@tanstack/history' import { BaseRootRoute, BaseRoute, + _getAssetMatches, createSerializationAdapter, isNotFound, notFound, @@ -218,7 +219,7 @@ describe('hydrate', () => { expect(clientLoader).not.toHaveBeenCalled() }) - it('omits undefined loader data from hydrated matches', async () => { + it('restores undefined loader data without serializing it', async () => { const serverRootRoute = new BaseRootRoute({}) const serverRoute = new BaseRoute({ getParentRoute: () => serverRootRoute, @@ -255,7 +256,71 @@ describe('hydrate', () => { routeId: clientRoute.id, status: 'success', }) - expect(match).not.toHaveProperty('loaderData') + expect(match).toHaveProperty('loaderData', undefined) + }) + + it('preserves successful undefined loader data when selecting a later failure', async () => { + const serverRootRoute = new BaseRootRoute({}) + const serverParentRoute = new BaseRoute({ + getParentRoute: () => serverRootRoute, + path: '/parent', + loader: () => undefined, + }) + const serverChildRoute = new BaseRoute({ + getParentRoute: () => serverParentRoute, + path: '/child', + }) + const serverRouter = createTestRouter({ + routeTree: serverRootRoute.addChildren([ + serverParentRoute.addChildren([serverChildRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + isServer: true, + }) + + mockWindow.$_TSR = await dehydrateToBootstrap(serverRouter) + expect(mockWindow.$_TSR.router?.matches[1]).not.toHaveProperty('l') + + const parentError = new Error('parent reload failed') + const childError = new Error('child guard failed') + const clientRootRoute = new BaseRootRoute({}) + const clientParentRoute = new BaseRoute({ + getParentRoute: () => clientRootRoute, + path: '/parent', + loader: () => { + throw parentError + }, + errorComponent: () => null, + }) + const clientChildRoute = new BaseRoute({ + getParentRoute: () => clientParentRoute, + path: '/child', + beforeLoad: () => { + throw childError + }, + errorComponent: () => null, + }) + const clientRouter = createTestRouter({ + routeTree: clientRootRoute.addChildren([ + clientParentRoute.addChildren([clientChildRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + isServer: false, + }) + + await hydrate(clientRouter) + await clientRouter.invalidate() + + expect( + clientRouter.state.matches.find( + (match) => match.routeId === clientParentRoute.id, + ), + ).toMatchObject({ status: 'success', error: undefined }) + expect( + clientRouter.state.matches.find( + (match) => match.routeId === clientChildRoute.id, + ), + ).toMatchObject({ status: 'error', error: childError }) }) it.each([ @@ -372,6 +437,11 @@ describe('hydrate', () => { }) expect(childContext).not.toHaveBeenCalled() expect(clientParentLoader).not.toHaveBeenCalled() + expect( + _getAssetMatches(clientRouter.state.matches).map( + (match) => match.routeId, + ), + ).toEqual([clientRootRoute.id, clientParentRoute.id]) await clientRouter.load() diff --git a/packages/router-core/tests/hydration-currentness.test.ts b/packages/router-core/tests/hydration-currentness.test.ts index 8e325533b6..8477ccfafd 100644 --- a/packages/router-core/tests/hydration-currentness.test.ts +++ b/packages/router-core/tests/hydration-currentness.test.ts @@ -1,12 +1,17 @@ import { runInNewContext } from 'node:vm' import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' import { createMemoryHistory } from '@tanstack/history' -import { BaseRootRoute, BaseRoute, createControlledPromise } from '../src' +import { + BaseRootRoute, + BaseRoute, + _getAssetMatches, + createControlledPromise, +} from '../src' import { hydrate } from '../src/ssr/client' import { attachRouterServerSsrUtils } from '../src/ssr/ssr-server' import { dehydrateSsrMatchId } from '../src/ssr/ssr-match-id' import { createTestRouter } from './routerTestUtils' -import type { AnyRouter, NavigateFn } from '../src' +import type { AnyRouteMatch, AnyRouter, NavigateFn } from '../src' import type { DehydratedRouter, TsrSsrGlobal } from '../src/ssr/types' import type { ServerManifest } from '../src/manifest' @@ -113,6 +118,160 @@ describe('hydration asset currentness', () => { expect(childLoader).not.toHaveBeenCalled() }) + test('includes an identity-verified ssr:false boundary in a data-only asset prefix', async () => { + const serverChildLoader = vi.fn(() => 'server child data') + const serverRootRoute = new BaseRootRoute({}) + const serverParentRoute = new BaseRoute({ + getParentRoute: () => serverRootRoute, + path: '/parent', + ssr: 'data-only', + }) + const serverChildRoute = new BaseRoute({ + getParentRoute: () => serverParentRoute, + path: '/child', + ssr: false, + loader: serverChildLoader, + }) + const serverTailRoute = new BaseRoute({ + getParentRoute: () => serverChildRoute, + path: '/tail', + }) + const serverRouter = createTestRouter({ + routeTree: serverRootRoute.addChildren([ + serverParentRoute.addChildren([ + serverChildRoute.addChildren([serverTailRoute]), + ]), + ]), + history: createMemoryHistory({ + initialEntries: ['/parent/child/tail'], + }), + isServer: true, + }) + mockWindow.$_TSR = await dehydrateToBootstrap(serverRouter) + expect(serverChildLoader).not.toHaveBeenCalled() + + const childContext = vi.fn(() => ({ assetSource: 'child context' })) + const childHead = vi.fn(({ match }: { match: AnyRouteMatch }) => ({ + meta: [ + { + name: 'ssr-false-boundary', + content: (match.context as { assetSource?: string }).assetSource, + }, + ], + })) + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + ssr: 'data-only', + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + ssr: false, + loader: () => 'client child data', + context: childContext, + head: childHead, + }) + const tailRoute = new BaseRoute({ + getParentRoute: () => childRoute, + path: '/tail', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([childRoute.addChildren([tailRoute])]), + ]), + history: createMemoryHistory({ + initialEntries: ['/parent/child/tail'], + }), + isServer: false, + }) + + await hydrate(router) + + expect( + _getAssetMatches(router.state.matches).map((match) => match.routeId), + ).toEqual([rootRoute.id, parentRoute.id, childRoute.id]) + expect(childContext).toHaveBeenCalledOnce() + expect(childHead).toHaveBeenCalledOnce() + expect(router.state.matches[2]?.meta).toEqual([ + { name: 'ssr-false-boundary', content: 'child context' }, + ]) + }) + + test('preserves a verified data-only asset prefix through its client continuation', async () => { + const serverRootRoute = new BaseRootRoute({}) + const serverParentRoute = new BaseRoute({ + getParentRoute: () => serverRootRoute, + path: '/parent', + ssr: 'data-only', + }) + const serverChildRoute = new BaseRoute({ + getParentRoute: () => serverParentRoute, + path: '/child', + ssr: false, + loader: () => 'server child data', + }) + const serverRouter = createTestRouter({ + routeTree: serverRootRoute.addChildren([ + serverParentRoute.addChildren([serverChildRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + isServer: true, + }) + mockWindow.$_TSR = await dehydrateToBootstrap(serverRouter) + + const childLoaderResult = createControlledPromise() + let continuationAssetEnd: number | undefined + let router!: AnyRouter + const childLoader = vi.fn(() => { + continuationAssetEnd = router._tx?.[3][1]?._assetEnd + return childLoaderResult + }) + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + ssr: 'data-only', + pendingComponent: () => null, + pendingMs: 0, + pendingMinMs: 0, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + ssr: false, + loader: childLoader, + }) + router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + isServer: false, + }) + + await hydrate(router) + const load = router.load() + + await vi.waitFor(() => { + expect(childLoader).toHaveBeenCalledOnce() + expect(router.state.status).toBe('pending') + }) + expect(continuationAssetEnd).toBe(3) + expect( + _getAssetMatches(router.state.matches).map((match) => match.routeId), + ).toEqual([rootRoute.id, parentRoute.id, childRoute.id]) + expect(router.state.matches[1]?._assetEnd).toBe(3) + + childLoaderResult.resolve('client child data') + await load + + expect(router.state.matches[1]?._assetEnd).toBeUndefined() + expect(router.state.matches[2]).toMatchObject({ + status: 'success', + loaderData: 'client child data', + }) + }) + test('settles when navigation supersedes a pending custom hydrate hook', async () => { const hydrateGate = createControlledPromise() const hydrateStarted = createControlledPromise() @@ -269,6 +428,65 @@ describe('hydration asset currentness', () => { expect(childLoader).toHaveBeenCalledTimes(1) }) + test('failed HMR restores a partial hydration presentation and handoff', async () => { + let hydrationController: AbortController | undefined + const childLoader = vi.fn(() => 'client child data') + const rootRoute = new BaseRootRoute({ + context: ({ abortController }: { abortController: AbortController }) => { + hydrationController ??= abortController + }, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/child', + ssr: false, + loader: childLoader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([childRoute]), + history: createMemoryHistory({ initialEntries: ['/child'] }), + isServer: false, + }) + const matches = router.matchRoutes(router.stores.location.get()) + installHydrationPayload(mockWindow, [ + { + i: dehydrateSsrMatchId(matches[0]!.id), + s: 'success', + ssr: true, + u: Date.now(), + }, + ]) + + await hydrate(router) + const handoff = router._handoff + const startTransition = router.startTransition + router.startTransition = async (fn) => { + fn() + throw new Error('HMR render failed') + } + + await router._refreshRoute!() + + expect(router.state.matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + childRoute.id, + ]) + expect(router.state.matches[1]).toMatchObject({ + status: 'pending', + ssr: false, + }) + expect(router._handoff).toBe(handoff) + expect(hydrationController?.signal.aborted).toBe(false) + + router.startTransition = startTransition + await router.load() + expect(router.state.matches[1]).toMatchObject({ + status: 'success', + loaderData: 'client child data', + }) + expect(childLoader).toHaveBeenCalledTimes(2) + }) + test('a synchronous context navigation prevents stale hydration assets from running', async () => { const oldHead = vi.fn(() => ({ meta: [{ title: 'Old route' }] })) const oldScripts = vi.fn(() => [ @@ -423,6 +641,9 @@ describe('hydration asset currentness', () => { expect(parentBeforeLoad).not.toHaveBeenCalled() expect(childBeforeLoad).not.toHaveBeenCalled() expect(childLoader).not.toHaveBeenCalled() + expect( + _getAssetMatches(router.state.matches).map((match) => match.routeId), + ).toEqual([rootRoute.id, parentRoute.id]) await router.load() diff --git a/packages/router-core/tests/rendered-matches.test.ts b/packages/router-core/tests/rendered-matches.test.ts new file mode 100644 index 0000000000..2a2ea362ae --- /dev/null +++ b/packages/router-core/tests/rendered-matches.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, test } from 'vitest' +import { _getAssetMatches } from '../src' +import type { AnyRouteMatch } from '../src' + +describe('_getAssetMatches', () => { + test('does not cross an ordinary data-only pending boundary', () => { + const matches = [ + { status: 'success' }, + { status: 'pending', ssr: 'data-only' }, + { status: 'success' }, + ] as Array + + expect(_getAssetMatches(matches)).toEqual(matches.slice(0, 2)) + }) + + test('limits a hydration handoff to its verified asset prefix', () => { + const matches = [ + { status: 'success' }, + { + status: 'pending', + ssr: 'data-only', + _assetEnd: 3, + }, + { status: 'success' }, + { status: 'success' }, + ] as Array + + expect(_getAssetMatches(matches)).toEqual(matches.slice(0, 3)) + }) +}) diff --git a/packages/router-core/tests/routerTestUtils.ts b/packages/router-core/tests/routerTestUtils.ts index 8078068954..413b810b95 100644 --- a/packages/router-core/tests/routerTestUtils.ts +++ b/packages/router-core/tests/routerTestUtils.ts @@ -50,10 +50,14 @@ export function createTestRouter< } /** Materialize the request-local server result as the HTTP response users see. */ -export function loadServerResponse(router: AnyRouter, path: string) { +export function loadServerResponse( + router: AnyRouter, + path: string, + signal?: AbortSignal, +) { return createRequestHandler({ createRouter: () => router, - request: new Request(`http://localhost${path}`), + request: new Request(`http://localhost${path}`, { signal }), })(({ router: loadedRouter, responseHeaders }) => { const result = loadedRouter._serverResult return new Response(null, { diff --git a/packages/router-core/tests/server-chunk-failure-lifecycle.test.ts b/packages/router-core/tests/server-chunk-failure-lifecycle.test.ts index b1aa2049a7..3cf7ec7051 100644 --- a/packages/router-core/tests/server-chunk-failure-lifecycle.test.ts +++ b/packages/router-core/tests/server-chunk-failure-lifecycle.test.ts @@ -144,6 +144,67 @@ describe('server route chunk failure lifecycle', () => { }) }) + test('does not leave later chunk rejections unhandled after request abort', async () => { + const rootError = new Error('root component failed') + const abortError = new Error('request closed') + const rootChunkGate = createControlledPromise() + const childChunkGate = createControlledPromise() + const rootChunkStarted = createControlledPromise() + const childChunkStarted = createControlledPromise() + const RootComponent = Object.assign(() => null, { + preload: () => { + rootChunkStarted.resolve() + return rootChunkGate + }, + }) + const ChildComponent = Object.assign(() => null, { + preload: () => { + childChunkStarted.resolve() + return childChunkGate + }, + }) + const rootRoute = new BaseRootRoute({ + component: RootComponent as any, + errorComponent: () => null, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/child', + component: ChildComponent as any, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([childRoute]), + history: createMemoryHistory({ initialEntries: ['/child'] }), + isServer: true, + }) + const controller = new AbortController() + const unhandled: Array = [] + const onUnhandled = (error: unknown) => { + unhandled.push(error) + } + process.on('unhandledRejection', onUnhandled) + + try { + const responsePromise = loadServerResponse( + router, + '/child', + controller.signal, + ) + await Promise.all([rootChunkStarted, childChunkStarted]) + + rootChunkGate.reject(rootError) + await expect(responsePromise).resolves.toMatchObject({ status: 500 }) + + controller.abort(abortError) + childChunkGate.resolve() + await new Promise((resolve) => setTimeout(resolve, 0)) + + expect(unhandled).not.toContain(abortError) + } finally { + process.off('unhandledRejection', onUnhandled) + } + }) + test('a required ancestor lazy chunk failure wins over a deeper loader notFound', async () => { const chunkError = new Error('ancestor lazy chunk failed') const rootRoute = new BaseRootRoute({}) diff --git a/packages/router-devtools-core/package.json b/packages/router-devtools-core/package.json index f717cd1f2c..7a0114daf0 100644 --- a/packages/router-devtools-core/package.json +++ b/packages/router-devtools-core/package.json @@ -25,7 +25,8 @@ ], "scripts": { "clean": "rimraf ./dist && rimraf ./coverage", - "test:eslint": "eslint ./src", + "test:eslint": "eslint ./src ./tests", + "test:unit": "vitest", "test:types": "pnpm run \"/^test:types:ts[0-9]{2}$/\"", "test:types:ts55": "node ../../node_modules/typescript55/lib/tsc.js", "test:types:ts56": "node ../../node_modules/typescript56/lib/tsc.js", @@ -66,6 +67,7 @@ "goober": "^2.1.16" }, "devDependencies": { + "@testing-library/jest-dom": "^6.6.3", "solid-js": "^1.9.10", "vite": "*", "vite-plugin-solid": "^2.11.10" diff --git a/packages/router-devtools-core/src/BaseTanStackRouterDevtoolsPanel.tsx b/packages/router-devtools-core/src/BaseTanStackRouterDevtoolsPanel.tsx index 295655447e..966eb32bc5 100644 --- a/packages/router-devtools-core/src/BaseTanStackRouterDevtoolsPanel.tsx +++ b/packages/router-devtools-core/src/BaseTanStackRouterDevtoolsPanel.tsx @@ -289,17 +289,27 @@ export const BaseTanStackRouterDevtoolsPanel = : [] } let cache = router()._cache - let cacheSize = cache.size - const [cachedMatches, setCachedMatches] = createSignal([...cache.values()]) + let cacheMatches = [...cache.values()] + const [cachedMatches, setCachedMatches] = createSignal(cacheMatches) createEffect(() => { const refreshCache = () => { const next = router()._cache - // Core replaces the map for writes and only deletes entries in place. - if (next !== cache || next.size !== cacheSize) { + let valuesChanged = next.size !== cacheMatches.length + if (!valuesChanged) { + let index = 0 + for (const match of next.values()) { + if (match !== cacheMatches[index++]) { + valuesChanged = true + break + } + } + } + + if (next !== cache || valuesChanged) { cache = next - cacheSize = next.size - setCachedMatches([...next.values()]) + cacheMatches = [...next.values()] + setCachedMatches(cacheMatches) } } refreshCache() diff --git a/packages/router-devtools-core/tests/cache-replacement.test.ts b/packages/router-devtools-core/tests/cache-replacement.test.ts new file mode 100644 index 0000000000..1f543ec408 --- /dev/null +++ b/packages/router-devtools-core/tests/cache-replacement.test.ts @@ -0,0 +1,100 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { TanStackRouterDevtoolsPanelCore } from '../src/TanStackRouterDevtoolsPanelCore' +import type { AnyRouteMatch, AnyRouter } from '@tanstack/router-core' + +function createCachedMatch(loaderData: string): AnyRouteMatch { + return { + id: 'cached-match', + routeId: '/cached', + pathname: '/cached', + params: {}, + search: {}, + status: 'success', + isFetching: false, + updatedAt: Date.now(), + loaderData, + } as AnyRouteMatch +} + +describe('cached matches', () => { + let panel: TanStackRouterDevtoolsPanelCore | undefined + + afterEach(() => { + panel?.unmount() + panel = undefined + document.body.innerHTML = '' + try { + window.localStorage.clear() + } catch {} + vi.useRealTimers() + }) + + it('refreshes when an existing cache entry is replaced', async () => { + // Keep this cache-polling test independent of Vite's lazy transform time. + await import('../src/BaseTanStackRouterDevtoolsPanel') + vi.useFakeTimers() + + const route = { + id: '/cached', + path: 'cached', + fullPath: '/cached', + rank: 0, + children: [], + options: { loader: () => undefined }, + } + const routeTree = { + id: '__root__', + path: '/', + fullPath: '/', + rank: 0, + children: [route], + options: {}, + } + const cache = new Map([['cached-match', createCachedMatch('old data')]]) + const router = { + _cache: cache, + routeTree, + routesById: { + __root__: routeTree, + '/cached': route, + }, + options: {}, + navigate: vi.fn(), + } as unknown as AnyRouter + const routerState = { + location: { + href: '/', + pathname: '/', + search: {}, + searchStr: '', + hash: '', + }, + matches: [], + } + const container = document.createElement('div') + document.body.append(container) + + panel = new TanStackRouterDevtoolsPanelCore({ router, routerState }) + panel.mount(container) + + await vi.waitFor(() => { + expect( + container.querySelector( + '[aria-label="Open match details for cached-match"]', + ), + ).not.toBeNull() + }) + + const cachedMatch = container.querySelector( + '[aria-label="Open match details for cached-match"]', + ) as HTMLElement + cachedMatch.click() + expect(container.textContent).toContain('old data') + + cache.set('cached-match', createCachedMatch('new data')) + await vi.advanceTimersByTimeAsync(500) + + expect(container.textContent).toContain('new data') + expect(container.textContent).not.toContain('old data') + }) +}) diff --git a/packages/router-devtools-core/tsconfig.json b/packages/router-devtools-core/tsconfig.json index 1b802b64d1..e24672b5de 100644 --- a/packages/router-devtools-core/tsconfig.json +++ b/packages/router-devtools-core/tsconfig.json @@ -4,5 +4,5 @@ "jsx": "preserve", "jsxImportSource": "solid-js" }, - "include": ["src", "vite.config.ts"] + "include": ["src", "tests", "vite.config.ts"] } diff --git a/packages/router-devtools-core/vite.config.ts b/packages/router-devtools-core/vite.config.ts index 53da7f8839..b14dd2bdf5 100644 --- a/packages/router-devtools-core/vite.config.ts +++ b/packages/router-devtools-core/vite.config.ts @@ -1,9 +1,23 @@ import { defineConfig, mergeConfig } from 'vitest/config' import { tanstackViteConfig } from '@tanstack/vite-config' import solid from 'vite-plugin-solid' +import packageJson from './package.json' const config = defineConfig({ plugins: [solid()], + test: { + name: packageJson.name, + dir: './tests', + watch: false, + environment: 'jsdom', + typecheck: { enabled: true }, + setupFiles: [], + server: { + deps: { + inline: [/solid-js/], + }, + }, + }, }) const merged = mergeConfig( diff --git a/packages/solid-router/src/Scripts.tsx b/packages/solid-router/src/Scripts.tsx index cf91414acf..0a547521e2 100644 --- a/packages/solid-router/src/Scripts.tsx +++ b/packages/solid-router/src/Scripts.tsx @@ -1,5 +1,5 @@ import * as Solid from 'solid-js' -import { _getRenderedMatches, replaceEqualDeep } from '@tanstack/router-core' +import { _getAssetMatches, replaceEqualDeep } from '@tanstack/router-core' import { isServer } from '@tanstack/router-core/isServer' import { Asset } from './Asset' import { useRouter } from './useRouter' @@ -11,7 +11,7 @@ export const Scripts = () => { const scripts = Solid.createMemo( (previous: Array | undefined) => { - const matches = _getRenderedMatches(router.stores.matches.get()) + const matches = _getAssetMatches(router.stores.matches.get()) const next: Array = [] const assets: Array = [] const manifest = router.ssr?.manifest diff --git a/packages/solid-router/src/Transitioner.tsx b/packages/solid-router/src/Transitioner.tsx index 10aab0e163..dfdd3c2c73 100644 --- a/packages/solid-router/src/Transitioner.tsx +++ b/packages/solid-router/src/Transitioner.tsx @@ -47,7 +47,11 @@ export function Transitioner() { trimPathRight(router.latestLocation.publicHref) !== trimPathRight(nextLocation.publicHref) ) { - router.commitLocation({ ...nextLocation, replace: true }) + router.commitLocation({ + ...nextLocation, + replace: true, + ignoreBlocker: true, + }) return } diff --git a/packages/solid-router/src/headContentUtils.tsx b/packages/solid-router/src/headContentUtils.tsx index ee0d24ccb5..9dcad352fb 100644 --- a/packages/solid-router/src/headContentUtils.tsx +++ b/packages/solid-router/src/headContentUtils.tsx @@ -1,6 +1,6 @@ import * as Solid from 'solid-js' import { - _getRenderedMatches, + _getAssetMatches, appendUniqueUserTags, escapeHtml, getAssetCrossOrigin, @@ -21,7 +21,7 @@ export const useTags = (assetCrossOrigin?: AssetCrossOriginConfig) => { const router = useRouter() const nonce = router.options.ssr?.nonce return Solid.createMemo((prev: Array | undefined) => { - const matches = _getRenderedMatches(router.stores.matches.get()) + const matches = _getAssetMatches(router.stores.matches.get()) const resultMeta: Array = [] const metaByAttribute: Record = {} let title: RouterManagedTag | undefined diff --git a/packages/solid-router/tests/Scripts.test.tsx b/packages/solid-router/tests/Scripts.test.tsx index 87a37da6b5..29f6553d56 100644 --- a/packages/solid-router/tests/Scripts.test.tsx +++ b/packages/solid-router/tests/Scripts.test.tsx @@ -1,4 +1,4 @@ -import { afterEach, describe, expect, test } from 'vitest' +import { afterEach, describe, expect, test, vi } from 'vitest' import { cleanup, fireEvent, @@ -6,11 +6,14 @@ import { screen, waitFor, } from '@solidjs/testing-library' +import { hydrate } from '@tanstack/router-core/ssr/client' +import { dehydrateSsrMatchId } from '../../router-core/src/ssr/ssr-match-id' import { HeadContent, Link, Outlet, + RouterContextProvider, RouterProvider, createBrowserHistory, createMemoryHistory, @@ -47,6 +50,7 @@ afterEach(() => { cleanup() browserHistories.splice(0).forEach((history) => history.destroy()) window.history.replaceState(null, 'root', '/') + delete window.$_TSR }) describe('ssr scripts', () => { @@ -507,6 +511,104 @@ describe('ssr scripts', () => { }) describe('ssr HeadContent', () => { + test('renders descendant assets during a data-only hydration handoff', async () => { + const rootRoute = createRootRoute({}) + const dataOnlyRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/report', + ssr: 'data-only', + loader: () => 'report', + }) + const childRoute = createRoute({ + getParentRoute: () => dataOnlyRoute, + path: '/details', + loader: () => 'details', + head: () => ({ + meta: [{ name: 'solid-data-only-child', content: 'visible' }], + }), + scripts: () => [ + { + id: 'solid-data-only-body-script', + type: 'application/json', + children: '{"source":"body"}', + }, + ], + }) + const router = createRouter({ + history: createMemoryHistory({ + initialEntries: ['/report/details'], + }), + routeTree: rootRoute.addChildren([ + dataOnlyRoute.addChildren([childRoute]), + ]), + }) + const matches = router.matchRoutes(router.latestLocation) + window.$_TSR = { + router: { + dehydratedData: {}, + manifest: { + routes: { + [childRoute.id]: { + preloads: ['/solid-data-only-manifest.js'], + scripts: [ + { + attrs: { + id: 'solid-data-only-manifest-script', + type: 'application/json', + }, + children: '{"source":"manifest"}', + }, + ], + }, + }, + }, + matches: matches.map((match, index) => ({ + i: dehydrateSsrMatchId(match.id), + s: 'success', + ssr: index === 1 ? 'data-only' : true, + l: index ? (index === 1 ? 'report' : 'details') : undefined, + u: Date.now(), + })), + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + } + + await hydrate(router) + + expect(router.state.matches.map((match) => match.status)).toEqual([ + 'success', + 'pending', + 'success', + ]) + render(() => ( + + {() => ( + <> + + + + )} + + )) + + expect( + document.querySelector('meta[name="solid-data-only-child"]'), + ).not.toBeNull() + expect( + document.querySelector('link[href="/solid-data-only-manifest.js"]'), + ).not.toBeNull() + expect( + document.querySelector('#solid-data-only-body-script'), + ).not.toBeNull() + expect( + document.querySelector('#solid-data-only-manifest-script'), + ).not.toBeNull() + }) + test('derives title, dedupes meta, and allows non-loader HeadContent', async () => { const rootRoute = createRootRoute({ loader: () => diff --git a/packages/vue-router/src/Scripts.tsx b/packages/vue-router/src/Scripts.tsx index c326f00fde..8c0a1f87f3 100644 --- a/packages/vue-router/src/Scripts.tsx +++ b/packages/vue-router/src/Scripts.tsx @@ -1,5 +1,5 @@ import * as Vue from 'vue' -import { _getRenderedMatches } from '@tanstack/router-core' +import { _getAssetMatches } from '@tanstack/router-core' import { useStore } from '@tanstack/vue-store' import { isServer } from '@tanstack/router-core/isServer' import { Asset } from './Asset' @@ -18,7 +18,7 @@ export const Scripts = Vue.defineComponent({ setup() { const router = useRouter() const nonce = router.options.ssr?.nonce - const matches = useStore(router.stores.matches, _getRenderedMatches) + const matches = useStore(router.stores.matches, _getAssetMatches) const scripts = Vue.computed(() => { const userScripts: Array = [] diff --git a/packages/vue-router/src/Transitioner.tsx b/packages/vue-router/src/Transitioner.tsx index 6b7e92eb5e..4878a51398 100644 --- a/packages/vue-router/src/Transitioner.tsx +++ b/packages/vue-router/src/Transitioner.tsx @@ -32,7 +32,11 @@ export function useTransitionerSetup() { trimPathRight(router.latestLocation.publicHref) !== trimPathRight(nextLocation.publicHref) ) { - router.commitLocation({ ...nextLocation, replace: true }) + router.commitLocation({ + ...nextLocation, + replace: true, + ignoreBlocker: true, + }) return } diff --git a/packages/vue-router/src/headContentUtils.tsx b/packages/vue-router/src/headContentUtils.tsx index a63e94d53e..adfc156c72 100644 --- a/packages/vue-router/src/headContentUtils.tsx +++ b/packages/vue-router/src/headContentUtils.tsx @@ -1,6 +1,6 @@ import * as Vue from 'vue' import { - _getRenderedMatches, + _getAssetMatches, appendUniqueUserTags, escapeHtml, getAssetCrossOrigin, @@ -16,7 +16,7 @@ import type { export const useTags = (assetCrossOrigin?: AssetCrossOriginConfig) => { const router = useRouter() - const matches = useStore(router.stores.matches, _getRenderedMatches) + const matches = useStore(router.stores.matches, _getAssetMatches) const tags = Vue.computed>(() => { const currentMatches = matches.value diff --git a/packages/vue-router/src/useMatch.tsx b/packages/vue-router/src/useMatch.tsx index 495d87d5fc..a02b5ae109 100644 --- a/packages/vue-router/src/useMatch.tsx +++ b/packages/vue-router/src/useMatch.tsx @@ -130,8 +130,15 @@ export function useMatch< } } + const ownsMatch = + nearestRouteId !== undefined && + (opts.from ?? nearestRouteId) === nearestRouteId + let lastOwnedMatch: any const result = Vue.computed(() => { - const selectedMatch = match.value + if (match.value !== undefined && ownsMatch) { + lastOwnedMatch = match.value + } + const selectedMatch = match.value ?? lastOwnedMatch if (selectedMatch === undefined) { if (opts.shouldThrow ?? true) { if (process.env.NODE_ENV !== 'production') { diff --git a/packages/vue-router/tests/Scripts.test.tsx b/packages/vue-router/tests/Scripts.test.tsx index 5cd2eacd4f..8d6724076b 100644 --- a/packages/vue-router/tests/Scripts.test.tsx +++ b/packages/vue-router/tests/Scripts.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,11 +7,14 @@ import { waitFor, } from '@testing-library/vue' import { Teleport } from 'vue' +import { hydrate } from '@tanstack/router-core/ssr/client' +import { dehydrateSsrMatchId } from '../../router-core/src/ssr/ssr-match-id' import { HeadContent, Link, Outlet, + RouterContextProvider, RouterProvider, createBrowserHistory, createMemoryHistory, @@ -48,6 +51,7 @@ afterEach(() => { cleanup() browserHistories.splice(0).forEach((history) => history.destroy()) window.history.replaceState(null, 'root', '/') + delete window.$_TSR }) describe('ssr scripts', () => { @@ -148,6 +152,98 @@ describe('ssr scripts', () => { }) describe('ssr HeadContent', () => { + test('renders descendant assets during a data-only hydration handoff', async () => { + const rootRoute = createRootRoute({}) + const dataOnlyRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/report', + ssr: 'data-only', + loader: () => 'report', + }) + const childRoute = createRoute({ + getParentRoute: () => dataOnlyRoute, + path: '/details', + loader: () => 'details', + head: () => ({ + meta: [{ name: 'vue-data-only-child', content: 'visible' }], + }), + scripts: () => [ + { + id: 'vue-data-only-body-script', + type: 'application/json', + children: '{"source":"body"}', + }, + ], + }) + const router = createRouter({ + history: createMemoryHistory({ + initialEntries: ['/report/details'], + }), + routeTree: rootRoute.addChildren([ + dataOnlyRoute.addChildren([childRoute]), + ]), + }) + const matches = router.matchRoutes(router.latestLocation) + window.$_TSR = { + router: { + dehydratedData: {}, + manifest: { + routes: { + [childRoute.id]: { + preloads: ['/vue-data-only-manifest.js'], + scripts: [ + { + attrs: { + id: 'vue-data-only-manifest-script', + type: 'application/json', + }, + children: '{"source":"manifest"}', + }, + ], + }, + }, + }, + matches: matches.map((match, index) => ({ + i: dehydrateSsrMatchId(match.id), + s: 'success', + ssr: index === 1 ? 'data-only' : true, + l: index ? (index === 1 ? 'report' : 'details') : undefined, + u: Date.now(), + })), + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + } + + await hydrate(router) + + expect(router.state.matches.map((match) => match.status)).toEqual([ + 'success', + 'pending', + 'success', + ]) + render( + + + + , + ) + + expect( + document.querySelector('meta[name="vue-data-only-child"]'), + ).not.toBeNull() + expect( + document.querySelector('link[href="/vue-data-only-manifest.js"]'), + ).not.toBeNull() + expect(document.querySelector('#vue-data-only-body-script')).not.toBeNull() + expect( + document.querySelector('#vue-data-only-manifest-script'), + ).not.toBeNull() + }) + test('applies assetCrossOrigin to manifest stylesheets and preloads', async () => { const history = createTestBrowserHistory() diff --git a/packages/vue-router/tests/useMatch.test.tsx b/packages/vue-router/tests/useMatch.test.tsx index 3a802798d2..7a73cdbea7 100644 --- a/packages/vue-router/tests/useMatch.test.tsx +++ b/packages/vue-router/tests/useMatch.test.tsx @@ -235,6 +235,44 @@ describe('useMatch', () => { } }) + test('an outgoing component never observes its own match disappear', async () => { + const observedRouteIds: Array = [] + const rootRoute = createRootRoute({ component: () => }) + const firstRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/first', + component: Vue.defineComponent({ + setup() { + const match = useMatch({ + from: '/first', + shouldThrow: false, + }) + Vue.watchEffect(() => observedRouteIds.push(match.value?.routeId), { + flush: 'sync', + }) + return () =>
First route
+ }, + }), + }) + const nextRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/next', + component: () =>
Next route
, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([firstRoute, nextRoute]), + history: createMemoryHistory({ initialEntries: ['/first'] }), + }) + + render() + expect(await screen.findByText('First route')).toBeInTheDocument() + + await router.navigate({ to: '/next' }) + + expect(await screen.findByText('Next route')).toBeInTheDocument() + expect(observedRouteIds).not.toContain(undefined) + }) + describe('when match is not found', () => { test.each([undefined, true])( 'throws if shouldThrow = %s', diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e602c8f53f..25a386ce81 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -13006,6 +13006,9 @@ importers: specifier: ^2.1.16 version: 2.1.16(csstype@3.2.3) devDependencies: + '@testing-library/jest-dom': + specifier: ^6.6.3 + version: 6.6.3 solid-js: specifier: 1.9.12 version: 1.9.12 From baa18cd913aa9f6e79f493cacb9c286702241da1 Mon Sep 17 00:00:00 2001 From: Flo Date: Thu, 23 Jul 2026 15:35:11 +0200 Subject: [PATCH 53/59] fix(router): final-review regressions, changeset, and byte recovery (#7883) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(router): final-review regressions, changeset, and byte recovery Fixes the regressions vs main found in the final review of #7805: - restore history-subscription cleanup on router provider unmount in all three adapters (react returns the unsubscribe unconditionally, solid uses onCleanup, vue uses onUnmounted), pinned by new transitioner-remount tests — a discarded router could previously keep loading on back/forward as a zombie - same-destination navigations now join the in-flight transaction instead of aborting and restarting it (double-click no longer reruns loaders); reloads and same-location redirects keep restart semantics - commitMatches cache retention can no longer resurrect a one-generation-old loaderData when a newer committed success exists for the same match id - same-location dedup keeps __tempLocation/__tempKey so masked vs real same-href navigations commit their state again Adds the missing release changeset enumerating the removed/changed public API with migration hints. Byte recovery: merges rendered-matches.ts, route-chunks.ts and hydrate.ts into load-client.ts so the client bundle shares gzip dictionary context across what were separate module boundaries (-104..-186 gzip B per start scenario; plain router scenarios remain net-negative vs main and hydration still tree-shakes out of them). The solid/vue store-update-count pins were re-adjusted after verifying the published update sequences are byte-identical: the counts only shifted because a one-microtask timing change moves the tests' waitFor-sampled window boundary (5 of 7 counts decreased). * test(router-devtools-core): keep panel chunk warm-up out of the test budget The cache-replacement test warmed Vite's lazy transform of BaseTanStackRouterDevtoolsPanel inside the test body, so on slow CI runners the transform alone could blow the 5s test timeout (observed at 5.89s). Move the warm-up to a beforeAll with its own generous timeout and give the test itself explicit headroom. Pre-existing flake on the lane branch tip, surfaced by this PR's CI being the first to run on it. * refactor(router-core): extend lane typestate to matches and commits The lane pipeline already carried phase brands at lane granularity (Lane<'matched'|'contextualized'|'reduced'|'projected'>); this finishes the pattern at the two granularities it was missing, at zero runtime cost (all emitted dist JS verified byte-identical): - settleInto becomes the sole granter of a SettledMatch brand via an assertion signature, and cacheLoaderMatch requires it — the loader -> settle -> cache ordering is now compiler-enforced. The one legitimate phase jump (hydration cache-seeding of already-settled dehydrated data) is a single named, commented boundary cast. - commitMatches/commitRefreshMatches only accept a projected lane's matches (LaneMatches<'projected'>), so committing an earlier-phase lane no longer compiles. - LoadTransaction's dev-only refresh triple collapses into one optional slot [presentation, handoff?], making a half-armed refresh state unrepresentable and shrinking the clear/read sites. --- .changeset/lane-match-loader-rewrite.md | 29 + packages/react-router/src/Transitioner.tsx | 6 +- .../tests/transitioner-remount.test.tsx | 91 +++ packages/router-core/src/hydrate.ts | 395 ------------ packages/router-core/src/index.ts | 2 +- packages/router-core/src/load-client.ts | 584 +++++++++++++++++- packages/router-core/src/load-server.ts | 2 +- packages/router-core/src/rendered-matches.ts | 35 -- packages/router-core/src/route-chunks.ts | 70 --- packages/router-core/src/router.ts | 30 +- .../src/ssr/createRequestHandler.ts | 2 +- packages/router-core/src/ssr/ssr-client.ts | 2 +- packages/router-core/src/ssr/ssr-server.ts | 2 +- .../router-core/tests/build-location.test.ts | 4 +- .../error-boundary-cache-generation.test.ts | 81 +++ .../loader-architecture-regressions.test.ts | 8 +- .../masked-location-state-commit.test.ts | 55 ++ .../same-destination-navigation-join.test.ts | 110 ++++ .../tests/cache-replacement.test.ts | 12 +- packages/solid-router/src/Transitioner.tsx | 2 +- .../store-updates-during-navigation.test.tsx | 14 +- .../tests/transitioner-remount.test.tsx | 91 +++ packages/vue-router/src/Transitioner.tsx | 2 +- .../store-updates-during-navigation.test.tsx | 14 +- .../tests/transitioner-remount.test.tsx | 92 +++ 25 files changed, 1164 insertions(+), 571 deletions(-) create mode 100644 .changeset/lane-match-loader-rewrite.md create mode 100644 packages/react-router/tests/transitioner-remount.test.tsx delete mode 100644 packages/router-core/src/hydrate.ts delete mode 100644 packages/router-core/src/rendered-matches.ts delete mode 100644 packages/router-core/src/route-chunks.ts create mode 100644 packages/router-core/tests/error-boundary-cache-generation.test.ts create mode 100644 packages/router-core/tests/masked-location-state-commit.test.ts create mode 100644 packages/router-core/tests/same-destination-navigation-join.test.ts create mode 100644 packages/solid-router/tests/transitioner-remount.test.tsx create mode 100644 packages/vue-router/tests/transitioner-remount.test.tsx diff --git a/.changeset/lane-match-loader-rewrite.md b/.changeset/lane-match-loader-rewrite.md new file mode 100644 index 0000000000..ddd71fa4c5 --- /dev/null +++ b/.changeset/lane-match-loader-rewrite.md @@ -0,0 +1,29 @@ +--- +'@tanstack/router-core': patch +'@tanstack/react-router': patch +'@tanstack/solid-router': patch +'@tanstack/vue-router': patch +--- + +Rewrite match loading around a lane-based scheduler that tracks each navigation, preload, and background reload as an ordered unit of work. This fixes pending/redirect/retry state leaking between overlapping navigations, restores correct SSR status codes for redirects, errors, and not-found responses, and closes hydration gaps where the client re-ran work the server had already completed. + +- Route `headers()` now only runs on the server, matching the documented behavior — it is no longer invoked during client-side asset projection. +- Default `gcTime` and `preloadGcTime` are reduced from 30 minutes (`1_800_000`) to 5 minutes (`300_000`). + +**Removed / changed public API** + +- `RouterState` no longer includes `loadedAt`, `isTransitioning`, `statusCode`, or `redirect`. Use `match.updatedAt` in place of `loadedAt`; subscribe to `router.state.status` / `router.state.isLoading` in place of `isTransitioning`; server response status and redirect handling are now internal to the server loader and are no longer exposed on `router.state`. +- `RouteMatch.fetchCount` has been removed, with no replacement — it was purely informational. +- `RouteMatch.status` no longer includes `'redirected'` (it remains `'pending' | 'success' | 'error' | 'notFound'`) — redirected matches are dropped from the match list instead of being rendered. +- `RouteMatch.globalNotFound` has been renamed and privatized to the internal `_notFound` field. Use `match.status === 'notFound'` instead. +- Removed `RouterCore` members `getMatch()`, `updateMatch()`, `cancelMatch()`, and `cancelMatches()` — read matches from `router.state.matches` (e.g. `router.state.matches.find((m) => m.id === id)`); there is no replacement for mutating or cancelling an individual in-flight match from outside the router. +- Removed `hasNotFoundMatch()` — use `router.state.matches.some((m) => m.status === 'notFound')`. +- Removed `looseRoutesById` — use `routesById`. +- Removed `isPrerendering()`, `isViewTransitionTypesSupported`, and `viewTransitionPromise`, with no replacement. +- Removed `getParsedLocationHref()` and `clearExpiredCache()`, with no replacement — expired cache entries are now reconciled automatically as part of match commit. +- Removed `latestLoadPromise` and `beforeLoad()`, with no replacement. +- `commitLocationPromise` and `pendingBuiltLocation` are now private (`_commitPromise`, `_pendingLocation`) and no longer part of the public `RouterCore` surface. +- Removed the exported `GetMatchFn` and `UpdateMatchFn` types, along with the methods they typed. +- Removed the standalone `getMatchedRoutes()` export from `@tanstack/router-core` — use the `router.getMatchedRoutes()` instance method instead. +- `MatchRoutesOpts.preload` and `MatchRoutesOpts.dest` have been removed. +- `StartTransitionFn` is now `(fn, expected, urgent?) => Promise` (previously `(fn) => void`). This only affects custom framework adapters that implement `startTransition`. diff --git a/packages/react-router/src/Transitioner.tsx b/packages/react-router/src/Transitioner.tsx index ccf1373c0e..acbb60b5bf 100644 --- a/packages/react-router/src/Transitioner.tsx +++ b/packages/react-router/src/Transitioner.tsx @@ -81,7 +81,7 @@ export function Transitioner() { const unsub = router.history.subscribe(router.load) if (mounted?.current) { - return process.env.NODE_ENV !== 'production' ? unsub : undefined + return unsub } if (mounted) { mounted.current = true @@ -110,7 +110,7 @@ export function Transitioner() { replace: true, ignoreBlocker: true, }) - return process.env.NODE_ENV !== 'production' ? unsub : undefined + return unsub } const resolvedLocation = router.stores.resolvedLocation.get() @@ -133,7 +133,7 @@ export function Transitioner() { router.load().catch(console.error) } - return process.env.NODE_ENV !== 'production' ? unsub : undefined + return unsub // `mounted` exists only in development and is a stable ref when present. // eslint-disable-next-line react-hooks/exhaustive-deps }, [router, router.history]) diff --git a/packages/react-router/tests/transitioner-remount.test.tsx b/packages/react-router/tests/transitioner-remount.test.tsx new file mode 100644 index 0000000000..aca37ae2de --- /dev/null +++ b/packages/react-router/tests/transitioner-remount.test.tsx @@ -0,0 +1,91 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { cleanup, render, screen, waitFor } from '@testing-library/react' +import { + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +afterEach(() => { + cleanup() +}) + +function setup() { + const rootRoute = createRootRoute({ component: () => }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
Index
, + }) + const nextRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/next', + component: () =>
Next
, + }) + const history = createMemoryHistory({ initialEntries: ['/'] }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, nextRoute]), + history, + }) + return { history, router } +} + +describe('Transitioner remount', () => { + // Zombie-router pin: once the provider unmounts, the history subscription + // must be torn down so a later history change never re-drives the router. + it('does not load after the provider unmounts', async () => { + const { history, router } = setup() + const loadSpy = vi.spyOn(router, 'load') + + const first = render() + expect(await screen.findByText('Index')).toBeInTheDocument() + await waitFor(() => expect(router.state.status).toBe('idle')) + + first.unmount() + loadSpy.mockClear() + + // A history change while unmounted must not reach the router. + history.push('/next') + await new Promise((resolve) => setTimeout(resolve, 0)) + + expect(loadSpy).not.toHaveBeenCalled() + // Raw history advanced... + expect(router.history.location.pathname).toBe('/next') + // ...but the router never processed it, so its committed state stayed put. + expect(router.state.location.pathname).toBe('/') + + loadSpy.mockRestore() + }) + + // Remounting the same router instance must re-establish the subscription so + // navigation keeps working, without leaving a stale duplicate behind. + it('re-subscribes and loads on remount with the same router', async () => { + const { history, router } = setup() + // Spy before the first mount so the subscription captures the spy by + // reference — both the first and second mounts subscribe with it. + const loadSpy = vi.spyOn(router, 'load') + + const first = render() + expect(await screen.findByText('Index')).toBeInTheDocument() + await waitFor(() => expect(router.state.status).toBe('idle')) + + first.unmount() + + render() + expect(await screen.findByText('Index')).toBeInTheDocument() + await waitFor(() => expect(router.state.status).toBe('idle')) + + // A push on the remounted provider must drive exactly one load, proving + // the subscription was re-established (and is singular). + loadSpy.mockClear() + history.push('/next') + expect(await screen.findByText('Next')).toBeInTheDocument() + expect(router.state.location.pathname).toBe('/next') + await waitFor(() => expect(loadSpy).toHaveBeenCalledTimes(1)) + + loadSpy.mockRestore() + }) +}) diff --git a/packages/router-core/src/hydrate.ts b/packages/router-core/src/hydrate.ts deleted file mode 100644 index f8b67cfafe..0000000000 --- a/packages/router-core/src/hydrate.ts +++ /dev/null @@ -1,395 +0,0 @@ -import { - cacheLoaderMatch, - getRoute, - laneInputs, - navigateFrom, - projectLane, - transferMatchResources, - waitFor, -} from './load-client' -import { loadRouteChunk } from './route-chunks' -import { hydrateSsrMatchId } from './ssr/ssr-match-id' -import { deepEqual } from './utils' -import type { AnyRouteMatch } from './Matches' -import type { AnyRouter } from './router' -import type { GLOBAL_SEROVAL, GLOBAL_TSR } from './ssr/constants' -import type { AnySerializationAdapter } from './ssr/serializer/transformer' -import type { TsrSsrGlobal } from './ssr/types' - -declare global { - interface Window { - [GLOBAL_TSR]?: TsrSsrGlobal - [GLOBAL_SEROVAL]?: any - } -} - -export async function hydrate(router: AnyRouter): Promise { - if (process.env.NODE_ENV !== 'production' && !window.$_TSR) { - throw new Error( - 'Invariant failed: Expected to find bootstrap data on window.$_TSR, but we did not. Please file an issue!', - ) - } - const tsr = window.$_TSR! - - const adapters = router.options.serializationAdapters as - | Array - | undefined - if (adapters?.length) { - tsr.t = new Map( - adapters.map((adapter) => [adapter.key, adapter.fromSerializable]), - ) - tsr.buffer.forEach((script) => script()) - } - tsr.initialized = true - - const dehydratedRouter = tsr.router - if (process.env.NODE_ENV !== 'production' && !dehydratedRouter) { - throw new Error( - 'Invariant failed: Expected to find a dehydrated data on window.$_TSR.router, but we did not. Please file an issue!', - ) - } - router.ssr = { manifest: dehydratedRouter!.manifest } - const nonce = ( - document.querySelector('meta[property="csp-nonce"]') as - | HTMLMetaElement - | undefined - )?.content - router.options.ssr = { nonce } - - const dehydratedMatches = dehydratedRouter!.matches - - const controller = new AbortController() - const previousPreflight = router._preflight - router._preflight = controller - previousPreflight?.abort() - const retire = (cause?: unknown) => { - if (router._preflight === controller) { - router._preflight = undefined - } - controller.abort(cause) - return false - } - const isCurrent = () => - (!router._tx && - router._preflight === controller && - !controller.signal.aborted) || - retire() - - let location!: AnyRouter['latestLocation'] - let candidates!: Array - let handoffInputs!: ReturnType - try { - await waitFor( - router.options.hydrate?.(dehydratedRouter!.dehydratedData), - controller.signal, - ) - if (!isCurrent()) { - return - } - router.updateLatestLocation() - location = router.latestLocation - router.stores.location.set(location) - handoffInputs = laneInputs(router, location) - candidates = router.matchRoutes(location, { - _controller: controller, - }) - } catch (cause) { - retire(cause) - if (cause !== controller.signal) { - throw cause - } - } - if (!isCurrent()) { - return - } - const committed: Array = [] - let pendingBoundary: number | undefined - let verifiedAssetEnd = 0 - const retryFrom = (index: number) => { - // The failing route's identity is still verified, but no descendant is. - verifiedAssetEnd = Math.min(verifiedAssetEnd, index + 1) - const removed = committed.splice(index) - for (const match of removed) { - if ( - getRoute(router, match).options.loader && - (match.status === 'success' || - (!match.invalid && 'loaderData' in match)) - ) { - cacheLoaderMatch( - router, - { - ...match, - status: 'success', - error: undefined, - preload: true, - }, - router._cache.get(match.id), - ) - } - } - transferMatchResources(router, removed) - } - - // A longer server lane is valid only when the local match already caps the - // branch at a global not-found boundary. Otherwise no transported work is - // safe to attach to the shorter client lane. - const shared = - dehydratedMatches.length > candidates.length - ? candidates.findIndex((match) => match._notFound) + 1 - : dehydratedMatches.length - let isTerminal = false - for (let index = 0; index < shared; index++) { - const candidate = candidates[index]! - const dehydrated = dehydratedMatches[index]! - if ( - typeof dehydrated.i !== 'string' || - hydrateSsrMatchId(dehydrated.i) !== candidate.id - ) { - pendingBoundary ??= index - break - } - verifiedAssetEnd = index + 1 - const route = getRoute(router, candidate) - if ( - 'l' in dehydrated || - (dehydrated.s === 'success' && - dehydrated.e === undefined && - route.options.loader) - ) { - candidate.loaderData = dehydrated.l - } - candidate.status = dehydrated.s - candidate.ssr = dehydrated.ssr - route.options.ssr = candidate.ssr - candidate.updatedAt = dehydrated.u - candidate.error = dehydrated.e - candidate._notFound ||= dehydrated.g - const terminal = - candidate.status === 'error' || - candidate.status === 'notFound' || - candidate._notFound - if (terminal) { - isTerminal = true - committed.push(candidate) - if (candidate.ssr === false || candidate.ssr === 'data-only') { - pendingBoundary ??= index - } - break - } - if (candidate.status === 'pending') { - pendingBoundary ??= index - break - } - - committed.push(candidate) - if (candidate.ssr === 'data-only') { - pendingBoundary ??= index - } - } - let verifiedContextEnd = verifiedAssetEnd - - if ( - !isTerminal && - committed.length === shared && - shared < candidates.length - ) { - pendingBoundary = shared - } - - // Hooks observe structural membership. Execution remains limited to - // `committed`, the accepted server prefix. - const chunks = committed.map(async (match) => { - try { - const route = getRoute(router, match) - if (match._notFound) { - await Promise.all([ - loadRouteChunk(route), - loadRouteChunk(route, 'notFoundComponent'), - ]) - } else { - await loadRouteChunk( - route, - match.status === 'error' - ? 'errorComponent' - : match.status === 'notFound' - ? 'notFoundComponent' - : undefined, - ) - } - return true - } catch { - return false - } - }) - let chunkFailure = 0 - try { - while ( - chunkFailure < chunks.length && - (await waitFor(chunks[chunkFailure]!, controller.signal)) - ) { - chunkFailure++ - } - } catch { - isCurrent() - return - } - if (!isCurrent()) { - return - } - if (chunkFailure < committed.length) { - verifiedContextEnd = Math.min(verifiedContextEnd, chunkFailure) - retryFrom(chunkFailure) - } - - // The first pending match is already visible, so prepare its route context - // without granting its beforeLoad or loader any hydration authority. - const contextEnd = Math.max( - pendingBoundary === committed.length - ? committed.length + 1 - : committed.length, - verifiedContextEnd, - ) - for (let index = 0; index < contextEnd; index++) { - const match = candidates[index]! - const route = getRoute(router, match) - const parentContext = - candidates[index - 1]?.context ?? router.options.context ?? {} - let routeContext - if (route.options.context) { - try { - routeContext = match._ctx = - route.options.context({ - deps: match.loaderDeps, - params: match.params, - context: parentContext, - location, - navigate: navigateFrom(router, location), - buildLocation: router.buildLocation, - cause: match.cause, - abortController: controller, - preload: false, - matches: candidates, - routeId: route.id, - }) || {} - } catch { - if (!isCurrent()) { - return - } - if ( - match.status !== 'error' && - match.status !== 'notFound' && - !match._notFound - ) { - retryFrom(index) - break - } - } - if (!isCurrent()) { - return - } - } - match.context = { - ...parentContext, - ...routeContext, - ...(committed[index] && dehydratedMatches[index]!.b), - } - } - - await projectLane( - router, - [location, candidates] as any, - controller.signal, - 0, - verifiedAssetEnd, - ) - if (!isCurrent()) { - return - } - const needsClientLoad = - pendingBoundary !== undefined || committed.length < shared - const committedMatches = - isTerminal && committed.length === shared ? candidates : committed - let presented = needsClientLoad ? candidates : committedMatches - let dataOnlyAssetEnd: number | undefined - if (needsClientLoad && pendingBoundary !== undefined) { - const boundary = presented[pendingBoundary]! - dataOnlyAssetEnd = - boundary.status === 'success' && - boundary.ssr === 'data-only' && - boundary.error === undefined && - !boundary._notFound && - verifiedAssetEnd > pendingBoundary + 1 - ? verifiedAssetEnd - : undefined - presented = presented.slice() - presented[pendingBoundary] = { - ...boundary, - status: 'pending', - ssr: boundary.ssr === 'data-only' ? 'data-only' : false, - _assetEnd: dataOnlyAssetEnd, - } - } - - const claim = () => - needsClientLoad && - !router._tx && - router.latestLocation.state === location.state && - deepEqual(handoffInputs, laneInputs(router, router.latestLocation)) && - router._committed === committedMatches && - committedMatches.length && - !controller.signal.aborted - ? controller - : undefined - const handoff: NonNullable = [ - claim, - (matches) => { - if (router._handoff !== handoff) { - return - } - const prefix = committedMatches.length - if ( - !matches || - !claim() || - committedMatches.some((match, index) => match.id !== matches[index]?.id) - ) { - router._handoff = undefined - controller.abort() - return - } - let handoffAssetEnd = dataOnlyAssetEnd - if (handoffAssetEnd !== undefined) { - for (let index = prefix; index < handoffAssetEnd; index++) { - if (candidates[index]?.id !== matches[index]?.id) { - handoffAssetEnd = - index > (pendingBoundary ?? -1) + 1 ? index : undefined - break - } - } - } - const clones = committedMatches.map((match) => ({ ...match })) - if (handoffAssetEnd !== undefined) { - clones[pendingBoundary!]!._assetEnd = handoffAssetEnd - } - transferMatchResources(router, matches.splice(0, prefix, ...clones)) - for (let index = prefix; index < matches.length; index++) { - const match = matches[index]! - const hydrated = candidates[index] - if (hydrated?.id === match.id && hydrated._ctx) { - match._ctx = hydrated._ctx - } - match.abortController = controller - } - return prefix - }, - ] - router._committed = committedMatches - router._handoff = handoff - router._preflight = undefined - router.batch(() => { - router.stores.setMatches(presented) - router.stores.status.set('idle') - if (!needsClientLoad) { - router.stores.resolvedLocation.set(router.stores.location.get()) - } - }) -} diff --git a/packages/router-core/src/index.ts b/packages/router-core/src/index.ts index 946f18b6ca..a296629ffa 100644 --- a/packages/router-core/src/index.ts +++ b/packages/router-core/src/index.ts @@ -103,7 +103,7 @@ export { resolveManifestCssLink, } from './manifest' export { isMatch } from './Matches' -export { _getAssetMatches, _getRenderedMatches } from './rendered-matches' +export { _getAssetMatches, _getRenderedMatches } from './load-client' export type { AnyMatchAndValue, FindValueByIndex, diff --git a/packages/router-core/src/load-client.ts b/packages/router-core/src/load-client.ts index 8b5e28ca43..51151ad56b 100644 --- a/packages/router-core/src/load-client.ts +++ b/packages/router-core/src/load-client.ts @@ -2,14 +2,16 @@ // can rewrite relative imports for both ESM and CJS. import { isNotFound } from './not-found' import { isRedirect } from './redirect' -import { loadRouteChunk } from './route-chunks' -import { _getRenderedMatches } from './rendered-matches' import { _getUserHistoryState, getLocationChangeInfo, runRouteLifecycle, } from './router' import { deepEqual } from './utils' +import { hydrateSsrMatchId } from './ssr/ssr-match-id' +import type { GLOBAL_SEROVAL, GLOBAL_TSR } from './ssr/constants' +import type { AnySerializationAdapter } from './ssr/serializer/transformer' +import type { TsrSsrGlobal } from './ssr/types' import type { ParsedLocation } from './location' import type { AnyRouteMatch } from './Matches' import type { NotFoundError } from './not-found' @@ -23,13 +25,125 @@ import type { import type { AnyRedirect } from './redirect' import type { AnyRouter } from './router' +type RouteComponentType = + | 'component' + | 'pendingComponent' + | 'errorComponent' + | 'notFoundComponent' + +export function replaceRouteChunk( + route: AnyRoute, + lazyFn: AnyRoute['lazyFn'], +): void { + route.lazyFn = lazyFn ?? route.lazyFn + route._lazy = undefined +} + +function preloadComponent( + route: AnyRoute, + type: RouteComponentType, +): Promise | undefined { + return (route.options[type] as any)?.preload?.() +} + +function loadComponents(route: AnyRoute): Promise | undefined { + const component = preloadComponent(route, 'component') + const pending = preloadComponent(route, 'pendingComponent') + if (component && pending) { + return Promise.all([component, pending]).then(() => {}) + } + return component ?? pending +} + +export function loadRouteChunk( + route: AnyRoute, + // `false` waits only for lazy route options, before a boundary is selected. + componentType?: 'errorComponent' | 'notFoundComponent' | false, +): Promise | undefined { + const afterLazy = () => + componentType === false + ? undefined + : componentType + ? preloadComponent(route, componentType) + : loadComponents(route) + const current = route._lazy + if (current) { + return current === true ? afterLazy() : current.then(afterLazy) + } + if (!route.lazyFn) { + return afterLazy() + } + + const promise = route.lazyFn().then( + (lazyRoute) => { + // HMR clears the owner before an obsolete import can settle. + if (process.env.NODE_ENV === 'production' || route._lazy === promise) { + const { id: _id, ...options } = lazyRoute.options + Object.assign(route.options, options) + route._lazy = true + } + }, + (error) => { + if (process.env.NODE_ENV === 'production' || route._lazy === promise) { + route._lazy = undefined + } + throw error + }, + ) + route._lazy = promise + return promise.then(afterLazy) +} + +/** Return the structural lane through the first terminal render boundary. */ +export function _getRenderedMatches( + matches: Array, +): Array { + const end = + matches.findIndex( + (match) => match.status !== 'success' || match._notFound, + ) + 1 + return end && end < matches.length ? matches.slice(0, end) : matches +} + +/** Return the lane whose document assets belong to the current presentation. */ +export function _getAssetMatches( + matches: Array, +): Array { + let end = matches.length + for (let index = 0; index < end; index++) { + const match = matches[index]! + // `_assetEnd` is only ever set on hydration presentation clones that are + // `status: 'pending'`, `ssr: 'data-only'`, error-free, and not not-found + // (see hydrate.ts), and commits clear it — so its presence alone is the guard. + if (match._assetEnd !== undefined) { + end = Math.min(end, Math.max(index + 1, match._assetEnd)) + continue + } + if (match.status !== 'success' || match._notFound) { + end = index + 1 + break + } + } + // `end` only ever shrinks to `index + 1 >= 1`, so no zero guard is needed. + return end < matches.length ? matches.slice(0, end) : matches +} + declare const lanePhase: unique symbol -type Lane< - TPhase extends 'matched' | 'contextualized' | 'reduced' | 'projected', -> = [ +type LanePhase = 'matched' | 'contextualized' | 'reduced' | 'projected' + +/** + * Lane matches carry their lane's phase so functions can demand evidence of + * pipeline position (e.g. `commitMatches` only accepts a projected lane's + * matches). The brand is phantom — it never exists at runtime. + */ +type LaneMatches = Array & { + readonly [lanePhase]?: TPhase +} + +type Lane = [ location: ParsedLocation, - matches: Array, + matches: LaneMatches, background?: Array, backgroundSettlement?: Promise, ] & { readonly [lanePhase]?: TPhase } @@ -65,6 +179,17 @@ type WorkMatch = AnyRouteMatch & { _flight?: LoaderFlight } +declare const matchPhase: unique symbol + +/** + * A match whose loader outcome has been applied by `settleInto`, which is the + * sole granter of this brand (phantom, zero-runtime). Consumers that require + * it — e.g. `cacheLoaderMatch` — can only be reached after settlement, so the + * compiler enforces the loader→settle→cache ordering. Sources that arrive + * already settled (dehydrated server data) must cast at a named boundary. + */ +type SettledMatch = WorkMatch & { readonly [matchPhase]: 'settled' } + export type LaneInputs = [ routeTree: AnyRoute, context: unknown, @@ -97,9 +222,15 @@ export type LoadTransaction = [ matches: Array, startedAt: number, done: Promise, - refresh?: true, - refreshPresentation?: Array, - refreshHandoff?: NonNullable, + /** + * Dev-only HMR refresh mode. Presence is the mode flag; a refresh always + * carries the presentation it started from, while the hydration handoff is + * genuinely optional — the tuple makes a half-armed refresh unrepresentable. + */ + refresh?: [ + presentation: Array, + handoff: NonNullable | undefined, + ], ] export type PendingSession = [ @@ -569,7 +700,7 @@ function settleInto( match: WorkMatch, result: LoaderOutcome, preload: boolean, -): void { +): asserts match is SettledMatch { if (result[0] === SUCCESS) { match.loaderData = result[1] match.error = undefined @@ -588,7 +719,7 @@ function settleInto( export function cacheLoaderMatch( router: CoordinatorRouter, - match: WorkMatch, + match: SettledMatch, planned: AnyRouteMatch | undefined, ): void { const current = router._cache.get(match.id) as WorkMatch | undefined @@ -1119,6 +1250,9 @@ async function executeClientLane( plannedBoundary = boundary } let end = plannedBoundary < 0 ? matches.length : plannedBoundary + 1 + // From here on `matched` is contextualized: `contextualize` communicates + // through mutation plus a failure return, so the phase brand is asserted at + // the two use sites below rather than granted by a (byte-costing) return. const failure = await contextualize(router, matched, options, end) if (failure) { options[5] = true @@ -1344,7 +1478,7 @@ function discardLane(router: AnyRouter, lane: ProjectedLane): void { function commitMatches( router: CoordinatorRouter, tx: LoadTransaction, - matches: Array, + matches: LaneMatches<'projected'>, resolvedPrefix?: number, ): void { const previous = router._committed @@ -1355,12 +1489,20 @@ function commitMatches( match._assetEnd = undefined } } - const rendered = _getRenderedMatches(matches) + const cut = _getRenderedMatches(matches).length const cached = new Map() const now = Date.now() for (const match of [...previous, ...previousCached.values()]) { + // Rendered-prefix ids and settled successes anywhere in the lane are + // authoritative: retaining an older same-id generation would shadow them + // at the next planning pass. Unsettled beyond-boundary matches are not — + // they must not evict a newer same-id preload. if ( - rendered.some((candidate) => candidate.id === match.id) || + matches.some( + (candidate, index) => + candidate.id === match.id && + (index < cut || candidate.status === 'success'), + ) || match.status !== 'success' ) { continue @@ -1405,7 +1547,7 @@ function commitMatches( function commitRefreshMatches( router: CoordinatorRouter, tx: LoadTransaction, - matches: Array, + matches: LaneMatches<'projected'>, checkpoint: PublicationCheckpoint, ): void { const previous = router._committed @@ -1500,7 +1642,7 @@ async function transitionRefresh( ): Promise { const checkpoint: PublicationCheckpoint = { previousMatches: router._committed, - previousPresentation: tx[7] ?? router.stores.matches.get(), + previousPresentation: tx[6]?.[0] ?? router.stores.matches.get(), previousCache: router._cache, commitPromise: router._commitPromise, published: false, @@ -1531,14 +1673,12 @@ async function transitionRefresh( router._rollbackRefresh = undefined } if (checkpoint.published) { - const handoff = tx[8] + const handoff = tx[6]?.[1] if (handoff && router._handoff === handoff) { handoff[1]() } if (router._tx === tx) { tx[6] = undefined - tx[7] = undefined - tx[8] = undefined } } settlePublication(router, checkpoint) @@ -1612,6 +1752,8 @@ async function runBackground( releaseFlight(router, next[task[0]]!) next[task[0]] = task[3] } + // Phase jump: the clones inherit beforeLoad context from the committed + // foreground lane, which already ran `contextualize` for these matches. const lane = [tx[2], next] as ContextualizedLane let reduced: ReducedLane | ControlOutcome try { @@ -1825,7 +1967,7 @@ async function runClientTransaction( export async function loadClientRoute( router: CoordinatorRouter, - opts?: { sync?: boolean }, + opts?: { sync?: boolean; _dedupe?: boolean }, ): Promise { let rematerialize = false if (process.env.NODE_ENV !== 'production') { @@ -1846,6 +1988,20 @@ export async function loadClientRoute( pendingLocation?.href === location.href ? (pendingLocation._redirects ?? 0) : 0 + // A same-location navigation joins the transaction already loading it + // instead of restarting its work. Reload requests never carry the flag, + // and same-location redirects must restart the lane they came from. + if ( + opts?._dedupe && + !redirects && + previousOwner && + !rematerialize && + previousOwner[2].href === location.href && + router.stores.status.get() === 'pending' + ) { + await awaitCurrent(router) + return + } const handoff = router._handoff const hydrationController = rematerialize ? undefined : handoff?.[0]() const preflight = new AbortController() @@ -1979,9 +2135,8 @@ export async function loadClientRoute( }), ] if (process.env.NODE_ENV !== 'production' && rematerialize) { - tx[6] = true - tx[7] = refreshPresentation - tx[8] = handoff + // `refreshPresentation` is always captured when `rematerialize` is set. + tx[6] = [refreshPresentation!, handoff] router._refreshNextLoad = undefined } router._tx = tx @@ -2157,3 +2312,386 @@ export async function preloadClientRoute( return } } + +// --- SSR hydration (client entry via @tanstack/router-core/ssr/client) --- + +declare global { + interface Window { + [GLOBAL_TSR]?: TsrSsrGlobal + [GLOBAL_SEROVAL]?: any + } +} + +export async function hydrate(router: AnyRouter): Promise { + if (process.env.NODE_ENV !== 'production' && !window.$_TSR) { + throw new Error( + 'Invariant failed: Expected to find bootstrap data on window.$_TSR, but we did not. Please file an issue!', + ) + } + const tsr = window.$_TSR! + + const adapters = router.options.serializationAdapters as + | Array + | undefined + if (adapters?.length) { + tsr.t = new Map( + adapters.map((adapter) => [adapter.key, adapter.fromSerializable]), + ) + tsr.buffer.forEach((script) => script()) + } + tsr.initialized = true + + const dehydratedRouter = tsr.router + if (process.env.NODE_ENV !== 'production' && !dehydratedRouter) { + throw new Error( + 'Invariant failed: Expected to find a dehydrated data on window.$_TSR.router, but we did not. Please file an issue!', + ) + } + router.ssr = { manifest: dehydratedRouter!.manifest } + const nonce = ( + document.querySelector('meta[property="csp-nonce"]') as + | HTMLMetaElement + | undefined + )?.content + router.options.ssr = { nonce } + + const dehydratedMatches = dehydratedRouter!.matches + + const controller = new AbortController() + const previousPreflight = router._preflight + router._preflight = controller + previousPreflight?.abort() + const retire = (cause?: unknown) => { + if (router._preflight === controller) { + router._preflight = undefined + } + controller.abort(cause) + return false + } + const isCurrent = () => + (!router._tx && + router._preflight === controller && + !controller.signal.aborted) || + retire() + + let location!: AnyRouter['latestLocation'] + let candidates!: Array + let handoffInputs!: ReturnType + try { + await waitFor( + router.options.hydrate?.(dehydratedRouter!.dehydratedData), + controller.signal, + ) + if (!isCurrent()) { + return + } + router.updateLatestLocation() + location = router.latestLocation + router.stores.location.set(location) + handoffInputs = laneInputs(router, location) + candidates = router.matchRoutes(location, { + _controller: controller, + }) + } catch (cause) { + retire(cause) + if (cause !== controller.signal) { + throw cause + } + } + if (!isCurrent()) { + return + } + const committed: Array = [] + let pendingBoundary: number | undefined + let verifiedAssetEnd = 0 + const retryFrom = (index: number) => { + // The failing route's identity is still verified, but no descendant is. + verifiedAssetEnd = Math.min(verifiedAssetEnd, index + 1) + const removed = committed.splice(index) + for (const match of removed) { + if ( + getRoute(router, match).options.loader && + (match.status === 'success' || + (!match.invalid && 'loaderData' in match)) + ) { + cacheLoaderMatch( + router, + // Phase jump: dehydrated server data is already past the loader + // phase — the guard above verified a settled success (or transported + // loaderData), so this clone is settled without a client settleInto. + { + ...match, + status: 'success', + error: undefined, + preload: true, + } as SettledMatch, + router._cache.get(match.id), + ) + } + } + transferMatchResources(router, removed) + } + + // A longer server lane is valid only when the local match already caps the + // branch at a global not-found boundary. Otherwise no transported work is + // safe to attach to the shorter client lane. + const shared = + dehydratedMatches.length > candidates.length + ? candidates.findIndex((match) => match._notFound) + 1 + : dehydratedMatches.length + let isTerminal = false + for (let index = 0; index < shared; index++) { + const candidate = candidates[index]! + const dehydrated = dehydratedMatches[index]! + if ( + typeof dehydrated.i !== 'string' || + hydrateSsrMatchId(dehydrated.i) !== candidate.id + ) { + pendingBoundary ??= index + break + } + verifiedAssetEnd = index + 1 + const route = getRoute(router, candidate) + if ( + 'l' in dehydrated || + (dehydrated.s === 'success' && + dehydrated.e === undefined && + route.options.loader) + ) { + candidate.loaderData = dehydrated.l + } + candidate.status = dehydrated.s + candidate.ssr = dehydrated.ssr + route.options.ssr = candidate.ssr + candidate.updatedAt = dehydrated.u + candidate.error = dehydrated.e + candidate._notFound ||= dehydrated.g + const terminal = + candidate.status === 'error' || + candidate.status === 'notFound' || + candidate._notFound + if (terminal) { + isTerminal = true + committed.push(candidate) + if (candidate.ssr === false || candidate.ssr === 'data-only') { + pendingBoundary ??= index + } + break + } + if (candidate.status === 'pending') { + pendingBoundary ??= index + break + } + + committed.push(candidate) + if (candidate.ssr === 'data-only') { + pendingBoundary ??= index + } + } + let verifiedContextEnd = verifiedAssetEnd + + if ( + !isTerminal && + committed.length === shared && + shared < candidates.length + ) { + pendingBoundary = shared + } + + // Hooks observe structural membership. Execution remains limited to + // `committed`, the accepted server prefix. + const chunks = committed.map(async (match) => { + try { + const route = getRoute(router, match) + if (match._notFound) { + await Promise.all([ + loadRouteChunk(route), + loadRouteChunk(route, 'notFoundComponent'), + ]) + } else { + await loadRouteChunk( + route, + match.status === 'error' + ? 'errorComponent' + : match.status === 'notFound' + ? 'notFoundComponent' + : undefined, + ) + } + return true + } catch { + return false + } + }) + let chunkFailure = 0 + try { + while ( + chunkFailure < chunks.length && + (await waitFor(chunks[chunkFailure]!, controller.signal)) + ) { + chunkFailure++ + } + } catch { + isCurrent() + return + } + if (!isCurrent()) { + return + } + if (chunkFailure < committed.length) { + verifiedContextEnd = Math.min(verifiedContextEnd, chunkFailure) + retryFrom(chunkFailure) + } + + // The first pending match is already visible, so prepare its route context + // without granting its beforeLoad or loader any hydration authority. + const contextEnd = Math.max( + pendingBoundary === committed.length + ? committed.length + 1 + : committed.length, + verifiedContextEnd, + ) + for (let index = 0; index < contextEnd; index++) { + const match = candidates[index]! + const route = getRoute(router, match) + const parentContext = + candidates[index - 1]?.context ?? router.options.context ?? {} + let routeContext + if (route.options.context) { + try { + routeContext = match._ctx = + route.options.context({ + deps: match.loaderDeps, + params: match.params, + context: parentContext, + location, + navigate: navigateFrom(router, location), + buildLocation: router.buildLocation, + cause: match.cause, + abortController: controller, + preload: false, + matches: candidates, + routeId: route.id, + }) || {} + } catch { + if (!isCurrent()) { + return + } + if ( + match.status !== 'error' && + match.status !== 'notFound' && + !match._notFound + ) { + retryFrom(index) + break + } + } + if (!isCurrent()) { + return + } + } + match.context = { + ...parentContext, + ...routeContext, + ...(committed[index] && dehydratedMatches[index]!.b), + } + } + + await projectLane( + router, + [location, candidates] as any, + controller.signal, + 0, + verifiedAssetEnd, + ) + if (!isCurrent()) { + return + } + const needsClientLoad = + pendingBoundary !== undefined || committed.length < shared + const committedMatches = + isTerminal && committed.length === shared ? candidates : committed + let presented = needsClientLoad ? candidates : committedMatches + let dataOnlyAssetEnd: number | undefined + if (needsClientLoad && pendingBoundary !== undefined) { + const boundary = presented[pendingBoundary]! + dataOnlyAssetEnd = + boundary.status === 'success' && + boundary.ssr === 'data-only' && + boundary.error === undefined && + !boundary._notFound && + verifiedAssetEnd > pendingBoundary + 1 + ? verifiedAssetEnd + : undefined + presented = presented.slice() + presented[pendingBoundary] = { + ...boundary, + status: 'pending', + ssr: boundary.ssr === 'data-only' ? 'data-only' : false, + _assetEnd: dataOnlyAssetEnd, + } + } + + const claim = () => + needsClientLoad && + !router._tx && + router.latestLocation.state === location.state && + deepEqual(handoffInputs, laneInputs(router, router.latestLocation)) && + router._committed === committedMatches && + committedMatches.length && + !controller.signal.aborted + ? controller + : undefined + const handoff: NonNullable = [ + claim, + (matches) => { + if (router._handoff !== handoff) { + return + } + const prefix = committedMatches.length + if ( + !matches || + !claim() || + committedMatches.some((match, index) => match.id !== matches[index]?.id) + ) { + router._handoff = undefined + controller.abort() + return + } + let handoffAssetEnd = dataOnlyAssetEnd + if (handoffAssetEnd !== undefined) { + for (let index = prefix; index < handoffAssetEnd; index++) { + if (candidates[index]?.id !== matches[index]?.id) { + handoffAssetEnd = + index > (pendingBoundary ?? -1) + 1 ? index : undefined + break + } + } + } + const clones = committedMatches.map((match) => ({ ...match })) + if (handoffAssetEnd !== undefined) { + clones[pendingBoundary!]!._assetEnd = handoffAssetEnd + } + transferMatchResources(router, matches.splice(0, prefix, ...clones)) + for (let index = prefix; index < matches.length; index++) { + const match = matches[index]! + const hydrated = candidates[index] + if (hydrated?.id === match.id && hydrated._ctx) { + match._ctx = hydrated._ctx + } + match.abortController = controller + } + return prefix + }, + ] + router._committed = committedMatches + router._handoff = handoff + router._preflight = undefined + router.batch(() => { + router.stores.setMatches(presented) + router.stores.status.set('idle') + if (!needsClientLoad) { + router.stores.resolvedLocation.set(router.stores.location.get()) + } + }) +} diff --git a/packages/router-core/src/load-server.ts b/packages/router-core/src/load-server.ts index cc2a796b98..083d7ffb40 100644 --- a/packages/router-core/src/load-server.ts +++ b/packages/router-core/src/load-server.ts @@ -3,7 +3,7 @@ import { isNotFound } from './not-found' import { isRedirect, redirect } from './redirect' import { rootRouteId } from './root' -import { loadRouteChunk } from './route-chunks' +import { loadRouteChunk } from './load-client' import { waitForReason } from './await-signal' import { getLocationChangeInfo, runRouteLifecycle } from './router' import type { ParsedLocation } from './location' diff --git a/packages/router-core/src/rendered-matches.ts b/packages/router-core/src/rendered-matches.ts deleted file mode 100644 index 3534279312..0000000000 --- a/packages/router-core/src/rendered-matches.ts +++ /dev/null @@ -1,35 +0,0 @@ -import type { AnyRouteMatch } from './Matches' - -/** Return the structural lane through the first terminal render boundary. */ -export function _getRenderedMatches( - matches: Array, -): Array { - const end = - matches.findIndex( - (match) => match.status !== 'success' || match._notFound, - ) + 1 - return end && end < matches.length ? matches.slice(0, end) : matches -} - -/** Return the lane whose document assets belong to the current presentation. */ -export function _getAssetMatches( - matches: Array, -): Array { - let end = matches.length - for (let index = 0; index < end; index++) { - const match = matches[index]! - // `_assetEnd` is only ever set on hydration presentation clones that are - // `status: 'pending'`, `ssr: 'data-only'`, error-free, and not not-found - // (see hydrate.ts), and commits clear it — so its presence alone is the guard. - if (match._assetEnd !== undefined) { - end = Math.min(end, Math.max(index + 1, match._assetEnd)) - continue - } - if (match.status !== 'success' || match._notFound) { - end = index + 1 - break - } - } - // `end` only ever shrinks to `index + 1 >= 1`, so no zero guard is needed. - return end < matches.length ? matches.slice(0, end) : matches -} diff --git a/packages/router-core/src/route-chunks.ts b/packages/router-core/src/route-chunks.ts deleted file mode 100644 index 6b9f146136..0000000000 --- a/packages/router-core/src/route-chunks.ts +++ /dev/null @@ -1,70 +0,0 @@ -import type { AnyRoute } from './route' - -type RouteComponentType = - | 'component' - | 'pendingComponent' - | 'errorComponent' - | 'notFoundComponent' - -export function replaceRouteChunk( - route: AnyRoute, - lazyFn: AnyRoute['lazyFn'], -): void { - route.lazyFn = lazyFn ?? route.lazyFn - route._lazy = undefined -} - -function preloadComponent( - route: AnyRoute, - type: RouteComponentType, -): Promise | undefined { - return (route.options[type] as any)?.preload?.() -} - -function loadComponents(route: AnyRoute): Promise | undefined { - const component = preloadComponent(route, 'component') - const pending = preloadComponent(route, 'pendingComponent') - if (component && pending) { - return Promise.all([component, pending]).then(() => {}) - } - return component ?? pending -} - -export function loadRouteChunk( - route: AnyRoute, - // `false` waits only for lazy route options, before a boundary is selected. - componentType?: 'errorComponent' | 'notFoundComponent' | false, -): Promise | undefined { - const afterLazy = () => - componentType === false - ? undefined - : componentType - ? preloadComponent(route, componentType) - : loadComponents(route) - const current = route._lazy - if (current) { - return current === true ? afterLazy() : current.then(afterLazy) - } - if (!route.lazyFn) { - return afterLazy() - } - - const promise = route.lazyFn().then( - (lazyRoute) => { - // HMR clears the owner before an obsolete import can settle. - if (process.env.NODE_ENV === 'production' || route._lazy === promise) { - const { id: _id, ...options } = lazyRoute.options - Object.assign(route.options, options) - route._lazy = true - } - }, - (error) => { - if (process.env.NODE_ENV === 'production' || route._lazy === promise) { - route._lazy = undefined - } - throw error - }, - ) - route._lazy = promise - return promise.then(afterLazy) -} diff --git a/packages/router-core/src/router.ts b/packages/router-core/src/router.ts index 4d26bd7173..e2c9da3d25 100644 --- a/packages/router-core/src/router.ts +++ b/packages/router-core/src/router.ts @@ -37,11 +37,12 @@ import { rootRouteId } from './root' import { isRedirect } from './redirect' import { loadClientRoute, + loadRouteChunk, preloadClientRoute, refreshClientRoute, + replaceRouteChunk, transferMatchResources, } from './load-client' -import { loadRouteChunk, replaceRouteChunk } from './route-chunks' import { composeRewrites, executeRewriteInput, @@ -765,6 +766,7 @@ export type LoadFn = (opts?: { sync?: boolean action?: { type: HistoryAction } _signal?: AbortSignal + _dedupe?: boolean }) => Promise export type CommitLocationFn = ({ @@ -919,14 +921,16 @@ export function getLocationChangeInfo( } } -/** Return only state owned by the application, excluding history bookkeeping. */ +/** + * Return only state owned by the application, excluding volatile history + * bookkeeping. Mask payloads (`__tempLocation`/`__tempKey`) are kept: they + * distinguish otherwise-identical locations. + */ export function _getUserHistoryState({ key: _key, __TSR_key: _tsrKey, __TSR_index: _tsrIndex, __hashScrollIntoViewOptions: _hashScroll, - __tempLocation: _tempLocation, - __tempKey: _tempKey, ...state }: ParsedHistoryState): HistoryState { return state @@ -2165,7 +2169,7 @@ export class RouterCore< // Don't commit to history if nothing changed if (isSameLocation) { - this.load() + this.load({ _dedupe: true }) } else { let { // eslint-disable-next-line prefer-const @@ -2216,20 +2220,16 @@ export class RouterCore< nextHistory.state, { ignoreBlocker }, ) + + // Without a subscribed adapter the history commit cannot trigger the + // load itself. The same-location branch already loads directly. + if (!this.history.subscribers.size) { + this.load({ action: { type: historyAction } }) + } } this._scroll.next = next.resetScroll ?? true - if (!this.history.subscribers.size) { - this.load( - historyAction - ? { - action: { type: historyAction }, - } - : undefined, - ) - } - return this._commitPromise } diff --git a/packages/router-core/src/ssr/createRequestHandler.ts b/packages/router-core/src/ssr/createRequestHandler.ts index 49858ab286..a945effd01 100644 --- a/packages/router-core/src/ssr/createRequestHandler.ts +++ b/packages/router-core/src/ssr/createRequestHandler.ts @@ -1,5 +1,5 @@ import { createMemoryHistory } from '@tanstack/history' -import { _getRenderedMatches } from '../rendered-matches' +import { _getRenderedMatches } from '../load-client' import { mergeHeaders } from './headers' import { attachRouterServerSsrUtils, diff --git a/packages/router-core/src/ssr/ssr-client.ts b/packages/router-core/src/ssr/ssr-client.ts index 9f79934964..6b0921c8db 100644 --- a/packages/router-core/src/ssr/ssr-client.ts +++ b/packages/router-core/src/ssr/ssr-client.ts @@ -1 +1 @@ -export { hydrate } from '../hydrate' +export { hydrate } from '../load-client' diff --git a/packages/router-core/src/ssr/ssr-server.ts b/packages/router-core/src/ssr/ssr-server.ts index 24460e339f..30d3bc4890 100644 --- a/packages/router-core/src/ssr/ssr-server.ts +++ b/packages/router-core/src/ssr/ssr-server.ts @@ -8,7 +8,7 @@ import { import { decodePath } from '../utils' import { createLRUCache } from '../lru-cache' import { rootRouteId } from '../root' -import { _getRenderedMatches } from '../rendered-matches' +import { _getRenderedMatches } from '../load-client' import minifiedTsrBootStrapScript from './tsrScript?script-string' import { GLOBAL_TSR, TSR_SCRIPT_BARRIER_ID } from './constants' import { dehydrateSsrMatchId } from './ssr-match-id' diff --git a/packages/router-core/tests/build-location.test.ts b/packages/router-core/tests/build-location.test.ts index 94514a756b..ce0d5c3c98 100644 --- a/packages/router-core/tests/build-location.test.ts +++ b/packages/router-core/tests/build-location.test.ts @@ -9,7 +9,7 @@ import { import { _getUserHistoryState } from '../src/router' import { createTestRouter } from './routerTestUtils' -test('_getUserHistoryState removes router-owned bookkeeping', () => { +test('_getUserHistoryState removes volatile router bookkeeping but keeps mask payloads', () => { expect( _getUserHistoryState({ key: 'legacy-key', @@ -20,7 +20,7 @@ test('_getUserHistoryState removes router-owned bookkeeping', () => { __tempKey: 'temp-key', user: 'state', } as any), - ).toEqual({ user: 'state' }) + ).toEqual({ user: 'state', __tempLocation: {}, __tempKey: 'temp-key' }) }) describe('buildLocation - params function receives parsed params', () => { diff --git a/packages/router-core/tests/error-boundary-cache-generation.test.ts b/packages/router-core/tests/error-boundary-cache-generation.test.ts new file mode 100644 index 0000000000..447dace6ea --- /dev/null +++ b/packages/router-core/tests/error-boundary-cache-generation.test.ts @@ -0,0 +1,81 @@ +import { afterEach, describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, createControlledPromise } from '../src' +import { createTestRouter } from './routerTestUtils' + +afterEach(() => { + vi.restoreAllMocks() +}) + +describe('cache retention across an error-boundary commit', () => { + test('a superseded generation cannot shadow newer beyond-boundary data', async () => { + let parentFails = false + const parentGate = createControlledPromise() + const parentLoader = vi.fn(async () => { + if (parentFails) { + await parentGate + throw new Error('parent boom') + } + }) + let childVersion = 0 + let wantChildReload = false + const childLoader = vi.fn(() => ({ version: ++childVersion })) + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/p', + loader: parentLoader, + errorComponent: () => null, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: 'c', + shouldReload: () => wantChildReload, + loader: childLoader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/p/c'] }), + defaultStaleReloadMode: 'blocking', + }) + + await router.load() + expect(childLoader).toHaveBeenCalledTimes(1) + + // Same-destination refresh where the child settles a newer generation + // before the parent fails at the boundary. + parentFails = true + wantChildReload = true + const refresh = router.navigate({ to: '/p/c' }) + await vi.waitFor(() => expect(childLoader).toHaveBeenCalledTimes(2)) + parentGate.resolve() + await refresh + expect( + router.state.matches.find((match) => match.routeId === parentRoute.id), + ).toMatchObject({ status: 'error' }) + + // Leave and return with reloads declined: the presented child data must + // be the newer generation, not the superseded one. + parentFails = false + wantChildReload = false + await router.navigate({ to: '/' }) + await router.navigate({ to: '/p/c' }) + + const child = router.state.matches.find( + (match) => match.routeId === childRoute.id, + ) + expect(childLoader).toHaveBeenCalledTimes(2) + expect(child).toMatchObject({ + status: 'success', + loaderData: { version: 2 }, + }) + }) +}) diff --git a/packages/router-core/tests/loader-architecture-regressions.test.ts b/packages/router-core/tests/loader-architecture-regressions.test.ts index d85cf40ab2..e014a93bbe 100644 --- a/packages/router-core/tests/loader-architecture-regressions.test.ts +++ b/packages/router-core/tests/loader-architecture-regressions.test.ts @@ -862,7 +862,7 @@ test('a stale shouldReload cannot continue a superseded preload', async () => { expect(onError).not.toHaveBeenCalled() }) -test('an onLeave navigation suppresses stale lifecycle callbacks', async () => { +test('an onLeave navigation to the in-flight destination joins it and enters once', async () => { const firstEnter = vi.fn() const firstStay = vi.fn() let successor: Promise | undefined @@ -897,6 +897,8 @@ test('an onLeave navigation suppresses stale lifecycle callbacks', async () => { expect(router.state.location.pathname).toBe('/first') expect(router.state.matches.at(-1)?.routeId).toBe(firstRoute.id) - expect(firstEnter).not.toHaveBeenCalled() - expect(firstStay).toHaveBeenCalledOnce() + // The reentrant same-destination navigation joins the in-flight lane, so + // the route is entered exactly once rather than restarted into a stay. + expect(firstEnter).toHaveBeenCalledOnce() + expect(firstStay).not.toHaveBeenCalled() }) diff --git a/packages/router-core/tests/masked-location-state-commit.test.ts b/packages/router-core/tests/masked-location-state-commit.test.ts new file mode 100644 index 0000000000..9738b42261 --- /dev/null +++ b/packages/router-core/tests/masked-location-state-commit.test.ts @@ -0,0 +1,55 @@ +import { afterEach, describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +afterEach(() => { + vi.restoreAllMocks() +}) + +describe('masked location remnants in history state', () => { + test('a same-href navigation clears an expired mask from history state', async () => { + const makeRoutes = () => { + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const realRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/real', + }) + const prettyRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/pretty', + }) + return rootRoute.addChildren([indexRoute, realRoute, prettyRoute]) + } + const history = createMemoryHistory({ initialEntries: ['/'] }) + + const router1 = createTestRouter({ + routeTree: makeRoutes(), + history, + unmaskOnReload: true, + }) + await router1.load() + await router1.navigate({ to: '/real', mask: { to: '/pretty' } }) + expect(history.location.state.__tempLocation).toBeDefined() + + // A fresh router over the same history models a page reload: the + // per-session temp key no longer matches, so the mask has expired and the + // literal URL resolves. + const router2 = createTestRouter({ + routeTree: makeRoutes(), + history, + unmaskOnReload: true, + }) + await router2.load() + expect(router2.state.location.pathname).toBe('/pretty') + + // Navigating to the same href must still commit so the expired mask + // payload is dropped from history state, matching pre-lane behavior. + await router2.navigate({ to: '/pretty' }) + expect(history.location.state.__tempLocation).toBeUndefined() + }) +}) diff --git a/packages/router-core/tests/same-destination-navigation-join.test.ts b/packages/router-core/tests/same-destination-navigation-join.test.ts new file mode 100644 index 0000000000..cfe6c5ad45 --- /dev/null +++ b/packages/router-core/tests/same-destination-navigation-join.test.ts @@ -0,0 +1,110 @@ +import { afterEach, describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, createControlledPromise } from '../src' +import { createTestRouter } from './routerTestUtils' + +afterEach(() => { + vi.restoreAllMocks() +}) + +describe('same-destination navigation while one is in flight', () => { + function setup() { + const gate = createControlledPromise() + const loader = vi.fn(() => gate) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + return { router, loader, gate, targetRoute } + } + + test('a second navigation to the same destination joins the in-flight load', async () => { + const { router, loader, gate, targetRoute } = setup() + await router.load() + + const first = router.navigate({ to: '/target' }) + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(1)) + const second = router.navigate({ to: '/target' }) + + gate.resolve('once') + await Promise.all([first, second]) + + expect(loader).toHaveBeenCalledTimes(1) + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: targetRoute.id, + status: 'success', + loaderData: 'once', + }) + }) + + test('a double navigation in the same tick joins the in-flight load', async () => { + const { router, loader, gate, targetRoute } = setup() + await router.load() + + const first = router.navigate({ to: '/target' }) + const second = router.navigate({ to: '/target' }) + + gate.resolve('once') + await Promise.all([first, second]) + + expect(loader).toHaveBeenCalledTimes(1) + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: targetRoute.id, + status: 'success', + loaderData: 'once', + }) + }) + + test('invalidate reruns the loader after the navigation settles', async () => { + const { router, loader, gate } = setup() + gate.resolve('data') + await router.load() + await router.navigate({ to: '/target' }) + expect(loader).toHaveBeenCalledTimes(1) + + await router.invalidate() + + expect(loader).toHaveBeenCalledTimes(2) + }) + + test('invalidate during an in-flight navigation still reruns the loader', async () => { + const { router, loader, gate } = setup() + await router.load() + + const first = router.navigate({ to: '/target' }) + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(1)) + const second = router.invalidate() + + gate.resolve('data') + await Promise.all([first, second]) + + expect(loader).toHaveBeenCalledTimes(2) + }) + + test('a repeat navigation after settle reloads instead of joining', async () => { + const { router, loader, gate, targetRoute } = setup() + gate.resolve('data') + await router.load() + await router.navigate({ to: '/target' }) + + // Once the first navigation settles there is nothing to join: a repeat + // same-destination navigation keeps its refresh semantics. + await router.navigate({ to: '/target' }) + + expect(loader).toHaveBeenCalledTimes(2) + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: targetRoute.id, + status: 'success', + }) + }) +}) diff --git a/packages/router-devtools-core/tests/cache-replacement.test.ts b/packages/router-devtools-core/tests/cache-replacement.test.ts index 1f543ec408..1da523a1fb 100644 --- a/packages/router-devtools-core/tests/cache-replacement.test.ts +++ b/packages/router-devtools-core/tests/cache-replacement.test.ts @@ -1,4 +1,4 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest' import { TanStackRouterDevtoolsPanelCore } from '../src/TanStackRouterDevtoolsPanelCore' import type { AnyRouteMatch, AnyRouter } from '@tanstack/router-core' @@ -19,6 +19,12 @@ function createCachedMatch(loaderData: string): AnyRouteMatch { describe('cached matches', () => { let panel: TanStackRouterDevtoolsPanelCore | undefined + // Warm Vite's lazy transform of the panel chunk outside any test so its + // cost never counts against a test's timeout budget on slow CI runners. + beforeAll(async () => { + await import('../src/BaseTanStackRouterDevtoolsPanel') + }, 30_000) + afterEach(() => { panel?.unmount() panel = undefined @@ -30,8 +36,6 @@ describe('cached matches', () => { }) it('refreshes when an existing cache entry is replaced', async () => { - // Keep this cache-polling test independent of Vite's lazy transform time. - await import('../src/BaseTanStackRouterDevtoolsPanel') vi.useFakeTimers() const route = { @@ -96,5 +100,5 @@ describe('cached matches', () => { expect(container.textContent).toContain('new data') expect(container.textContent).not.toContain('old data') - }) + }, 10_000) }) diff --git a/packages/solid-router/src/Transitioner.tsx b/packages/solid-router/src/Transitioner.tsx index dfdd3c2c73..58b3dca076 100644 --- a/packages/solid-router/src/Transitioner.tsx +++ b/packages/solid-router/src/Transitioner.tsx @@ -29,7 +29,7 @@ export function Transitioner() { // Subscribe to location changes // and try to load the new location Solid.onMount(() => { - router.history.subscribe(router.load) + Solid.onCleanup(router.history.subscribe(router.load)) const nextLocation = router.buildLocation({ to: router.latestLocation.pathname, 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 656789b643..3ef09b437f 100644 --- a/packages/solid-router/tests/store-updates-during-navigation.test.tsx +++ b/packages/solid-router/tests/store-updates-during-navigation.test.tsx @@ -172,7 +172,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(3) + expect(updates).toBe(4) }) test('nothing', async () => { @@ -183,7 +183,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(3) + expect(updates).toBe(2) }) test('not found in beforeLoad', async () => { @@ -198,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(3) + expect(updates).toBe(2) }) test('hover preload, then navigate, w/ async loaders', async () => { @@ -224,7 +224,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('navigate, w/ preloaded & async loaders', async () => { @@ -240,7 +240,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(3) + expect(updates).toBe(2) }) test('navigate, w/ preloaded & sync loaders', async () => { @@ -256,7 +256,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(3) + expect(updates).toBe(2) }) test('navigate, w/ previous navigation & async loader', async () => { @@ -272,7 +272,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(3) + expect(updates).toBe(2) }) test('preload a preloaded route w/ async loader', async () => { diff --git a/packages/solid-router/tests/transitioner-remount.test.tsx b/packages/solid-router/tests/transitioner-remount.test.tsx new file mode 100644 index 0000000000..3c1bb37025 --- /dev/null +++ b/packages/solid-router/tests/transitioner-remount.test.tsx @@ -0,0 +1,91 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { cleanup, render, screen, waitFor } from '@solidjs/testing-library' +import { + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +afterEach(() => { + cleanup() +}) + +function setup() { + const rootRoute = createRootRoute({ component: () => }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
Index
, + }) + const nextRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/next', + component: () =>
Next
, + }) + const history = createMemoryHistory({ initialEntries: ['/'] }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, nextRoute]), + history, + }) + return { history, router } +} + +describe('Transitioner remount', () => { + // Zombie-router pin: once the provider unmounts, the history subscription + // must be torn down so a later history change never re-drives the router. + it('does not load after the provider unmounts', async () => { + const { history, router } = setup() + const loadSpy = vi.spyOn(router, 'load') + + const first = render(() => ) + expect(await screen.findByText('Index')).toBeTruthy() + await waitFor(() => expect(router.state.status).toBe('idle')) + + first.unmount() + loadSpy.mockClear() + + // A history change while unmounted must not reach the router. + history.push('/next') + await new Promise((resolve) => setTimeout(resolve, 0)) + + expect(loadSpy).not.toHaveBeenCalled() + // Raw history advanced... + expect(router.history.location.pathname).toBe('/next') + // ...but the router never processed it, so its committed state stayed put. + expect(router.state.location.pathname).toBe('/') + + loadSpy.mockRestore() + }) + + // Remounting the same router instance must re-establish the subscription so + // navigation keeps working, without leaving a stale duplicate behind. + it('re-subscribes and loads on remount with the same router', async () => { + const { history, router } = setup() + // Spy before the first mount so the subscription captures the spy by + // reference — both the first and second mounts subscribe with it. + const loadSpy = vi.spyOn(router, 'load') + + const first = render(() => ) + expect(await screen.findByText('Index')).toBeTruthy() + await waitFor(() => expect(router.state.status).toBe('idle')) + + first.unmount() + + render(() => ) + expect(await screen.findByText('Index')).toBeTruthy() + await waitFor(() => expect(router.state.status).toBe('idle')) + + // A push on the remounted provider must drive exactly one load, proving + // the subscription was re-established (and is singular). + loadSpy.mockClear() + history.push('/next') + expect(await screen.findByText('Next')).toBeTruthy() + expect(router.state.location.pathname).toBe('/next') + await waitFor(() => expect(loadSpy).toHaveBeenCalledTimes(1)) + + loadSpy.mockRestore() + }) +}) diff --git a/packages/vue-router/src/Transitioner.tsx b/packages/vue-router/src/Transitioner.tsx index 4878a51398..96f98b7bf3 100644 --- a/packages/vue-router/src/Transitioner.tsx +++ b/packages/vue-router/src/Transitioner.tsx @@ -17,7 +17,7 @@ export function useTransitionerSetup() { router.startTransition = transition Vue.onMounted(() => { - router.history.subscribe(router.load) + Vue.onUnmounted(router.history.subscribe(router.load)) const nextLocation = router.buildLocation({ to: router.latestLocation.pathname, 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 5fef250fec..8ad9a4b423 100644 --- a/packages/vue-router/tests/store-updates-during-navigation.test.tsx +++ b/packages/vue-router/tests/store-updates-during-navigation.test.tsx @@ -174,7 +174,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(4) }) test('nothing', async () => { @@ -186,7 +186,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 () => { @@ -202,7 +202,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 () => { @@ -229,7 +229,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('navigate, w/ preloaded & async loaders', async () => { @@ -246,7 +246,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 () => { @@ -263,7 +263,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 () => { @@ -280,7 +280,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 () => { diff --git a/packages/vue-router/tests/transitioner-remount.test.tsx b/packages/vue-router/tests/transitioner-remount.test.tsx new file mode 100644 index 0000000000..9ffb0e6f36 --- /dev/null +++ b/packages/vue-router/tests/transitioner-remount.test.tsx @@ -0,0 +1,92 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { cleanup, render, screen, waitFor } from '@testing-library/vue' +import { createMemoryHistory } from '@tanstack/history' +import { + Outlet, + RouterProvider, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +afterEach(() => { + cleanup() + document.body.innerHTML = '' +}) + +function setup() { + const rootRoute = createRootRoute({ component: () => }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
Index
, + }) + const nextRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/next', + component: () =>
Next
, + }) + const history = createMemoryHistory({ initialEntries: ['/'] }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, nextRoute]), + history, + }) + return { history, router } +} + +describe('Transitioner remount', () => { + // Zombie-router pin: once the provider unmounts, the history subscription + // must be torn down so a later history change never re-drives the router. + it('does not load after the provider unmounts', async () => { + const { history, router } = setup() + const loadSpy = vi.spyOn(router, 'load') + + const first = render() + expect(await screen.findByText('Index')).toBeTruthy() + await waitFor(() => expect(router.state.status).toBe('idle')) + + first.unmount() + loadSpy.mockClear() + + // A history change while unmounted must not reach the router. + history.push('/next') + await new Promise((resolve) => setTimeout(resolve, 0)) + + expect(loadSpy).not.toHaveBeenCalled() + // Raw history advanced... + expect(router.history.location.pathname).toBe('/next') + // ...but the router never processed it, so its committed state stayed put. + expect(router.state.location.pathname).toBe('/') + + loadSpy.mockRestore() + }) + + // Remounting the same router instance must re-establish the subscription so + // navigation keeps working, without leaving a stale duplicate behind. + it('re-subscribes and loads on remount with the same router', async () => { + const { history, router } = setup() + // Spy before the first mount so the subscription captures the spy by + // reference — both the first and second mounts subscribe with it. + const loadSpy = vi.spyOn(router, 'load') + + const first = render() + expect(await screen.findByText('Index')).toBeTruthy() + await waitFor(() => expect(router.state.status).toBe('idle')) + + first.unmount() + + render() + expect(await screen.findByText('Index')).toBeTruthy() + await waitFor(() => expect(router.state.status).toBe('idle')) + + // A push on the remounted provider must drive exactly one load, proving + // the subscription was re-established (and is singular). + loadSpy.mockClear() + history.push('/next') + expect(await screen.findByText('Next')).toBeTruthy() + expect(router.state.location.pathname).toBe('/next') + await waitFor(() => expect(loadSpy).toHaveBeenCalledTimes(1)) + + loadSpy.mockRestore() + }) +}) From 55ceb3a3e442055aa6b61cf4952c3afb5da6034a Mon Sep 17 00:00:00 2001 From: Flo Date: Thu, 23 Jul 2026 17:50:25 +0200 Subject: [PATCH 54/59] chore(router-core): lane match loader final byte-shave (#7885) --- packages/router-core/src/load-client.ts | 38 ++++++++------ .../loader-architecture-regressions.test.ts | 6 ++- .../tests/preflight-reentrant-context.test.ts | 7 ++- .../preload-public-cache-behavior.test.ts | 52 +++++++++++++++++++ 4 files changed, 83 insertions(+), 20 deletions(-) diff --git a/packages/router-core/src/load-client.ts b/packages/router-core/src/load-client.ts index 51151ad56b..897d479e09 100644 --- a/packages/router-core/src/load-client.ts +++ b/packages/router-core/src/load-client.ts @@ -913,20 +913,21 @@ function createLoaderTask( normalizeLaneError(route, cause, options), ], ) - const chunkFailure = rawChunkFailure.then(async (failure) => { - const result = await outcome - if ( - blocking && - !failure && - result[0] === SUCCESS && - match.status === 'pending' && - options[2]() - ) { - match.status = 'success' - options[8]?.() - } - return failure - }) + const chunkFailure = rawChunkFailure.then((failure) => + outcome.then((result) => { + if ( + blocking && + !failure && + result[0] === SUCCESS && + match.status === 'pending' && + options[2]() + ) { + match.status = 'success' + options[8]?.() + } + return failure + }), + ) tasks.push([index, outcome, chunkFailure]) if (!background) { return outcome.then((result) => getParentSnapshot(match, result)) @@ -1498,12 +1499,12 @@ function commitMatches( // at the next planning pass. Unsettled beyond-boundary matches are not — // they must not evict a newer same-id preload. if ( + match.status !== 'success' || matches.some( (candidate, index) => candidate.id === match.id && (index < cut || candidate.status === 'success'), - ) || - match.status !== 'success' + ) ) { continue } @@ -2260,7 +2261,10 @@ export async function preloadClientRoute( executeClientLane(router, location, matches!, [ controller, redirects, - () => router._tx === owner || router._tx?.[0] === controller, + // Preload lanes run to completion even when unrelated navigations + // commit: finished work seeds the cache, and adoption safety is + // enforced independently by samePreloadLane's base identity check. + () => true, base, true, ]), diff --git a/packages/router-core/tests/loader-architecture-regressions.test.ts b/packages/router-core/tests/loader-architecture-regressions.test.ts index e014a93bbe..1efc42cc73 100644 --- a/packages/router-core/tests/loader-architecture-regressions.test.ts +++ b/packages/router-core/tests/loader-architecture-regressions.test.ts @@ -859,7 +859,11 @@ test('a stale shouldReload cannot continue a superseded preload', async () => { expect(router.state.location.pathname).toBe('/winner') expect(router.state.matches.at(-1)?.routeId).toBe(winnerRoute.id) expect(loader).toHaveBeenCalledOnce() - expect(onError).not.toHaveBeenCalled() + // Preload lanes run to completion despite the navigation, so the stale + // shouldReload's failure surfaces through onError (matching pre-rewrite + // behavior for preload errors) — but it cannot restart the loader or + // disturb the winning navigation. + expect(onError).toHaveBeenCalledOnce() }) test('an onLeave navigation to the in-flight destination joins it and enters once', async () => { diff --git a/packages/router-core/tests/preflight-reentrant-context.test.ts b/packages/router-core/tests/preflight-reentrant-context.test.ts index 62d4c6fbb7..415e5f0e50 100644 --- a/packages/router-core/tests/preflight-reentrant-context.test.ts +++ b/packages/router-core/tests/preflight-reentrant-context.test.ts @@ -50,7 +50,7 @@ test('synchronous navigation from route context stops abandoned descendant conte expect(childContext).not.toHaveBeenCalled() }) -test('synchronous navigation from preloaded route context stops abandoned descendant context work', async () => { +test('synchronous navigation from preloaded route context lets the preload finish quietly', async () => { let redirected = false let redirectNavigation: Promise | undefined const childContext = vi.fn(() => ({ child: true })) @@ -94,5 +94,8 @@ test('synchronous navigation from preloaded route context stops abandoned descen await redirectNavigation expect(router.state.location.pathname).toBe('/target') - expect(childContext).not.toHaveBeenCalled() + // Preload lanes are not cancelled by navigations: the descendant context + // still computes (and may seed the cache), while the navigation wins the + // presented state. Only navigation lanes stop abandoned descendant work. + expect(childContext).toHaveBeenCalledOnce() }) diff --git a/packages/router-core/tests/preload-public-cache-behavior.test.ts b/packages/router-core/tests/preload-public-cache-behavior.test.ts index 1962b30ab5..5a7b6b2b98 100644 --- a/packages/router-core/tests/preload-public-cache-behavior.test.ts +++ b/packages/router-core/tests/preload-public-cache-behavior.test.ts @@ -407,3 +407,55 @@ test('invalidate and an unrelated in-flight preload both settle cleanly', async ).toBe('target data') expect(loader).toHaveBeenCalledTimes(1) }) + +// Preload lanes are not cancelled by unrelated navigations: an in-flight +// async beforeLoad runs to completion, its loader still executes and seeds +// the cache, and a later navigation to the target reuses that work. +test('an unrelated navigation does not cancel an in-flight preload beforeLoad', async () => { + const beforeLoadGate = createControlledPromise<{ token: string }>() + const beforeLoad = vi.fn(() => beforeLoadGate) + const loader = vi.fn(() => 'target data') + const rootRoute = new BaseRootRoute({}) + const homeRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const otherRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/other', + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + preloadStaleTime: Infinity, + staleTime: Infinity, + beforeLoad, + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([homeRoute, otherRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const preload = router.preloadRoute({ to: '/target' }) + await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledTimes(1)) + + // Unrelated navigation commits while the preload's beforeLoad is pending. + await router.navigate({ to: '/other' }) + expect(router.state.location.pathname).toBe('/other') + + beforeLoadGate.resolve({ token: 'ctx' }) + await preload + // The preload completed its work despite the navigation. + expect(loader).toHaveBeenCalledTimes(1) + + // Navigating to the target consumes the seeded cache without a new load. + await router.navigate({ to: '/target' }) + expect(router.state.location.pathname).toBe('/target') + expect( + router.state.matches.find((match) => match.routeId === targetRoute.id) + ?.loaderData, + ).toBe('target data') + expect(loader).toHaveBeenCalledTimes(1) +}) From c1ba06ab3ffeb637036751840e2c7d80fe7dc4a6 Mon Sep 17 00:00:00 2001 From: Manuel Schiller <6340397+schiller-manuel@users.noreply.github.com> Date: Thu, 23 Jul 2026 22:45:31 +0200 Subject: [PATCH 55/59] failing regression test for #4614 --- .../selective-ssr/src/routes/__root.tsx | 37 +++++------- .../selective-ssr/src/routes/issue-4614.tsx | 7 +-- .../selective-ssr/tests/app.spec.ts | 57 ++++--------------- 3 files changed, 29 insertions(+), 72 deletions(-) diff --git a/e2e/react-start/selective-ssr/src/routes/__root.tsx b/e2e/react-start/selective-ssr/src/routes/__root.tsx index 3465abf298..d4e96a27e6 100644 --- a/e2e/react-start/selective-ssr/src/routes/__root.tsx +++ b/e2e/react-start/selective-ssr/src/routes/__root.tsx @@ -32,9 +32,7 @@ export const Route = createRootRoute({ }), validateSearch: z.object({ root: ssrSchema, - issue4614: z.string().optional(), }), - loaderDeps: ({ search }) => ({ issue4614: search.issue4614 }), ssr: ({ search }) => { if (typeof window !== 'undefined') { const error = `ssr() for ${Route.id} should not be called on the client` @@ -57,21 +55,23 @@ export const Route = createRootRoute({ console.error(error) throw new Error(error) } - const root = typeof window === 'undefined' ? 'server' : 'client' - const issue4614Context = `${root}:${search.issue4614 ?? 'cached'}` + const isClient = typeof window !== 'undefined' + const isServer = !isClient + const root = isServer ? 'server' : 'client' if (typeof window !== 'undefined' && location.pathname === '/issue-4614') { const calls = ((globalThis as any).__issue4614RootBeforeLoads ??= []) calls.push({ cause, preload, - root, - issue4614Context, + isClient, + isServer, }) } return { root, search, - issue4614Context, + isClient, + isServer, } }, loader: ({ context }) => { @@ -120,6 +120,12 @@ export const Route = createRootRoute({ context:{' '} {Route.useRouteContext().root} +
+ issue #4614 context:{' '} + + {`${Route.useRouteContext().isClient}:${Route.useRouteContext().isServer}`} + +

@@ -149,21 +155,8 @@ function RootDocument({ children }: { children: React.ReactNode }) { > Home - - Issue 4614 cached parent - - - Issue 4614 reloaded parent + + Issue 4614
diff --git a/e2e/react-start/selective-ssr/src/routes/issue-4614.tsx b/e2e/react-start/selective-ssr/src/routes/issue-4614.tsx index 7e59b8d0ac..5bf4b72a5f 100644 --- a/e2e/react-start/selective-ssr/src/routes/issue-4614.tsx +++ b/e2e/react-start/selective-ssr/src/routes/issue-4614.tsx @@ -2,13 +2,12 @@ import { createFileRoute } from '@tanstack/react-router' export const Route = createFileRoute('/issue-4614')({ ssr: false, - beforeLoad: ({ context, cause, preload, search }) => { + beforeLoad: ({ context, cause, preload }) => { ;(globalThis as any).__issue4614TargetBeforeLoad = { cause, preload, - rootContext: context.root, - issue4614Context: context.issue4614Context, - scenario: search.issue4614 ?? 'cached', + isClient: context.isClient, + isServer: context.isServer, } }, component: () =>
Issue 4614
, diff --git a/e2e/react-start/selective-ssr/tests/app.spec.ts b/e2e/react-start/selective-ssr/tests/app.spec.ts index 89eff32cae..e926f57354 100644 --- a/e2e/react-start/selective-ssr/tests/app.spec.ts +++ b/e2e/react-start/selective-ssr/tests/app.spec.ts @@ -4,49 +4,15 @@ import { test } from '@tanstack/router-e2e-utils' const testCount = 7 test.describe('selective ssr', () => { - test('#4614: cached parent loader data does not cache its beforeLoad context', async ({ + test('propagates client root context to an ssr:false child during intent preload (#4614)', async ({ page, }) => { await page.goto('/') - await page.getByTestId('issue-4614-cached-link').hover() + await expect(page.getByTestId('issue-4614-root-context')).toHaveText( + 'false:true', + ) - await expect - .poll(() => - page.evaluate(() => (globalThis as any).__issue4614TargetBeforeLoad), - ) - .not.toBeUndefined() - - const { rootBeforeLoads, targetBeforeLoad } = await page.evaluate(() => { - const rootBeforeLoads = - (globalThis as any).__issue4614RootBeforeLoads ?? [] - return { - rootBeforeLoads, - targetBeforeLoad: (globalThis as any).__issue4614TargetBeforeLoad, - } - }) - - expect(rootBeforeLoads).toEqual([ - { - cause: 'preload', - preload: true, - root: 'client', - issue4614Context: 'client:cached', - }, - ]) - expect(targetBeforeLoad).toEqual({ - cause: 'preload', - preload: true, - rootContext: 'client', - issue4614Context: 'client:cached', - scenario: 'cached', - }) - }) - - test('new loaderDeps match generation propagates fresh parent context to child (control)', async ({ - page, - }) => { - await page.goto('/') - await page.getByTestId('issue-4614-reload-link').hover() + await page.getByTestId('issue-4614-link').hover() await expect .poll(() => @@ -54,10 +20,10 @@ test.describe('selective ssr', () => { ) .toEqual([ { - cause: 'preload', - preload: true, - root: 'client', - issue4614Context: 'client:reload', + cause: 'enter', + preload: false, + isClient: true, + isServer: false, }, ]) await expect @@ -67,9 +33,8 @@ test.describe('selective ssr', () => { .toEqual({ cause: 'preload', preload: true, - rootContext: 'client', - issue4614Context: 'client:reload', - scenario: 'reload', + isClient: true, + isServer: false, }) }) From 185fcccbf0c712c5b456f6acc6f6f7d325cfa7bc Mon Sep 17 00:00:00 2001 From: Manuel Schiller <6340397+schiller-manuel@users.noreply.github.com> Date: Fri, 24 Jul 2026 00:04:38 +0200 Subject: [PATCH 56/59] failing regressiontest for #6221 --- e2e/react-start/basic/src/routeTree.gen.ts | 42 +++++ .../src/routes/issue-6221.article.$id.tsx | 42 +++++ .../basic/src/routes/issue-6221.dashboard.tsx | 6 + .../basic/tests/issue-6221-head.spec.ts | 41 +++++ .../issue-6221-head-waits-for-loader.test.ts | 162 ------------------ 5 files changed, 131 insertions(+), 162 deletions(-) create mode 100644 e2e/react-start/basic/src/routes/issue-6221.article.$id.tsx create mode 100644 e2e/react-start/basic/src/routes/issue-6221.dashboard.tsx create mode 100644 e2e/react-start/basic/tests/issue-6221-head.spec.ts delete mode 100644 packages/router-core/tests/issue-6221-head-waits-for-loader.test.ts diff --git a/e2e/react-start/basic/src/routeTree.gen.ts b/e2e/react-start/basic/src/routeTree.gen.ts index 10a40bc044..ea09864d8e 100644 --- a/e2e/react-start/basic/src/routeTree.gen.ts +++ b/e2e/react-start/basic/src/routeTree.gen.ts @@ -29,6 +29,7 @@ import { Route as TypeOnlyReexportRouteImport } from './routes/type-only-reexpor import { Route as UsersRouteImport } from './routes/users' import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' import { Route as ApiUsersRouteImport } from './routes/api.users' +import { Route as Issue6221DashboardRouteImport } from './routes/issue-6221.dashboard' import { Route as MultiCookieRedirectIndexRouteImport } from './routes/multi-cookie-redirect/index' import { Route as MultiCookieRedirectTargetRouteImport } from './routes/multi-cookie-redirect/target' import { Route as NotFoundIndexRouteImport } from './routes/not-found/index' @@ -61,6 +62,7 @@ import { Route as UsersUserIdRouteImport } from './routes/users.$userId' import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' import { Route as ApiUsersIdRouteImport } from './routes/api/users.$id' +import { Route as Issue6221ArticleIdRouteImport } from './routes/issue-6221.article.$id' import { Route as NotFoundDeepIndexRouteImport } from './routes/not-found/deep/index' import { Route as NotFoundDeepBRouteRouteImport } from './routes/not-found/deep/b/route' import { Route as NotFoundParentBoundaryIndexRouteImport } from './routes/not-found/parent-boundary/index' @@ -179,6 +181,11 @@ const ApiUsersRoute = ApiUsersRouteImport.update({ path: '/api/users', getParentRoute: () => rootRouteImport, } as any) +const Issue6221DashboardRoute = Issue6221DashboardRouteImport.update({ + id: '/issue-6221/dashboard', + path: '/issue-6221/dashboard', + getParentRoute: () => rootRouteImport, +} as any) const MultiCookieRedirectIndexRoute = MultiCookieRedirectIndexRouteImport.update({ id: '/multi-cookie-redirect/', @@ -346,6 +353,11 @@ const ApiUsersIdRoute = ApiUsersIdRouteImport.update({ path: '/$id', getParentRoute: () => ApiUsersRoute, } as any) +const Issue6221ArticleIdRoute = Issue6221ArticleIdRouteImport.update({ + id: '/issue-6221/article/$id', + path: '/issue-6221/article/$id', + getParentRoute: () => rootRouteImport, +} as any) const NotFoundDeepIndexRoute = NotFoundDeepIndexRouteImport.update({ id: '/', path: '/', @@ -468,6 +480,7 @@ export interface FileRoutesByFullPath { '/not-found/parent-boundary': typeof NotFoundParentBoundaryRouteRouteWithChildren '/specialChars/malformed': typeof SpecialCharsMalformedRouteRouteWithChildren '/api/users': typeof ApiUsersRouteWithChildren + '/issue-6221/dashboard': typeof Issue6221DashboardRoute '/multi-cookie-redirect/target': typeof MultiCookieRedirectTargetRoute '/not-found/via-beforeLoad': typeof NotFoundViaBeforeLoadRoute '/not-found/via-beforeLoad-target-root': typeof NotFoundViaBeforeLoadTargetRootRoute @@ -498,6 +511,7 @@ export interface FileRoutesByFullPath { '/layout-a': typeof LayoutLayout2LayoutARoute '/layout-b': typeof LayoutLayout2LayoutBRoute '/api/users/$id': typeof ApiUsersIdRoute + '/issue-6221/article/$id': typeof Issue6221ArticleIdRoute '/not-found/parent-boundary/via-beforeLoad': typeof NotFoundParentBoundaryViaBeforeLoadRoute '/posts/$postId/deep': typeof PostsPostIdDeepRoute '/redirect/$target/via-beforeLoad': typeof RedirectTargetViaBeforeLoadRoute @@ -531,6 +545,7 @@ export interface FileRoutesByTo { '/type-only-reexport': typeof TypeOnlyReexportRoute '/specialChars/malformed': typeof SpecialCharsMalformedRouteRouteWithChildren '/api/users': typeof ApiUsersRouteWithChildren + '/issue-6221/dashboard': typeof Issue6221DashboardRoute '/multi-cookie-redirect/target': typeof MultiCookieRedirectTargetRoute '/not-found/via-beforeLoad': typeof NotFoundViaBeforeLoadRoute '/not-found/via-beforeLoad-target-root': typeof NotFoundViaBeforeLoadTargetRootRoute @@ -560,6 +575,7 @@ export interface FileRoutesByTo { '/layout-a': typeof LayoutLayout2LayoutARoute '/layout-b': typeof LayoutLayout2LayoutBRoute '/api/users/$id': typeof ApiUsersIdRoute + '/issue-6221/article/$id': typeof Issue6221ArticleIdRoute '/not-found/parent-boundary/via-beforeLoad': typeof NotFoundParentBoundaryViaBeforeLoadRoute '/posts/$postId/deep': typeof PostsPostIdDeepRoute '/redirect/$target/via-beforeLoad': typeof RedirectTargetViaBeforeLoadRoute @@ -602,6 +618,7 @@ export interface FileRoutesById { '/specialChars/malformed': typeof SpecialCharsMalformedRouteRouteWithChildren '/_layout/_layout-2': typeof LayoutLayout2RouteWithChildren '/api/users': typeof ApiUsersRouteWithChildren + '/issue-6221/dashboard': typeof Issue6221DashboardRoute '/multi-cookie-redirect/target': typeof MultiCookieRedirectTargetRoute '/not-found/via-beforeLoad': typeof NotFoundViaBeforeLoadRoute '/not-found/via-beforeLoad-target-root': typeof NotFoundViaBeforeLoadTargetRootRoute @@ -632,6 +649,7 @@ export interface FileRoutesById { '/_layout/_layout-2/layout-a': typeof LayoutLayout2LayoutARoute '/_layout/_layout-2/layout-b': typeof LayoutLayout2LayoutBRoute '/api/users/$id': typeof ApiUsersIdRoute + '/issue-6221/article/$id': typeof Issue6221ArticleIdRoute '/not-found/parent-boundary/via-beforeLoad': typeof NotFoundParentBoundaryViaBeforeLoadRoute '/posts_/$postId/deep': typeof PostsPostIdDeepRoute '/redirect/$target/via-beforeLoad': typeof RedirectTargetViaBeforeLoadRoute @@ -674,6 +692,7 @@ export interface FileRouteTypes { | '/not-found/parent-boundary' | '/specialChars/malformed' | '/api/users' + | '/issue-6221/dashboard' | '/multi-cookie-redirect/target' | '/not-found/via-beforeLoad' | '/not-found/via-beforeLoad-target-root' @@ -704,6 +723,7 @@ export interface FileRouteTypes { | '/layout-a' | '/layout-b' | '/api/users/$id' + | '/issue-6221/article/$id' | '/not-found/parent-boundary/via-beforeLoad' | '/posts/$postId/deep' | '/redirect/$target/via-beforeLoad' @@ -737,6 +757,7 @@ export interface FileRouteTypes { | '/type-only-reexport' | '/specialChars/malformed' | '/api/users' + | '/issue-6221/dashboard' | '/multi-cookie-redirect/target' | '/not-found/via-beforeLoad' | '/not-found/via-beforeLoad-target-root' @@ -766,6 +787,7 @@ export interface FileRouteTypes { | '/layout-a' | '/layout-b' | '/api/users/$id' + | '/issue-6221/article/$id' | '/not-found/parent-boundary/via-beforeLoad' | '/posts/$postId/deep' | '/redirect/$target/via-beforeLoad' @@ -807,6 +829,7 @@ export interface FileRouteTypes { | '/specialChars/malformed' | '/_layout/_layout-2' | '/api/users' + | '/issue-6221/dashboard' | '/multi-cookie-redirect/target' | '/not-found/via-beforeLoad' | '/not-found/via-beforeLoad-target-root' @@ -837,6 +860,7 @@ export interface FileRouteTypes { | '/_layout/_layout-2/layout-a' | '/_layout/_layout-2/layout-b' | '/api/users/$id' + | '/issue-6221/article/$id' | '/not-found/parent-boundary/via-beforeLoad' | '/posts_/$postId/deep' | '/redirect/$target/via-beforeLoad' @@ -876,10 +900,12 @@ export interface RootRouteChildren { TypeOnlyReexportRoute: typeof TypeOnlyReexportRoute UsersRoute: typeof UsersRouteWithChildren ApiUsersRoute: typeof ApiUsersRouteWithChildren + Issue6221DashboardRoute: typeof Issue6221DashboardRoute MultiCookieRedirectTargetRoute: typeof MultiCookieRedirectTargetRoute RedirectTargetRoute: typeof RedirectTargetRouteWithChildren MultiCookieRedirectIndexRoute: typeof MultiCookieRedirectIndexRoute RedirectIndexRoute: typeof RedirectIndexRoute + Issue6221ArticleIdRoute: typeof Issue6221ArticleIdRoute PostsPostIdDeepRoute: typeof PostsPostIdDeepRoute FooBarQuxHereRoute: typeof FooBarQuxHereRouteWithChildren } @@ -1026,6 +1052,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ApiUsersRouteImport parentRoute: typeof rootRouteImport } + '/issue-6221/dashboard': { + id: '/issue-6221/dashboard' + path: '/issue-6221/dashboard' + fullPath: '/issue-6221/dashboard' + preLoaderRoute: typeof Issue6221DashboardRouteImport + parentRoute: typeof rootRouteImport + } '/multi-cookie-redirect/': { id: '/multi-cookie-redirect/' path: '/multi-cookie-redirect' @@ -1250,6 +1283,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ApiUsersIdRouteImport parentRoute: typeof ApiUsersRoute } + '/issue-6221/article/$id': { + id: '/issue-6221/article/$id' + path: '/issue-6221/article/$id' + fullPath: '/issue-6221/article/$id' + preLoaderRoute: typeof Issue6221ArticleIdRouteImport + parentRoute: typeof rootRouteImport + } '/not-found/deep/': { id: '/not-found/deep/' path: '/' @@ -1648,10 +1688,12 @@ const rootRouteChildren: RootRouteChildren = { TypeOnlyReexportRoute: TypeOnlyReexportRoute, UsersRoute: UsersRouteWithChildren, ApiUsersRoute: ApiUsersRouteWithChildren, + Issue6221DashboardRoute: Issue6221DashboardRoute, MultiCookieRedirectTargetRoute: MultiCookieRedirectTargetRoute, RedirectTargetRoute: RedirectTargetRouteWithChildren, MultiCookieRedirectIndexRoute: MultiCookieRedirectIndexRoute, RedirectIndexRoute: RedirectIndexRoute, + Issue6221ArticleIdRoute: Issue6221ArticleIdRoute, PostsPostIdDeepRoute: PostsPostIdDeepRoute, FooBarQuxHereRoute: FooBarQuxHereRouteWithChildren, } diff --git a/e2e/react-start/basic/src/routes/issue-6221.article.$id.tsx b/e2e/react-start/basic/src/routes/issue-6221.article.$id.tsx new file mode 100644 index 0000000000..c923a5f1cb --- /dev/null +++ b/e2e/react-start/basic/src/routes/issue-6221.article.$id.tsx @@ -0,0 +1,42 @@ +import { Link, createFileRoute } from '@tanstack/react-router' +import { createClientOnlyFn } from '@tanstack/react-start' + +const isAuthed = createClientOnlyFn( + () => localStorage.getItem('issue-6221-auth') === 'good', +) + +const fetchArticle = async (id: string) => { + await new Promise((resolve) => setTimeout(resolve, 1000)) + return isAuthed() + ? { + title: `Article Title for ${id}`, + content: `Article content for ${id}`, + } + : null +} + +export const Route = createFileRoute('/issue-6221/article/$id')({ + ssr: false, + loader: ({ params }) => fetchArticle(params.id), + head: ({ loaderData }) => ({ + meta: [{ title: loaderData?.title ?? 'title n/a' }], + }), + component: Article, +}) + +function Article() { + const article = Route.useLoaderData() + + return ( +
+ + Dashboard + + {article ? ( +
{article.content}
+ ) : ( +
Article Not Accessible.
+ )} +
+ ) +} diff --git a/e2e/react-start/basic/src/routes/issue-6221.dashboard.tsx b/e2e/react-start/basic/src/routes/issue-6221.dashboard.tsx new file mode 100644 index 0000000000..8c93da669c --- /dev/null +++ b/e2e/react-start/basic/src/routes/issue-6221.dashboard.tsx @@ -0,0 +1,6 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/issue-6221/dashboard')({ + head: () => ({ meta: [{ title: 'Dashboard' }] }), + component: () =>
Dashboard
, +}) diff --git a/e2e/react-start/basic/tests/issue-6221-head.spec.ts b/e2e/react-start/basic/tests/issue-6221-head.spec.ts new file mode 100644 index 0000000000..96274ce0f9 --- /dev/null +++ b/e2e/react-start/basic/tests/issue-6221-head.spec.ts @@ -0,0 +1,41 @@ +import { expect } from '@playwright/test' +import { test } from '@tanstack/router-e2e-utils' +import { isPreview } from './utils/isPreview' +import { isSpaMode } from './utils/isSpaMode' + +// Ported to React from the regression app in +// https://github.com/TanStack/router/pull/6222 +test.skip( + isSpaMode || isPreview, + 'head() coverage for an ssr:false route requires the SSR test mode', +) + +test('browser back uses fresh loaderData for both the body and head (#6221)', async ({ + page, +}) => { + await page.goto('/') + await page.evaluate(() => localStorage.setItem('issue-6221-auth', 'good')) + + await page.goto('/issue-6221/article/1') + + await expect(page.getByTestId('issue-6221-article')).toHaveText( + 'Article content for 1', + ) + await expect(page).toHaveTitle('Article Title for 1') + + await page.evaluate(() => localStorage.removeItem('issue-6221-auth')) + await page.reload() + await expect(page.getByText('Article Not Accessible.')).toBeVisible() + await expect(page).toHaveTitle('title n/a') + + await page.evaluate(() => localStorage.setItem('issue-6221-auth', 'good')) + await page.getByTestId('issue-6221-dashboard-link').click() + await expect(page.getByTestId('issue-6221-dashboard')).toBeVisible() + await expect(page).toHaveTitle('Dashboard') + + await page.goBack() + await expect(page.getByTestId('issue-6221-article')).toHaveText( + 'Article content for 1', + ) + await expect(page).toHaveTitle('Article Title for 1') +}) 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 deleted file mode 100644 index 55cf11c277..0000000000 --- a/packages/router-core/tests/issue-6221-head-waits-for-loader.test.ts +++ /dev/null @@ -1,162 +0,0 @@ -import { createMemoryHistory } from '@tanstack/history' -import { describe, expect, test, vi } from 'vitest' -import { - BaseRootRoute, - BaseRoute, - createControlledPromise, - notFound, -} from '../src' -import { createTestRouter } from './routerTestUtils' - -// 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('existing-behavior control: head sees fresh loaderData after a notFound visit', async () => { - let authed = false - const articleResponse = createControlledPromise<{ title: string }>() - const successfulLoadStarted = createControlledPromise() - - const articleLoader = async () => { - if (!authed) { - await Promise.resolve() - throw notFound() - } - - successfulLoadStarted.resolve() - return articleResponse - } - - const rootRoute = new BaseRootRoute({}) - const dashboardRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/dashboard', - }) - const articleRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/article', - loader: articleLoader, - notFoundComponent: () => 'Not found', - head: ({ loaderData }) => ({ - meta: [{ title: loaderData?.title ?? 'Generic title' }], - }), - }) - - const router = createTestRouter({ - routeTree: rootRoute.addChildren([dashboardRoute, articleRoute]), - history: createMemoryHistory({ initialEntries: ['/article'] }), - }) - const backLoadFinished = createControlledPromise() - let backLoadStarted = false - let unsubscribe: (() => void) | undefined - - try { - await router.load() - const notFoundMatch = router.state.matches.find( - (match) => match.routeId === articleRoute.id, - ) - expect(notFoundMatch?.status).toBe('notFound') - expect(notFoundMatch?.meta).toEqual([{ title: 'Generic title' }]) - - // Model the reported auth redirect and browser Back without relying on a - // wall-clock loader delay. - authed = true - await router.navigate({ to: '/dashboard' }) - unsubscribe = router.history.subscribe(() => { - backLoadStarted = true - void router.load().then( - () => backLoadFinished.resolve(), - (error) => backLoadFinished.reject(error), - ) - }) - router.history.back() - await successfulLoadStarted - expect(articleResponse.status).toBe('pending') - - articleResponse.resolve({ title: 'Article 123' }) - await backLoadFinished - - const articleMatch = router.state.matches.find( - (match) => match.routeId === articleRoute.id, - ) - expect(articleMatch?.status).toBe('success') - expect(articleMatch?.loaderData).toEqual({ title: 'Article 123' }) - expect(articleMatch?.meta).toEqual([{ title: 'Article 123' }]) - } finally { - articleResponse.resolve({ title: 'Article 123' }) - if (backLoadStarted) { - await backLoadFinished.catch(() => undefined) - } - unsubscribe?.() - } - }) - - test('head title does not lag one loaderData run behind on revisits', async () => { - const secondLoaderStarted = createControlledPromise() - const secondLoaderResponse = createControlledPromise<{ author: string }>() - let version = 0 - const quoteLoader = () => { - version += 1 - if (version === 2) { - secondLoaderStarted.resolve() - return secondLoaderResponse - } - - return { author: 'author-1' } - } - - const rootRoute = new BaseRootRoute({}) - const indexRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/', - }) - const quoteRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/quote', - loader: quoteLoader, - staleTime: 0, - head: ({ loaderData }) => ({ - meta: [{ title: `Quote by ${loaderData?.author ?? '...'}` }], - }), - }) - - const router = createTestRouter({ - routeTree: rootRoute.addChildren([indexRoute, quoteRoute]), - history: createMemoryHistory({ initialEntries: ['/'] }), - }) - - const getQuoteMatch = () => - router.state.matches.find((match) => match.routeId === quoteRoute.id) - try { - await router.load() - - await router.navigate({ to: '/quote' }) - expect(getQuoteMatch()?.loaderData).toEqual({ author: 'author-1' }) - expect(getQuoteMatch()?.meta).toEqual([{ title: 'Quote by author-1' }]) - - await router.navigate({ to: '/' }) - const revisit = router.navigate({ to: '/quote' }) - await secondLoaderStarted - await revisit - - // The cached generation remains internally consistent while its stale - // loader is pending in the background. - expect(secondLoaderResponse.status).toBe('pending') - expect(getQuoteMatch()?.loaderData).toEqual({ author: 'author-1' }) - expect(getQuoteMatch()?.meta).toEqual([{ title: 'Quote by author-1' }]) - - secondLoaderResponse.resolve({ author: 'author-2' }) - await vi.waitFor(() => { - expect(getQuoteMatch()?.loaderData).toEqual({ author: 'author-2' }) - expect(getQuoteMatch()?.meta).toEqual([{ title: 'Quote by author-2' }]) - }) - } finally { - secondLoaderResponse.resolve({ author: 'author-2' }) - } - }) -}) From aba4ddc4bed7adb5908307e98f0fc6a75dfcdefc Mon Sep 17 00:00:00 2001 From: Manuel Schiller <6340397+schiller-manuel@users.noreply.github.com> Date: Fri, 24 Jul 2026 00:13:01 +0200 Subject: [PATCH 57/59] tests --- .../selective-ssr/tests/app.spec.ts | 4 +- .../tests/transitioner-render-ack.test.tsx | 94 ++++++++++++-- .../src/tests/hydrateStart.test.ts | 18 ++- .../public-preload-lane-contract.test.ts | 118 +++++++++++++----- .../src/tests/hydrateStart.test.ts | 18 ++- 5 files changed, 207 insertions(+), 45 deletions(-) diff --git a/e2e/react-start/selective-ssr/tests/app.spec.ts b/e2e/react-start/selective-ssr/tests/app.spec.ts index e926f57354..ad85bf3e22 100644 --- a/e2e/react-start/selective-ssr/tests/app.spec.ts +++ b/e2e/react-start/selective-ssr/tests/app.spec.ts @@ -20,8 +20,8 @@ test.describe('selective ssr', () => { ) .toEqual([ { - cause: 'enter', - preload: false, + cause: 'preload', + preload: true, isClient: true, isServer: false, }, diff --git a/packages/react-router/tests/transitioner-render-ack.test.tsx b/packages/react-router/tests/transitioner-render-ack.test.tsx index 535a1e0e71..b533c225b3 100644 --- a/packages/react-router/tests/transitioner-render-ack.test.tsx +++ b/packages/react-router/tests/transitioner-render-ack.test.tsx @@ -21,7 +21,7 @@ afterEach(() => { vi.useRealTimers() }) -test('same-location invalidation resolves after its refreshed DOM commits', async () => { +test('same-location invalidation emits onResolved after its refreshed DOM commits', async () => { let generation = 0 const rootRoute = createRootRoute({ component: Outlet }) const indexRoute = createRoute({ @@ -57,31 +57,103 @@ test('same-location invalidation resolves after its refreshed DOM commits', asyn expect(refreshedDomWasVisible).toEqual([true]) }) -test('an immediately completed background refresh cannot replace the acknowledged foreground generation', async () => { - let generation = 0 +test('a late background refresh is discarded after foreground navigation commits', async () => { + const backgroundRefresh = createControlledPromise() + let sourceGeneration = 0 + const itemLoader = vi.fn((itemId: string) => { + if (itemId === 'source') { + sourceGeneration++ + if (sourceGeneration === 1) { + return 'initial source data' + } + return backgroundRefresh + } + return 'foreground target data' + }) const rootRoute = createRootRoute({ component: Outlet }) - const indexRoute = createRoute({ + const itemRoute = createRoute({ getParentRoute: () => rootRoute, - path: '/', + path: '/items/$itemId', loader: { staleReloadMode: 'background', - handler: () => ++generation, + handler: ({ params }) => itemLoader(params.itemId), }, - component: () =>
Generation {indexRoute.useLoaderData()}
, + component: () => ( +
+ Item {itemRoute.useParams().itemId}: {itemRoute.useLoaderData()} +
+ ), }) const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute]), - history: createMemoryHistory({ initialEntries: ['/'] }), + routeTree: rootRoute.addChildren([itemRoute]), + history: createMemoryHistory({ initialEntries: ['/items/source'] }), }) render() - expect(await screen.findByText('Generation 1')).toBeInTheDocument() + expect( + await screen.findByText('Item source: initial source data'), + ).toBeInTheDocument() await waitFor(() => expect(router.state.status).toBe('idle')) + const sourceMatchId = router.state.matches.at(-1)!.id + + const eventLog: Array = [] + const unsubscribers = [ + router.subscribe('onResolved', (event) => { + eventLog.push(`onResolved:${event.toLocation.pathname}`) + }), + router.subscribe('onRendered', (event) => { + eventLog.push(`onRendered:${event.toLocation.pathname}`) + }), + ] + testCleanups.push(...unsubscribers) await act(() => router.invalidate()) + expect(itemLoader).toHaveBeenCalledTimes(2) - expect(await screen.findByText('Generation 2')).toBeInTheDocument() + await act(() => + router.navigate({ + to: '/items/$itemId', + params: { itemId: 'target' }, + }), + ) + expect( + screen.getByText('Item target: foreground target data'), + ).toBeInTheDocument() + expect(eventLog.filter((event) => event.endsWith('/items/target'))).toEqual([ + 'onResolved:/items/target', + 'onRendered:/items/target', + ]) + expect(router.state.resolvedLocation?.pathname).toBe('/items/target') + const eventCountAfterForegroundCommit = eventLog.length + + await act(async () => { + backgroundRefresh.resolve('obsolete source data') + await Promise.resolve() + }) + await waitFor(() => { + expect(router._flights?.has(sourceMatchId) ?? false).toBe(false) + const cachedSourceMatch = router._cache.get(sourceMatchId) + expect(cachedSourceMatch?.loaderData).toBe('initial source data') + expect(cachedSourceMatch?.isFetching).toBe(false) + }) + + expect( + screen.getByText('Item target: foreground target data'), + ).toBeInTheDocument() + expect( + screen.queryByText('Item source: obsolete source data'), + ).not.toBeInTheDocument() + expect(router.state.location.pathname).toBe('/items/target') + expect(router.state.resolvedLocation?.pathname).toBe('/items/target') + expect(router.state.matches.at(-1)?.routeId).toBe(itemRoute.id) + expect(router.state.matches.at(-1)?.params).toEqual({ itemId: 'target' }) + expect(router.state.matches.at(-1)?.loaderData).toBe('foreground target data') expect(router.state.status).toBe('idle') + expect( + eventLog + .slice(eventCountAfterForegroundCommit) + .every((event) => event.endsWith('/items/target')), + ).toBe(true) }) test('a navigation started by route lifecycle keeps the pending minimum of its own render', async () => { diff --git a/packages/react-start-client/src/tests/hydrateStart.test.ts b/packages/react-start-client/src/tests/hydrateStart.test.ts index 2d34400009..51de4981ea 100644 --- a/packages/react-start-client/src/tests/hydrateStart.test.ts +++ b/packages/react-start-client/src/tests/hydrateStart.test.ts @@ -14,11 +14,23 @@ afterEach(() => { test('signals streaming cleanup after hydration succeeds', async () => { const router = {} - coreHydrateStart.mockResolvedValue(router) + let resolveCoreHydration!: (value: object) => void + coreHydrateStart.mockReturnValue( + new Promise((resolve) => { + resolveCoreHydration = resolve + }), + ) const hydrated = vi.fn() window.$_TSR = { h: hydrated } as any - await expect(hydrateStart()).resolves.toBe(router) + const hydration = hydrateStart() + await Promise.resolve() + + expect(coreHydrateStart).toHaveBeenCalledOnce() + expect(hydrated).not.toHaveBeenCalled() + + resolveCoreHydration(router) + await expect(hydration).resolves.toBe(router) expect(hydrated).toHaveBeenCalledTimes(1) }) @@ -29,5 +41,7 @@ test('signals streaming cleanup without hiding a hydration failure', async () => window.$_TSR = { h: hydrated } as any await expect(hydrateStart()).rejects.toBe(error) + + expect(coreHydrateStart).toHaveBeenCalledOnce() expect(hydrated).toHaveBeenCalledTimes(1) }) diff --git a/packages/router-core/tests/public-preload-lane-contract.test.ts b/packages/router-core/tests/public-preload-lane-contract.test.ts index 42170003ad..7b13e6a0c9 100644 --- a/packages/router-core/tests/public-preload-lane-contract.test.ts +++ b/packages/router-core/tests/public-preload-lane-contract.test.ts @@ -245,6 +245,12 @@ describe('public preload lane contracts', () => { navigationMask: { to: '/mask-b' }, preloadPathname: '/mask-a', navigationPathname: '/mask-b', + preloadUnmaskOnReload: undefined, + navigationUnmaskOnReload: undefined, + preloadSearchSource: undefined, + navigationSearchSource: undefined, + preloadStateSource: undefined, + navigationStateSource: undefined, }, { difference: 'unmaskOnReload', @@ -252,6 +258,12 @@ describe('public preload lane contracts', () => { navigationMask: { to: '/mask-a', unmaskOnReload: true }, preloadPathname: '/mask-a', navigationPathname: '/mask-a', + preloadUnmaskOnReload: undefined, + navigationUnmaskOnReload: true, + preloadSearchSource: undefined, + navigationSearchSource: undefined, + preloadStateSource: undefined, + navigationStateSource: undefined, }, { difference: 'search', @@ -259,6 +271,12 @@ describe('public preload lane contracts', () => { navigationMask: { to: '/mask-a', search: { source: 'navigation' } }, preloadPathname: '/mask-a', navigationPathname: '/mask-a', + preloadUnmaskOnReload: undefined, + navigationUnmaskOnReload: undefined, + preloadSearchSource: 'preload', + navigationSearchSource: 'navigation', + preloadStateSource: undefined, + navigationStateSource: undefined, }, { difference: 'state', @@ -266,6 +284,12 @@ describe('public preload lane contracts', () => { navigationMask: { to: '/mask-a', state: { source: 'navigation' } }, preloadPathname: '/mask-a', navigationPathname: '/mask-a', + preloadUnmaskOnReload: undefined, + navigationUnmaskOnReload: undefined, + preloadSearchSource: undefined, + navigationSearchSource: undefined, + preloadStateSource: 'preload', + navigationStateSource: 'navigation', }, ])( 'navigation reruns beforeLoad for a different explicit mask $difference on the same destination', @@ -274,20 +298,16 @@ describe('public preload lane contracts', () => { navigationMask, preloadPathname, navigationPathname, + preloadUnmaskOnReload, + navigationUnmaskOnReload, + preloadSearchSource, + navigationSearchSource, + preloadStateSource, + navigationStateSource, }) => { const beforeLoadGate = createControlledPromise() const loaderGate = createControlledPromise() - const beforeLoad = vi.fn( - async (context: { - location: { maskedLocation?: { pathname: string } } - preload: boolean - }) => { - if (context.preload) { - await beforeLoadGate - } - return { source: context.preload ? 'preload' : 'navigation' } - }, - ) + const beforeLoadCalls = vi.fn() const loader = vi.fn(() => loaderGate) const rootRoute = new BaseRootRoute({}) const indexRoute = new BaseRoute({ @@ -297,7 +317,24 @@ describe('public preload lane contracts', () => { const targetRoute = new BaseRoute({ getParentRoute: () => rootRoute, path: '/target', - beforeLoad, + beforeLoad: async (context) => { + const maskedLocation = context.location.maskedLocation + beforeLoadCalls({ + preload: context.preload, + pathname: maskedLocation?.pathname, + unmaskOnReload: maskedLocation?.unmaskOnReload, + searchSource: ( + maskedLocation?.search as { source?: string } | undefined + )?.source, + stateSource: ( + maskedLocation?.state as { source?: string } | undefined + )?.source, + }) + if (context.preload) { + await beforeLoadGate + } + return { source: context.preload ? 'preload' : 'navigation' } + }, loader, }) const maskARoute = new BaseRoute({ @@ -327,7 +364,7 @@ describe('public preload lane contracts', () => { to: '/target', mask: preloadMask as any, }) - await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledTimes(1)) + await vi.waitFor(() => expect(beforeLoadCalls).toHaveBeenCalledTimes(1)) beforeLoadGate.resolve() await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(1)) @@ -337,14 +374,21 @@ describe('public preload lane contracts', () => { mask: navigationMask as any, }) await vi.waitFor(() => - expect( - beforeLoad.mock.calls.map(([callContext]) => ({ - preload: callContext.preload, - pathname: callContext.location.maskedLocation?.pathname, - })), - ).toEqual([ - { preload: true, pathname: preloadPathname }, - { preload: false, pathname: navigationPathname }, + expect(beforeLoadCalls.mock.calls.map(([call]) => call)).toEqual([ + { + preload: true, + pathname: preloadPathname, + unmaskOnReload: preloadUnmaskOnReload, + searchSource: preloadSearchSource, + stateSource: preloadStateSource, + }, + { + preload: false, + pathname: navigationPathname, + unmaskOnReload: navigationUnmaskOnReload, + searchSource: navigationSearchSource, + stateSource: navigationStateSource, + }, ]), ) @@ -1151,20 +1195,24 @@ describe('public preload lane contracts', () => { expect(router.state.matches.at(-1)?.loaderData).toBe('loader data 1') }) - test('filtered invalidation reloads every generation of the selected match id', async () => { + test('filtered invalidation invalidates active and cached generations of the selected route', async () => { const loader = vi.fn(() => `loader data ${loader.mock.calls.length}`) const rootRoute = new BaseRootRoute({}) const targetRoute = new BaseRoute({ getParentRoute: () => rootRoute, path: '/target', + staleTime: Infinity, + preloadStaleTime: Infinity, + preloadGcTime: Infinity, + gcTime: Infinity, validateSearch: (search: Record) => ({ revision: Number(search.revision ?? 1), }), - shouldReload: ({ location }) => - (location.search as { revision: number }).revision === 2 - ? true - : undefined, - loader, + loaderDeps: ({ search }) => ({ revision: search.revision }), + loader: { + staleReloadMode: 'blocking', + handler: loader, + }, }) const router = createTestRouter({ routeTree: rootRoute.addChildren([targetRoute]), @@ -1178,12 +1226,26 @@ describe('public preload lane contracts', () => { to: '/target', search: { revision: 2 }, }) + expect(loader).toHaveBeenCalledTimes(2) + await router.invalidate({ - filter: (match) => (match.search as { revision?: number }).revision === 1, + filter: (match) => match.routeId === targetRoute.id, }) expect(loader).toHaveBeenCalledTimes(3) expect(router.state.matches.at(-1)?.loaderData).toBe('loader data 3') + + await router.navigate({ + to: '/target', + search: { revision: 2 }, + }) + + expect(loader).toHaveBeenCalledTimes(4) + expect(router.state.matches.at(-1)).toMatchObject({ + invalid: false, + loaderData: 'loader data 4', + search: { revision: 2 }, + }) }) test('a hidden terminal suffix does not evict a newer same-id preload', async () => { diff --git a/packages/solid-start-client/src/tests/hydrateStart.test.ts b/packages/solid-start-client/src/tests/hydrateStart.test.ts index 2d34400009..51de4981ea 100644 --- a/packages/solid-start-client/src/tests/hydrateStart.test.ts +++ b/packages/solid-start-client/src/tests/hydrateStart.test.ts @@ -14,11 +14,23 @@ afterEach(() => { test('signals streaming cleanup after hydration succeeds', async () => { const router = {} - coreHydrateStart.mockResolvedValue(router) + let resolveCoreHydration!: (value: object) => void + coreHydrateStart.mockReturnValue( + new Promise((resolve) => { + resolveCoreHydration = resolve + }), + ) const hydrated = vi.fn() window.$_TSR = { h: hydrated } as any - await expect(hydrateStart()).resolves.toBe(router) + const hydration = hydrateStart() + await Promise.resolve() + + expect(coreHydrateStart).toHaveBeenCalledOnce() + expect(hydrated).not.toHaveBeenCalled() + + resolveCoreHydration(router) + await expect(hydration).resolves.toBe(router) expect(hydrated).toHaveBeenCalledTimes(1) }) @@ -29,5 +41,7 @@ test('signals streaming cleanup without hiding a hydration failure', async () => window.$_TSR = { h: hydrated } as any await expect(hydrateStart()).rejects.toBe(error) + + expect(coreHydrateStart).toHaveBeenCalledOnce() expect(hydrated).toHaveBeenCalledTimes(1) }) From 8aa727f415d6c1d49f7ecb126c6f70be152cb065 Mon Sep 17 00:00:00 2001 From: Manuel Schiller <6340397+schiller-manuel@users.noreply.github.com> Date: Mon, 27 Jul 2026 23:00:49 +0200 Subject: [PATCH 58/59] fixes --- .changeset/lane-match-loader-rewrite.md | 8 +- docs/router/api/router/RouterType.md | 9 +- docs/router/guide/preloading.md | 9 +- .../src/routeTree.gen.ts | 21 + .../src/routes/__root.tsx | 1 + .../src/routes/preload-disabled.tsx | 6 + .../tests/preload.spec.ts | 25 + .../basic-file-based/src/main.tsx | 4 + .../basic-file-based/tests/mask.spec.ts | 65 + .../issue-7120/src/routeTree.gen.ts | 26 +- .../issue-7457/src/routeTree.gen.ts | 26 +- e2e/react-start/basic/src/routeTree.gen.ts | 21 + .../src/routes/client-context-failure.tsx | 23 + .../tests/client-context-failure.spec.ts | 29 + .../selective-ssr/src/routeTree.gen.ts | 62 +- packages/react-router/src/Matches.tsx | 27 +- packages/react-router/src/Transitioner.tsx | 225 ++- .../react-router/src/headContentUtils.tsx | 129 +- .../react-router/src/lazyRouteComponent.tsx | 39 +- .../tests/component-preload-retry.test.tsx | 66 + .../tests/errorComponent.test.tsx | 46 +- .../issue-4467-lazy-route-pending.test.tsx | 29 +- .../react-render-owner-contract.test.tsx | 140 ++ .../router-client-context-retry.test.tsx | 88 ++ packages/react-router/tests/router.test.tsx | 8 +- .../tests/transitioner-remount.test.tsx | 52 +- .../tests/transitioner-render-ack.test.tsx | 180 ++- packages/router-core/INTERNALS.md | 398 +++--- packages/router-core/src/load-client.ts | 1262 ++++++++--------- packages/router-core/src/router.ts | 186 ++- .../router-core/src/ssr/handlerCallback.ts | 153 +- packages/router-core/src/ssr/server.ts | 1 + .../src/ssr/transformStreamWithRouter.ts | 5 +- packages/router-core/src/stores.ts | 6 +- packages/router-core/src/utils.ts | 9 - .../router-core/tests/build-location.test.ts | 8 +- packages/router-core/tests/callbacks.test.ts | 99 +- .../tests/hmr-refresh-lifecycle.test.ts | 48 +- ...search-default-normalization-abort.test.ts | 109 -- packages/router-core/tests/load.test.ts | 23 +- .../loader-architecture-regressions.test.ts | 577 +++++++- .../masked-location-state-commit.test.ts | 2 +- .../tests/pending-terminal-boundary.test.ts | 103 ++ .../tests/preload-adoption.test.ts | 133 +- .../tests/preload-beforeload-reuse.test.ts | 78 +- .../tests/preload-navigation-adoption.test.ts | 66 +- .../preload-public-cache-behavior.test.ts | 222 ++- .../preload-public-signal-lifetime.test.ts | 20 +- .../tests/public-hydration-contract.test.ts | 167 ++- .../public-preload-lane-contract.test.ts | 1205 ++++++++++------ .../tests/ssr-server-cleanup.test.ts | 272 +++- .../solid-router/src/lazyRouteComponent.tsx | 77 +- .../tests/component-preload-retry.test.tsx | 66 + .../src/client-rpc/frame-decoder.ts | 466 +++--- .../src/client-rpc/serverFnFetcher.ts | 155 +- packages/start-client-core/src/constants.ts | 8 +- packages/start-client-core/src/index.tsx | 2 + .../tests/frame-decoder.test.ts | 354 ++++- .../tests/serverFnFetcher.test.ts | 395 ++++++ .../src/createStartHandler.ts | 288 ++-- .../start-server-core/src/frame-protocol.ts | 292 ++-- .../src/server-functions-handler.ts | 262 ++-- .../tests/createStartHandler.test.ts | 569 +++++++- .../tests/frame-protocol.test.ts | 456 +++--- .../tests/server-functions-handler.test.ts | 247 ++++ packages/vue-router/src/CatchBoundary.tsx | 45 +- packages/vue-router/src/headContentUtils.tsx | 58 +- .../vue-router/src/lazyRouteComponent.tsx | 120 +- .../vue-router/tests/CatchBoundary.test.tsx | 144 ++ .../tests/component-preload-retry.test.tsx | 234 ++- 70 files changed, 7423 insertions(+), 3331 deletions(-) create mode 100644 e2e/react-router/basic-file-based-code-splitting/src/routes/preload-disabled.tsx create mode 100644 e2e/react-start/basic/src/routes/client-context-failure.tsx create mode 100644 e2e/react-start/basic/tests/client-context-failure.spec.ts create mode 100644 packages/react-router/tests/react-render-owner-contract.test.tsx create mode 100644 packages/react-router/tests/router-client-context-retry.test.tsx delete mode 100644 packages/router-core/tests/issue-6371-search-default-normalization-abort.test.ts create mode 100644 packages/router-core/tests/pending-terminal-boundary.test.ts create mode 100644 packages/start-client-core/tests/serverFnFetcher.test.ts create mode 100644 packages/start-server-core/tests/server-functions-handler.test.ts create mode 100644 packages/vue-router/tests/CatchBoundary.test.tsx diff --git a/.changeset/lane-match-loader-rewrite.md b/.changeset/lane-match-loader-rewrite.md index ddd71fa4c5..3833ca60bc 100644 --- a/.changeset/lane-match-loader-rewrite.md +++ b/.changeset/lane-match-loader-rewrite.md @@ -3,12 +3,18 @@ '@tanstack/react-router': patch '@tanstack/solid-router': patch '@tanstack/vue-router': patch +'@tanstack/router-devtools-core': patch +'@tanstack/react-router-devtools': patch +'@tanstack/solid-router-devtools': patch +'@tanstack/vue-router-devtools': patch +'@tanstack/router-devtools': patch --- Rewrite match loading around a lane-based scheduler that tracks each navigation, preload, and background reload as an ordered unit of work. This fixes pending/redirect/retry state leaking between overlapping navigations, restores correct SSR status codes for redirects, errors, and not-found responses, and closes hydration gaps where the client re-ran work the server had already completed. - Route `headers()` now only runs on the server, matching the documented behavior — it is no longer invoked during client-side asset projection. - Default `gcTime` and `preloadGcTime` are reduced from 30 minutes (`1_800_000`) to 5 minutes (`300_000`). +- Devtools packages are released alongside the router packages so they consume the rewritten router store interface. **Removed / changed public API** @@ -26,4 +32,4 @@ Rewrite match loading around a lane-based scheduler that tracks each navigation, - Removed the exported `GetMatchFn` and `UpdateMatchFn` types, along with the methods they typed. - Removed the standalone `getMatchedRoutes()` export from `@tanstack/router-core` — use the `router.getMatchedRoutes()` instance method instead. - `MatchRoutesOpts.preload` and `MatchRoutesOpts.dest` have been removed. -- `StartTransitionFn` is now `(fn, expected, urgent?) => Promise` (previously `(fn) => void`). This only affects custom framework adapters that implement `startTransition`. +- `StartTransitionFn` is now `(fn, expected) => Promise` (previously `(fn) => void`). This only affects custom framework adapters that implement `startTransition`. diff --git a/docs/router/api/router/RouterType.md b/docs/router/api/router/RouterType.md index 0252eb5b80..9c659fa02c 100644 --- a/docs/router/api/router/RouterType.md +++ b/docs/router/api/router/RouterType.md @@ -134,8 +134,8 @@ protocol. - Type: `(opts?: {filter?: (d: MakeRouteMatchUnion) => boolean, sync?: boolean, forcePending?: boolean }) => Promise` - This is useful any time your loader data might be out of date or stale. For example, if you have a route that displays a list of posts, and you have a loader function that fetches the list of posts from an API, you might want to invalidate the route matches for that route any time a new post is created so that the list of posts is always up-to-date. -- If `filter` is not supplied, all committed and cached match generations are invalidated. -- If `filter` is supplied, it is evaluated against committed and cached matches. Selecting one generation invalidates every committed or cached generation with the same match ID. +- If `filter` is not supplied, all committed and cached match generations are invalidated and all active preloads are canceled. +- If `filter` is supplied, it is evaluated against the available committed, cached, loading, and preloading matches. Selecting one match invalidates every generation with the same match ID. An active preload is canceled when its lane contains a selected match ID. - Invalidation reruns `beforeLoad`; reusable loader data is marked stale and reloads through the normal loading protocol. Route-level `context` remains reusable while the match ID is unchanged. - If `sync` is `true`, stale loader work is blocking and the returned promise resolves after it finishes instead of leaving a background refresh detached. - If `forcePending` is `true`, selected routes that need loading enter the normal pending protocol even when successful data was already available. @@ -169,9 +169,8 @@ presentation. Successful loader data can enter the normal in-memory route cache and remain reusable according to `preloadStaleTime` and `preloadGcTime`. Completed preload `beforeLoad` context is not cached. A later navigation reruns -`beforeLoad` unless it adopts an identical whole-route preload that is still -active. Adoption also requires unchanged router context, additional context, -and user-supplied location state. +`beforeLoad` with navigation semantics. It can still join a pending loader for +the same match ID or reuse completed cached loader data. - Type: `(opts: NavigateOptions) => Promise` - Properties diff --git a/docs/router/guide/preloading.md b/docs/router/guide/preloading.md index 669a11175d..1b13b438b6 100644 --- a/docs/router/guide/preloading.md +++ b/docs/router/guide/preloading.md @@ -26,9 +26,8 @@ two independent lifetimes: - **Unused retention defaults to 5 minutes.** Configure it with `defaultPreloadGcTime` or a route's `preloadGcTime`. - **The speculative lane is never promoted into router state.** Navigation - creates its own presentation and can reuse cached loader data. It reruns - `beforeLoad` unless it adopts the same whole lane while that preload is still - active. + creates its own presentation and reruns `beforeLoad`, but it can reuse cached + loader data or join a loader for the same match that is still pending. If you need more control over preloading, caching and/or garbage collection of preloaded data, you should use an external caching library like [TanStack Query](https://tanstack.com/query). @@ -145,9 +144,7 @@ export const Route = createFileRoute('/posts/$postId')({ Client-side preloading also runs each new route's `beforeLoad` with `preload: true`. A completed preload never caches the context returned by `beforeLoad`; a later navigation calls `beforeLoad` again with `preload: false`, even when it reuses the preload's cached loader data. -There is one exception: if navigation starts while an identical whole-route preload is still running, it can adopt that active work. Compatibility includes the complete ordered route lane, params, search, router context, additional context, user-supplied location state, redirect depth, and any explicit mask's href, search, state, and `unmaskOnReload` value. Router-managed history and temporary-mask keys are ignored. In that case navigation can use the active preload's `beforeLoad` result, or follow its redirect, without calling `beforeLoad` again. A completed, failed, not-found, or canceled preload does not donate `beforeLoad` context to a later navigation. The `shouldReload` option remains loader-only. - -If any route in the lane has `preload: false`, navigation does not adopt the active preload. It reruns the `beforeLoad` chain and performs the loader work that speculation skipped. +A navigation never adopts speculative `beforeLoad` context or control flow. If a loader for the same match ID is already pending, navigation can join that loader promise after running its own `beforeLoad`. The joined promise shares its loader outcome, including an error, not-found result, or redirect. Cancellation remains lane-local: canceling one waiter releases its lease without canceling a generation that another lane still owns. Only successful loader data persists in the loader cache; after a failed preload loader has settled, a later navigation runs a new generation. Invalidation or a `shouldReload` decision can also require a new generation. A route with `preload: false` skips its speculative loader work and loads normally during navigation. ## Preloading with External Libraries diff --git a/e2e/react-router/basic-file-based-code-splitting/src/routeTree.gen.ts b/e2e/react-router/basic-file-based-code-splitting/src/routeTree.gen.ts index c7a15cd84e..613c5a7dae 100644 --- a/e2e/react-router/basic-file-based-code-splitting/src/routeTree.gen.ts +++ b/e2e/react-router/basic-file-based-code-splitting/src/routeTree.gen.ts @@ -12,6 +12,7 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' import { Route as LayoutRouteImport } from './routes/_layout' import { Route as PostsRouteImport } from './routes/posts' +import { Route as PreloadDisabledRouteImport } from './routes/preload-disabled' import { Route as SharedSingletonRouteImport } from './routes/shared-singleton' import { Route as ViewportTestRouteImport } from './routes/viewport-test' import { Route as WithoutLoaderRouteImport } from './routes/without-loader' @@ -35,6 +36,11 @@ const PostsRoute = PostsRouteImport.update({ path: '/posts', getParentRoute: () => rootRouteImport, } as any) +const PreloadDisabledRoute = PreloadDisabledRouteImport.update({ + id: '/preload-disabled', + path: '/preload-disabled', + getParentRoute: () => rootRouteImport, +} as any) const SharedSingletonRoute = SharedSingletonRouteImport.update({ id: '/shared-singleton', path: '/shared-singleton', @@ -78,6 +84,7 @@ const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ export interface FileRoutesByFullPath { '/': typeof IndexRoute '/posts': typeof PostsRouteWithChildren + '/preload-disabled': typeof PreloadDisabledRoute '/shared-singleton': typeof SharedSingletonRoute '/viewport-test': typeof ViewportTestRoute '/without-loader': typeof WithoutLoaderRoute @@ -88,6 +95,7 @@ export interface FileRoutesByFullPath { } export interface FileRoutesByTo { '/': typeof IndexRoute + '/preload-disabled': typeof PreloadDisabledRoute '/shared-singleton': typeof SharedSingletonRoute '/viewport-test': typeof ViewportTestRoute '/without-loader': typeof WithoutLoaderRoute @@ -101,6 +109,7 @@ export interface FileRoutesById { '/': typeof IndexRoute '/_layout': typeof LayoutRouteWithChildren '/posts': typeof PostsRouteWithChildren + '/preload-disabled': typeof PreloadDisabledRoute '/shared-singleton': typeof SharedSingletonRoute '/viewport-test': typeof ViewportTestRoute '/without-loader': typeof WithoutLoaderRoute @@ -115,6 +124,7 @@ export interface FileRouteTypes { fullPaths: | '/' | '/posts' + | '/preload-disabled' | '/shared-singleton' | '/viewport-test' | '/without-loader' @@ -125,6 +135,7 @@ export interface FileRouteTypes { fileRoutesByTo: FileRoutesByTo to: | '/' + | '/preload-disabled' | '/shared-singleton' | '/viewport-test' | '/without-loader' @@ -137,6 +148,7 @@ export interface FileRouteTypes { | '/' | '/_layout' | '/posts' + | '/preload-disabled' | '/shared-singleton' | '/viewport-test' | '/without-loader' @@ -151,6 +163,7 @@ export interface RootRouteChildren { IndexRoute: typeof IndexRoute LayoutRoute: typeof LayoutRouteWithChildren PostsRoute: typeof PostsRouteWithChildren + PreloadDisabledRoute: typeof PreloadDisabledRoute SharedSingletonRoute: typeof SharedSingletonRoute ViewportTestRoute: typeof ViewportTestRoute WithoutLoaderRoute: typeof WithoutLoaderRoute @@ -179,6 +192,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsRouteImport parentRoute: typeof rootRouteImport } + '/preload-disabled': { + id: '/preload-disabled' + path: '/preload-disabled' + fullPath: '/preload-disabled' + preLoaderRoute: typeof PreloadDisabledRouteImport + parentRoute: typeof rootRouteImport + } '/shared-singleton': { id: '/shared-singleton' path: '/shared-singleton' @@ -279,6 +299,7 @@ const rootRouteChildren: RootRouteChildren = { IndexRoute: IndexRoute, LayoutRoute: LayoutRouteWithChildren, PostsRoute: PostsRouteWithChildren, + PreloadDisabledRoute: PreloadDisabledRoute, SharedSingletonRoute: SharedSingletonRoute, ViewportTestRoute: ViewportTestRoute, WithoutLoaderRoute: WithoutLoaderRoute, diff --git a/e2e/react-router/basic-file-based-code-splitting/src/routes/__root.tsx b/e2e/react-router/basic-file-based-code-splitting/src/routes/__root.tsx index cb2a94ee19..f42053dad0 100644 --- a/e2e/react-router/basic-file-based-code-splitting/src/routes/__root.tsx +++ b/e2e/react-router/basic-file-based-code-splitting/src/routes/__root.tsx @@ -51,6 +51,7 @@ function RootComponent() { > without-loader {' '} + preload-disabled{' '}
preload disabled
, +}) diff --git a/e2e/react-router/basic-file-based-code-splitting/tests/preload.spec.ts b/e2e/react-router/basic-file-based-code-splitting/tests/preload.spec.ts index 0bc3265760..96f4d834bf 100644 --- a/e2e/react-router/basic-file-based-code-splitting/tests/preload.spec.ts +++ b/e2e/react-router/basic-file-based-code-splitting/tests/preload.spec.ts @@ -40,3 +40,28 @@ test('scrolling into viewport a link with preload=viewport to a route should pre : '/assets/viewport-test' expect(request.url()).toEqual(expect.stringContaining(expectedString)) }) + +test('preload: false skips an auto-code-split component chunk until navigation', async ({ + page, +}) => { + await page.waitForLoadState('networkidle') + const expectedString = + process.env.NODE_ENV === 'development' + ? 'preload-disabled.tsx?tsr-split' + : '/assets/preload-disabled' + const matchingRequests: Array = [] + page.on('request', (request) => { + if (request.url().includes(expectedString)) { + matchingRequests.push(request.url()) + } + }) + + const link = page.getByRole('link', { name: 'preload-disabled' }) + await link.hover() + await page.waitForTimeout(300) + expect(matchingRequests).toEqual([]) + + await link.click() + await expect(page.getByTestId('preload-disabled')).toBeVisible() + expect(matchingRequests.length).toBeGreaterThan(0) +}) diff --git a/e2e/react-router/basic-file-based/src/main.tsx b/e2e/react-router/basic-file-based/src/main.tsx index 12e202dae4..a35a10673e 100644 --- a/e2e/react-router/basic-file-based/src/main.tsx +++ b/e2e/react-router/basic-file-based/src/main.tsx @@ -24,8 +24,12 @@ const router = createRouter({ defaultStaleTime: 5000, scrollRestoration: true, routeMasks: [mask], + unmaskOnReload: true, }) +// Test hook for browser-history integration tests in this fixture. +;(window as any).__TSR_TEST_ROUTER__ = router + // Register things for typesafety declare module '@tanstack/react-router' { interface Register { diff --git a/e2e/react-router/basic-file-based/tests/mask.spec.ts b/e2e/react-router/basic-file-based/tests/mask.spec.ts index 1b77760de6..2af13beed2 100644 --- a/e2e/react-router/basic-file-based/tests/mask.spec.ts +++ b/e2e/react-router/basic-file-based/tests/mask.spec.ts @@ -1,4 +1,17 @@ import { expect, test } from '@playwright/test' +import type { Page } from '@playwright/test' + +async function readLocation(page: Page) { + return page.evaluate(() => { + const location = (window as any).__TSR_TEST_ROUTER__.state.location + return { + pathname: location.pathname, + maskedPathname: location.maskedLocation?.pathname, + maskedSearch: location.maskedLocation?.search, + maskedStateSource: location.maskedLocation?.state?.source, + } + }) +} test('route masks transform params and expose masked pathname in the browser (react)', async ({ page, @@ -24,3 +37,55 @@ test('route masks transform params and expose masked pathname in the browser (re '/masks/public/user-42', ) }) + +test('native history restores a reversible mask across traversal and reload', async ({ + page, +}) => { + await page.goto('/masks') + + await page.evaluate(async () => { + await (window as any).__TSR_TEST_ROUTER__.navigate({ + to: '/masks/admin/$userId', + params: { userId: '42' }, + mask: { + to: '/masks/public/$username', + params: { username: 'user-42' }, + search: { source: 'reversible' }, + state: { source: 'state' }, + unmaskOnReload: false, + }, + }) + }) + + await page.waitForURL('/masks/public/user-42?source=reversible') + await expect(page.getByTestId('admin-user-id')).toHaveText('42') + expect(await readLocation(page)).toEqual({ + pathname: '/masks/admin/42', + maskedPathname: '/masks/public/user-42', + maskedSearch: { source: 'reversible' }, + maskedStateSource: 'state', + }) + + await page.evaluate(async () => { + await (window as any).__TSR_TEST_ROUTER__.navigate({ to: '/masks' }) + }) + await page.waitForURL('/masks') + await page.goBack() + await expect(page.getByTestId('admin-user-id')).toHaveText('42') + expect(await readLocation(page)).toMatchObject({ + pathname: '/masks/admin/42', + maskedPathname: '/masks/public/user-42', + maskedSearch: { source: 'reversible' }, + maskedStateSource: 'state', + }) + + await page.reload() + await expect(page).toHaveURL('/masks/public/user-42?source=reversible') + await expect(page.getByTestId('admin-user-id')).toHaveText('42') + expect(await readLocation(page)).toMatchObject({ + pathname: '/masks/admin/42', + maskedPathname: '/masks/public/user-42', + maskedSearch: { source: 'reversible' }, + maskedStateSource: 'state', + }) +}) diff --git a/e2e/react-router/issue-7120/src/routeTree.gen.ts b/e2e/react-router/issue-7120/src/routeTree.gen.ts index fc671589c7..e8c6d92110 100644 --- a/e2e/react-router/issue-7120/src/routeTree.gen.ts +++ b/e2e/react-router/issue-7120/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // 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 PostsRouteImport } from './routes/posts' import { Route as IndexRouteImport } from './routes/index' +import { Route as PostsRouteImport } from './routes/posts' -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => rootRouteImport, -} as any).lazy(() => import('./routes/posts.lazy').then((d) => d.Route)) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', + getParentRoute: () => rootRouteImport, +} as any).lazy(() => import('./routes/posts.lazy').then((d) => d.Route)) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/e2e/react-router/issue-7457/src/routeTree.gen.ts b/e2e/react-router/issue-7457/src/routeTree.gen.ts index 72a8f23384..04a2c94ce8 100644 --- a/e2e/react-router/issue-7457/src/routeTree.gen.ts +++ b/e2e/react-router/issue-7457/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // 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' +import { Route as AnotherRouteImport } from './routes/another' -const AnotherRoute = AnotherRouteImport.update({ - id: '/another', - path: '/another', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const AnotherRoute = AnotherRouteImport.update({ + id: '/another', + path: '/another', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/another': { - id: '/another' - path: '/another' - fullPath: '/another' - preLoaderRoute: typeof AnotherRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/another': { + id: '/another' + path: '/another' + fullPath: '/another' + preLoaderRoute: typeof AnotherRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/e2e/react-start/basic/src/routeTree.gen.ts b/e2e/react-start/basic/src/routeTree.gen.ts index ea09864d8e..27b10415d7 100644 --- a/e2e/react-start/basic/src/routeTree.gen.ts +++ b/e2e/react-start/basic/src/routeTree.gen.ts @@ -12,6 +12,7 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' import { Route as LayoutRouteImport } from './routes/_layout' import { Route as AsyncScriptsRouteImport } from './routes/async-scripts' +import { Route as ClientContextFailureRouteImport } from './routes/client-context-failure' import { Route as ClientOnlyRouteImport } from './routes/client-only' import { Route as DeferredRouteImport } from './routes/deferred' import { Route as InlineScriptsRouteImport } from './routes/inline-scripts' @@ -96,6 +97,11 @@ const AsyncScriptsRoute = AsyncScriptsRouteImport.update({ path: '/async-scripts', getParentRoute: () => rootRouteImport, } as any) +const ClientContextFailureRoute = ClientContextFailureRouteImport.update({ + id: '/client-context-failure', + path: '/client-context-failure', + getParentRoute: () => rootRouteImport, +} as any) const ClientOnlyRoute = ClientOnlyRouteImport.update({ id: '/client-only', path: '/client-only', @@ -464,6 +470,7 @@ export interface FileRoutesByFullPath { '/search-params': typeof SearchParamsRouteRouteWithChildren '/specialChars': typeof SpecialCharsRouteRouteWithChildren '/async-scripts': typeof AsyncScriptsRoute + '/client-context-failure': typeof ClientContextFailureRoute '/client-only': typeof ClientOnlyRoute '/deferred': typeof DeferredRoute '/inline-scripts': typeof InlineScriptsRoute @@ -534,6 +541,7 @@ export interface FileRoutesByTo { '/': typeof IndexRoute '/specialChars': typeof SpecialCharsRouteRouteWithChildren '/async-scripts': typeof AsyncScriptsRoute + '/client-context-failure': typeof ClientContextFailureRoute '/client-only': typeof ClientOnlyRoute '/deferred': typeof DeferredRoute '/inline-scripts': typeof InlineScriptsRoute @@ -601,6 +609,7 @@ export interface FileRoutesById { '/specialChars': typeof SpecialCharsRouteRouteWithChildren '/_layout': typeof LayoutRouteWithChildren '/async-scripts': typeof AsyncScriptsRoute + '/client-context-failure': typeof ClientContextFailureRoute '/client-only': typeof ClientOnlyRoute '/deferred': typeof DeferredRoute '/inline-scripts': typeof InlineScriptsRoute @@ -676,6 +685,7 @@ export interface FileRouteTypes { | '/search-params' | '/specialChars' | '/async-scripts' + | '/client-context-failure' | '/client-only' | '/deferred' | '/inline-scripts' @@ -746,6 +756,7 @@ export interface FileRouteTypes { | '/' | '/specialChars' | '/async-scripts' + | '/client-context-failure' | '/client-only' | '/deferred' | '/inline-scripts' @@ -812,6 +823,7 @@ export interface FileRouteTypes { | '/specialChars' | '/_layout' | '/async-scripts' + | '/client-context-failure' | '/client-only' | '/deferred' | '/inline-scripts' @@ -887,6 +899,7 @@ export interface RootRouteChildren { SpecialCharsRouteRoute: typeof SpecialCharsRouteRouteWithChildren LayoutRoute: typeof LayoutRouteWithChildren AsyncScriptsRoute: typeof AsyncScriptsRoute + ClientContextFailureRoute: typeof ClientContextFailureRoute ClientOnlyRoute: typeof ClientOnlyRoute DeferredRoute: typeof DeferredRoute InlineScriptsRoute: typeof InlineScriptsRoute @@ -933,6 +946,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AsyncScriptsRouteImport parentRoute: typeof rootRouteImport } + '/client-context-failure': { + id: '/client-context-failure' + path: '/client-context-failure' + fullPath: '/client-context-failure' + preLoaderRoute: typeof ClientContextFailureRouteImport + parentRoute: typeof rootRouteImport + } '/client-only': { id: '/client-only' path: '/client-only' @@ -1675,6 +1695,7 @@ const rootRouteChildren: RootRouteChildren = { SpecialCharsRouteRoute: SpecialCharsRouteRouteWithChildren, LayoutRoute: LayoutRouteWithChildren, AsyncScriptsRoute: AsyncScriptsRoute, + ClientContextFailureRoute: ClientContextFailureRoute, ClientOnlyRoute: ClientOnlyRoute, DeferredRoute: DeferredRoute, InlineScriptsRoute: InlineScriptsRoute, diff --git a/e2e/react-start/basic/src/routes/client-context-failure.tsx b/e2e/react-start/basic/src/routes/client-context-failure.tsx new file mode 100644 index 0000000000..412cc00e48 --- /dev/null +++ b/e2e/react-start/basic/src/routes/client-context-failure.tsx @@ -0,0 +1,23 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/client-context-failure')({ + context: () => { + if (typeof window !== 'undefined') { + throw new Error('Client context reconstruction failed') + } + return { serverContext: true } + }, + component: ClientContextSuccess, + errorComponent: ({ error }) => ( +
{error.message}
+ ), +}) + +function ClientContextSuccess() { + if (typeof window !== 'undefined') { + const testWindow = window as any + testWindow.__clientContextSuccessRenders = + (testWindow.__clientContextSuccessRenders ?? 0) + 1 + } + return
server success
+} diff --git a/e2e/react-start/basic/tests/client-context-failure.spec.ts b/e2e/react-start/basic/tests/client-context-failure.spec.ts new file mode 100644 index 0000000000..feb36ed1bd --- /dev/null +++ b/e2e/react-start/basic/tests/client-context-failure.spec.ts @@ -0,0 +1,29 @@ +import { expect, test } from '@playwright/test' + +test('client context failure never hydrates transported success', async ({ + page, + request, + baseURL, +}) => { + const response = await request.get(`${baseURL}/client-context-failure`) + expect(response.ok()).toBe(true) + const serverHtml = await response.text() + expect(serverHtml).toContain('data-testid="client-context-success"') + expect(serverHtml).toContain('>server success') + + const pageErrors: Array = [] + page.on('pageerror', (error) => pageErrors.push(error)) + await page.addInitScript(() => { + ;(window as any).__clientContextSuccessRenders = 0 + }) + await page.goto('/client-context-failure') + + await expect(page.getByTestId('client-context-error')).toHaveText( + 'Client context reconstruction failed', + ) + await expect(page.getByTestId('client-context-success')).toHaveCount(0) + expect( + await page.evaluate(() => (window as any).__clientContextSuccessRenders), + ).toBe(0) + expect(pageErrors).toEqual([]) +}) diff --git a/e2e/solid-start/selective-ssr/src/routeTree.gen.ts b/e2e/solid-start/selective-ssr/src/routeTree.gen.ts index 8fb128de38..d0ea8db3a2 100644 --- a/e2e/solid-start/selective-ssr/src/routeTree.gen.ts +++ b/e2e/solid-start/selective-ssr/src/routeTree.gen.ts @@ -9,20 +9,15 @@ // 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 DataOnlyPendingComponentRouteImport } from './routes/data-only-pending-component' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as SsrFalsePendingMinRouteImport } from './routes/ssr-false-pending-min' 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', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const DataOnlyPendingComponentRoute = @@ -31,9 +26,14 @@ const DataOnlyPendingComponentRoute = path: '/data-only-pending-component', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', + getParentRoute: () => rootRouteImport, +} as any) +const SsrFalsePendingMinRoute = SsrFalsePendingMinRouteImport.update({ + id: '/ssr-false-pending-min', + path: '/ssr-false-pending-min', getParentRoute: () => rootRouteImport, } as any) const PostsPostIdRoute = PostsPostIdRouteImport.update({ @@ -97,18 +97,11 @@ export interface RootRouteChildren { 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' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/data-only-pending-component': { @@ -118,11 +111,18 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof DataOnlyPendingComponentRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport + } + '/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/$postId': { diff --git a/packages/react-router/src/Matches.tsx b/packages/react-router/src/Matches.tsx index d9977db272..a555848535 100644 --- a/packages/react-router/src/Matches.tsx +++ b/packages/react-router/src/Matches.tsx @@ -8,10 +8,11 @@ import { CatchBoundary } from './CatchBoundary' import { useRouter } from './useRouter' import { useStructuralSharing } from './useMatch' import { useLayoutEffect } from './utils' -import { Transitioner } from './Transitioner' +import { Transitioner, clearOwner } from './Transitioner' import { matchContext } from './matchContext' import { Match, renderPending } from './Match' import { SafeFragment } from './SafeFragment' +import type { ReactRenderOwner } from './Transitioner' import type { StructuralSharingOption, ValidateSelected, @@ -47,6 +48,9 @@ declare module '@tanstack/router-core' { */ export function Matches() { const router = useRouter() + // Stable render receipt: Transitioner offers a generation and MatchesInner + // acknowledges that exact array after it commits. + const [owner] = React.useState([]) const rootRoute: AnyRoute = router.routesById[rootRouteId] const pendingElement = renderPending(router, rootRoute) @@ -57,9 +61,9 @@ export function Matches() { const inner = ( <> - {!(isServer ?? router.isServer) && } + {!(isServer ?? router.isServer) && } - + ) @@ -71,19 +75,24 @@ export function Matches() { ) } -function MatchesInner() { +function MatchesInner({ owner }: { owner: ReactRenderOwner }) { const router = useRouter() - const matches = + const presentation = (isServer ?? router.isServer) ? router.stores.matches.get() : // eslint-disable-next-line react-hooks/rules-of-hooks - useStore(router.stores.matches, (value) => value) - const match = matches[0] + useStore( + router.stores.ids, + () => owner[0] ?? router.stores.matches.get(), + ) + const match = presentation[0] const routeId = match?.routeId useLayoutEffect(() => { - router._rendered!(matches) - }, [matches, router]) + if (owner[0] === presentation) { + clearOwner(owner)?.(true) + } + }, [owner, presentation]) const matchComponent = routeId ? : null diff --git a/packages/react-router/src/Transitioner.tsx b/packages/react-router/src/Transitioner.tsx index acbb60b5bf..e65d76012e 100644 --- a/packages/react-router/src/Transitioner.tsx +++ b/packages/react-router/src/Transitioner.tsx @@ -6,137 +6,130 @@ import { useLayoutEffect } from './utils' import { useRouter } from './useRouter' import type { AnyRouteMatch } from '@tanstack/router-core' -export function Transitioner() { - const router = useRouter() - const acknowledgement = React.useRef< - [Array, (rendered: boolean) => void] | undefined - >(undefined) - const mounted = - process.env.NODE_ENV !== 'production' - ? // eslint-disable-next-line react-hooks/rules-of-hooks - React.useRef(false) - : undefined +export type ReactRenderOwner = [ + offered?: Array, + settle?: (rendered: boolean) => void, + active?: boolean, +] - // `` precedes ``, so install the render - // acknowledgement before the latter can publish a rendered lane. - router._rendered = (matches) => { - const current = acknowledgement.current - if ( - current?.[0].length === matches.length && - current[0].every( - (match, index) => - match.id === matches[index]!.id && - match.abortController === matches[index]!.abortController && - match.status === matches[index]!.status, - ) - ) { - acknowledgement.current = undefined - current[1](true) - } - } - if (process.env.NODE_ENV === 'production') { - router.startTransition = (fn, expected, urgent) => - new Promise((resolve) => { - acknowledgement.current?.[1](false) - acknowledgement.current = [expected, resolve] - if (urgent) { - fn() - } else { - React.startTransition(fn) - } - }) - } else { - router.startTransition = (fn, expected, urgent) => - new Promise((resolve, reject) => { - acknowledgement.current?.[1](false) - const next: NonNullable = [ - expected, - resolve, - ] - acknowledgement.current = next - try { - if (urgent) { - fn() - } else { - React.startTransition(fn) - } - } catch (cause) { - if (acknowledgement.current === next) { - acknowledgement.current = undefined - } - reject(cause) - } - }) - ;( - router as typeof router & { _cancelTransition?: () => void } - )._cancelTransition = () => { - const current = acknowledgement.current - acknowledgement.current = undefined - current?.[1](false) - } +export function clearOwner( + owner: ReactRenderOwner, + current = owner[1], +): typeof current { + if (owner[1] === current) { + owner[0] = owner[1] = undefined + return current } + return undefined +} + +export function Transitioner({ owner }: { owner: ReactRenderOwner }) { + const router = useRouter() // Subscribe before canonicalizing so the initial URL has exactly one load. useLayoutEffect(() => { + // Suspense and Activity can reconnect effects without rendering again. + const initialized = owner[2] !== undefined + owner[2] = true + router.startTransition = async (fn, expected) => { + if (!owner[2]) { + fn() + return false + } + + return new Promise((resolve, reject) => { + clearOwner(owner)?.(false) + owner[0] = expected + owner[1] = resolve + if (process.env.NODE_ENV === 'production') { + React.startTransition(fn) + } else { + // React captures transition-action errors, so HMR must catch inside it. + React.startTransition(() => { + try { + fn() + } catch (cause) { + clearOwner(owner, resolve) + reject(cause) + } + }) + } + }) + } + ;( + router as typeof router & { _cancelTransition?: () => void } + )._cancelTransition = () => clearOwner(owner)?.(false) const unsub = router.history.subscribe(router.load) - if (mounted?.current) { - return unsub - } - if (mounted) { - mounted.current = true - } - - router.updateLatestLocation() - const location = router.latestLocation - const nextLocation = router.buildLocation({ - to: location.pathname, - search: true, - params: true, - hash: true, - state: true, - _includeValidateSearch: true, - }) - - // Check if the current URL matches the canonical form. - // Compare publicHref (browser-facing URL) consistently with server - // canonicalization. if ( - trimPathRight(location.publicHref) !== - trimPathRight(nextLocation.publicHref) + !initialized || + router.history.location.state.__TSR_key !== + router.latestLocation.state.__TSR_key ) { - router.commitLocation({ - ...nextLocation, - replace: true, - ignoreBlocker: true, + router.updateLatestLocation() + const location = router.latestLocation + const nextLocation = router.buildLocation({ + to: location.pathname, + search: true, + params: true, + hash: true, + state: true, + _includeValidateSearch: true, }) - return unsub - } - const resolvedLocation = router.stores.resolvedLocation.get() - if ( - resolvedLocation?.href === location.href && - resolvedLocation.state.__TSR_key === location.state.__TSR_key - ) { - acknowledgement.current = [ - router.stores.matches.get(), - (rendered) => { - if (rendered) { - router.emit({ - type: 'onRendered', - ...getLocationChangeInfo(resolvedLocation, resolvedLocation), - }) + // Check if the current URL matches the canonical form. + // Compare publicHref (browser-facing URL) consistently with server + // canonicalization. + if ( + trimPathRight(location.publicHref) !== + trimPathRight(nextLocation.publicHref) + ) { + router.commitLocation({ + ...nextLocation, + replace: true, + ignoreBlocker: true, + }) + } else { + const resolvedLocation = router.stores.resolvedLocation.get() + if ( + resolvedLocation?.href === location.href && + resolvedLocation.state.__TSR_key === location.state.__TSR_key + ) { + if (!owner[1]) { + owner[0] = router.stores.matches.get() + owner[1] = (rendered) => { + if (rendered) { + router.emit({ + type: 'onRendered', + ...getLocationChangeInfo(resolvedLocation, resolvedLocation), + }) + } + } } - }, - ] - } else if (!router._tx) { - router.load().catch(console.error) + } else if (initialized || !router._tx) { + router.load().catch(console.error) + } + } } - return unsub - // `mounted` exists only in development and is a stable ref when present. + return () => { + unsub() + owner[2] = false + if (process.env.NODE_ENV === 'production') { + clearOwner(owner)?.(false) + } else { + const current = owner[1] + // StrictMode replays effects without another render. Its second setup + // reactivates this owner before the microtask; a real unmount does not. + queueMicrotask(() => { + if (!owner[2]) { + clearOwner(owner, current)?.(false) + } + }) + } + } // eslint-disable-next-line react-hooks/exhaustive-deps - }, [router, router.history]) + }, [owner, router, router.history]) return null } diff --git a/packages/react-router/src/headContentUtils.tsx b/packages/react-router/src/headContentUtils.tsx index d61ca829db..2c91ba7e62 100644 --- a/packages/react-router/src/headContentUtils.tsx +++ b/packages/react-router/src/headContentUtils.tsx @@ -24,25 +24,24 @@ function buildTagsFromMatches( assetCrossOrigin?: AssetCrossOriginConfig, ): Array { matches = _getAssetMatches(matches) - const routeMeta = matches - .map((match) => match.meta) - .filter((meta) => meta !== undefined) - const resultMeta: Array = [] const metaByAttribute: Record = {} let title: RouterManagedTag | undefined - for (let i = routeMeta.length - 1; i >= 0; i--) { - const metas = routeMeta[i]! + for (let i = matches.length - 1; i >= 0; i--) { + const metas = matches[i]!.meta + if (!metas) { + continue + } for (let j = metas.length - 1; j >= 0; j--) { const m = metas[j] - if (!m) continue + if (!m) { + continue + } if (m.title) { - if (!title) { - title = { - tag: 'title', - children: m.title, - } + title ??= { + tag: 'title', + children: m.title, } } else if ('script:ld+json' in m) { try { @@ -62,9 +61,8 @@ function buildTagsFromMatches( if (attribute) { if (metaByAttribute[attribute]) { continue - } else { - metaByAttribute[attribute] = true } + metaByAttribute[attribute] = true } resultMeta.push({ @@ -93,23 +91,24 @@ function buildTagsFromMatches( } resultMeta.reverse() - const constructedLinks = matches - .flatMap((match) => match.links ?? []) - .filter((link) => link !== undefined) - .map((link) => ({ - tag: 'link', - attrs: { - ...link, - nonce, - }, - })) satisfies Array - const manifest = router.ssr?.manifest + const constructedLinks: Array = [] const manifestCssTags: Array = [] - if (manifest) { - matches.forEach((match) => { - const css = manifest.routes[match.routeId]?.css - css?.forEach((link) => { + const preloadLinks: Array = [] + const styles: Array = [] + const headScripts: Array = [] + for (const match of matches) { + for (const link of match.links ?? []) { + if (link) { + constructedLinks.push({ + tag: 'link', + attrs: { ...link, nonce }, + }) + } + } + const manifestRoute = manifest?.routes[match.routeId] + if (manifestRoute) { + for (const link of manifestRoute.css ?? []) { const resolvedLink = resolveManifestCssLink(link) manifestCssTags.push({ tag: 'link', @@ -123,26 +122,8 @@ function buildTagsFromMatches( nonce, }, }) - }) - }) - - if (manifest.inlineStyle) { - manifestCssTags.push({ - tag: 'style', - attrs: { - ...manifest.inlineStyle.attrs, - nonce, - }, - children: manifest.inlineStyle.children, - inlineCss: true, - }) - } - } - - const preloadLinks: Array = [] - if (manifest) { - matches.forEach((match) => { - manifest.routes[match.routeId]?.preloads?.forEach((preload) => { + } + for (const preload of manifestRoute.preloads ?? []) { preloadLinks.push({ tag: 'link', attrs: { @@ -150,33 +131,41 @@ function buildTagsFromMatches( nonce, }, }) - }) - }) + } + } + for (const style of match.styles ?? []) { + if (style) { + const { children, ...attrs } = style + styles.push({ + tag: 'style', + attrs: { ...attrs, nonce }, + children: children as string | undefined, + }) + } + } + for (const script of match.headScripts ?? []) { + if (script) { + const { children, ...attrs } = script + headScripts.push({ + tag: 'script', + attrs: { ...attrs, nonce }, + children: children as string | undefined, + }) + } + } } - const styles = matches - .flatMap((match) => match.styles ?? []) - .filter((style) => style !== undefined) - .map(({ children, ...attrs }) => ({ + if (manifest?.inlineStyle) { + manifestCssTags.push({ tag: 'style', attrs: { - ...attrs, + ...manifest.inlineStyle.attrs, nonce, }, - children: children as string | undefined, - })) satisfies Array - - const headScripts = matches - .flatMap((match) => match.headScripts ?? []) - .filter((script) => script !== undefined) - .map(({ children, ...script }) => ({ - tag: 'script', - attrs: { - ...script, - nonce, - }, - children: children as string | undefined, - })) satisfies Array + children: manifest.inlineStyle.children, + inlineCss: true, + }) + } const tags: Array = [] appendUniqueUserTags(tags, resultMeta) diff --git a/packages/react-router/src/lazyRouteComponent.tsx b/packages/react-router/src/lazyRouteComponent.tsx index 7c387e0e31..d9352ce763 100644 --- a/packages/react-router/src/lazyRouteComponent.tsx +++ b/packages/react-router/src/lazyRouteComponent.tsx @@ -22,31 +22,32 @@ export function lazyRouteComponent< ): T[TKey] extends (props: infer TProps) => any ? AsyncRouteComponent : never { - let loadPromise: Promise | undefined + let loadPromise: Promise | undefined let comp: T[TKey] | T['default'] let error: any const load = () => { - if (!loadPromise) { - error = undefined - loadPromise = importer() - .then((res) => { - // Keep browser preload behavior unchanged; SSR can reuse the import. - if (!(isServer ?? typeof window === 'undefined')) { - loadPromise = undefined - } - comp = res[exportName ?? 'default'] - }) - .catch((err) => { - loadPromise = undefined - // We don't want an error thrown from preload in this case, because - // there's nothing we want to do about module not found during preload. - // Record the error, the rest is handled during the render path. - error = err - }) + if (loadPromise) { + return loadPromise } - return loadPromise + error = undefined + return (loadPromise = importer() + .then((res) => { + // Keep browser preload behavior unchanged; SSR can reuse the import. + if (!(isServer ?? typeof window === 'undefined')) { + loadPromise = undefined + } + comp = res[exportName ?? 'default'] + }) + .catch((err) => { + loadPromise = undefined + error = err + + if (!isModuleNotFoundError(err)) { + throw err + } + })) } const lazyComp = function Lazy(props: any) { diff --git a/packages/react-router/tests/component-preload-retry.test.tsx b/packages/react-router/tests/component-preload-retry.test.tsx index 2ce819f1bb..26cf472602 100644 --- a/packages/react-router/tests/component-preload-retry.test.tsx +++ b/packages/react-router/tests/component-preload-retry.test.tsx @@ -3,6 +3,7 @@ import { afterEach, expect, test, vi } from 'vitest' import { cleanup, fireEvent, render, screen } from '@testing-library/react' import { RouterProvider, + createControlledPromise, createMemoryHistory, createRootRoute, createRoute, @@ -31,6 +32,21 @@ test('a successful server component download is reused', async () => { expect(importer).toHaveBeenCalledTimes(1) }) +test('concurrent component preloads share the import', async () => { + const componentImport = createControlledPromise<{ + default: () => null + }>() + const importer = vi.fn(() => componentImport) + const Page = lazyRouteComponent(importer) + + const first = Page.preload?.() + expect(Page.preload?.()).toBe(first) + expect(importer).toHaveBeenCalledOnce() + + componentImport.resolve({ default: () => null }) + await first +}) + test('a failed component download is retried from the route error UI', async () => { vi.spyOn(console, 'error').mockImplementation(() => {}) @@ -112,3 +128,53 @@ test('renders after retrying a module download that failed during preload', asyn expect(await screen.findByText('Page content')).toBeInTheDocument() expect(importer).toHaveBeenCalledTimes(2) }) + +test('retries a module download from the error UI after reloading once', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + + const failure = new TypeError( + 'Failed to fetch dynamically imported module: /assets/page.js', + ) + sessionStorage.setItem(`tanstack_router_reload:${failure.message}`, '1') + + const PageContent = () =>
Page content
+ const importer = vi + .fn<() => Promise<{ default: typeof PageContent }>>() + .mockRejectedValueOnce(failure) + .mockResolvedValue({ default: PageContent }) + const Page = lazyRouteComponent(importer) + + function RouteError({ reset }: ErrorComponentProps) { + const router = useRouter() + return ( + + ) + } + + const rootRoute = createRootRoute() + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + component: Page, + errorComponent: RouteError, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + render() + + fireEvent.click(await screen.findByRole('button', { name: 'Retry' })) + + expect(await screen.findByText('Page content')).toBeInTheDocument() + expect(importer).toHaveBeenCalledTimes(2) +}) diff --git a/packages/react-router/tests/errorComponent.test.tsx b/packages/react-router/tests/errorComponent.test.tsx index b5ee4b6709..25e52259a4 100644 --- a/packages/react-router/tests/errorComponent.test.tsx +++ b/packages/react-router/tests/errorComponent.test.tsx @@ -774,12 +774,25 @@ test('#4684: SSR renders head content when beforeLoad throws', async () => { }) describe('notFoundComponent is rendered when an error is thrown in params.parse', () => { - test('displays notFoundComponent when error is thrown in params.parse', async () => { + test('renders a params.parse notFound without joining a pending intent-preload ancestor loader', async () => { const history = createMemoryHistory({ initialEntries: ['/'] }) - const rootLoader = vi.fn(async () => { - await new Promise((resolve) => setTimeout(resolve, 1)) - return { ok: true } - }) + const preloadGate = createControlledPromise() + let preloadController: AbortController | undefined + const rootLoader = vi.fn( + async ({ + preload, + abortController, + }: { + preload: boolean + abortController: AbortController + }) => { + if (preload) { + preloadController = abortController + await preloadGate + } + return { ok: true, preload } + }, + ) const rootRoute = createRootRoute({ component: function Root() { @@ -804,7 +817,7 @@ describe('notFoundComponent is rendered when an error is thrown in params.parse' component: function Home() { return (
- + link to rotten pizza
@@ -859,12 +872,31 @@ describe('notFoundComponent is rendered when an error is thrown in params.parse' expect(rootLoader).toHaveBeenCalledTimes(1) expect(linkToRottenPizza).toBeInTheDocument() await act(() => fireEvent.mouseOver(linkToRottenPizza)) + await vi.waitFor(() => expect(rootLoader).toHaveBeenCalledTimes(2)) await act(() => fireEvent.click(linkToRottenPizza)) + await vi.waitFor(() => expect(router.state.status).toBe('pending')) + + expect(preloadGate.status).toBe('pending') + expect(preloadController?.signal.aborted).toBe(false) + + await vi.waitFor(() => expect(rootLoader).toHaveBeenCalledTimes(3)) + expect(rootLoader.mock.calls.map(([context]) => context.preload)).toEqual([ + false, + true, + false, + ]) const notFoundComponent = await screen.findByText('No pizza', undefined, { timeout: 750, }) - expect(rootLoader).toHaveBeenCalledTimes(2) + expect(router.state.status).toBe('idle') + expect(preloadGate.status).toBe('pending') + expect(preloadController?.signal.aborted).toBe(false) expect(notFoundComponent).toBeInTheDocument() + + await act(async () => { + preloadGate.resolve() + await Promise.resolve() + }) }) }) diff --git a/packages/react-router/tests/issue-4467-lazy-route-pending.test.tsx b/packages/react-router/tests/issue-4467-lazy-route-pending.test.tsx index e05d2ee792..074816153f 100644 --- a/packages/react-router/tests/issue-4467-lazy-route-pending.test.tsx +++ b/packages/react-router/tests/issue-4467-lazy-route-pending.test.tsx @@ -87,9 +87,19 @@ test('a lazy pending component is offered while the eager loader is still pendin component: () =>

Index page

, }) const loader = createControlledPromise() + const componentPreload = createControlledPromise() + const pendingComponentPreload = createControlledPromise() + const preloadComponent = vi.fn(() => componentPreload) + const preloadPendingComponent = vi.fn(() => pendingComponentPreload) + const Page = Object.assign(() =>

Page

, { + preload: preloadComponent, + }) + const Pending = Object.assign(() =>

Loading lazy page

, { + preload: preloadPendingComponent, + }) const lazyPageOptions = createLazyRoute('/page')({ - pendingComponent: () =>

Loading lazy page

, - component: () =>

Page

, + pendingComponent: Pending, + component: Page, }) const lazyOptions = createControlledPromise() const pageRoute = createRoute({ @@ -121,6 +131,18 @@ test('a lazy pending component is offered while the eager loader is still pendin await act(async () => { lazyOptions.resolve(lazyPageOptions) + await Promise.resolve() + }) + + expect(preloadComponent).toHaveBeenCalledOnce() + expect(preloadPendingComponent).toHaveBeenCalledOnce() + expect(componentPreload.status).toBe('pending') + expect(pendingComponentPreload.status).toBe('pending') + expect(screen.getByRole('status')).toHaveTextContent('Loading default') + + await act(async () => { + pendingComponentPreload.resolve() + await Promise.resolve() }) expect(await screen.findByRole('status')).toHaveTextContent( @@ -131,6 +153,7 @@ test('a lazy pending component is offered while the eager loader is still pendin ).not.toBeInTheDocument() await act(async () => { + componentPreload.resolve() loader.resolve() await navigation }) @@ -139,6 +162,8 @@ test('a lazy pending component is offered while the eager loader is still pendin } finally { await act(async () => { lazyOptions.resolve(lazyPageOptions) + componentPreload.resolve() + pendingComponentPreload.resolve() loader.resolve() await navigation }) diff --git a/packages/react-router/tests/react-render-owner-contract.test.tsx b/packages/react-router/tests/react-render-owner-contract.test.tsx new file mode 100644 index 0000000000..0324ae38c3 --- /dev/null +++ b/packages/react-router/tests/react-render-owner-contract.test.tsx @@ -0,0 +1,140 @@ +import { act } from 'react' +import { cleanup, render, screen, waitFor } from '@testing-library/react' +import { afterEach, expect, test, vi } from 'vitest' +import { + Outlet, + RouterProvider, + createControlledPromise, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +const testCleanups: Array<() => void> = [] + +afterEach(() => { + while (testCleanups.length) { + testCleanups.pop()!() + } + cleanup() +}) + +test('a suspended same-membership publication cannot acknowledge its successor', async () => { + const firstRenderStarted = createControlledPromise() + const firstRenderGate = createControlledPromise() + let signaledFirstRender = false + + const rootRoute = createRootRoute({ + validateSearch: (search: Record) => ({ + revision: Number(search.revision), + }), + component: () => { + const revision = rootRoute.useSearch().revision + if (revision === 1 && firstRenderGate.status === 'pending') { + if (!signaledFirstRender) { + signaledFirstRender = true + firstRenderStarted.resolve() + } + throw firstRenderGate + } + return
Root revision {revision}
+ }, + }) + const router = createRouter({ + routeTree: rootRoute, + history: createMemoryHistory({ initialEntries: ['/?revision=0'] }), + }) + + render() + expect(await screen.findByText('Root revision 0')).toBeInTheDocument() + await waitFor(() => expect(router.state.status).toBe('idle')) + const initialIds = router.state.matches.map((match) => match.routeId) + + const renderedRevisions: Array = [] + testCleanups.push( + router.subscribe('onRendered', (event) => { + renderedRevisions.push( + Number((event.toLocation.search as Record).revision), + ) + }), + ) + + let firstNavigation!: Promise + await act(async () => { + firstNavigation = router.navigate({ + to: '/', + search: { revision: 1 }, + }) + await firstRenderStarted + }) + + const firstSettled = vi.fn() + void firstNavigation.then(firstSettled) + expect(router.state.matches.map((match) => match.routeId)).toEqual(initialIds) + expect(router.state.matches[0]?.search.revision).toBe(1) + expect(screen.getByText('Root revision 0')).toBeInTheDocument() + expect(firstSettled).not.toHaveBeenCalled() + expect(renderedRevisions).toEqual([]) + + try { + await act(() => + router.navigate({ + to: '/', + search: { revision: 2 }, + }), + ) + await firstNavigation + + expect(screen.getByText('Root revision 2')).toBeInTheDocument() + expect(router.state.matches.map((match) => match.routeId)).toEqual( + initialIds, + ) + expect(renderedRevisions).toEqual([2]) + expect(firstSettled).toHaveBeenCalledOnce() + } finally { + await act(async () => { + firstRenderGate.resolve() + await Promise.resolve() + }) + } + + expect(screen.getByText('Root revision 2')).toBeInTheDocument() + expect(renderedRevisions).toEqual([2]) +}) + +test('a development HMR lifecycle failure rolls back before recovery', async () => { + let generation = 1 + const rootRoute = createRootRoute({ component: Outlet }) + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + loader: () => generation, + component: () =>
Page generation {pageRoute.useLoaderData()}
, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + render() + expect(await screen.findByText('Page generation 1')).toBeInTheDocument() + await waitFor(() => expect(router.state.status).toBe('idle')) + + generation = 2 + pageRoute.options.onStay = () => { + throw new Error('hot route failed') + } + await act(() => router._refreshRoute!()) + + expect(screen.getByText('Page generation 1')).toBeInTheDocument() + expect(router.state.matches.at(-1)?.loaderData).toBe(1) + expect(router.state.status).toBe('idle') + + pageRoute.options.onStay = undefined + generation = 3 + await act(() => router._refreshRoute!()) + + expect(screen.getByText('Page generation 3')).toBeInTheDocument() + expect(router.state.matches.at(-1)?.loaderData).toBe(3) +}) diff --git a/packages/react-router/tests/router-client-context-retry.test.tsx b/packages/react-router/tests/router-client-context-retry.test.tsx new file mode 100644 index 0000000000..580d529a6d --- /dev/null +++ b/packages/react-router/tests/router-client-context-retry.test.tsx @@ -0,0 +1,88 @@ +import { cleanup, render, screen } from '@testing-library/react' +import { afterEach, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { hydrate } from '@tanstack/router-core/ssr/client' +import { dehydrateSsrMatchId } from '../../router-core/src/ssr/ssr-match-id' +import { + Outlet, + RouterProvider, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +afterEach(() => { + cleanup() + delete window.$_TSR +}) + +test('a RouterProvider mounted after router hydration never renders transported success after client context reconstruction fails', async () => { + const serverRootRoute = createRootRoute({ component: Outlet }) + const serverPageRoute = createRoute({ + getParentRoute: () => serverRootRoute, + path: '/page', + context: () => ({ clientReady: true }), + component: () =>
Server page
, + }) + const serverRouter = createRouter({ + routeTree: serverRootRoute.addChildren([serverPageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + serverRouter.isServer = true + await serverRouter.load() + const serverMatches = serverRouter.stores.matches.get() + expect(serverMatches.at(-1)).toMatchObject({ status: 'success' }) + + const contextError = new Error('Client context failed') + const pageRenders = vi.fn() + const clientRootRoute = createRootRoute({ component: Outlet }) + const clientPageRoute = createRoute({ + getParentRoute: () => clientRootRoute, + path: '/page', + context: () => { + throw contextError + }, + component: () => { + const context = clientRouter.state.matches.at(-1)?.context + pageRenders(context) + return context?.clientReady ? ( +
Client page
+ ) : ( +
Missing client context
+ ) + }, + errorComponent: ({ error }) =>
{error.message}
, + }) + const clientRouter = createRouter({ + routeTree: clientRootRoute.addChildren([clientPageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + window.$_TSR = { + router: { + manifest: { routes: {} }, + dehydratedData: {}, + matches: serverMatches.map((match) => ({ + i: dehydrateSsrMatchId(match.id), + u: match.updatedAt, + s: match.status, + l: match.loaderData, + e: match.error, + ssr: match.ssr, + })), + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + initialized: false, + } + + await hydrate(clientRouter) + render() + + expect(await screen.findByText(contextError.message)).toBeInTheDocument() + expect(screen.queryByText('Missing client context')).not.toBeInTheDocument() + expect(screen.queryByText('Client page')).not.toBeInTheDocument() + expect(pageRenders).not.toHaveBeenCalled() +}) diff --git a/packages/react-router/tests/router.test.tsx b/packages/react-router/tests/router.test.tsx index 43c4d47423..bfa89a73c1 100644 --- a/packages/react-router/tests/router.test.tsx +++ b/packages/react-router/tests/router.test.tsx @@ -2701,10 +2701,16 @@ describe('notFound in beforeLoad with pendingComponent', () => { } } finally { try { + // Navigation resolves from the final React layout acknowledgement. + // Do not await it inside the act callback that first makes that + // render possible, or fake timers and the concurrent render deadlock. + vi.useRealTimers() await act(async () => { beforeLoad.resolve() - await navigation + await Promise.resolve() }) + await act(async () => {}) + await navigation } finally { vi.useRealTimers() } diff --git a/packages/react-router/tests/transitioner-remount.test.tsx b/packages/react-router/tests/transitioner-remount.test.tsx index 76cc6393ce..e0b6122ec6 100644 --- a/packages/react-router/tests/transitioner-remount.test.tsx +++ b/packages/react-router/tests/transitioner-remount.test.tsx @@ -1,5 +1,7 @@ +import { useState } from 'react' +import { flushSync } from 'react-dom' import { afterEach, describe, expect, it, vi } from 'vitest' -import { cleanup, render, screen, waitFor } from '@testing-library/react' +import { act, cleanup, render, screen, waitFor } from '@testing-library/react' import { Outlet, RouterProvider, @@ -11,6 +13,7 @@ import { afterEach(() => { cleanup() + vi.unstubAllEnvs() }) function setup() { @@ -88,4 +91,51 @@ describe('Transitioner remount', () => { loadSpy.mockRestore() }) + + it.each(['development', 'production'] as const)( + 'settles an outstanding render when the provider unmounts in %s', + async (nodeEnv) => { + vi.stubEnv('NODE_ENV', nodeEnv) + + const { router } = setup() + let setMounted!: (mounted: boolean) => void + function Harness() { + const [mounted, set] = useState(true) + setMounted = set + return mounted ? : null + } + + render() + expect(await screen.findByText('Index')).toBeInTheDocument() + await waitFor(() => expect(router.state.status).toBe('idle')) + + const rendered = vi.fn() + const navigationSettled = vi.fn() + const unsubscribers = [ + router.subscribe('onRendered', (event) => { + if (event.toLocation.pathname === '/next') { + rendered() + } + }), + router.subscribe('onBeforeRouteMount', (event) => { + if (event.toLocation.pathname === '/next') { + expect(navigationSettled).not.toHaveBeenCalled() + flushSync(() => setMounted(false)) + } + }), + ] + + void router.navigate({ to: '/next' }).then(navigationSettled) + await waitFor(() => expect(navigationSettled).toHaveBeenCalledOnce()) + expect(rendered).not.toHaveBeenCalled() + + await act(() => setMounted(true)) + expect(await screen.findByText('Next')).toBeInTheDocument() + await waitFor(() => expect(rendered).toHaveBeenCalledOnce()) + + for (const unsubscribe of unsubscribers) { + unsubscribe() + } + }, + ) }) diff --git a/packages/react-router/tests/transitioner-render-ack.test.tsx b/packages/react-router/tests/transitioner-render-ack.test.tsx index b533c225b3..29c3b05554 100644 --- a/packages/react-router/tests/transitioner-render-ack.test.tsx +++ b/packages/react-router/tests/transitioner-render-ack.test.tsx @@ -1,4 +1,4 @@ -import { StrictMode, act } from 'react' +import { Activity, StrictMode, act, lazy } from 'react' import { cleanup, render, screen, waitFor } from '@testing-library/react' import { afterEach, expect, test, vi } from 'vitest' import { @@ -19,6 +19,7 @@ afterEach(() => { } cleanup() vi.useRealTimers() + vi.unstubAllEnvs() }) test('same-location invalidation emits onResolved after its refreshed DOM commits', async () => { @@ -74,6 +75,7 @@ test('a late background refresh is discarded after foreground navigation commits const itemRoute = createRoute({ getParentRoute: () => rootRoute, path: '/items/$itemId', + staleTime: Infinity, loader: { staleReloadMode: 'background', handler: ({ params }) => itemLoader(params.itemId), @@ -94,7 +96,6 @@ test('a late background refresh is discarded after foreground navigation commits await screen.findByText('Item source: initial source data'), ).toBeInTheDocument() await waitFor(() => expect(router.state.status).toBe('idle')) - const sourceMatchId = router.state.matches.at(-1)!.id const eventLog: Array = [] const unsubscribers = [ @@ -130,12 +131,6 @@ test('a late background refresh is discarded after foreground navigation commits backgroundRefresh.resolve('obsolete source data') await Promise.resolve() }) - await waitFor(() => { - expect(router._flights?.has(sourceMatchId) ?? false).toBe(false) - const cachedSourceMatch = router._cache.get(sourceMatchId) - expect(cachedSourceMatch?.loaderData).toBe('initial source data') - expect(cachedSourceMatch?.isFetching).toBe(false) - }) expect( screen.getByText('Item target: foreground target data'), @@ -154,6 +149,18 @@ test('a late background refresh is discarded after foreground navigation commits .slice(eventCountAfterForegroundCommit) .every((event) => event.endsWith('/items/target')), ).toBe(true) + + await act(() => + router.navigate({ + to: '/items/$itemId', + params: { itemId: 'source' }, + }), + ) + expect( + screen.getByText('Item source: initial source data'), + ).toBeInTheDocument() + expect(screen.queryByText('Item source: obsolete source data')).toBeNull() + expect(itemLoader).toHaveBeenCalledTimes(3) }) test('a navigation started by route lifecycle keeps the pending minimum of its own render', async () => { @@ -190,6 +197,7 @@ test('a navigation started by route lifecycle keeps the pending minimum of its o render() expect(await screen.findByText('Index')).toBeInTheDocument() await waitFor(() => expect(router.state.status).toBe('idle')) + vi.useFakeTimers() let firstNavigation!: Promise @@ -266,3 +274,159 @@ test('StrictMode effect replay preserves renderer commit sequencing', async () = expect(screen.getByText('Next')).toBeInTheDocument() expect(screen.queryByText('Index')).not.toBeInTheDocument() }) + +test('Activity reconnects render acknowledgement before the next navigation', async () => { + vi.stubEnv('NODE_ENV', 'production') + + const rootRoute = createRootRoute({ component: Outlet }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
Index
, + }) + const nextRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/next', + component: () =>
Next
, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, nextRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + const provider = + const view = render({provider}) + + expect(await screen.findByText('Index')).toBeInTheDocument() + await waitFor(() => expect(router.state.status).toBe('idle')) + + const rendered = vi.fn() + const unsubscribe = router.subscribe('onRendered', (event) => { + if (event.toLocation.pathname === '/next') { + rendered(screen.queryByText('Next') !== null) + } + }) + testCleanups.push(unsubscribe) + + view.rerender({provider}) + expect(screen.getByText('Index')).not.toBeVisible() + view.rerender({provider}) + expect(screen.getByText('Index')).toBeVisible() + + await act(() => router.navigate({ to: '/next' })) + + expect(screen.getByText('Next')).toBeVisible() + expect(rendered).toHaveBeenCalledOnce() + expect(rendered).toHaveBeenCalledWith(true) + + view.unmount() + vi.unstubAllEnvs() +}) + +test('Activity catches up with history changes made while hidden', async () => { + const rootRoute = createRootRoute({ component: Outlet }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
Index
, + }) + const nextRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/next', + component: () =>
Next
, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, nextRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + const provider = + const view = render({provider}) + + expect(await screen.findByText('Index')).toBeInTheDocument() + await waitFor(() => expect(router.state.status).toBe('idle')) + + view.rerender({provider}) + expect(screen.getByText('Index')).not.toBeVisible() + + await act(() => router.history.push('/next')) + expect(router.history.location.href).toBe('/next') + expect(router.latestLocation.pathname).toBe('/') + + view.rerender({provider}) + + expect(await screen.findByText('Next')).toBeVisible() + expect(router.latestLocation.pathname).toBe('/next') +}) + +test('Activity does not restart a navigation observed before it was hidden', async () => { + const next = createControlledPromise() + const loader = vi.fn(() => next) + const rootRoute = createRootRoute({ component: Outlet }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
Index
, + }) + const nextRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/next', + loader, + component: () =>
Next
, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, nextRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + const provider = + const view = render({provider}) + + expect(await screen.findByText('Index')).toBeInTheDocument() + await waitFor(() => expect(router.state.status).toBe('idle')) + + let navigation!: Promise + act(() => { + navigation = router.navigate({ to: '/next' }) + }) + await waitFor(() => expect(loader).toHaveBeenCalledOnce()) + + view.rerender({provider}) + view.rerender({provider}) + expect(loader).toHaveBeenCalledOnce() + + await act(async () => { + next.resolve() + await navigation + }) + expect(screen.getByText('Next')).toBeVisible() +}) + +test('an initial canceled pending publication restores the empty presentation', async () => { + let offeredRouteId: string | undefined + const offeredRoute = { readId: (): string | undefined => undefined } + const suspendedPending = createControlledPromise() + const Pending = lazy(async () => { + await suspendedPending + return { default: () =>
Initial pending
} + }) + const rootRoute = createRootRoute({ + pendingMs: 0, + pendingMinMs: 0, + pendingComponent: Pending, + beforeLoad: ({ abortController }) => { + offeredRouteId = offeredRoute.readId() + abortController.abort() + }, + component: () =>
Ready
, + }) + const router = createRouter({ + routeTree: rootRoute, + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + offeredRoute.readId = () => router.state.matches[0]?.routeId + + render() + + await waitFor(() => expect(offeredRouteId).toBe(rootRoute.id)) + await waitFor(() => expect(router.state.status).toBe('idle')) + expect(router.state.matches).toEqual([]) + expect(screen.queryByText('Something went wrong!')).not.toBeInTheDocument() +}) diff --git a/packages/router-core/INTERNALS.md b/packages/router-core/INTERNALS.md index d8efe633cf..5a8dc15597 100644 --- a/packages/router-core/INTERNALS.md +++ b/packages/router-core/INTERNALS.md @@ -34,31 +34,29 @@ The main authorities are: | `_committed` | The accepted current lane and lifecycle/background CAS base | | `stores.matches` | The current match presentation exposed to renderers and users | | `router._cache` | Off-screen loader generations and first same-ID planning seeds | -| Active preload entry | One still-running speculative whole lane | -| Loader flight registry entry | The latest same-ID loader generation available to new consumers | -| Match flight lease | Ownership keeping that loader work alive | +| `router._flights` | The discoverable loader generation currently producing a cache key | +| Active preload entry | One running speculative lane registered for cancellation | +| Match flight lease | Ownership keeping one match's loader generation alive | | Pending session | One reveal/minimum-visible deadline and its current owner | | React acknowledgement slot | The one requested publication whose render may settle a transition | | Request signal | Lifetime of one server request and any accepted SSR stream | | Accepted SSR stream response | Cleanup ownership transferred from the handler to the response body | These authorities are related, but none is a substitute for another. In -particular, presentation is not semantic authority, registry membership is not -resource ownership, and a promise settling is not permission to publish. +particular, presentation is not semantic authority, a cached generation is not +permission to skip a requested reload, and a promise settling is not permission +to publish. ## Code map - `src/router.ts` matches locations, creates match objects, owns public router state, history, cache operations, and entry points into loading. - `src/stores.ts` reconciles route-keyed presentation stores and their ordered - aggregate. + aggregate. It owns no React acknowledgement pointer. - `src/load-client.ts` owns client planning, transactions, preloads, loader - flights, reduction, pending presentation, background reloads, and commits. + flights, route/component readiness, reduction, pending presentation, + background reloads, hydration reconstruction, and commits. - `src/load-server.ts` runs the request-local server lane. -- `src/route-chunks.ts` owns lazy route-option installation and component - readiness without adding a JavaScript-module cache. -- `src/hydrate.ts` reconstructs the server-resolved prefix and the initial - selective-SSR presentation. - `src/ssr/createRequestHandler.ts` connects request lifetime, server loading, dehydration, redirects, rendering, and cleanup. - `src/ssr/handlerCallback.ts`, `ssr-server.ts`, and @@ -121,8 +119,8 @@ across match generations and A-to-B-to-A membership changes. `ids` is published before departure tombstones so framework trees stop reading a leaving route before its atom is cleared. The pool retains atoms for route IDs encountered during the router's lifetime; it is not an LRU or a cache of match generations. -Semantic caches and loader flights remain keyed by match ID and must not use the -presentation pool as their authority. +Semantic cache entries remain keyed by match ID; loader flights belong to exact +match generations. Neither may use the presentation pool as its authority. This distinction matters for user code. Once the destination is presented, a selector can inspect every destination match and observe `isFetching` while the @@ -202,8 +200,7 @@ reuse an older merged context or `beforeLoad` contribution. Server requests have fresh matches and execute route context normally. Hydration executes each accepted route context locally, stores its `_ctx`, and -then merges transported `beforeLoad` output. An active identical preload donates -the whole lane it is still contextualizing. +then merges transported `beforeLoad` output. ### Reduced @@ -282,7 +279,7 @@ Every asynchronous client publication checks `_tx` immediately before the write. Background publication additionally checks the exact committed base array from which it was derived. -## `beforeLoad`: execution, active adoption, and hydration +## `beforeLoad`: execution and hydration `beforeLoad` context is not a cache. @@ -292,59 +289,16 @@ same-ID route-local `_ctx` may remain reusable. A later navigation rebuilds the merged context from the current parent and `_ctx`, then reruns `beforeLoad`, even when it reuses completed loader data. -There are two deliberate exceptions. - -### Identical active whole-lane adoption - -A navigation may latch onto an entry in `router._preloads` that is still running -only when the whole lane is identical. Admission is decided before rematching -from the preload's href and redirect depth, route-tree identity, semantic owner, -parsed search, router root context, additional context, user-supplied location -state, and any explicit mask's href, search, user state, and -`unmaskOnReload`. Router-managed history and temporary-mask keys do not -participate. With deterministic route planning, those inputs imply the same -ordered routes, params, validated search, and global-path-miss meaning. They may -be observed by `beforeLoad` even when the route lane is unchanged. -Adoption inputs are treated as immutable values: replace a context/state object -to express a generation change; in-place mutation is not detected. -Adoption is all-or-nothing. There is no prefix donation and no -completed-preload freshness window for `beforeLoad`. Matching derives -global-path-miss semantics for every lane, including preloads, so an otherwise -identical candidate cannot erase that terminal meaning during adoption. - -The active preload also captures the identity of `_committed` from which -it was planned. Whole-lane adoption requires that semantic owner to remain -current. Invalidation replaces the committed generation, so an older preload -may still donate an identical loader flight but cannot donate its pre-invalidation -`beforeLoad` context. - -The adopting navigation takes ownership of the active lane and its controller. -The original public preload call must then stop releasing that lane. Individual -successful loader tasks may still publish cache entries through their original -per-match compare-and-swap; that publication belongs to the transferred lane, -not to a second whole-lane owner. - -If the adopted speculative lane succeeds, the navigation may use the -`beforeLoad` calls that ran with `preload: true`. A redirect from that same -active lane is also accepted as navigation control flow. An ordinary failure, -not-found, or cancellation is not authoritative for navigation: the real -navigation replans and reruns `beforeLoad` with `preload: false`. Successful -loader work anywhere in the settled lane remains eligible for reuse, including -a descendant that completed after an ancestor loader failed. Each successful -loader generation has already attempted its own cache publication at settlement, -so retry does not scan the terminal lane or create another cache handoff. It -discards the failed speculative semantic lane and replans cache-first. The retry -rebuilds the serial context chain and reruns `beforeLoad`; only independently -successful loader generations cross that boundary through the normal -cache/flight rules. - -Routes with `preload: false` do not permit active whole-lane adoption. Their -speculative `beforeLoad` may run with `preload: true`, but navigation reruns the -serial chain and performs the skipped loader work. - -Rejecting whole-lane adoption does not require discarding loader work before -the real lane reaches its reload decisions. The rejected preload may remain a -resource-only donor until that lane settles. +Navigation always builds its own context chain and calls `beforeLoad` with +`preload: false`, even while an identical preload is still running. This keeps +guard context and control flow owned by the operation that will publish them. +A same-ID loader generation is the narrower sharing boundary: navigation may +join its pending promise or reuse its accepted cache result without inheriting +the preload lane's `beforeLoad` context or control outcome. Joining a loader +promise does observe that loader generation's complete normalized outcome, +including error, not-found, or redirect. Cancellation is lane-local: a canceled +waiter releases its lease without canceling a generation that another lane +still owns. ### Hydration @@ -358,8 +312,8 @@ Hydration is not a general `beforeLoad` cache. Its temporary handoff is valid only for the initial client load of the same document entry and exact committed owner; rejection, invalidation, or any later load returns to normal serial execution. The claim also requires the same route tree, root/additional context, -search, user history state, and exact browser history generation. That initial -load may transfer the accepted hydration prefix and +internal href, browser-facing public href, and parsed history-state object. That +initial load may transfer the accepted hydration prefix and keep its transported context while it completes a selective-SSR suffix. A preload never claims this prefix. Frameworks must start the initial client load before descendant route code can preload; invoking a preload in the gap after @@ -391,7 +345,7 @@ generations when its error or not-found came from `beforeLoad`, validation, or another route. Each preload loader success attempts cache admission immediately, before whole-lane reduction. The cache receives a non-terminal copy and an additional flight lease; the speculative lane keeps its own lease and terminal -meaning until it is adopted or discarded. This works even below the eventual +meaning until it is discarded. This works even below the eventual render boundary and does not preserve the speculative parent chain: merged context and `beforeLoad` output are cleared. Same-ID `_ctx`, loader identity, and successful loader data remain reusable by design. @@ -417,36 +371,31 @@ been removed; the merged chain is rebuilt from current parents and same-ID route-local context before `beforeLoad` reruns. Committing a lane removes cache entries for its IDs. -### Same-id in-flight work +### Match-owned loader work -`router._flights` is the only registry from which a new consumer discovers -same-ID loader work. Every new loader generation registers there, whether it -was started by navigation, preload, or background refresh. A newer generation -replaces the registry entry synchronously. A flight has its own abort -controller; it does not use one consumer transaction's controller as its -lifetime. +Every loader execution creates a flight containing its outcome promise, +controller, lease count, and discovery registry. The originating match owns the +first lease. A semantic or cached copy that keeps the same generation alive +acquires another; every discarded copy releases exactly once. The last release +removes that exact generation from discovery and aborts its controller. -Two facts must remain separate: - -- registry membership means new consumers may join the flight; -- a match lease means an existing consumer keeps the flight alive. - -Registry membership itself owns no lease. A settled generation remains -discoverable while at least one semantic or cached match owns it. Releasing the -last lease removes that generation only if it is still the current registry -entry, then aborts its controller. Every copied semantic match that retains a -flight must acquire a lease, and every discarded match must release one exactly -once. Consequently, a flight referenced by a match or discoverable in the -registry always has a positive lease count. Acquisition code must not recover -from a referenced zero-lease flight; that would hide an ownership bug. +`router._flights` is the pending analogue of `router._cache`. Both are keyed by +match ID: a distinct lane rebuilds context and reruns `beforeLoad`, then may +lease the pending same-ID loader generation if its reload policy would accept +that work. A lease joins the complete pending loader outcome, including error, +not-found, or redirect; the recipient does not rerun that loader generation. +Lane cancellation only releases that lane's lease. Only success persists as +reusable cache data. Once a terminal generation has settled and left discovery, +a later lane runs its own loader. +Public invalidation and cache clearing revoke affected discovery entries before +old owners are detached, so pre-boundary work cannot supply a later generation. Releasing a set of matches is deliberately two-phase. First every outgoing -match drops its `_flight` lease and every zero-owner generation is removed from -the discovery registry. Only after the entire outgoing set is detached are the -collected flight controllers aborted. Do not interleave one flight abort with -detaching later matches in the same replacement: an abort listener can -synchronously reenter, and that load must observe every logically removed lease -and registry entry as already gone. +match drops its `_flight` lease. Only after the entire outgoing set is detached +are the collected flight controllers aborted. Do not interleave one flight +abort with detaching later matches in the same replacement: an abort listener +can synchronously reenter, and that load must observe every logically removed +lease as already gone. A successful accepted match may keep its lease after the loader promise has settled. This keeps the loader's public `AbortSignal` alive for that semantic @@ -460,26 +409,17 @@ rejection must not call user error hooks. This is an ownership check, not a separate cancellation flag. A loader that aborts its own flight controller while its match remains owned can still fulfill or reject normally. -A planned match holds only the lease for the accepted generation copied from -cache or committed state. After `beforeLoad` and `shouldReload` decide that a -loader will run, it may synchronously acquire the registry's latest different -same-ID generation. It never reacquires its own accepted generation merely to -avoid a requested reload. A blocking reload replaces the accepted lease with -the donor; a background reload keeps accepted data visible and gives the donor -lease to its private candidate. This one lookup covers work started by active -preloads, navigation, and background refresh without scanning those owners. +A planned match may hold a lease for an accepted generation copied from cache or +committed state. Once `beforeLoad` and `shouldReload` decide that a loader must +run, the lane releases that accepted lease and creates its own flight. A +blocking reload owns the new flight on the planned match; a background reload +keeps accepted data visible and owns the new flight on its private candidate. -When a different lane supersedes an active preload at the same href, the old -lane stops being adoptable but retains its resources until the successor lane -settles. Its leased flights therefore remain discoverable for the successor's -late reload decisions without giving every planned match a second reservation -lease. The successor then releases the old lane; any borrowed flight remains -alive through the successor match's ordinary `_flight` lease. - -A joining navigation accepts successful shared loader work. A failure, -not-found, or cancellation produced under another speculative generation is not -allowed to govern it; the navigation releases that flight and registers its own -generation. Redirect remains control flow and is never cached as loader data. +Each `preloadRoute` call owns its context and `beforeLoad` lane. Active entries +exist only so invalidation and cache clearing can retire those lanes. They do +not deduplicate by href. Pending same-ID loader work is shared independently +through `_flights`, including a loader redirect. `beforeLoad` control flow stays +lane-local, and redirects are never cached as loader data. ### Semantic parent chain @@ -658,11 +598,12 @@ Each reentrant callback can start another navigation. A currentness check after each publication boundary suppresses stale later events. In particular, an `onResolved` navigation suppresses the old transaction's `onRendered`. -Route lifecycle callbacks are invoked directly and are expected not to throw. -The coordinator does not carry a second error-handling path for callback -failures. All `onLeave` callbacks run before callbacks for retained or newly -entered routes; the relative ordering of `onEnter` and `onStay` is not a public -contract. +Ordinary route lifecycle callback failures are logged and isolated per callback, +so one user callback cannot interrupt the remaining callbacks or leave a commit +half-resolved. HMR refresh deliberately propagates lifecycle failures so its +publication checkpoint can roll the generation back. All `onLeave` callbacks +run before callbacks for retained or newly entered routes; the relative ordering +of `onEnter` and `onStay` is not a public contract. Server render results are published request-locally and run the documented route `onLeave`/`onEnter`/`onStay` callbacks against the previous server @@ -734,10 +675,17 @@ the superseded navigation. Changing the boundary discards the old session. - settlement means the framework transition can no longer block navigation completion; -- `true` means the exact requested match publication rendered; +- `true` means the exact requested match publication selected by React reached + the `MatchesInner` layout-commit phase; - `false` means core must finish without emitting `onRendered` or starting a pending minimum based on that publication. +This is publication-shell exactness, not proof that every nested Suspense +boundary revealed new child content. A route-owned Suspense boundary can retain +its previous child DOM while the surrounding `MatchesInner` publication commits +and acknowledges. Review code that uses `onRendered` for descendant DOM work +with that distinction in mind. + React cannot await `React.startTransition` directly. Its adapter has one current acknowledgement slot, and `Matches` settles that slot from a layout effect. A new expected publication first settles the previous slot as `false`, then installs @@ -745,36 +693,55 @@ itself before the transition callback runs. This ordering matters because publication can invoke a route lifecycle callback that synchronously starts and publishes a successor navigation. Installing the expectation after the callback would let the superseded publication replace the successor's slot. -The lifetime-owned Transitioner installs these callbacks during render, before -the sibling match tree can register its acknowledgement effect. +The mounted-tree-owned Transitioner precedes the sibling match tree, so its +layout effect installs these callbacks before the match tree can acknowledge. + +In development HMR, the transition callback is wrapped by a `try`/`catch` inside +the function passed to `React.startTransition`. React 19 captures callback +throws instead of rethrowing them from the outer `React.startTransition` call. +The development-only wrapper therefore clears only its exact owner and rejects +the adapter promise so the HMR transaction can restore `_committed`. Ordinary +production lifecycle and router-event callbacks are already isolated, so the +production adapter calls `React.startTransition` directly. An already-settled router mounted into React uses the same acknowledgement slot -for its initial `onRendered` event. It therefore emits only after the exact match -tree and its descendant layout effects have committed, rather than from the -earlier history-subscription effect. +for its initial `onRendered` event. It therefore emits from the matching +`MatchesInner` layout commit rather than from the earlier history-subscription +effect. Descendant layout effects in that commit run first, subject to the +nested-Suspense qualification above. -A generation is its array length plus the ordered sequence of match ID, -execution-controller identity, and render status. These are existing semantic -facts rather than a separate generation counter. A new transaction or -background candidate changes controller identity; pending-to-terminal -publication changes status. Object reference equality is deliberately not -required because `isFetching` and per-match store reconciliation can replace -objects without changing the logical publication. An exact signature settles -the current slot as `true`. A mismatched render is ignored; only installing a -successor settles the current slot as `false`. +`stores.matches` is the public presented match view, while `stores.ids` is the +ordered route-membership and publication notification used by framework +renderers. Every publication writes its already-created route-ID array, even +when membership is unchanged. Per-route stores can still replace live match +objects for `isFetching` without acknowledging another semantic publication. + +React keeps the exact offered match-array pointer in a small owner local to the +mounted `Matches` tree. It captures that pointer during render and compares it +by identity in a layout effect. An exact render settles the current slot as +`true`; a mismatched render is ignored. This pointer is neither public match +state nor semantic authority, and it does not exist in router-core. + +Direct core restoration clears an outstanding React offer before publishing +the restored stores. This matters on a canceled first load: the accepted lane +is empty, so leaving the offered root armed while tombstoning its route atom +would make React try to render a route that no longer has a presented match. Solid awaits its transition, and Vue awaits its render tick. For an already-settled Solid mount, history subscription remains before the route tree while a post-match notifier emits the initial `onRendered` event after -descendant mount effects. The architecture assumes exactly one Transitioner is -mounted per router and remains mounted for the lifetime of the application. Its -history subscription and acknowledgement machinery are therefore -lifetime-owned; there is deliberately no second unmount-time completion -authority. +descendant mount effects. The architecture supports one committed `Matches` +owner per router at a time. Unmounting it unsubscribes from history and retires +any outstanding acknowledgement as `false`; a later mount creates a new owner +and synchronizes with the router's current presented matches. Development +defers only that retirement through the StrictMode effect replay turn, while +production cleanup is synchronous. Effect setup always reactivates the owner: +React Suspense and Activity can disconnect and reconnect layout effects without +rendering the preserved child tree again. -Every core write passed to `startTransition` must notify the aggregate matches -store even if much of the lane is structurally reused. Suppressing the write can -strand the acknowledgement promise. +Every core publication passed to `startTransition` must publish the route-ID +generation signal even if route membership is unchanged. Suppressing that +notification can strand React's acknowledgement promise. ## `isFetching` and background reloads @@ -790,8 +757,8 @@ presented lane and therefore expose their phase immediately. A background reload keeps successful loader data visible while a private candidate runs. The full presented lane remains installed and the affected match reports the active phase. Completion clears fetching state whether the -candidate publishes, fails, or is superseded. A successor may join its loader -flight, but never adopts the private candidate lane. +candidate publishes, fails, or is superseded. A successor never adopts or joins +the private candidate lane. Background loader and chunk work may begin and settle while the foreground publication renders. Background reduction, projection, and publication do not @@ -850,12 +817,19 @@ generation from escaping invalidation merely because a different generation was the one passed to the filter. Route context needs no invalidation marker; every new lane rebuilds it regardless. +Invalidation also retires active preloads planned under the old generation. +Unfiltered invalidation retires every active preload; filtered invalidation +retires a preload when any match in its lane passes the filter. The retained +preload collection is installed before discarded match leases are released and +their lane controllers are aborted, so late speculative work cannot regain +cache publication authority after invalidation. + Invalidated successful data may remain visible until pending or terminal publication, depending on reload mode. Error/not-found generations reset through the same loading protocol rather than becoming cache successes. -Cache clearing derives the retained active-preload and cache maps, installs both -replacement authorities, bulk-detaches removed leases, lets that operation +Cache clearing derives the retained active-preload collection and cache map, +installs both replacement authorities, bulk-detaches removed leases, lets that operation abort zero-owner flight controllers, and only then aborts selected preload lane controllers. A public loader signal can synchronously reenter from its abort listener; that reentrant load must observe the cleared authorities and every @@ -864,11 +838,12 @@ independent, and every later cache publication must still pass the per-match cache-entry identity check captured during planning. Development refresh is deliberately aggressive: it aborts flights, discards -active preloads and caches, drops the committed semantic lane, and rematches -from the current route definitions. This prevents same-ID reuse from retaining -obsolete params, context, loader data, or projected assets. Correct ownership -and eventual usable state matter more than preserving speculative HMR work. -Flight discovery entries are removed before their controllers are aborted. +active preloads and caches, and prevents the committed lane from being reused +while rematching current route definitions. The old committed lane remains +installed for rendering and rollback until the replacement publishes. This +prevents same-ID reuse from retaining obsolete params, context, loader data, or +projected assets. Correct ownership and eventual usable state matter more than +preserving speculative HMR work. ## Speculative preloading @@ -877,9 +852,8 @@ navigation, but it never becomes `_tx` and never publishes match presentation. Its match/cache ownership effects are limited to: -- an active identical whole lane that a navigation may adopt while it is still - running; -- joinable same-id loader flights; and +- each active lane being registered so invalidation and cache clearing can + cancel it; - individual successful preload loader generations entering the loader cache as they settle. @@ -887,12 +861,14 @@ A preload can also install durable lazy route options through the separate route-chunk owner described above. That is route definition readiness, not authority over a completed match lane or `beforeLoad` result. -A completed preload's failure, not-found, redirect, cancellation, and route -context do not become authority for a later navigation. An adopted still-active -identical lane is the exception described above, including its redirect control -flow. Standalone preload redirects may be followed only while the preload -remains current and within its bounded redirect policy. A preload never performs -a document reload. +A preload's route context and `beforeLoad` control outcome do not become +authority for a navigation, and terminal outcomes do not become reusable cache +entries. A navigation that joins the preload's still-pending same-ID loader does +share that loader generation's complete outcome. A later navigation starts a +new loader after a terminal generation leaves discovery. A still-active +standalone preload follows redirects within its bounded policy even if an +unrelated navigation runs; this only starts more speculative work and cannot +publish location or presentation. A preload never performs a document reload. The public `preloadRoute` result describes the speculative lane, not merely its cacheable subset. An ordinary error or not-found therefore resolves with the @@ -905,8 +881,7 @@ the entry captured when that task was planned. It cannot overwrite a cache generation installed since that plan. Admission happens at loader settlement, without waiting for whole-lane success. A distinct successful generation may coexist with an older committed same-ID generation; this changes future -planning precedence, not current presentation. A duplicate sharing the already -accepted flight is discarded. +planning precedence, not current presentation. `preloadRoute` also works on a server router. It runs the same speculative protocol with `preload: true`, can return matches and populate that router's @@ -957,18 +932,26 @@ swallowed. Until a response is accepted, the request handler owns router SSR cleanup. A non-stream response, redirect, or failure leaves cleanup with the handler. An accepted SSR stream transfers that ownership to the response and is immediately -bound to the request signal, so an abort after handoff still disposes it. +bound to the request signal, so an abort after handoff still disposes it. An +ordinary response body has no router cleanup ownership, but is handed off +through an abortable stream pipe so a later request abort still cancels its +upstream body. -Disposal is idempotent and severs router SSR ownership before best-effort body -cancellation. This order matters because a custom or framework stream may ignore -or indefinitely delay cancellation. Replacing a stream response, resolving a -redirect from it, or stripping a HEAD body disposes the old stream under the -same request signal before accepting the replacement. +Disposal is idempotent and severs router SSR ownership before body cancellation. +Start's internal response-retirement and HEAD paths detach cancellation so a +custom or framework stream cannot delay request settlement. The public +router-core replacement and body-stripping helpers instead await a custom tagged +response disposer, so callers know that the old owner has finished cleanup. -Framework renderers connect request abort to their upstream renderer as well as -the router stream transform. Normal completion, downstream cancellation, -request abort, renderer failure, and stream lifetime timeout all converge on the -same cleanup authority; none creates a second response owner. +Framework renderers connect request abort to their upstream renderer when the +renderer exposes cancellation ownership, as well as to the router stream +transform. The current Solid and Vue renderer APIs expose no disposer for a +pending render: abort still releases router state and stops outbound bytes, but +cannot prove that the hidden framework render graph was retired. Hosting must +therefore enforce a request/render deadline until those upstream APIs expose +that ownership. Normal completion, downstream cancellation, request abort, +renderer failure, and stream lifetime timeout otherwise converge on the same +cleanup authority; none creates a second response owner. Once a server lane is accepted for rendering, its match controllers are registered with that same SSR cleanup authority. They remain live through @@ -1126,8 +1109,8 @@ The two-phase transfer proceeds as follows: 2. It installs its own `_preflight`, emits the events, matches a private lane, and asks the capability to finish the transfer. 3. Finish revalidates capability identity, transaction absence, hydration - controller liveness, captured location identity, and the exact committed - owner. + controller liveness, captured semantic location inputs, and the exact + committed owner. 4. On rejection, the capability clears itself before aborting its controller, so abort listeners cannot reenter and claim a rejected handoff. 5. On acceptance, the prefix replaces the planner's private copies. A terminal @@ -1176,22 +1159,20 @@ When changing this architecture, verify all of the following: 6. Each successful preload loader generation may enter the cache as it settles, even if its whole lane later becomes terminal or is canceled. It may retain same-ID route-local `_ctx`, but never merged context or `beforeLoad` output. -7. Active preload adoption is identical-whole-lane only, including router - context, additional context, and user-supplied location state. It also - requires the semantic committed owner captured during planning to remain - current; rejected lanes may donate loader flights, never `beforeLoad` - context. Retrying a terminal adopted lane may retain every independently - successful loader generation, but rebuilds merged context and reruns the - serial `beforeLoad` chain. +7. Every preload and navigation rebuilds merged context and reruns the serial + `beforeLoad` chain. Same-ID loader promises and accepted loader data remain + reusable independently through `_flights` and `_cache`. 8. Hydration is the only completed-work exception for `beforeLoad` reuse. It verifies each transported match identity, reconstructs the accepted ordered prefix, reruns route context locally, preserves terminal/selective-SSR authority, and presents the full local branch while executing only the accepted prefix. Its two-phase handoff is claimable only by the supported - initial document load and revalidates the live controller, captured location, - and exact committed owner. The framework's exact-document contract remains - the URL authority; the captured location rejects supported reentrant - successors, while compact serialized match IDs guard prefix compatibility. + initial document load and revalidates the live controller, captured route + tree and contexts, both internal and browser-facing hrefs, the parsed state + object, and the exact committed owner. The framework's exact-document + contract remains the URL authority; those semantic inputs reject supported + reentrant successors, while compact serialized match IDs guard prefix + compatibility. It clears before abort on rejection and remains reclaimable until `_tx` exists. Framework adapters start that load before descendant route code can create unsupported speculative work in the handoff gap. @@ -1199,15 +1180,16 @@ When changing this architecture, verify all of the following: 10. Cache publication retains only the generation allowed by its planning CAS; same-ID committed and cached generations invalidate together, and accepted recipients are installed before replaced resources are released. -11. The registry is the sole discovery authority for the latest same-ID flight - started by navigation, preload, or background work. Registry joinability - and lease ownership remain separate; donor selection happens synchronously - after the reload decision, and accepted signal lifetime may outlive promise - settlement. +11. Loader flights are match-owned. Same-ID lanes may lease the currently + discoverable generation after independently deciding loader policy, but + a lease observes the complete pending outcome. Only successful data persists + in the cache. Explicit invalidation and requested `shouldReload` generations + do not borrow older work. Lease ownership may outlive promise settlement so + the accepted public signal retains the semantic generation's lifetime. 12. Child `parentMatchPromise` follows the fresh semantic parent generation. 13. The first parallel ordinary failure is chronological unless a required ancestor failure has no accepted loader data or its required chunk fails; - any started descendant redirect can still win as control flow. + any started descendant redirect in that lane can still win as control flow. 14. Projection errors are logged and swallowed, and global path misses retain their `_notFound` representation, which may be a successful fuzzy/root match without an attached error. @@ -1216,30 +1198,31 @@ When changing this architecture, verify all of the following: exclusion derive the same cutoff, while SSR transport may cap its payload at the terminal prefix. 16. Every discarded semantic match and background candidate releases resources - exactly once; bulk release detaches every lease and registry entry before - aborting any collected flight controller. -17. A background write checks both writer and exact base identity. A successor - may join its flight but never adopts its candidate lane. + exactly once; bulk release detaches every lease before aborting any + collected flight controller. +17. A background write checks both writer and exact base identity. Its private + candidate flight is not discoverable by a successor lane. 18. Background publication waits for the foreground acknowledgement, then remains detached from foreground completion. Its eager settlement witness is retained across that wait so chronological failure/control selection is not recomputed later. 19. `isFetching` clears for success, failure, cancellation, and supersession. 20. Transition acknowledgement settlement gates resolved/idle completion; React - identifies the exact generation by length plus ordered ID, controller, and - status, and installs it in one superseding slot before running the possibly - reentrant transition callback. Only `true` gates `onRendered` and pending - minimum timing. -21. The single Transitioner and its acknowledgement machinery live for the - router's entire application lifetime. + identifies the exact generation by presentation-array identity and installs + it in one superseding slot before running the possibly reentrant transition + callback. Only `true` gates `onRendered` and pending minimum timing. +21. Exactly one mounted `Matches` tree owns a router's React acknowledgement at + a time. Final unmount retires it, and a later mount creates a new owner from + the router's current presentation. 22. Reentrant callbacks suppress every stale later event or publication. 23. Canonicalization compares browser-facing `publicHref`; semantic `href` is not a symmetric canonical key across input and output rewrites. 24. Request abort can settle every awaited server phase; late work cannot regain response or injection authority. 25. Exactly one of the request handler or an accepted stream owns SSR cleanup. - Accepted streams remain bound to request abort, and disposal releases router - state before best-effort body cancellation. + Every handed-off response body remains bound to request abort. Disposal + releases router state before best-effort body cancellation, and response + replacement never waits for that cancellation to settle. 26. Cleanup prevents a still-pending custom dehydration from beginning serialization. @@ -1260,7 +1243,8 @@ Useful assertions include: events, without asserting a relative `onEnter`/`onStay` order; - preload/cache reuse observable through user loader calls; - HTTP status, headers, redirects, and absence of renderer invocation; -- request-abort settlement, late-stream disposal, and single stream cleanup; +- request-abort settlement after body handoff, detached replacement disposal, + and single stream cleanup; - hydration output, completion on rejection, and absence of client reruns below server terminal boundaries; - absence of stale data/assets after supersession; and diff --git a/packages/router-core/src/load-client.ts b/packages/router-core/src/load-client.ts index 897d479e09..f0c7432128 100644 --- a/packages/router-core/src/load-client.ts +++ b/packages/router-core/src/load-client.ts @@ -2,12 +2,7 @@ // can rewrite relative imports for both ESM and CJS. import { isNotFound } from './not-found' import { isRedirect } from './redirect' -import { - _getUserHistoryState, - getLocationChangeInfo, - runRouteLifecycle, -} from './router' -import { deepEqual } from './utils' +import { getLocationChangeInfo, runRouteLifecycle } from './router' import { hydrateSsrMatchId } from './ssr/ssr-match-id' import type { GLOBAL_SEROVAL, GLOBAL_TSR } from './ssr/constants' import type { AnySerializationAdapter } from './ssr/serializer/transformer' @@ -25,12 +20,6 @@ import type { import type { AnyRedirect } from './redirect' import type { AnyRouter } from './router' -type RouteComponentType = - | 'component' - | 'pendingComponent' - | 'errorComponent' - | 'notFoundComponent' - export function replaceRouteChunk( route: AnyRoute, lazyFn: AnyRoute['lazyFn'], @@ -39,33 +28,29 @@ export function replaceRouteChunk( route._lazy = undefined } -function preloadComponent( - route: AnyRoute, - type: RouteComponentType, -): Promise | undefined { - return (route.options[type] as any)?.preload?.() -} - -function loadComponents(route: AnyRoute): Promise | undefined { - const component = preloadComponent(route, 'component') - const pending = preloadComponent(route, 'pendingComponent') - if (component && pending) { - return Promise.all([component, pending]).then(() => {}) - } - return component ?? pending -} - export function loadRouteChunk( route: AnyRoute, // `false` waits only for lazy route options, before a boundary is selected. componentType?: 'errorComponent' | 'notFoundComponent' | false, + onPendingReady?: () => void, ): Promise | undefined { - const afterLazy = () => - componentType === false - ? undefined - : componentType - ? preloadComponent(route, componentType) - : loadComponents(route) + const afterLazy = () => { + if (componentType === false) { + return + } + if (componentType) { + return (route.options[componentType] as any)?.preload?.() + } + const component = (route.options.component as any)?.preload?.() + const pending = (route.options.pendingComponent as any)?.preload?.() + if (onPendingReady) { + pending ? pending.then(onPendingReady, () => {}) : onPendingReady() + } + if (component && pending) { + return Promise.all([component, pending]).then(() => {}) + } + return component ?? pending + } const current = route._lazy if (current) { return current === true ? afterLazy() : current.then(afterLazy) @@ -114,7 +99,8 @@ export function _getAssetMatches( const match = matches[index]! // `_assetEnd` is only ever set on hydration presentation clones that are // `status: 'pending'`, `ssr: 'data-only'`, error-free, and not not-found - // (see hydrate.ts), and commits clear it — so its presence alone is the guard. + // (see hydration reconstruction below), and commits clear it — so its + // presence alone is the guard. if (match._assetEnd !== undefined) { end = Math.min(end, Math.max(index + 1, match._assetEnd)) continue @@ -138,7 +124,7 @@ type LanePhase = 'matched' | 'contextualized' | 'reduced' | 'projected' * matches). The brand is phantom — it never exists at runtime. */ type LaneMatches = Array & { - readonly [lanePhase]?: TPhase + readonly [lanePhase]: TPhase } type Lane = [ @@ -146,7 +132,7 @@ type Lane = [ matches: LaneMatches, background?: Array, backgroundSettlement?: Promise, -] & { readonly [lanePhase]?: TPhase } +] & { readonly [lanePhase]: TPhase } type MatchedLane = Lane<'matched'> type ContextualizedLane = Lane<'contextualized'> @@ -160,61 +146,51 @@ const NOT_FOUND = 2 const REDIRECTED = 3 const CANCELED = 4 -type LoaderOutcome = - | [typeof SUCCESS, data: unknown] +type SharedLoaderFailure = | [typeof ERROR, error: unknown] | [typeof NOT_FOUND, error: NotFoundError] | [typeof REDIRECTED, redirect: AnyRedirect] - | [typeof CANCELED] -type IndexedOutcome = [index: number, outcome: LoaderOutcome, boundary?: number] +type LoaderFailure = SharedLoaderFailure | [typeof CANCELED] + +type LoaderOutcome = + | [ + typeof SUCCESS, + data: unknown, + updatedAt?: number, + ] + | SharedLoaderFailure + +type LoaderSuccess = [ + typeof SUCCESS, + data: unknown, + updatedAt: number, +] + +type LoaderResult = LoaderSuccess | LoaderFailure +type LoaderFlightResult = LoaderSuccess | SharedLoaderFailure + +type IndexedOutcome = [index: number, outcome: LoaderFailure, boundary?: number] + +declare const flightGeneration: unique symbol export type LoaderFlight = [ - outcome: Promise, + outcome: Promise, controller: AbortController, leases: number, -] + registry: Map, +] & { readonly [flightGeneration]: true } type WorkMatch = AnyRouteMatch & { _flight?: LoaderFlight + _claimedFlight?: LoaderFlight } declare const matchPhase: unique symbol -/** - * A match whose loader outcome has been applied by `settleInto`, which is the - * sole granter of this brand (phantom, zero-runtime). Consumers that require - * it — e.g. `cacheLoaderMatch` — can only be reached after settlement, so the - * compiler enforces the loader→settle→cache ordering. Sources that arrive - * already settled (dehydrated server data) must cast at a named boundary. - */ +/** A match whose loader outcome has been applied by `settle`. */ type SettledMatch = WorkMatch & { readonly [matchPhase]: 'settled' } -export type LaneInputs = [ - routeTree: AnyRoute, - context: unknown, - additionalContext: unknown, - state: object, - search: object, - maskedLocation: - | [ - href: string, - state: object, - search: object, - unmaskOnReload: boolean | undefined, - ] - | undefined, -] - -export type ActivePreload = [ - matches: Array, - controller: AbortController, - result: Promise, - semanticOwner: Array, - inputs: LaneInputs, - redirects: number, -] - export type LoadTransaction = [ controller: AbortController, redirects: number, @@ -244,8 +220,6 @@ export type PendingSession = [ ] type CoordinatorRouter = AnyRouter & { - /** Whole speculative lanes that a matching navigation may adopt. */ - _preloads?: Map _refreshNextLoad?: boolean _rollbackRefresh?: () => void _cancelTransition?: () => void @@ -261,14 +235,14 @@ type PublicationCheckpoint = { type LoaderTask = [ index: number, - outcome: Promise, + outcome: Promise, ready: Promise, candidate?: WorkMatch, ] type BackgroundLoaderTask = [ index: number, - outcome: Promise, + outcome: Promise, ready: Promise, candidate: WorkMatch, ] @@ -278,7 +252,7 @@ type ExecuteLaneOptions = [ redirects: number, isCurrent: () => boolean, base: Array, - preload?: boolean, + preload: boolean, sync?: boolean, forceStaleReload?: boolean, resolvedPrefix?: number, @@ -317,6 +291,16 @@ export function getRoute(router: AnyRouter, match: WorkMatch): AnyRoute { return (router.routesById as Record)[match.routeId]! } +function normalize( + value: unknown, + rejected: true, + routeId?: string, +): SharedLoaderFailure +function normalize( + value: unknown, + rejected: false, + routeId?: string, +): LoaderOutcome function normalize( value: unknown, rejected: boolean, @@ -335,7 +319,7 @@ function normalize( return rejected ? [ERROR, value] : [SUCCESS, value] } -function normalizeError(route: AnyRoute, cause: unknown): LoaderOutcome { +function normalizeError(route: AnyRoute, cause: unknown): SharedLoaderFailure { let outcome = normalize(cause, true, route.id) if (outcome[0] !== ERROR) { return outcome @@ -352,7 +336,7 @@ function normalizeLaneError( route: AnyRoute, cause: unknown, options: ExecuteLaneOptions, -): LoaderOutcome { +): LoaderFailure { if (options[0].signal.aborted || !options[2]()) { options[0].abort() return [CANCELED] @@ -376,7 +360,7 @@ async function contextualize( ): Promise { const [location, matches] = lane const signal = options[0].signal - const preload = !!options[4] + const preload = options[4] for (let index = options[7] ?? 0; index < end; index++) { const match = matches[index]! const route = getRoute(router, match) @@ -414,7 +398,7 @@ async function contextualize( } match.context = context } catch (cause) { - releaseFlight(router, match) + releaseFlight(match) return [index, normalizeLaneError(route, cause, options)] } if (signal.aborted || !options[2]()) { @@ -423,7 +407,7 @@ async function contextualize( } const validationError = match.paramsError ?? match.searchError if (validationError !== undefined) { - releaseFlight(router, match) + releaseFlight(match) return [index, normalizeLaneError(route, validationError, options)] } const beforeLoad = route.options.beforeLoad @@ -462,7 +446,7 @@ async function contextualize( } const outcome = normalize(result, false, route.id) if (outcome[0] !== SUCCESS) { - releaseFlight(router, match) + releaseFlight(match) return [index, outcome] } match.context = { @@ -470,7 +454,7 @@ async function contextualize( ...result, } } catch (cause) { - releaseFlight(router, match) + releaseFlight(match) return [index, normalizeLaneError(route, cause, options)] } finally { if (previousStatus === 'success' && match.status === 'pending') { @@ -483,79 +467,57 @@ async function contextualize( return } -function releaseOwnedFlight( - router: AnyRouter, - id: string, - flight?: LoaderFlight, +function detachOwnedFlight( + matchId: string, + flight: LoaderFlight | undefined, ): AbortController | undefined { - if (!flight || --flight[2]) { - return + if (flight && !--flight[2]) { + if (flight[3].get(matchId) === flight) { + flight[3].delete(matchId) + } + return flight[1] } - if (router._flights?.get(id) === flight) { - router._flights.delete(id) - } - return flight[1] + return } -function releaseFlight(router: AnyRouter, match: WorkMatch): void { +function detachFlight(match: WorkMatch): AbortController | undefined { const flight = match._flight match._flight = undefined - releaseOwnedFlight(router, match.id, flight)?.abort() -} -export function laneInputs( - router: AnyRouter, - location: ParsedLocation, -): LaneInputs { - const masked = location.maskedLocation - return [ - router.routeTree, - router.options.context ?? {}, - router.options.additionalContext, - _getUserHistoryState(location.state), - location.search, - masked && [ - masked.href, - _getUserHistoryState(masked.state), - masked.search, - masked.unmaskOnReload, - ], - ] + return detachOwnedFlight(match.id, flight) } -function samePreloadLane( - preload: ActivePreload, - router: AnyRouter, - location: ParsedLocation, - redirects: number, -): boolean { - return ( - preload[3] === router._committed && - preload[5] === redirects && - deepEqual(preload[4], laneInputs(router, location)) && - !preload[0].some( - (match) => getRoute(router, match as WorkMatch).options.preload === false, - ) - ) +function detachClaim(match: WorkMatch): AbortController | undefined { + const flight = match._claimedFlight + match._claimedFlight = undefined + return detachOwnedFlight(match.id, flight) } -/** - * Not passing in a `next` ownership recipient - * is equivalent to discarding the match resources - */ +function releaseFlight(match: WorkMatch): void { + const claimed = detachClaim(match) + const accepted = detachFlight(match) + claimed?.abort() + accepted?.abort() +} + +function retireFlight(matchId: string, flight: LoaderFlight): void { + if (flight[3].get(matchId) === flight) { + flight[3].delete(matchId) + } +} + +/** Release every loader-flight lease owned by a discarded match set. */ export function transferMatchResources( - router: AnyRouter, previous: Array, - next?: Array, ): void { const abort: Array = [] for (const match of previous as Array) { - if (!next?.includes(match)) { - const flight = match._flight - match._flight = undefined - const controller = releaseOwnedFlight(router, match.id, flight) - if (controller) { - abort.push(controller) - } + const claimed = detachClaim(match) + const accepted = detachFlight(match) + if (claimed) { + abort.push(claimed) + } + if (accepted) { + abort.push(accepted) } } for (const controller of abort) { @@ -563,16 +525,15 @@ export function transferMatchResources( } } -function discardPreload(router: AnyRouter, preload: ActivePreload): void { - preload[1].abort() - transferMatchResources(router, preload[0]) -} - -function acquireMatchResources(matches: Array): void { +function claimPendingFlights( + router: AnyRouter, + matches: Array, +): void { for (const match of matches as Array) { - const flight = match._flight - if (flight) { + const flight = router._flights.get(match.id) + if (flight && flight !== match._flight) { flight[2]++ + match._claimedFlight = flight } } } @@ -624,97 +585,96 @@ async function loadResource( lane: ContextualizedLane, match: WorkMatch, route: AnyRoute, - loader: RouteLoaderFn | undefined, + loader: RouteLoaderFn, parentMatchPromise: Promise | undefined, preload: boolean, owner: AbortController, -): Promise { +): Promise { const signal = owner.signal if (signal.aborted) { return [CANCELED] } - if (!loader) { - return [SUCCESS, undefined] - } - let flight = match._flight - let joined = !!flight setFetching(router, match, 'loader', owner) + const registry = router._flights try { - for (;;) { - if (!flight) { - const controller = new AbortController() - const outcome = Promise.resolve() - .then(() => - loader( - getLoaderContext( - router, - lane, - match, - route, - controller, - parentMatchPromise, - preload, - ), - ), - ) - .then( - (value) => normalize(value, false, route.id), - (cause) => normalize(cause, true, route.id), - ) - .then((result): LoaderOutcome => { - return result[0] === ERROR && match._flight === flight - ? normalizeError(route, result[1]) - : result - }) - flight = [outcome, controller, 1] - ;(router._flights ??= new Map()).set(match.id, flight) + let flight = match._claimedFlight + match._claimedFlight = undefined + if (!flight) { + flight = registry.get(match.id) + if (flight) { + flight[2]++ } - match._flight = flight - match.abortController = flight[1] - try { - const outcome = await waitFor(flight[0], signal) - if (!joined || outcome[0] === SUCCESS || outcome[0] === REDIRECTED) { - return outcome - } - } catch (cause) { - if (cause === signal) { - releaseFlight(router, match) - return [CANCELED] - } + } + if (!flight) { + const controller = new AbortController() + const outcome = Promise.resolve() + .then(() => + loader( + getLoaderContext( + router, + lane, + match, + route, + controller, + parentMatchPromise, + preload, + ), + ), + ) + .then( + (value): LoaderFlightResult => { + const result = normalize(value, false, route.id) + if (result[0] === SUCCESS) { + result[2] = Date.now() + } else { + retireFlight(match.id, flight!) + } + return result as LoaderFlightResult + }, + (cause) => { + retireFlight(match.id, flight!) + return flight![2] + ? normalizeError(route, cause) + : normalize(cause, true, route.id) + }, + ) + flight = [outcome, controller, 1, registry] as LoaderFlight + registry.set(match.id, flight) + } + match._flight = flight + match.abortController = flight[1] + try { + return await waitFor(flight[0], signal) + } catch (cause) { + if (cause !== signal) { throw cause } - releaseFlight(router, match) - if (signal.aborted) { - return [CANCELED] - } - flight = undefined - joined = false + releaseFlight(match) + return [CANCELED] } } finally { setFetching(router, match, false, owner) } } -function settleInto( +function settle( match: WorkMatch, - result: LoaderOutcome, + result: LoaderResult, preload: boolean, -): asserts match is SettledMatch { - if (result[0] === SUCCESS) { - match.loaderData = result[1] +): match is SettledMatch { + const success = result[0] === SUCCESS + if (result[0] < REDIRECTED) { match.error = undefined match.status = 'success' - match.invalid = false - match.updatedAt = Date.now() - match.preload = preload - } else if (result[0] !== REDIRECTED) { - // Reduction installs only the selected terminal failure. Every other - // settled attempt remains a renderable, stale match in that lane. - match.status = 'success' - match.error = undefined - match.invalid = true + match.invalid = !success + if (success) { + match.loaderData = result[1] + match.updatedAt = result[2] + match.preload = preload + } } + return success } export function cacheLoaderMatch( @@ -723,13 +683,16 @@ export function cacheLoaderMatch( planned: AnyRouteMatch | undefined, ): void { const current = router._cache.get(match.id) as WorkMatch | undefined + const flight = match._flight if ( current !== planned || - router._committed.some( - (candidate) => - candidate.id === match.id && - (candidate as WorkMatch)._flight === match._flight, - ) + (flight && + (flight[3].get(match.id) !== flight || + ( + router._committed.find((candidate) => candidate.id === match.id) as + | WorkMatch + | undefined + )?._flight === flight)) ) { return } @@ -743,13 +706,13 @@ export function cacheLoaderMatch( } router._cache.set(match.id, cached) if (current) { - releaseFlight(router, current) + releaseFlight(current) } } function getParentSnapshot( match: WorkMatch, - outcome: LoaderOutcome, + outcome: LoaderResult, ): WorkMatch { if (outcome[0] === ERROR || outcome[0] === NOT_FOUND) { return { @@ -772,12 +735,16 @@ function createLoaderTask( ): Promise { const match = lane[1][index]! const route = getRoute(router, match) - const preload = !!options[4] + const preload = options[4] + if (preload && route.options.preload === false) { + match.isFetching = false + return Promise.resolve(match) + } const plannedCacheMatch = preload ? router._cache.get(match.id) : undefined + let configured let reload = false - let reloadFailure: LoaderOutcome | undefined + let reloadFailure: LoaderFailure | undefined try { - let configured if (match.status === 'success') { configured = route.options.shouldReload if (typeof configured === 'function') { @@ -803,11 +770,13 @@ function createLoaderTask( reload = true } else { const staleAge = - options[4] || match.preload + preload || match.preload ? (route.options.preloadStaleTime ?? router.options.defaultPreloadStaleTime ?? 30_000) - : (route.options.staleTime ?? router.options.defaultStaleTime ?? 0) + : (route.options.staleTime ?? + router.options.defaultStaleTime ?? + 0) reload = !!( match.invalid || configured || @@ -825,14 +794,23 @@ function createLoaderTask( } } catch (cause) { match.invalid = true - releaseFlight(router, match) + releaseFlight(match) reloadFailure = normalizeLaneError(route, cause, options) } const routeLoader = route.options.loader const loader = typeof routeLoader === 'function' ? routeLoader : routeLoader?.handler + let claimed = match._claimedFlight + if (claimed) { + if (configured === undefined && !reloadFailure && loader) { + reload = true + } else { + detachClaim(match)?.abort() + claimed = undefined + } + } const background = !!( - routeLoader && + loader && reload && match.status === 'success' && !preload && @@ -842,23 +820,29 @@ function createLoaderTask( : routeLoader?.staleReloadMode) ?? router.options.defaultStaleReloadMode) !== 'blocking' ) - const loaded = reload && (!preload || route.options.preload !== false) const blocking = - loaded && !background && (match.status !== 'success' || !!routeLoader) - if (loaded && !routeLoader) { + reload && !background && (match.status !== 'success' || !!loader) + if (!reload) { + match.isFetching = false + } else if (!loader) { match.invalid = false match.updatedAt = Date.now() - } - let donor = loaded && routeLoader ? router._flights?.get(match.id) : undefined - if (donor === match._flight) { - donor = undefined - } else if (donor) { - donor[2]++ + } else if (!claimed) { + if (configured === undefined) { + if (match._flight) { + retireFlight(match.id, match._flight) + } + } else { + router._flights.delete(match.id) + } } if (blocking) { - const acceptedFlight = match._flight - match._flight = donor - releaseOwnedFlight(router, match.id, acceptedFlight)?.abort() + if (claimed) { + const accepted = detachFlight(match) + accepted?.abort() + } else { + releaseFlight(match) + } // A successful route without a loader has no blocking work to present. It // still gets a task so its chunk and derived assets participate in the // lane, but putting it back into pending would hide an already-rendered @@ -868,13 +852,14 @@ function createLoaderTask( } options[8]?.() } - if (!loaded) { - match.isFetching = false - } - const rawOutcome = reloadFailure + const rawOutcome: Promise = reloadFailure ? Promise.resolve(reloadFailure) - : !blocking - ? Promise.resolve([SUCCESS, match.loaderData]) + : !blocking || !loader + ? Promise.resolve([ + SUCCESS, + match.loaderData, + match.updatedAt, + ]) : loadResource( router, lane, @@ -886,33 +871,28 @@ function createLoaderTask( options[0], ) const outcome = rawOutcome.then((result) => { - if (blocking) { - settleInto(match, result, preload) - if (result[0] === SUCCESS) { - if (preload && routeLoader) { - cacheLoaderMatch(router, match, plannedCacheMatch) - } - // A route is renderable only after both its data and normal component - // chunk are ready. Its loader data is already available to descendants. - match.status = 'pending' + if (blocking && settle(match, result, preload)) { + if (preload && loader) { + cacheLoaderMatch(router, match, plannedCacheMatch) } + // A route is renderable only after both its data and normal component + // chunk are ready. Its loader data is already available to descendants. + match.status = 'pending' } return result }) const rawChunkFailure = waitFor( - Promise.resolve().then(() => loadRouteChunk(route)), + Promise.resolve().then(() => + loadRouteChunk(route, undefined, options[8]), + ), options[0].signal, - ).then( - () => { - options[8]?.() - return undefined - }, + ).catch( (cause): IndexedOutcome => [ index, normalizeLaneError(route, cause, options), ], - ) + ) as Promise const chunkFailure = rawChunkFailure.then((failure) => outcome.then((result) => { if ( @@ -936,8 +916,10 @@ function createLoaderTask( ...match, status: 'pending', preload: false, - _flight: donor, + _flight: undefined, + _claimedFlight: claimed, } + match._claimedFlight = undefined match.invalid = false match.isFetching = 'loader' const backgroundOutcome = loadResource( @@ -951,7 +933,10 @@ function createLoaderTask( options[0], ).then((result) => { match.isFetching = false - settleInto(candidate, result, false) + if (result[0] === SUCCESS) { + retireFlight(match.id, candidate._flight!) + } + settle(candidate, result, false) return result }) ;(lane[2] ??= []).push([index, backgroundOutcome, chunkFailure, candidate]) @@ -966,6 +951,7 @@ async function getNotFoundBoundary( indexed: IndexedOutcome | undefined, signal: AbortSignal, fallback = 0, + preload?: boolean, ): Promise { const cause = indexed?.[1][1] as NotFoundError | undefined let index = cause?.routeId @@ -976,13 +962,15 @@ async function getNotFoundBoundary( } for (let i = index; i >= 0; i--) { const route = getRoute(router, matches[i]!) - const loading = loadRouteChunk(route, false) - if (loading) { - try { - await waitFor(loading, signal) - } catch (cause) { - if (cause === signal) { - throw cause + if (!preload || route.options.preload !== false) { + const loading = loadRouteChunk(route, false) + if (loading) { + try { + await waitFor(loading, signal) + } catch (cause) { + if (cause === signal) { + throw cause + } } } } @@ -993,16 +981,30 @@ async function getNotFoundBoundary( return cause?.routeId ? index : fallback } -function discardBackground(router: AnyRouter, lane: Lane): void { +function discardBackground(lane: Lane): void { if (lane[2]) { - transferMatchResources( - router, - lane[2].map((task) => task[3]), - ) + transferMatchResources(lane[2].map((task) => task[3])) lane[2] = undefined } } +function waitForDescendantRedirects( + tasks: Array | undefined, + boundary: number, +): Promise { + return Promise.all( + (tasks ?? []).map( + (task) => + task[0] > boundary && + task[1].then((outcome) => { + if (outcome[0] === REDIRECTED) { + throw [task[0], outcome] as IndexedOutcome + } + }), + ), + ) +} + async function settleTasks( tasks: Array, serialFailure?: IndexedOutcome, @@ -1022,22 +1024,11 @@ async function settleTasks( if (outcome[0] >= REDIRECTED) { throw [taskIndex, outcome] as IndexedOutcome } - if (!loaderFailure && outcome[0] !== SUCCESS) { - loaderFailure = [taskIndex, outcome] + if (outcome[0] !== SUCCESS) { + loaderFailure ||= [taskIndex, outcome] // Every started descendant must settle before an ordinary failure // wins because a redirect from any of them remains control flow. - await Promise.all( - (redirectTasks ?? []).map((nextTask) => { - if (nextTask[0] <= taskIndex) { - return - } - return nextTask[1].then((nextOutcome) => { - if (nextOutcome[0] === REDIRECTED) { - throw [nextTask[0], nextOutcome] as IndexedOutcome - } - }) - }), - ) + await waitForDescendantRedirects(redirectTasks, taskIndex) } }), ), @@ -1056,6 +1047,7 @@ async function reduceLane( redirects: number, settlement: Promise, onReady?: () => void, + preload?: boolean, ): Promise { const matches = lane[1] let failure = await settlement @@ -1063,7 +1055,14 @@ async function reduceLane( const plannedBoundary = matches.findIndex((match) => match._notFound) const boundaryOf = (found: IndexedOutcome) => found[1][0] === NOT_FOUND - ? getNotFoundBoundary(router, matches, found, controller.signal) + ? getNotFoundBoundary( + router, + matches, + found, + controller.signal, + 0, + preload, + ) : found[0] let readinessEnd = plannedBoundary < 0 ? matches.length : plannedBoundary @@ -1101,6 +1100,17 @@ async function reduceLane( break } + if (failure && failure[1][0] < REDIRECTED) { + try { + await waitForDescendantRedirects( + lane[2], + (failure[2] ??= await boundaryOf(failure)), + ) + } catch (cause) { + failure = cause as IndexedOutcome + } + } + if ((failure?.[1][0] ?? 0) >= REDIRECTED) { const outcome = failure![1] if ( @@ -1108,7 +1118,7 @@ async function reduceLane( outcome[1].options.reloadDocument || redirects < 20 ) { - discardBackground(router, lane) + discardBackground(lane) return outcome as ControlOutcome } redirectLimitExceeded = true @@ -1123,44 +1133,44 @@ async function reduceLane( const kind = outcome?.[0] const match = matches[boundary]! const cause = outcome?.[1] - const install = () => { - if (outcome) { - match._notFound = undefined - if (kind === ERROR) { - match.status = 'error' + const route = getRoute(router, match) + if (outcome) { + match._notFound = undefined + if (kind === ERROR) { + match.status = 'error' + } else { + ;(cause as NotFoundError).routeId = match.routeId + if (match.routeId === router.routeTree.id) { + match.status = 'success' + match._notFound = true } else { - ;(cause as NotFoundError).routeId = match.routeId - if (match.routeId === router.routeTree.id) { - match.status = 'success' - match._notFound = true - } else { - match.status = 'notFound' - } + match.status = 'notFound' } - match.error = cause - match.isFetching = false } + match.error = cause + match.isFetching = false } - install() - try { - await waitFor( - outcome - ? Promise.resolve().then(() => - loadRouteChunk( - getRoute(router, match), - kind === ERROR ? 'errorComponent' : 'notFoundComponent', - ), - ) - : Promise.all([ - loadRouteChunk(getRoute(router, match)), - loadRouteChunk(getRoute(router, match), 'notFoundComponent'), - ]), - controller.signal, - ) - } catch (cause) { - if (cause === controller.signal) { - discardBackground(router, lane) - return [CANCELED] + if (!preload || route.options.preload !== false) { + try { + await waitFor( + outcome + ? Promise.resolve().then(() => + loadRouteChunk( + route, + kind === ERROR ? 'errorComponent' : 'notFoundComponent', + ), + ) + : Promise.all([ + loadRouteChunk(route), + loadRouteChunk(route, 'notFoundComponent'), + ]), + controller.signal, + ) + } catch (cause) { + if (cause === controller.signal) { + discardBackground(lane) + return [CANCELED] + } } } if (!outcome) { @@ -1173,13 +1183,12 @@ async function reduceLane( ...tasks.map((task) => task[2]), ...(lane[2] ?? []).map((task) => task[1]), ]) - discardBackground(router, lane) - transferMatchResources(router, matches) - install() + discardBackground(lane) + transferMatchResources(matches) } } - return lane as ReducedLane + return lane as unknown as ReducedLane } export async function projectLane( @@ -1225,7 +1234,7 @@ export async function projectLane( break } } - return lane as ProjectedLane + return lane as unknown as ProjectedLane } async function executeClientLane( @@ -1243,6 +1252,7 @@ async function executeClientLane( undefined, options[0].signal, plannedBoundary, + options[4], ) if (boundary !== plannedBoundary) { matches[plannedBoundary]!._notFound = undefined @@ -1270,6 +1280,8 @@ async function executeClientLane( matched[1], failure, options[0].signal, + 0, + options[4], ) end = Math.min(end, failure[2] + 1) } else if ((failure?.[1][0] ?? 0) >= REDIRECTED) { @@ -1281,23 +1293,27 @@ async function executeClientLane( } semanticParent = createLoaderTask( router, - matched as ContextualizedLane, + matched as unknown as ContextualizedLane, index, tasks, semanticParent, options, ) } + for (const match of matched[1]) { + detachClaim(match)?.abort() + } let reduced: ReducedLane | ControlOutcome try { const reduction = reduceLane( router, - matched as ContextualizedLane, + matched as unknown as ContextualizedLane, tasks, options[0], options[1], settleTasks(tasks, failure, matched[2]), options[8], + options[4], ) if (matched[2]?.length) { matched[3] = settleTasks( @@ -1315,7 +1331,7 @@ async function executeClientLane( } reduced = await reduction } catch (cause) { - discardBackground(router, matched) + discardBackground(matched) throw cause } if (isControl(reduced)) { @@ -1329,49 +1345,6 @@ async function executeClientLane( ) } -/** - * Finds the first route that should show pending UI and its two timing values. - * A fallback already on screen remains selected after its route loads, so we - * do not jump to a child fallback. Matches put back into pending by invalidation - * skip pendingMs, and a route without a usable fallback blocks pending UI for deeper routes. - */ -function pendingConfig( - router: AnyRouter, - matches: Array, -): - | [delay: number, boundary: number, min: number, component: unknown] - | undefined - | void { - const presented = router.stores.matches.get() - for (let index = 0; index < matches.length; index++) { - const match = matches[index]! - const success = match.status === 'success' - const visible = - success && - presented[index]?.id === match.id && - presented[index]?.status === 'pending' - if (success && !visible) { - continue - } - const route = getRoute(router, match as WorkMatch) - const delay = - visible || match.invalid - ? 0 - : (route.options.pendingMs ?? router.options.defaultPendingMs) - const component = - route.options.pendingComponent ?? - (router.options as any).defaultPendingComponent - return component && typeof delay === 'number' && delay !== Infinity - ? [ - delay, - index, - route.options.pendingMinMs ?? router.options.defaultPendingMinMs ?? 0, - component, - ] - : undefined - } -} - /** * Waits for `pendingMs`, then presents the complete lane. Rendering applies the * selected boundary cutoff while retaining every match's structural state. @@ -1394,18 +1367,49 @@ function offerPending(router: CoordinatorRouter, tx: LoadTransaction): void { router._pending = session = undefined } } - const config = pendingConfig(router, tx[3]) - if (!config) { + // The first unresolved match chooses the fallback. A visible fallback stays + // selected after its route resolves, and a route without one blocks children. + const presented = router.stores.matches.get() + let boundary = 0 + let delay: number | undefined + let min = 0 + let component: unknown + for (; boundary < tx[3].length; boundary++) { + const match = tx[3][boundary]! + const success = match.status === 'success' + const visible = + success && + presented[boundary]?.id === match.id && + presented[boundary]?.status === 'pending' + if (success && !visible) { + continue + } + const route = getRoute(router, match as WorkMatch) + delay = + visible || match.invalid + ? 0 + : (route.options.pendingMs ?? router.options.defaultPendingMs) + component = + route.options.pendingComponent ?? + (router.options as any).defaultPendingComponent + if (!component || typeof delay !== 'number' || delay === Infinity) { + return + } + min = + route.options.pendingMinMs ?? router.options.defaultPendingMinMs ?? 0 + break + } + if (delay === undefined) { return } - const [delay, boundary, min, component] = config const matchId = tx[3][boundary]!.id if (!session || session[1] !== boundary || sessionMatchId !== matchId) { // Hydration and redirects can preserve pending presentation without a session. // Do not delay it again; conservatively start pendingMinMs from now. clearTimeout(session?.[3]) - const presented = router.stores.matches.get()[boundary] - const visible = presented?.id === matchId && presented.status === 'pending' + const presentedMatch = presented[boundary] + const visible = + presentedMatch?.id === matchId && presentedMatch.status === 'pending' router._pending = session = [ tx, boundary, @@ -1436,7 +1440,7 @@ function offerPending(router: CoordinatorRouter, tx: LoadTransaction): void { })) offered[boundary]!.status = 'pending' const ack = router - .startTransition(() => router.stores.setMatches(offered), offered, true) + .startTransition(() => router.stores.setMatches(offered), offered) .then((rendered) => { if ( rendered && @@ -1471,9 +1475,9 @@ function publishMatches( router.stores.setMatches(matches) } -function discardLane(router: AnyRouter, lane: ProjectedLane): void { - transferMatchResources(router, lane[1]) - discardBackground(router, lane) +function discardLane(lane: ProjectedLane): void { + transferMatchResources(lane[1]) + discardBackground(lane) } function commitMatches( @@ -1492,6 +1496,7 @@ function commitMatches( } const cut = _getRenderedMatches(matches).length const cached = new Map() + const discarded: Array = [] const now = Date.now() for (const match of [...previous, ...previousCached.values()]) { // Rendered-prefix ids and settled successes anywhere in the lane are @@ -1506,6 +1511,7 @@ function commitMatches( (index < cut || candidate.status === 'success'), ) ) { + discarded.push(match) continue } const work = match as WorkMatch @@ -1519,29 +1525,26 @@ function commitMatches( 300_000) : (route.options.gcTime ?? router.options.defaultGcTime ?? 300_000)) ) { + discarded.push(match) continue } - cached.set( - match.id, - previousCached.get(match.id) === match - ? match - : ({ - ...match, - _flight: undefined, - isFetching: false, - context: {}, - } as WorkMatch), - ) + if (previousCached.get(match.id) === match) { + cached.set(match.id, match) + } else { + cached.set(match.id, { + ...match, + _flight: undefined, + isFetching: false, + context: {}, + } as WorkMatch) + discarded.push(match) + } } // The lane becomes committed before publication can synchronously reenter. tx[3] = [] router._cache = cached publishMatches(router, matches) - transferMatchResources( - router, - [...previousCached.values(), ...previous], - [...matches, ...cached.values()], - ) + transferMatchResources(discarded) runRouteLifecycle(router, previous, matches, () => router._tx === tx) } @@ -1568,7 +1571,7 @@ function commitRefreshMatches( if (!checkpoint.published || router._tx !== tx) { return } - runRouteLifecycle(router, previous, matches, () => router._tx === tx) + runRouteLifecycle(router, previous, matches, () => router._tx === tx, true) } function settlePublication( @@ -1579,10 +1582,11 @@ function settlePublication( return } checkpoint.published = false + const retained = [...router._cache.values(), ...router._committed] transferMatchResources( - router, - [...checkpoint.previousCache.values(), ...checkpoint.previousMatches], - [...router._cache.values(), ...router._committed], + [...checkpoint.previousCache.values(), ...checkpoint.previousMatches].filter( + (match) => !retained.includes(match), + ), ) } @@ -1601,6 +1605,7 @@ function rollbackPublication( return false } + router._cancelTransition?.() const discarded = [...router._cache.values(), ...router._committed] const restored = [ ...checkpoint.previousCache.values(), @@ -1610,24 +1615,16 @@ function rollbackPublication( router._committed = checkpoint.previousMatches checkpoint.published = false - for (const match of discarded as Array) { - if ( - !restored.includes(match) && - match._flight && - router._flights?.get(match.id) === match._flight - ) { - router._flights.delete(match.id) - } - } - finishPending(router, tx) router.batch(() => { router.stores.status.set('idle') router.stores.setMatches(checkpoint.previousPresentation) }) tx[0].abort() - transferMatchResources(router, discarded, restored) - discardBackground(router, lane) + transferMatchResources( + discarded.filter((match) => !restored.includes(match)), + ) + discardBackground(lane) if (router._tx === tx && router._commitPromise === checkpoint.commitPromise) { router._commitPromise?.resolve() router._commitPromise = undefined @@ -1664,9 +1661,7 @@ async function transitionRefresh( if (router._rollbackRefresh === rollback) { router._rollbackRefresh = undefined } - const restored = rollbackPublication(router, tx, lane, checkpoint) - router._cancelTransition?.() - return restored + return rollbackPublication(router, tx, lane, checkpoint) } try { const rendered = await router.startTransition(commit, lane[1]) @@ -1725,11 +1720,12 @@ function restoreCommitted( ): void { finishPending(router, tx) tx[0].abort() - transferMatchResources(router, tx[3]) + transferMatchResources(tx[3]) tx[3] = [] if (router._tx !== tx) { return } + router._cancelTransition?.() router.batch(() => { router.stores.status.set('idle') router.stores.setMatches(router._committed) @@ -1747,12 +1743,21 @@ async function runBackground( tasks: Array, settlement: Promise, ): Promise { - const next = base.map((match) => ({ ...match })) - acquireMatchResources(next) - for (const task of tasks) { - releaseFlight(router, next[task[0]]!) - next[task[0]] = task[3] - } + // Tasks are appended in route order, so candidates can transfer ownership + // while untouched matches are cloned in the same pass. + let taskIndex = 0 + const next = base.map((match, index) => { + const task = tasks[taskIndex] + if (task?.[0] === index) { + taskIndex++ + return task[3] + } + const clone = { ...match } as WorkMatch + if (clone._flight) { + clone._flight[2]++ + } + return clone + }) // Phase jump: the clones inherit beforeLoad context from the committed // foreground lane, which already ran `contextualize` for these matches. const lane = [tx[2], next] as ContextualizedLane @@ -1760,11 +1765,11 @@ async function runBackground( try { reduced = await reduceLane(router, lane, tasks, tx[0], tx[1], settlement) } catch (cause) { - transferMatchResources(router, next) + transferMatchResources(next) throw cause } if (isControl(reduced)) { - transferMatchResources(router, next) + transferMatchResources(next) if ( reduced[0] === REDIRECTED && router._tx === tx && @@ -1776,18 +1781,19 @@ async function runBackground( } const projected = await projectLane(router, reduced, tx[0].signal) if (router._tx !== tx || router._committed !== base) { - transferMatchResources(router, projected[1]) + transferMatchResources(projected[1]) return } - for (const match of projected[1] as Array) { + for (const task of tasks) { + const match = task[3] const cached = router._cache.get(match.id) as WorkMatch | undefined if (cached?._flight && cached._flight === match._flight) { router._cache.delete(match.id) - releaseFlight(router, cached) + releaseFlight(cached) } } publishMatches(router, projected[1]) - transferMatchResources(router, base, projected[1]) + transferMatchResources(base) } async function runClientTransaction( @@ -1797,60 +1803,24 @@ async function runClientTransaction( onReady?: () => void, sync?: boolean, resolvedPrefix?: number, - adopted?: ActivePreload, - retained?: ActivePreload, ): Promise { const options: ExecuteLaneOptions = [ tx[0], tx[1], () => router._tx === tx && !!tx[3].length, router._committed, - undefined, + false, sync, forceStaleReload, resolvedPrefix, onReady, ] - let result: LaneResult - try { - result = adopted - ? await adopted[2] - : await executeClientLane(router, tx[2], tx[3], options) - } finally { - if (retained) { - discardPreload(router, retained) - } - } - if ( - adopted && - router._tx === tx && - ((isControl(result) && result[0] === CANCELED) || - (!isControl(result) && - result[1].some( - (match) => match.status !== 'success' || match._notFound, - ))) - ) { - // Successful loaders already seeded the cache; retry only the guard lane. - const donors = tx[3] as Array - tx[3] = [] - transferMatchResources(router, donors) - tx[0].abort() - if (router._tx !== tx) { - return - } - const controller = new AbortController() - tx[0] = options[0] = controller - tx[3] = router.matchRoutes(tx[2], { - _controller: controller, - }) - acquireMatchResources(tx[3]) - result = await executeClientLane(router, tx[2], tx[3], options) - } + const result = await executeClientLane(router, tx[2], tx[3], options) if (isControl(result)) { if (result[0] === REDIRECTED && router._tx === tx) { finishPending(router, tx) - transferMatchResources(router, tx[3]) + transferMatchResources(tx[3]) tx[3] = [] if (router._tx === tx) { if (process.env.NODE_ENV !== 'production' && tx[6]) { @@ -1900,7 +1870,7 @@ async function runClientTransaction( } if (router._tx !== tx) { finishPending(router, tx) - discardLane(router, result) + discardLane(result) return } const toLocation = tx[2] @@ -1911,7 +1881,7 @@ async function runClientTransaction( const background = result[2] await router.startViewTransition(async () => { if (router._tx !== tx) { - discardLane(router, result) + discardLane(result) return } const commit = () => { @@ -1937,7 +1907,7 @@ async function runClientTransaction( return } if (router._tx !== tx) { - discardBackground(router, result) + discardBackground(result) return } if (background?.length) { @@ -2028,87 +1998,52 @@ export async function loadClientRoute( return } const sameHref = previousLocation.href === location.href - let adopted = router._preloads?.get(location.href) - let retained: ActivePreload | undefined - if (rematerialize && adopted) { - router._preloads!.delete(location.href) - discardPreload(router, adopted) - adopted = undefined - if (preflight.signal.aborted || router._tx !== previousOwner) { - preflight.abort() - await awaitCurrent(router, previousOwner) - return - } - } - if ( - adopted && - (hydrationController || - !samePreloadLane( - adopted, - router, - pendingLocation?.href === location.href ? pendingLocation : location, - redirects, - )) - ) { - router._preloads!.delete(location.href) - // Keep incompatible loader flights alive through the real lane's reload - // decisions so matching generations can still donate their work. - retained = adopted - adopted = undefined - } let matches: Array let controller = preflight let resolvedPrefix: number | undefined - if (adopted) { - controller = adopted[1] - matches = adopted[0] - router._preloads!.delete(location.href) - } else { - try { - matches = - process.env.NODE_ENV !== 'production' && rematerialize - ? router.matchRoutes(location, { - _controller: preflight, - _rematerialize: true, - }) - : router.matchRoutes(location, { _controller: preflight }) - acquireMatchResources(matches) - } catch (cause) { - preflight.abort() - if (retained) { - discardPreload(router, retained) + try { + matches = + process.env.NODE_ENV !== 'production' && rematerialize + ? router.matchRoutes(location, { + _controller: preflight, + _rematerialize: true, + }) + : router.matchRoutes(location, { _controller: preflight }) + } catch (cause) { + preflight.abort() + if (!isRedirect(cause)) { + if (process.env.NODE_ENV !== 'production' && rematerialize) { + router._refreshNextLoad = undefined } - if (!isRedirect(cause)) { - if (process.env.NODE_ENV !== 'production' && rematerialize) { - router._refreshNextLoad = undefined - } - await awaitCurrent(router) - router._commitPromise?.resolve() - router._commitPromise = undefined - return - } - await router.navigate({ - ...cause.options, - replace: true, - ignoreBlocker: true, - }) - await awaitCurrent(router, previousOwner) + await awaitCurrent(router) + router._commitPromise?.resolve() + router._commitPromise = undefined return } - resolvedPrefix = hydrationController ? handoff![1](matches) : undefined - if (resolvedPrefix) { - controller = hydrationController! - } else { - hydrationController?.abort() - } + await router.navigate({ + ...cause.options, + replace: true, + ignoreBlocker: true, + }) + await awaitCurrent(router, previousOwner) + return + } + resolvedPrefix = hydrationController ? handoff![1](matches) : undefined + if (resolvedPrefix) { + controller = hydrationController! + } else { + hydrationController?.abort() } if (router._preflight !== preflight || router._tx !== previousOwner) { preflight.abort() - transferMatchResources(router, matches) + transferMatchResources(matches) await awaitCurrent(router, previousOwner) return } router._preflight = undefined + if (!rematerialize) { + claimPendingFlights(router, matches) + } const tx: LoadTransaction = [ controller, @@ -2125,8 +2060,6 @@ export async function loadClientRoute( () => offerPending(router, tx), opts?.sync, resolvedPrefix, - adopted, - retained, ), ) .catch(() => { @@ -2154,10 +2087,10 @@ export async function loadClientRoute( } } previousOwner[0].abort() - transferMatchResources(router, previousOwner[3]) + transferMatchResources(previousOwner[3]) } if (router._tx !== tx) { - transferMatchResources(router, tx[3]) + transferMatchResources(tx[3]) tx[3] = [] await awaitCurrent(router, tx) return @@ -2178,6 +2111,7 @@ export async function loadClientRoute( export async function refreshClientRoute( router: CoordinatorRouter, ): Promise { + router._refreshNextLoad = true router._rollbackRefresh?.() const pending = router._tx if (pending && !pending[6] && router.stores.status.get() === 'pending') { @@ -2186,35 +2120,11 @@ export async function refreshClientRoute( await awaitCurrent(router, pending) } } - // Existing owners remain alive for rollback but cannot donate stale work. - router._flights?.clear() - router.clearCache() - router._refreshNextLoad = true - await loadClientRoute(router, { sync: true }) -} - -function followPreloadRedirect( - router: CoordinatorRouter, - result: ControlOutcome, - location: ParsedLocation, - owner: LoadTransaction | undefined, - redirects: number, -): Promise | undefined> | undefined { - if ( - result[0] === REDIRECTED && - !result[1].options.reloadDocument && - router._tx === owner - ) { - return preloadClientRoute( - router, - { - ...result[1].options, - _fromLocation: location, - }, - redirects + 1, - ) + if (process.env.NODE_ENV !== 'production') { + router._flights.clear() } - return + router.clearCache() + await loadClientRoute(router, { sync: true }) } export async function preloadClientRoute( @@ -2222,93 +2132,62 @@ export async function preloadClientRoute( opts: any, redirects = 0, ): Promise | undefined> { - if (redirects > 20) { - return - } - const owner = router._tx if ( process.env.NODE_ENV !== 'production' && - (router._refreshNextLoad || owner?.[6]) + (router._refreshNextLoad || router._tx?.[6]) ) { return } const location = opts._builtLocation ?? router.buildLocation(opts) const base = router._committed const controller = new AbortController() - let matches: Array | undefined - let preload: ActivePreload | undefined - let replaced: ActivePreload | undefined + let matches: Array try { - const pending = router._preloads?.get(location.href) - if (pending) { - if (samePreloadLane(pending, router, location, redirects)) { - const result = await pending[2] - return isControl(result) - ? followPreloadRedirect(router, result, location, owner, redirects) - : result[1] - } - router._preloads!.delete(location.href) - // Keep the superseded lane alive until this lane has made its reload - // decisions. Its active flights are the synchronous donor authority. - replaced = pending - } matches = router.matchRoutes(location, { _controller: controller, }) - acquireMatchResources(matches) - const promise = Promise.resolve() - .then(() => - executeClientLane(router, location, matches!, [ - controller, - redirects, - // Preload lanes run to completion even when unrelated navigations - // commit: finished work seeds the cache, and adoption safety is - // enforced independently by samePreloadLane's base identity check. - () => true, - base, - true, - ]), - ) - .finally(() => { - if (replaced) { - discardPreload(router, replaced) - } - }) - preload = [ - matches, - controller, - promise, - base, - laneInputs(router, location), - redirects, - ] - ;(router._preloads ??= new Map()).set(location.href, preload) - const result = await promise - if (router._preloads?.get(location.href) !== preload) { - return isControl(result) ? undefined : result[1] - } - router._preloads.delete(location.href) - if (isControl(result)) { - controller.abort() - transferMatchResources(router, matches) - return followPreloadRedirect(router, result, location, owner, redirects) - } - - transferMatchResources(router, result[1]) - controller.abort() - return result[1] } catch (cause) { - if (!preload || router._preloads?.get(location.href) === preload) { - if (preload) { - router._preloads!.delete(location.href) - } - controller.abort() - if (matches) { - transferMatchResources(router, matches) - } + controller.abort() + if (!isNotFound(cause)) { + console.error(cause) } - if (router._tx !== owner) { - return + return + } + router._preloads.set(controller, matches) + try { + const result = await executeClientLane(router, location, matches, [ + controller, + redirects, + // Preload lanes run to completion even when unrelated navigations + // commit: finished work seeds the cache. + () => true, + base, + true, + ]) + const control = isControl(result) + if (!router._preloads.delete(controller)) { + return control ? undefined : matches + } + transferMatchResources(matches) + controller.abort() + if (!control) { + return matches + } + if (result[0] === REDIRECTED && !result[1].options.reloadDocument) { + return preloadClientRoute( + router, + { + ...result[1].options, + _fromLocation: location, + }, + redirects + 1, + ) + } + return + } catch (cause) { + if (router._preloads.delete(controller)) { + transferMatchResources(matches) + controller.abort() } if (!isNotFound(cause)) { console.error(cause) @@ -2380,7 +2259,8 @@ export async function hydrate(router: AnyRouter): Promise { let location!: AnyRouter['latestLocation'] let candidates!: Array - let handoffInputs!: ReturnType + let handoffHistoryHref!: string + let handoffHistoryState: unknown try { await waitFor( router.options.hydrate?.(dehydratedRouter!.dehydratedData), @@ -2389,10 +2269,12 @@ export async function hydrate(router: AnyRouter): Promise { if (!isCurrent()) { return } + const historyLocation = router.history.location + handoffHistoryHref = historyLocation.href + handoffHistoryState = historyLocation.state router.updateLatestLocation() location = router.latestLocation router.stores.location.set(location) - handoffInputs = laneInputs(router, location) candidates = router.matchRoutes(location, { _controller: controller, }) @@ -2405,13 +2287,16 @@ export async function hydrate(router: AnyRouter): Promise { if (!isCurrent()) { return } - const committed: Array = [] + let committedEnd = 0 let pendingBoundary: number | undefined let verifiedAssetEnd = 0 - const retryFrom = (index: number) => { - // The failing route's identity is still verified, but no descendant is. - verifiedAssetEnd = Math.min(verifiedAssetEnd, index + 1) - const removed = committed.splice(index) + const retryFrom = (index: number, assetEnd = index + 1) => { + // The failing route's identity is still verified, but its client context + // and assets are not. Present it as the boundary for the client retry. + pendingBoundary = Math.min(pendingBoundary ?? index, index) + verifiedAssetEnd = Math.min(verifiedAssetEnd, assetEnd) + const removed = candidates.slice(index, committedEnd) + committedEnd = index for (const match of removed) { if ( getRoute(router, match).options.loader && @@ -2433,7 +2318,7 @@ export async function hydrate(router: AnyRouter): Promise { ) } } - transferMatchResources(router, removed) + transferMatchResources(removed) } // A longer server lane is valid only when the local match already caps the @@ -2476,7 +2361,7 @@ export async function hydrate(router: AnyRouter): Promise { candidate._notFound if (terminal) { isTerminal = true - committed.push(candidate) + committedEnd = index + 1 if (candidate.ssr === false || candidate.ssr === 'data-only') { pendingBoundary ??= index } @@ -2487,24 +2372,20 @@ export async function hydrate(router: AnyRouter): Promise { break } - committed.push(candidate) + committedEnd = index + 1 if (candidate.ssr === 'data-only') { pendingBoundary ??= index } } let verifiedContextEnd = verifiedAssetEnd - if ( - !isTerminal && - committed.length === shared && - shared < candidates.length - ) { + if (!isTerminal && committedEnd === shared && shared < candidates.length) { pendingBoundary = shared } // Hooks observe structural membership. Execution remains limited to - // `committed`, the accepted server prefix. - const chunks = committed.map(async (match) => { + // the accepted server prefix. + const chunks = candidates.slice(0, committedEnd).map(async (match) => { try { const route = getRoute(router, match) if (match._notFound) { @@ -2542,7 +2423,7 @@ export async function hydrate(router: AnyRouter): Promise { if (!isCurrent()) { return } - if (chunkFailure < committed.length) { + if (chunkFailure < committedEnd) { verifiedContextEnd = Math.min(verifiedContextEnd, chunkFailure) retryFrom(chunkFailure) } @@ -2550,9 +2431,7 @@ export async function hydrate(router: AnyRouter): Promise { // The first pending match is already visible, so prepare its route context // without granting its beforeLoad or loader any hydration authority. const contextEnd = Math.max( - pendingBoundary === committed.length - ? committed.length + 1 - : committed.length, + pendingBoundary === committedEnd ? committedEnd + 1 : committedEnd, verifiedContextEnd, ) for (let index = 0; index < contextEnd; index++) { @@ -2586,7 +2465,7 @@ export async function hydrate(router: AnyRouter): Promise { match.status !== 'notFound' && !match._notFound ) { - retryFrom(index) + retryFrom(index, index) break } } @@ -2597,7 +2476,7 @@ export async function hydrate(router: AnyRouter): Promise { match.context = { ...parentContext, ...routeContext, - ...(committed[index] && dehydratedMatches[index]!.b), + ...(index < committedEnd && dehydratedMatches[index]!.b), } } @@ -2611,10 +2490,11 @@ export async function hydrate(router: AnyRouter): Promise { if (!isCurrent()) { return } - const needsClientLoad = - pendingBoundary !== undefined || committed.length < shared + const needsClientLoad = pendingBoundary !== undefined || committedEnd < shared const committedMatches = - isTerminal && committed.length === shared ? candidates : committed + isTerminal && committedEnd === shared + ? candidates + : candidates.slice(0, committedEnd) let presented = needsClientLoad ? candidates : committedMatches let dataOnlyAssetEnd: number | undefined if (needsClientLoad && pendingBoundary !== undefined) { @@ -2636,16 +2516,18 @@ export async function hydrate(router: AnyRouter): Promise { } } - const claim = () => - needsClientLoad && - !router._tx && - router.latestLocation.state === location.state && - deepEqual(handoffInputs, laneInputs(router, router.latestLocation)) && - router._committed === committedMatches && - committedMatches.length && - !controller.signal.aborted + const claim = () => { + const historyLocation = router.history.location + return needsClientLoad && + !router._tx && + historyLocation.href === handoffHistoryHref && + historyLocation.state === handoffHistoryState && + router._committed === committedMatches && + committedMatches.length && + !controller.signal.aborted ? controller : undefined + } const handoff: NonNullable = [ claim, (matches) => { @@ -2676,7 +2558,7 @@ export async function hydrate(router: AnyRouter): Promise { if (handoffAssetEnd !== undefined) { clones[pendingBoundary!]!._assetEnd = handoffAssetEnd } - transferMatchResources(router, matches.splice(0, prefix, ...clones)) + transferMatchResources(matches.splice(0, prefix, ...clones)) for (let index = prefix; index < matches.length; index++) { const match = matches[index]! const hydrated = candidates[index] diff --git a/packages/router-core/src/router.ts b/packages/router-core/src/router.ts index e2c9da3d25..e18269802a 100644 --- a/packages/router-core/src/router.ts +++ b/packages/router-core/src/router.ts @@ -58,7 +58,6 @@ import type { import type { SearchParser, SearchSerializer } from './searchParams' import type { AnyRedirect, ResolvedRedirect } from './redirect' import type { - ActivePreload, LoadTransaction, LoaderFlight, PendingSession, @@ -778,7 +777,6 @@ export type CommitLocationFn = ({ export type StartTransitionFn = ( fn: () => void, expected: Array, - urgent?: boolean, ) => Promise export interface MatchRoutesFn { @@ -936,21 +934,41 @@ export function _getUserHistoryState({ return state } +function runCallback( + callback: ((arg: T) => void) | undefined, + arg: T, + throwOnError?: boolean, +): void { + if (throwOnError && process.env.NODE_ENV !== 'production') { + callback?.(arg) + return + } + try { + callback?.(arg) + } catch (error) { + console.error(error) + } +} + /** Run route lifecycle callbacks in leave/enter/stay phases. */ export function runRouteLifecycle( router: AnyRouter, previous: Array, matches: Array, isCurrent?: () => boolean, + throwOnError?: boolean, ): void { for (const match of previous) { if (isCurrent?.() === false) { return } if (!matches.some((candidate) => candidate.routeId === match.routeId)) { - ;(router.routesById as Record)[ - match.routeId - ]!.options.onLeave?.(match) + runCallback( + (router.routesById as Record)[match.routeId]!.options + .onLeave, + match, + throwOnError, + ) } } for (const match of matches) { @@ -960,11 +978,15 @@ export function runRouteLifecycle( const route = (router.routesById as Record)[ match.routeId ]! - route.options[ - previous.some((candidate) => candidate.routeId === match.routeId) - ? 'onStay' - : 'onEnter' - ]?.(match) + runCallback( + route.options[ + previous.some((candidate) => candidate.routeId === match.routeId) + ? 'onStay' + : 'onEnter' + ], + match, + throwOnError, + ) } } @@ -1025,10 +1047,10 @@ export interface RouterCore< shouldViewTransition?: boolean | ViewTransitionOptions /** Current client load transaction and owner of navigation writes. */ _tx?: LoadTransaction - /** Joinable in-flight loader generations keyed by match ID. */ - _flights?: Map - /** Whole speculative lanes that an identical navigation may adopt. */ - _preloads?: Map + /** Joinable loader generations keyed by match ID. */ + _flights: Map + /** Active speculative lane matches keyed by their cancellation owner. */ + _preloads: Map> /** Owns cancellable work before a client transaction publishes. */ _preflight?: AbortController /** Transfers one reconstructed SSR prefix into its initial client load. */ @@ -1037,8 +1059,6 @@ export interface RouterCore< _pending?: PendingSession /** Result of the latest server load, used to render or redirect. */ _serverResult?: ServerLoadResult - /** Framework callback that acknowledges an exact matches publication. */ - _rendered?: (matches: Array) => void /** Development-only HMR reload for a route and its descendants. */ _refreshRoute: (() => Promise) | undefined /** Development-only replacement for a route's lazy chunk owner. */ @@ -1083,9 +1103,12 @@ export class RouterCore< subscribers = new Set>() /** Accepted off-screen loader generations keyed by match ID. */ _cache = new Map() + /** Joinable loader generations keyed by match ID. */ + _flights = new Map() + /** Active speculative lane matches keyed by their cancellation owner. */ + _preloads = new Map>() /** Accepted semantic lane, excluding temporary pending presentation. */ _committed: Array = [] - // Must build in constructor stores!: RouterStores private getStoreConfig!: GetStoreConfig @@ -1377,11 +1400,7 @@ export class RouterCore< emit: EmitFn = (routerEvent) => { for (const listener of this.subscribers) { if (listener.eventType === routerEvent.type) { - try { - listener.fn(routerEvent) - } catch (e) { - console.error(e) - } + runCallback(listener.fn, routerEvent) } } } @@ -1463,7 +1482,6 @@ export class RouterCore< parsedTempLocation.state.__TSR_key = location.state.__TSR_key delete parsedTempLocation.state.__tempLocation - return { ...parsedTempLocation, maskedLocation: location, @@ -1541,14 +1559,7 @@ export class RouterCore< const matches = new Array(matchedRoutes.length) const committed = this._committed - const previousAt = (route: AnyRoute, index: number) => { - const match = committed[index] - return match?.routeId === route.id - ? match - : route === this.options.notFoundRoute - ? committed.find((candidate) => candidate.routeId === route.id) - : undefined - } + const controller = opts?._controller for (let index = 0; index < matchedRoutes.length; index++) { const route = matchedRoutes[index]! @@ -1633,7 +1644,13 @@ export class RouterCore< // explicit deps loaderDepsHash - const previousMatch = previousAt(route, index) + let previousMatch = committed[index] + if (previousMatch?.routeId !== route.id) { + previousMatch = + route === this.options.notFoundRoute + ? committed.find((candidate) => candidate.routeId === route.id) + : undefined + } const existingMatch = process.env.NODE_ENV !== 'production' && opts?._rematerialize ? undefined @@ -1702,7 +1719,7 @@ export class RouterCore< error: undefined, paramsError, context: {}, - abortController: opts?._controller ?? new AbortController(), + abortController: controller ?? new AbortController(), cause, loaderDeps: previousMatch ? replaceEqualDeep(previousMatch.loaderDeps, loaderDeps) @@ -1730,8 +1747,13 @@ export class RouterCore< match.cause === 'stay' ? nullReplaceEqualDeep(match.params, routeParams) : routeParams - if (opts?._controller) { + if (controller) { match.context = {} + const flight = (match as AnyRouteMatch & { _flight?: LoaderFlight }) + ._flight + if (flight) { + flight[2]++ + } } } @@ -2469,13 +2491,37 @@ export class RouterCore< > = (opts) => { const committedMatches = this._committed const filter = opts?.filter - const invalidIds = filter - ? new Set( - [...committedMatches, ...this._cache.values()] - .filter((match) => filter(match as MakeRouteMatchUnion)) - .map((match) => match.id), - ) - : undefined + let invalidIds: Set | undefined + if (filter) { + invalidIds = new Set() + const collect = (matches: Iterable) => { + for (const match of matches) { + if (filter(match as MakeRouteMatchUnion)) { + invalidIds!.add(match.id) + } + } + } + collect(committedMatches) + collect(this._cache.values()) + for (const matches of this._preloads.values()) { + collect(matches) + } + if (this._tx) { + collect(this._tx[3]) + } + } + const discardedPreloads: Array = [] + const preloadControllers: Array = [] + for (const [controller, matches] of this._preloads) { + if ( + !invalidIds || + matches.some((match) => invalidIds.has(match.id)) + ) { + this._preloads.delete(controller) + discardedPreloads.push(...matches) + preloadControllers.push(controller) + } + } const invalidate = (d: MakeRouteMatch) => { if (!invalidIds || invalidIds.has(d.id)) { const route = this.routesById[d.routeId] as AnyRoute @@ -2498,11 +2544,20 @@ export class RouterCore< const committed = committedMatches.map(invalidate) this._committed = committed - const cache = new Map() for (const [id, match] of this._cache) { - cache.set(id, invalidate(match)) + this._cache.set(id, invalidate(match)) + } + if (invalidIds) { + for (const id of invalidIds) { + this._flights.delete(id) + } + } else { + this._flights.clear() + } + transferMatchResources(discardedPreloads) + for (const controller of preloadControllers) { + controller.abort() } - this._cache = cache this.shouldViewTransition = false return this.load({ sync: opts?.sync }) @@ -2551,36 +2606,33 @@ export class RouterCore< } clearCache: ClearCacheFn = (opts) => { - const cached = this._cache - const preloads = this._preloads const filter = opts?.filter - const retained = new Map() const discarded: Array = [] - for (const [id, match] of cached) { - if (filter && !filter(match as MakeRouteMatchUnion)) { - retained.set(id, match) - } else { + const cacheIds: Array = [] + for (const [id, match] of this._cache) { + if (!filter || filter(match as MakeRouteMatchUnion)) { + cacheIds.push(id) discarded.push(match) } } - const retainedPreloads = new Map() - const discardedPreloads: Array = [] - for (const [href, preload] of preloads ?? []) { - if (!filter || preload[0].some(filter as any)) { - discardedPreloads.push(preload) - discarded.push(...preload[0]) - } else { - retainedPreloads.set(href, preload) + const preloadControllers: Array = [] + for (const [controller, matches] of this._preloads) { + if (!filter || matches.some(filter as any)) { + discarded.push(...matches) + preloadControllers.push(controller) } } - - // Install both replacement authorities before releasing a public loader - // signal, whose abort listeners can synchronously reenter the router. - this._cache = retained - this._preloads = retainedPreloads - transferMatchResources(this, discarded) - for (const preload of discardedPreloads) { - preload[1].abort() + // Update both authorities before releasing a public loader signal, whose + // abort listeners can synchronously reenter the router. + for (const id of cacheIds) { + this._cache.delete(id) + } + for (const controller of preloadControllers) { + this._preloads.delete(controller) + } + transferMatchResources(discarded) + for (const controller of preloadControllers) { + controller.abort() } } diff --git a/packages/router-core/src/ssr/handlerCallback.ts b/packages/router-core/src/ssr/handlerCallback.ts index 368c8a2a61..ac06c45f3b 100644 --- a/packages/router-core/src/ssr/handlerCallback.ts +++ b/packages/router-core/src/ssr/handlerCallback.ts @@ -30,17 +30,12 @@ export function normalizeSsrResponse( : { response: result, serverSsrCleanup: 'none' } } -export function disposeSsrResponse( +export async function disposeSsrResponse( response: SsrResponse, reason?: unknown, ): Promise { - if (response.serverSsrCleanup !== 'stream') { - return Promise.resolve() - } - try { - return Promise.resolve(response.dispose(reason)) - } catch (error) { - return Promise.reject(error) + if (response.serverSsrCleanup === 'stream') { + await response.dispose(reason) } } @@ -55,12 +50,78 @@ export function disposeSsrResponseDetached( return } - if (ssrResponse.response.body) { - try { - void ssrResponse.response.body.cancel(reason).catch(onError) - } catch (error) { - onError(error) + const body = ssrResponse.response.body + if (body && !body.locked) { + void body.cancel(reason).catch(onError) + } +} + +function ownResponseBody( + response: Response, + onTerminal: (reason?: unknown) => void, +): [Response, (reason?: unknown) => void] { + const reader = response.body!.getReader() + let controller!: ReadableStreamDefaultController + let terminal = false + const finish = (reason?: unknown) => { + terminal = true + onTerminal(reason) + } + const cancel = (reason?: unknown): Promise | undefined => { + if (!terminal) { + finish(reason) + return reader.cancel(reason) } + return + } + const body = new ReadableStream({ + start(ctrl) { + controller = ctrl + }, + async pull(ctrl) { + try { + const { done, value } = await reader.read() + if (terminal) { + return + } + if (done) { + finish() + ctrl.close() + } else { + ctrl.enqueue(value) + } + } catch (error) { + if (!terminal) { + finish(error) + ctrl.error(error) + } + } + }, + cancel, + }) + return [ + new Response(body, response), + (reason) => { + if (!terminal) { + controller.error(reason) + finish(reason) + void reader.cancel(reason).catch(console.error) + } + }, + ] +} + +function ownSsrResponse( + response: Response, + onTerminal: (reason?: unknown) => void, +): Extract { + const [ownedResponse, dispose] = ownResponseBody(response, onTerminal) + return { + response: ownedResponse, + serverSsrCleanup: 'stream', + async dispose(reason?: unknown) { + dispose(reason) + }, } } @@ -72,27 +133,16 @@ export function createSsrStreamResponse( throw new Error('Invariant failed: SSR stream response requires a body') } - let disposed = false - return { - response, - serverSsrCleanup: 'stream', - async dispose(reason?: unknown) { - if (disposed) { - return - } - disposed = true + return ownSsrResponse(response, () => router.serverSsr?.cleanup()) +} - // Sever router ownership before asking user/renderer stream machinery to - // cancel. A custom stream is allowed to ignore cancellation forever. - router.serverSsr?.cleanup() - - try { - await response.body!.cancel(reason) - } catch { - // Cleanup above already released router SSR state. - } - }, - } +export function _transferSsrResponse( + owner: Extract, + response: Response & { body: ReadableStream }, +): SsrResponse { + return ownSsrResponse(response, (reason) => { + disposeSsrResponseDetached(owner, reason) + }) } export function bindSsrResponseToRequest( @@ -104,14 +154,28 @@ export function bindSsrResponseToRequest( if (ssrResponse.serverSsrCleanup !== 'stream') { if (signal.aborted) { disposeSsrResponseDetached(result, signal.reason) + return ssrResponse } - return ssrResponse + const body = ssrResponse.response.body + if (!body) { + return ssrResponse + } + let abort = () => {} + const [response, dispose] = ownResponseBody(ssrResponse.response, () => { + signal.removeEventListener('abort', abort) + }) + abort = () => dispose(signal.reason) + signal.addEventListener('abort', abort, { once: true }) + return { response, serverSsrCleanup: 'none' } } - const failed = (error: unknown) => { router?.serverSsr?.cleanup() console.error(error) } + if (!ssrResponse.response.body) { + disposeSsrResponseDetached(ssrResponse, signal.reason, failed) + return { response: ssrResponse.response, serverSsrCleanup: 'none' } + } const abort = () => { disposeSsrResponseDetached(ssrResponse, signal.reason, failed) } @@ -127,13 +191,25 @@ export function bindSsrResponseToRequest( return ssrResponse } +async function disposeReplacedSsrResponse( + result: HandlerCallbackResult, + reason?: unknown, +): Promise { + const ssrResponse = normalizeSsrResponse(result) + if (ssrResponse.serverSsrCleanup === 'stream') { + await ssrResponse.dispose(reason) + } else { + disposeSsrResponseDetached(ssrResponse, reason) + } + return ssrResponse +} + export async function replaceSsrResponse( result: HandlerCallbackResult, response: Response, reason?: unknown, ): Promise { - const ssrResponse = normalizeSsrResponse(result) - await disposeSsrResponse(ssrResponse, reason) + await disposeReplacedSsrResponse(result, reason) return { response, serverSsrCleanup: 'none' } } @@ -141,8 +217,7 @@ export async function stripSsrResponseBody( result: HandlerCallbackResult, reason?: unknown, ): Promise { - const ssrResponse = normalizeSsrResponse(result) - await disposeSsrResponse(ssrResponse, reason) + const ssrResponse = await disposeReplacedSsrResponse(result, reason) return { response: new Response(null, ssrResponse.response), serverSsrCleanup: 'none', diff --git a/packages/router-core/src/ssr/server.ts b/packages/router-core/src/ssr/server.ts index 93973999cb..415cead0ef 100644 --- a/packages/router-core/src/ssr/server.ts +++ b/packages/router-core/src/ssr/server.ts @@ -10,6 +10,7 @@ export { normalizeSsrResponse, replaceSsrResponse, stripSsrResponseBody, + _transferSsrResponse, } from './handlerCallback' export type { HandlerCallback, diff --git a/packages/router-core/src/ssr/transformStreamWithRouter.ts b/packages/router-core/src/ssr/transformStreamWithRouter.ts index 03c6ecf2e1..68a9f3a00b 100644 --- a/packages/router-core/src/ssr/transformStreamWithRouter.ts +++ b/packages/router-core/src/ssr/transformStreamWithRouter.ts @@ -796,10 +796,11 @@ function makeMainStream( safeError(reason) cleanup(reason) }) - if (cleanedUp || isDone()) + if (cleanedUp || isDone()) { return stream + } - // Transform the appStream + // Transform the appStream ;(async () => { try { while (true) { diff --git a/packages/router-core/src/stores.ts b/packages/router-core/src/stores.ts index 8c2beeb2e7..c3c5770d07 100644 --- a/packages/router-core/src/stores.ts +++ b/packages/router-core/src/stores.ts @@ -1,4 +1,4 @@ -import { arraysEqual, functionalUpdate } from './utils' +import { functionalUpdate } from './utils' import type { AnyRoute } from './route' import type { RouterState } from './router' @@ -157,9 +157,7 @@ export function createRouterStores( batch(() => { // Publish lane membership first so framework trees reconcile departures // before observers of a leaving route receive its tombstone. - if (!arraysEqual(previousIds, nextIds)) { - ids.set(nextIds) - } + ids.set(nextIds) for (const id of previousIds) { if (!nextIds.includes(id)) { diff --git a/packages/router-core/src/utils.ts b/packages/router-core/src/utils.ts index 91011bfa7f..5d15d9a839 100644 --- a/packages/router-core/src/utils.ts +++ b/packages/router-core/src/utils.ts @@ -716,12 +716,3 @@ export function buildDevStylesUrl( const normalizedBasepath = trimmedBasepath === '' ? '' : `/${trimmedBasepath}` return `${normalizedBasepath}/@tanstack-start/styles.css?routes=${encodeURIComponent(routeIds.join(','))}` } - -export function arraysEqual(a: Array, b: Array) { - if (a === b) return true - if (a.length !== b.length) return false - for (let i = 0; i < a.length; i++) { - if (a[i] !== b[i]) return false - } - return true -} diff --git a/packages/router-core/tests/build-location.test.ts b/packages/router-core/tests/build-location.test.ts index ce0d5c3c98..dabfa42629 100644 --- a/packages/router-core/tests/build-location.test.ts +++ b/packages/router-core/tests/build-location.test.ts @@ -9,7 +9,7 @@ import { import { _getUserHistoryState } from '../src/router' import { createTestRouter } from './routerTestUtils' -test('_getUserHistoryState removes volatile router bookkeeping but keeps mask payloads', () => { +test('_getUserHistoryState removes volatile router bookkeeping', () => { expect( _getUserHistoryState({ key: 'legacy-key', @@ -20,7 +20,11 @@ test('_getUserHistoryState removes volatile router bookkeeping but keeps mask pa __tempKey: 'temp-key', user: 'state', } as any), - ).toEqual({ user: 'state', __tempLocation: {}, __tempKey: 'temp-key' }) + ).toEqual({ + __tempLocation: {}, + __tempKey: 'temp-key', + user: 'state', + }) }) describe('buildLocation - params function receives parsed params', () => { diff --git a/packages/router-core/tests/callbacks.test.ts b/packages/router-core/tests/callbacks.test.ts index 7a1b062d4f..c320dc7bd7 100644 --- a/packages/router-core/tests/callbacks.test.ts +++ b/packages/router-core/tests/callbacks.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it, test, vi } from 'vitest' import { createMemoryHistory } from '@tanstack/history' import { BaseRootRoute, BaseRoute } from '../src' -import { createTestRouter } from './routerTestUtils' +import { createTestRouter, loadServerResponse } from './routerTestUtils' describe('callbacks', () => { const setup = ({ @@ -159,6 +159,103 @@ describe('callbacks', () => { }) }) + test('a throwing lifecycle callback cannot interrupt later callbacks or leave a client commit half-resolved', async () => { + const lifecycleError = new Error('root onStay failed') + const log = vi.spyOn(console, 'error').mockImplementation(() => {}) + const rootOnStay = vi.fn(() => { + throw lifecycleError + }) + const targetOnEnter = vi.fn() + const sourceOnLeave = vi.fn() + const rootRoute = new BaseRootRoute({ onStay: rootOnStay }) + const sourceRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/source', + onLeave: sourceOnLeave, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + onEnter: targetOnEnter, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([sourceRoute, targetRoute]), + history: createMemoryHistory(), + }) + + // Establish the source lane through the same public navigation path used + // by the lifecycle contract tests above. + await router.navigate({ to: '/source' }) + rootOnStay.mockClear() + const onLoad = vi.fn() + const onResolved = vi.fn() + const unsubscribers = [ + router.subscribe('onLoad', onLoad), + router.subscribe('onResolved', onResolved), + ] + + try { + await router.navigate({ to: '/target' }) + + // Prove the throwing callback was reached before checking the work that + // must remain isolated from it. + expect(sourceOnLeave).toHaveBeenCalledOnce() + expect(rootOnStay).toHaveBeenCalledOnce() + expect(targetOnEnter).toHaveBeenCalledOnce() + expect(onLoad).toHaveBeenCalledOnce() + expect(onResolved).toHaveBeenCalledOnce() + expect(router.state).toMatchObject({ + status: 'idle', + location: { pathname: '/target' }, + resolvedLocation: { pathname: '/target' }, + }) + expect(router.state.matches.at(-1)?.routeId).toBe(targetRoute.id) + expect(log).toHaveBeenCalledWith(lifecycleError) + } finally { + for (const unsubscribe of unsubscribers) { + unsubscribe() + } + log.mockRestore() + } + }) + + test('a throwing lifecycle callback cannot reject an otherwise committed server load', async () => { + const lifecycleError = new Error('root onEnter failed') + const log = vi.spyOn(console, 'error').mockImplementation(() => {}) + const childOnEnter = vi.fn() + const rootRoute = new BaseRootRoute({ + onEnter: () => { + throw lifecycleError + }, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/child', + onEnter: childOnEnter, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([childRoute]), + history: createMemoryHistory({ initialEntries: ['/child'] }), + isServer: true, + }) + + try { + const response = await loadServerResponse(router, '/child') + + expect(response.status).toBe(200) + expect(log).toHaveBeenCalledWith(lifecycleError) + expect(childOnEnter).toHaveBeenCalledOnce() + expect(router.state).toMatchObject({ + status: 'idle', + location: { pathname: '/child' }, + resolvedLocation: { pathname: '/child' }, + }) + expect(router.state.matches.at(-1)?.routeId).toBe(childRoute.id) + } finally { + log.mockRestore() + } + }) + // Regression tests: switching lifecycle hooks to use routeId must NOT break // match-level caching, which still relies on match.id (routeId + params + loaderDeps). describe('same-route match caching', () => { diff --git a/packages/router-core/tests/hmr-refresh-lifecycle.test.ts b/packages/router-core/tests/hmr-refresh-lifecycle.test.ts index 2807c05951..cac5e942d1 100644 --- a/packages/router-core/tests/hmr-refresh-lifecycle.test.ts +++ b/packages/router-core/tests/hmr-refresh-lifecycle.test.ts @@ -433,7 +433,7 @@ describe('HMR route refresh', () => { expect(router.state.matches.at(-1)?.loaderData).toBe(3) }) - test('does not adopt a preload created by HMR preflight hooks', async () => { + test('ignores preloads triggered by HMR preflight hooks', async () => { let generation = 1 const rootRoute = new BaseRootRoute({}) const pageRoute = new BaseRoute({ @@ -459,4 +459,50 @@ describe('HMR route refresh', () => { expect(router.state.matches.at(-1)?.loaderData).toBe(2) }) + + test('ignores a preload reentered from cache cleanup during HMR', async () => { + let reentrantPreload: Promise | undefined + let router!: ReturnType + const reentrantLoader = vi.fn(() => 'reentrant data') + const rootRoute = new BaseRootRoute({}) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + }) + const cachedRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/cached', + loader: ({ abortController }) => { + abortController.signal.addEventListener( + 'abort', + () => { + reentrantPreload = router.preloadRoute({ to: '/reentrant' }) + }, + { once: true }, + ) + return 'cached data' + }, + }) + const reentrantRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/reentrant', + loader: reentrantLoader, + }) + router = createTestRouter({ + routeTree: rootRoute.addChildren([ + pageRoute, + cachedRoute, + reentrantRoute, + ]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + await router.load() + await router.preloadRoute({ to: '/cached' }) + await router._refreshRoute!() + expect(reentrantPreload).toBeDefined() + await reentrantPreload + + expect(reentrantLoader).not.toHaveBeenCalled() + }) }) 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 deleted file mode 100644 index a52a7f183d..0000000000 --- a/packages/router-core/tests/issue-6371-search-default-normalization-abort.test.ts +++ /dev/null @@ -1,109 +0,0 @@ -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) { - 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/load.test.ts b/packages/router-core/tests/load.test.ts index 7e465c20cb..62d919f1bd 100644 --- a/packages/router-core/tests/load.test.ts +++ b/packages/router-core/tests/load.test.ts @@ -215,8 +215,7 @@ describe('beforeLoad skip or exec', () => { await router.navigate({ to: '/foo' }) expect(router.state.location.pathname).toBe('/foo') - // An identical navigation may latch onto the still-active whole lane. - expect(beforeLoad).toHaveBeenCalledTimes(1) + expect(beforeLoad).toHaveBeenCalledTimes(2) }) test('exec if rejected preload (notFound)', async () => { @@ -278,9 +277,9 @@ describe('beforeLoad skip or exec', () => { await Promise.resolve() await router.navigate({ to: '/foo' }) - expect(router.state.location.pathname).toBe('/bar') + expect(router.state.location.pathname).toBe('/foo') expect(router.state.matches.at(-1)?.status).toBe('success') - expect(beforeLoad).toHaveBeenCalledTimes(1) + expect(beforeLoad).toHaveBeenCalledTimes(2) }) test('exec if rejected preload (error)', async () => { @@ -458,7 +457,7 @@ describe('loader skip or exec', () => { expect(loader).toHaveBeenCalledTimes(2) }) - test('exec if pending preload returns notFound', async () => { + test('shares a pending preload notFound with navigation', async () => { const loader: Loader = vi.fn(async ({ preload }) => { await sleep(100) if (preload) throw notFound() @@ -471,8 +470,12 @@ describe('loader skip or exec', () => { await router.navigate({ to: '/foo' }) expect(router.state.location.pathname).toBe('/foo') - expect(router.state.matches.at(-1)?.status).toBe('success') - expect(loader).toHaveBeenCalledTimes(2) + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: '/foo', + status: 'notFound', + error: { isNotFound: true, routeId: '/foo' }, + }) + expect(loader).toHaveBeenCalledTimes(1) }) test('exec if rejected preload (redirect)', async () => { @@ -524,7 +527,7 @@ describe('loader skip or exec', () => { expect(loader).toHaveBeenCalledTimes(2) }) - test('exec if pending preload errors', async () => { + test('shares a pending preload error with navigation', async () => { const loader: Loader = vi.fn(async ({ preload }) => { await sleep(100) if (preload) throw new Error('error') @@ -537,8 +540,8 @@ describe('loader skip or exec', () => { await router.navigate({ to: '/foo' }) expect(router.state.location.pathname).toBe('/foo') - expect(router.state.matches.at(-1)?.status).toBe('success') - expect(loader).toHaveBeenCalledTimes(2) + expect(router.state.matches.at(-1)?.status).toBe('error') + expect(loader).toHaveBeenCalledTimes(1) }) }) diff --git a/packages/router-core/tests/loader-architecture-regressions.test.ts b/packages/router-core/tests/loader-architecture-regressions.test.ts index 1efc42cc73..823b760311 100644 --- a/packages/router-core/tests/loader-architecture-regressions.test.ts +++ b/packages/router-core/tests/loader-architecture-regressions.test.ts @@ -279,37 +279,6 @@ test('invalidation reruns the loader with same-id route context', async () => { }) }) -test('a preload cannot abort its controller after navigation adopts its lane', async () => { - const suspended = createControlledPromise() - let adoptedSignal: AbortSignal | undefined - const rootRoute = new BaseRootRoute({}) - const indexRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/', - }) - const guardedRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/guarded', - beforeLoad: ({ abortController }) => { - adoptedSignal = abortController.signal - throw suspended - }, - }) - const router = createTestRouter({ - routeTree: rootRoute.addChildren([indexRoute, guardedRoute]), - history: createMemoryHistory({ initialEntries: ['/'] }), - }) - - await router.load() - const preload = router.preloadRoute({ to: '/guarded' }) - const navigation = router.navigate({ to: '/guarded' }) - - await preload - expect(adoptedSignal?.aborted).toBe(false) - - await navigation -}) - test('a fast background candidate remains private when a reentrant navigation wins', async () => { let parentLoads = 0 let childLoads = 0 @@ -387,6 +356,464 @@ test('a fast background candidate remains private when a reentrant navigation wi expect(replacementSignal?.aborted).toBe(true) }) +test('a successor reload does not join a settled background candidate awaiting render acknowledgement', async () => { + let generation = 0 + const signals: Array = [] + const rootRoute = new BaseRootRoute({}) + const route = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + validateSearch: (search: Record) => ({ + reload: Number(search.reload ?? 0), + }), + shouldReload: ({ location }) => { + return (location.search as { reload: number }).reload > 0 + }, + loader: ({ abortController }) => { + signals.push(abortController.signal) + return ++generation + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([route]), + history: createMemoryHistory({ initialEntries: ['/page?reload=0'] }), + }) + + await router.load() + + let transitionCount = 0 + let acknowledgeFirst!: () => void + router.startTransition = (commit) => { + commit() + transitionCount++ + if (transitionCount === 1) { + return new Promise((resolve) => { + acknowledgeFirst = () => resolve(false) + }) + } + return Promise.resolve(true) + } + + const first = router.navigate({ + to: '/page', + search: { reload: 1 }, + }) + await vi.waitFor(() => { + expect(generation).toBe(2) + expect(transitionCount).toBe(1) + }) + + await router.navigate({ + to: '/page', + search: { reload: 2 }, + }) + + await vi.waitFor(() => { + expect(generation).toBe(3) + expect(router.state.matches.at(-1)?.loaderData).toBe(3) + }) + + acknowledgeFirst() + await first + + expect(signals[1]?.aborted).toBe(true) + expect(signals[2]?.aborted).toBe(false) +}) + +test('a superseding navigation adopts a pending background loader before async beforeLoad', async () => { + const backgroundResult = createControlledPromise() + const beforeLoadStarted = createControlledPromise() + const beforeLoadGate = createControlledPromise() + const signals: Array = [] + let generation = 0 + + const rootRoute = new BaseRootRoute({}) + const route = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + validateSearch: (search: Record) => ({ + reload: Number(search.reload ?? 0), + }), + shouldReload: ({ location }) => { + return (location.search as { reload: number }).reload === 1 + ? true + : undefined + }, + beforeLoad: async ({ search }) => { + if (search.reload === 2) { + beforeLoadStarted.resolve() + await beforeLoadGate + } + }, + loader: { + staleReloadMode: 'background', + handler: ({ abortController }) => { + signals.push(abortController.signal) + generation++ + return generation === 2 ? backgroundResult : generation + }, + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([route]), + history: createMemoryHistory({ initialEntries: ['/page?reload=0'] }), + }) + + await router.load() + await router.navigate({ + to: '/page', + search: { reload: 1 }, + }) + await vi.waitFor(() => expect(generation).toBe(2)) + + const successor = router.navigate({ + to: '/page', + search: { reload: 2 }, + }) + await beforeLoadStarted + + backgroundResult.resolve(2) + beforeLoadGate.resolve() + await successor + + await vi.waitFor(() => { + expect(router.state.matches.at(-1)?.loaderData).toBe(2) + }) + expect(generation).toBe(2) + expect(signals[1]?.aborted).toBe(false) + expect(router.state.matches.at(-1)?.preload).toBe(false) +}) + +test('rejecting a pending background loader preserves the active loader owner', async () => { + const backgroundResult = createControlledPromise() + const signals: Array = [] + let generation = 0 + + const rootRoute = new BaseRootRoute({}) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + validateSearch: (search: Record) => ({ + reload: Number(search.reload ?? 0), + }), + shouldReload: ({ location }) => { + return (location.search as { reload: number }).reload === 1 + }, + loader: { + staleReloadMode: 'background', + handler: ({ abortController }) => { + signals.push(abortController.signal) + generation++ + return generation === 2 ? backgroundResult : generation + }, + }, + }) + const otherRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/other', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute, otherRoute]), + history: createMemoryHistory({ initialEntries: ['/page?reload=0'] }), + }) + + await router.load() + await router.navigate({ to: '/page', search: { reload: 1 } }) + await vi.waitFor(() => expect(generation).toBe(2)) + + await router.navigate({ to: '/page', search: { reload: 2 } }) + + expect(generation).toBe(2) + expect(signals[0]?.aborted).toBe(false) + expect(signals[1]?.aborted).toBe(true) + expect(router.state.matches.at(-1)?.loaderData).toBe(1) + + await router.navigate({ to: '/other' }) + expect(signals[0]?.aborted).toBe(true) +}) + +test('an ancestor beforeLoad failure releases an unconsumed background claim', async () => { + const backgroundResult = createControlledPromise() + const signals: Array = [] + let generation = 0 + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + validateSearch: (search: Record) => ({ + phase: String(search.phase ?? 'initial'), + }), + beforeLoad: ({ search }) => { + if (search.phase === 'fail') { + throw new Error('parent failed') + } + }, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + shouldReload: ({ location }) => { + return (location.search as { phase: string }).phase === 'refresh' + ? true + : undefined + }, + staleTime: Infinity, + loader: { + staleReloadMode: 'background', + handler: ({ abortController }) => { + signals.push(abortController.signal) + generation++ + return generation === 2 ? backgroundResult : generation + }, + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ + initialEntries: ['/parent/child?phase=initial'], + }), + }) + + await router.load() + await router.navigate({ + to: '/parent/child', + search: { phase: 'refresh' }, + }) + await vi.waitFor(() => expect(generation).toBe(2)) + + await router.navigate({ + to: '/parent/child', + search: { phase: 'fail' }, + }) + + expect( + router.state.matches.find((match) => match.routeId === parentRoute.id), + ).toMatchObject({ status: 'error' }) + expect(signals[1]?.aborted).toBe(true) + + backgroundResult.resolve(2) + await router.navigate({ + to: '/parent/child', + search: { phase: 'recovered' }, + }) + + expect(generation).toBe(2) + expect(router.state.matches.at(-1)?.loaderData).toBe(1) +}) + +test('a background redirect beats a slower ancestor failure promoted over a child failure', async () => { + const parentFailureGate = createControlledPromise() + const middleRedirectGate = createControlledPromise() + const middleStarted = createControlledPromise() + const childFailureStarted = createControlledPromise() + + const rootRoute = new BaseRootRoute({ + validateSearch: (search: Record) => ({ + revision: Number(search.revision ?? 0), + }), + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loaderDeps: ({ search }) => ({ revision: search.revision }), + loader: async ({ location }) => { + if ((location.search as { revision: number }).revision === 1) { + await parentFailureGate + throw new Error('parent failed') + } + return 'parent data' + }, + }) + const middleRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/middle', + shouldReload: ({ location }) => + (location.search as { revision: number }).revision === 1, + loader: { + staleReloadMode: 'background', + handler: async ({ location }) => { + if ((location.search as { revision: number }).revision === 0) { + return 'middle data' + } + middleStarted.resolve() + await middleRedirectGate + throw redirect({ to: '/target' }) + }, + }, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => middleRoute, + path: '/child', + loaderDeps: ({ search }) => ({ revision: search.revision }), + loader: ({ location }) => { + if ((location.search as { revision: number }).revision === 1) { + childFailureStarted.resolve() + throw new Error('child failed') + } + return 'child data' + }, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([middleRoute.addChildren([childRoute])]), + targetRoute, + ]), + history: createMemoryHistory({ + initialEntries: ['/parent/middle/child?revision=0'], + }), + }) + + await router.load() + const navigation = router.navigate({ + to: '/parent/middle/child', + search: { revision: 1 }, + }) + await Promise.all([middleStarted, childFailureStarted]) + + middleRedirectGate.resolve() + parentFailureGate.resolve() + await navigation + + expect(router.state.location.pathname).toBe('/target') +}) + +test('navigation retries a failed preload loader while its error boundary is still loading', async () => { + const boundaryGate = createControlledPromise() + const failure = new Error('preload failed') + const loader = vi.fn(() => { + if (loader.mock.calls.length === 1) { + throw failure + } + return 'navigation data' + }) + const errorComponent = Object.assign(() => null, { + preload: vi.fn(() => boundaryGate), + }) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + loader, + errorComponent, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const preload = router.preloadRoute({ to: '/target' }) + await vi.waitFor(() => { + expect(errorComponent.preload).toHaveBeenCalledOnce() + }) + + const navigation = router.navigate({ to: '/target' }) + await vi.waitFor(() => { + expect(loader).toHaveBeenCalledTimes(2) + }) + + boundaryGate.resolve() + await Promise.all([preload, navigation]) + + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: targetRoute.id, + status: 'success', + loaderData: 'navigation data', + }) +}) + +test('a preload started from onError retries the rejected loader flight', async () => { + const failure = new Error('first preload failed') + const loader = vi.fn(() => { + if (loader.mock.calls.length === 1) { + throw failure + } + return 'retry data' + }) + let retry: ReturnType | undefined + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + loader, + onError: () => { + retry ??= router.preloadRoute({ to: '/target' }) + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.preloadRoute({ to: '/target' }) + const retried = await retry + + expect(loader).toHaveBeenCalledTimes(2) + expect(retried?.at(-1)?.loaderData).toBe('retry data') +}) + +test('a preload started after a returned terminal result gets a fresh loader flight', async () => { + const firstResult = createControlledPromise>() + const loader = vi.fn(() => { + if (loader.mock.calls.length === 1) { + return firstResult + } + return 'retry data' + }) + let retry: ReturnType | undefined + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const preload = router.preloadRoute({ to: '/target' }) + await vi.waitFor(() => expect(loader).toHaveBeenCalledOnce()) + + // A real application can react to the same request promise in a later + // microtask, after the router has normalized its result but before a loader + // lane waiter resumes. + firstResult.then(() => { + queueMicrotask(() => { + retry = router.preloadRoute({ to: '/target' }) + }) + }) + firstResult.resolve(notFound()) + + await preload + await vi.waitFor(() => expect(retry).toBeDefined()) + const retried = await retry + + expect(loader).toHaveBeenCalledTimes(2) + expect(retried?.at(-1)?.loaderData).toBe('retry data') +}) + test('reentrant navigation from onError cancels stale serial work', async () => { const failure = new Error('stale context failed') const parentLoader = vi.fn(() => 'parent data') @@ -437,7 +864,7 @@ test('reentrant navigation from onError cancels stale serial work', async () => expect(parentLoader).not.toHaveBeenCalled() }) -test('a joined descendant loader redirect still wins after an ancestor loader fails', async () => { +test('an unrelated preload redirect does not override a navigation error', async () => { const childStarted = createControlledPromise() const childRedirect = createControlledPromise() const ancestorFailure = new Error('navigation parent failed') @@ -466,6 +893,7 @@ test('a joined descendant loader redirect still wins after an ancestor loader fa const childRoute = new BaseRoute({ getParentRoute: () => parentRoute, path: '/child', + loaderDeps: ({ search }) => ({ mode: search.mode }), loader: async () => { childLoads++ if (childLoads === 1) { @@ -503,12 +931,15 @@ test('a joined descendant loader redirect still wins after an ancestor loader fa childRedirect.resolve() await Promise.all([preload, navigation]) - expect(router.state.location.pathname).toBe('/target') - expect(router.state.matches.at(-1)).toMatchObject({ - routeId: targetRoute.id, - status: 'success', + expect(router.state.location.pathname).toBe('/parent/child') + expect(router.state.location.search).toEqual({ mode: 'navigation' }) + expect( + router.state.matches.find((match) => match.routeId === parentRoute.id), + ).toMatchObject({ + status: 'error', + error: ancestorFailure, }) - expect(childLoads).toBe(1) + expect(childLoads).toBe(2) }) test('a loaderDeps error is handled by the route error boundary', async () => { @@ -906,3 +1337,75 @@ test('an onLeave navigation to the in-flight destination joins it and enters onc expect(firstEnter).toHaveBeenCalledOnce() expect(firstStay).not.toHaveBeenCalled() }) + +test('a delayed legacy notFound preload cannot replace committed cache policy at another match index', async () => { + const preloadBeforeLoadStarted = createControlledPromise() + const releasePreloadBeforeLoad = createControlledPromise() + let generation = 0 + const loader = vi.fn(({ preload }: { preload: boolean }) => ({ + generation: ++generation, + preload, + })) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + }) + const legacyNotFoundRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/404', + staleTime: Infinity, + gcTime: Infinity, + preloadStaleTime: 0, + preloadGcTime: Infinity, + beforeLoad: async ({ preload }) => { + if (preload) { + preloadBeforeLoadStarted.resolve() + await releasePreloadBeforeLoad + } + }, + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, parentRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + notFoundRoute: legacyNotFoundRoute, + }) + + await router.load() + + const delayedPreload = router.preloadRoute({ + to: '/parent/missing', + } as any) + try { + await preloadBeforeLoadStarted + await router.navigate({ to: '/missing' } as any) + + expect(loader).toHaveBeenCalledOnce() + expect(router.state.matches.at(-1)?.loaderData).toEqual({ + generation: 1, + preload: false, + }) + + releasePreloadBeforeLoad.resolve() + await delayedPreload + + expect(loader).toHaveBeenCalledOnce() + + await router.navigate({ to: '/' }) + await router.navigate({ to: '/missing' } as any) + + expect(loader).toHaveBeenCalledOnce() + expect(router.state.matches.at(-1)?.loaderData).toEqual({ + generation: 1, + preload: false, + }) + } finally { + releasePreloadBeforeLoad.resolve() + await Promise.allSettled([delayedPreload]) + } +}) diff --git a/packages/router-core/tests/masked-location-state-commit.test.ts b/packages/router-core/tests/masked-location-state-commit.test.ts index 9738b42261..fae2f275b2 100644 --- a/packages/router-core/tests/masked-location-state-commit.test.ts +++ b/packages/router-core/tests/masked-location-state-commit.test.ts @@ -8,7 +8,7 @@ afterEach(() => { }) describe('masked location remnants in history state', () => { - test('a same-href navigation clears an expired mask from history state', async () => { + test('a same-href navigation clears an expired mask payload from history state', async () => { const makeRoutes = () => { const rootRoute = new BaseRootRoute({}) const indexRoute = new BaseRoute({ diff --git a/packages/router-core/tests/pending-terminal-boundary.test.ts b/packages/router-core/tests/pending-terminal-boundary.test.ts new file mode 100644 index 0000000000..3d7959998d --- /dev/null +++ b/packages/router-core/tests/pending-terminal-boundary.test.ts @@ -0,0 +1,103 @@ +import { expect, test } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { + BaseRootRoute, + BaseRoute, + createControlledPromise, +} from '../src' +import { createTestRouter } from './routerTestUtils' + +test('a known parent error does not offer a descendant pending boundary while its error component loads', async () => { + const failure = new Error('parent failed') + const errorComponentStarted = createControlledPromise() + const errorComponentGate = createControlledPromise() + const childPendingStarted = createControlledPromise() + const childPendingGate = createControlledPromise() + const childComponentGate = createControlledPromise() + + const errorComponent = Object.assign(() => null, { + preload: () => { + errorComponentStarted.resolve() + return errorComponentGate + }, + }) + const childPendingComponent = Object.assign(() => null, { + preload: () => { + childPendingStarted.resolve() + return childPendingGate + }, + }) + const childComponent = Object.assign(() => null, { + preload: () => childComponentGate, + }) + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: () => { + throw failure + }, + errorComponent, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: () => 'child data', + component: childComponent, + pendingComponent: childPendingComponent, + pendingMs: 0, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + + const transitions: Array< + Array<{ routeId: string; status: string; error: unknown }> + > = [] + const startTransition = router.startTransition + router.startTransition = (commit, expected) => { + transitions.push( + expected.map((match) => ({ + routeId: match.routeId, + status: match.status, + error: match.error, + })), + ) + return startTransition(commit, expected) + } + + const navigation = router.navigate({ to: '/parent/child' }) + await Promise.all([errorComponentStarted, childPendingStarted]) + + childPendingGate.resolve() + await new Promise((resolve) => setTimeout(resolve, 0)) + + expect( + transitions.some((matches) => { + const parent = matches.find( + (match) => match.routeId === parentRoute.id, + ) + const child = matches.find((match) => match.routeId === childRoute.id) + return parent?.status === 'success' && child?.status === 'pending' + }), + ).toBe(false) + + errorComponentGate.resolve() + childComponentGate.resolve() + await navigation + + expect( + router.state.matches.find((match) => match.routeId === parentRoute.id), + ).toMatchObject({ status: 'error', error: failure }) +}) diff --git a/packages/router-core/tests/preload-adoption.test.ts b/packages/router-core/tests/preload-adoption.test.ts index 18ec7385d5..dcc7548225 100644 --- a/packages/router-core/tests/preload-adoption.test.ts +++ b/packages/router-core/tests/preload-adoption.test.ts @@ -8,16 +8,65 @@ afterEach(() => { }) /** - * 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 - * adoption boundary: a donor must have its loader genuinely in flight. A - * preload still in its serial phase can itself be waiting on the navigation - * through the borrow protocol, while a stale successful donor can still have - * fresh loader work pending behind its cached snapshot. + * Preload concurrency edge cases. A navigation owns a fresh serial context + * lane while same-ID loader work can still be shared with an active preload. + * Concurrent public preloads own independent context lanes while sharing + * same-ID loader work. */ -describe('preload adoption', () => { +describe('preload concurrency', () => { + test('a superseded preload cannot cache over a newer navigation generation', async () => { + const oldPreload = createControlledPromise() + const newerNavigation = createControlledPromise() + let reload = true + let loaderCalls = 0 + + const rootRoute = new BaseRootRoute({}) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + shouldReload: () => reload, + loader: { + staleReloadMode: 'blocking', + handler: () => { + loaderCalls++ + if (loaderCalls === 1) { + return 'initial' + } + return loaderCalls === 2 ? oldPreload : newerNavigation + }, + }, + }) + const otherRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/other', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([targetRoute, otherRoute]), + history: createMemoryHistory({ initialEntries: ['/target'] }), + }) + + await router.load() + + const preload = router.preloadRoute({ to: '/target' }) + await vi.waitFor(() => expect(loaderCalls).toBe(2)) + + const navigation = router.load() + await vi.waitFor(() => expect(loaderCalls).toBe(3)) + newerNavigation.resolve('newer navigation') + await navigation + + oldPreload.resolve('older preload') + await preload + + reload = false + await router.navigate({ to: '/other' }) + await router.navigate({ to: '/target' }) + + expect(loaderCalls).toBe(3) + expect(router.state.matches.at(-1)?.loaderData).toBe('newer navigation') + }) + test('navigation waits for fresh data from an in-flight stale preload revalidation', async () => { vi.useFakeTimers() vi.setSystemTime(0) @@ -78,17 +127,15 @@ describe('preload adoption', () => { }) await Promise.resolve() - // The navigation may share the revalidation, but it must not treat the - // stale cached snapshot as the completed result while fresh work runs. + // The navigation must share the pending revalidation rather than treating + // the stale cached snapshot as complete or starting a third generation. expect(revalidationGate.status).toBe('pending') expect(navigationSettled).toBe(false) revalidationGate.resolve({ notifications: ['fresh'] }) await Promise.all([revalidation, navigation]) - // A fix may either share the fresh revalidation or run a navigation - // loader of its own; correctness only requires publishing fresh data. - expect(loaderCalls).toBeGreaterThanOrEqual(2) + expect(loaderCalls).toBe(2) expect( router.state.matches.find( (match) => match.routeId === notificationsRoute.id, @@ -96,7 +143,7 @@ describe('preload adoption', () => { ).toEqual({ notifications: ['fresh'] }) }) - test('navigation adopts an identical preload still in its serial phase', async () => { + test('navigation does not wait for a pending preload beforeLoad and shares its loader', async () => { const beforeLoadGate = createControlledPromise() const preloadSerialStarted = createControlledPromise() let beforeLoadCalls = 0 @@ -110,13 +157,14 @@ describe('preload adoption', () => { const fooRoute = new BaseRoute({ getParentRoute: () => rootRoute, path: '/foo', - beforeLoad: async () => { + beforeLoad: async ({ preload }) => { beforeLoadCalls++ if (beforeLoadCalls === 1) { // Keep the shared lane's serial phase in flight. preloadSerialStarted.resolve() await beforeLoadGate } + return { source: preload ? 'preload' : 'navigation' } }, loader, }) @@ -134,20 +182,23 @@ describe('preload adoption', () => { expect(beforeLoadCalls).toBe(1) const navigation = router.navigate({ to: '/foo' }) - await Promise.resolve() - expect(loader).not.toHaveBeenCalled() + await vi.waitFor(() => expect(beforeLoadCalls).toBe(2)) + expect(loader).toHaveBeenCalledTimes(1) beforeLoadGate.resolve() await Promise.all([navigation, preload]) - expect(beforeLoadCalls).toBe(1) + expect(beforeLoadCalls).toBe(2) expect(loader).toHaveBeenCalledTimes(1) expect( - router.state.matches.find((match) => match.routeId === fooRoute.id) - ?.status, - ).toBe('success') + router.state.matches.find((match) => match.routeId === fooRoute.id), + ).toMatchObject({ + status: 'success', + context: { source: 'navigation' }, + loaderData: 'data', + }) }) - test("a sibling preload adopts another preload lane's in-flight loader", async () => { + test('identical preloads rerun beforeLoad while sharing the active loader', async () => { const loaderGate = createControlledPromise() const loaderStarted = createControlledPromise() let preloadBeforeLoadCalls = 0 @@ -185,7 +236,7 @@ describe('preload adoption', () => { const second = router.preloadRoute({ to: '/foo' } as any) await Promise.resolve() - expect(preloadBeforeLoadCalls).toBe(1) + expect(preloadBeforeLoadCalls).toBe(2) expect(loader).toHaveBeenCalledTimes(1) loaderGate.resolve('once') @@ -201,7 +252,7 @@ describe('preload adoption', () => { ).toBe('once') }) - test('a fulfilled undefined loader result is adopted as success', async () => { + test('a fulfilled undefined loader result is shared as success', async () => { const loaderGate = createControlledPromise() const loaderStarted = createControlledPromise() const loader = vi.fn(() => { @@ -246,13 +297,13 @@ describe('preload adoption', () => { expect(match?.loaderData).toBeUndefined() }) - test('navigation retries a failed joined preload without starving sibling work', async () => { + test('navigation shares a pending preload loader failure without starving sibling work', async () => { const preloadParentStarted = createControlledPromise() const preloadFailureGate = createControlledPromise() const navigationStarted = createControlledPromise() - const navigationParentRetryStarted = createControlledPromise() const childStarted = createControlledPromise() const childGate = createControlledPromise() + const sharedFailure = new Error('shared loader failed') let parentLoads = 0 let childLoads = 0 const rootRoute = new BaseRootRoute({}) @@ -268,15 +319,11 @@ describe('preload adoption', () => { navigationStarted.resolve() } }, - loader: async ({ preload }) => { + loader: async () => { parentLoads++ - if (preload) { - preloadParentStarted.resolve() - await preloadFailureGate - throw new Error('preload failed') - } - navigationParentRetryStarted.resolve() - return 'navigation data' + preloadParentStarted.resolve() + await preloadFailureGate + throw sharedFailure }, }) const childRoute = new BaseRoute({ @@ -303,33 +350,27 @@ describe('preload adoption', () => { expect(childLoads).toBe(1) const navigation = router.navigate({ to: '/parent/child' }) - await Promise.resolve() + await navigationStarted expect(preloadFailureGate.status).toBe('pending') expect(parentLoads).toBe(1) expect(childLoads).toBe(1) preloadFailureGate.resolve() // An ordinary ancestor failure waits for every started descendant so a - // later redirect can still win before navigation retries. + // later redirect can still win, while both lanes keep sharing the failed + // parent generation. childGate.resolve('child data') - await navigationStarted - await navigationParentRetryStarted - expect(parentLoads).toBe(2) - expect(childLoads).toBe(1) - await Promise.all([navigation, preload]) - expect(parentLoads).toBe(2) + expect(parentLoads).toBe(1) expect(childLoads).toBe(1) expect(router.state.location.pathname).toBe('/parent/child') expect( router.state.matches.find((match) => match.routeId === parentRoute.id) - ?.loaderData, - ).toBe('navigation data') + ).toMatchObject({ status: 'error', error: sharedFailure }) expect( router.state.matches.find((match) => match.routeId === childRoute.id) - ?.loaderData, - ).toBe('child data') + ).toMatchObject({ status: 'success', loaderData: 'child data' }) }) test('a route with preload disabled does not discard its preloaded ancestor', async () => { diff --git a/packages/router-core/tests/preload-beforeload-reuse.test.ts b/packages/router-core/tests/preload-beforeload-reuse.test.ts index 84cdb5bfde..b061233fb9 100644 --- a/packages/router-core/tests/preload-beforeload-reuse.test.ts +++ b/packages/router-core/tests/preload-beforeload-reuse.test.ts @@ -90,56 +90,9 @@ describe('preloaded loader reuse with fresh beforeLoad context', () => { }) }) - test('adopts beforeLoad and loader from an identical active preload', async () => { - const loaderGate = createControlledPromise() - const beforeLoad = vi.fn(({ preload }: { preload: boolean }) => ({ - guard: preload ? 'preloaded' : 'loaded', - })) - const loader = vi.fn(() => loaderGate) - const rootRoute = new BaseRootRoute({}) - const indexRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/', - }) - const guardedRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/guarded', - preloadStaleTime: Infinity, - beforeLoad, - loader, - }) - const router = createTestRouter({ - routeTree: rootRoute.addChildren([indexRoute, guardedRoute]), - history: createMemoryHistory({ initialEntries: ['/'] }), - }) - - await router.load() - const preload = router.preloadRoute({ to: '/guarded' }) - await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(1)) - - const navigation = router.navigate({ to: '/guarded' }) - await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledTimes(1)) - expect(beforeLoad.mock.calls.map(([context]) => context.preload)).toEqual([ - true, - ]) - expect(loader).toHaveBeenCalledTimes(1) - - loaderGate.resolve('shared loader data') - await Promise.all([preload, navigation]) - - expect(loader).toHaveBeenCalledTimes(1) - expect(router.state.matches.at(-1)?.context).toEqual({ guard: 'preloaded' }) - expect(router.state.matches.at(-1)?.loaderData).toBe('shared loader data') - }) - - test.each([ - { age: 50, expected: [false, true, false], guard: 'loaded' }, - { age: 100, expected: [false, true, false], guard: 'loaded' }, - ])( - 'reruns completed beforeLoad while retaining navigation-owned loader data at age $age', - async ({ age, expected, guard }) => { - vi.useFakeTimers() - vi.setSystemTime(1_000) + test( + 'reruns completed beforeLoad while retaining navigation-owned loader data', + async () => { const beforeLoad = vi.fn(({ preload }: { preload: boolean }) => ({ guard: preload ? 'preloaded' : 'loaded', })) @@ -152,8 +105,6 @@ describe('preloaded loader reuse with fresh beforeLoad context', () => { const guardedRoute = new BaseRoute({ getParentRoute: () => rootRoute, path: '/guarded', - staleTime: Infinity, - preloadStaleTime: 100, beforeLoad, shouldReload: false, loader, @@ -166,18 +117,16 @@ describe('preloaded loader reuse with fresh beforeLoad context', () => { await router.load() await router.navigate({ to: '/guarded' }) await router.navigate({ to: '/' }) - vi.setSystemTime(5_000) await router.preloadRoute({ to: '/guarded' }) - vi.setSystemTime(5_000 + age) await router.navigate({ to: '/guarded' }) expect(beforeLoad.mock.calls.map(([context]) => context.preload)).toEqual( - expected, + [false, true, false], ) expect(loader.mock.calls.map(([context]) => context.preload)).toEqual([ false, ]) - expect(router.state.matches.at(-1)?.context).toEqual({ guard }) + expect(router.state.matches.at(-1)?.context).toEqual({ guard: 'loaded' }) }, ) @@ -399,14 +348,18 @@ describe('preloaded loader reuse with fresh beforeLoad context', () => { expect(seen).toEqual([true, false]) }) - test('invalidation prevents adoption of context from an active preload', async () => { - const loaderGate = createControlledPromise() + test('invalidation prevents joining an active preload loader generation', async () => { + const preloadLoaderGate = createControlledPromise() let generation = 1 const beforeLoad = vi.fn(({ preload }: { preload: boolean }) => ({ generation, preload, })) - const loader = vi.fn(() => loaderGate) + const loader = vi.fn(({ context }: { context: { generation: number } }) => + context.generation === 1 + ? preloadLoaderGate + : `generation ${context.generation} data`, + ) const rootRoute = new BaseRootRoute({}) const indexRoute = new BaseRoute({ getParentRoute: () => rootRoute, @@ -433,19 +386,20 @@ describe('preloaded loader reuse with fresh beforeLoad context', () => { await router.invalidate() const navigation = router.navigate({ to: '/guarded' }) await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledTimes(2)) - loaderGate.resolve('shared loader data') + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(2)) + preloadLoaderGate.resolve('generation 1 data') await Promise.all([preload, navigation]) expect(beforeLoad.mock.calls.map(([context]) => context.preload)).toEqual([ true, false, ]) - expect(loader).toHaveBeenCalledOnce() + expect(loader).toHaveBeenCalledTimes(2) expect(router.state.matches.at(-1)?.context).toEqual({ generation: 2, preload: false, }) - expect(router.state.matches.at(-1)?.loaderData).toBe('shared loader data') + expect(router.state.matches.at(-1)?.loaderData).toBe('generation 2 data') }) test('preload false does not cache beforeLoad context for navigation', async () => { diff --git a/packages/router-core/tests/preload-navigation-adoption.test.ts b/packages/router-core/tests/preload-navigation-adoption.test.ts index 675a69b037..589ea36496 100644 --- a/packages/router-core/tests/preload-navigation-adoption.test.ts +++ b/packages/router-core/tests/preload-navigation-adoption.test.ts @@ -3,12 +3,11 @@ import { createMemoryHistory } from '@tanstack/history' import { BaseRootRoute, BaseRoute, createControlledPromise } from '../src' import { createTestRouter } from './routerTestUtils' -// A navigation that adopts an in-flight preload's loader run must reuse that -// run: it must not abort the preload's loader signal or rerun the loader. This -// is generic router adoption coverage; issue #4476 is covered separately with -// the React Query observer-unmount sequence from its reproduction. -describe('navigation adopting an in-flight preload', () => { - test('adopted preload loader runs once and its signal is not aborted', async () => { +// Navigation owns its beforeLoad context, but a matching pending loader remains +// shared with speculation. Issue #4476 is covered separately with the React +// Query observer-unmount sequence from its reproduction. +describe('navigation joining an in-flight preload loader', () => { + test('reruns beforeLoad, reuses the loader, and keeps its signal alive', async () => { const loaderGate = createControlledPromise() const loaderStarted = createControlledPromise() const beforeLoad = vi.fn() @@ -50,12 +49,13 @@ describe('navigation adopting an in-flight preload', () => { expect(preloadSignal).toBeDefined() expect(preloadSignal?.aborted).toBe(false) - // The identical navigation adopts the whole active lane, including its - // already-completed beforeLoad context. + // The click is a fresh semantic lane even when its speculative loader is + // already pending. const navigation = router.navigate({ to: '/foo' }) - await Promise.resolve() + await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledTimes(2)) expect(beforeLoad.mock.calls.map(([context]) => context.preload)).toEqual([ true, + false, ]) expect(loaderGate.status).toBe('pending') expect(loader).toHaveBeenCalledTimes(1) @@ -65,18 +65,18 @@ describe('navigation adopting an in-flight preload', () => { loaderGate.resolve('adopted') await Promise.all([navigation, preload]) - // Loader ran exactly once; the adopted run's signal was never aborted. + // Loader ran exactly once; the joined run's signal was never aborted. expect(loader).toHaveBeenCalledTimes(1) expect(preloadSignal?.aborted).toBe(false) - // Navigation committed with the adopted loaderData. + // Navigation committed with the shared loaderData. const committed = router.state.matches.find( (match) => match.routeId === fooRoute.id, ) expect(committed?.status).toBe('success') expect(committed?.loaderData).toBe('adopted') - // Adoption transfers loader-data lifetime ownership to the active match. + // Publication transfers loader-data lifetime ownership to the active match. // The shared request remains alive while rendered, then aborts on unload. await router.navigate({ to: '/' }) expect(preloadSignal?.aborted).toBe(true) @@ -125,12 +125,13 @@ describe('navigation adopting an in-flight preload', () => { ]) expect(loader).toHaveBeenCalledTimes(1) - loaderGate.resolve('shared') + loaderGate.resolve('shared data') await Promise.all([preload, navigation]) expect(router.state.matches.at(-1)?.context).toEqual({ auth: true, authorization: 'true:false', }) + expect(router.state.matches.at(-1)?.loaderData).toBe('shared data') }) test('reruns beforeLoad when user location state changes at the same href', async () => { @@ -176,46 +177,11 @@ describe('navigation adopting an in-flight preload', () => { ]) expect(loader).toHaveBeenCalledTimes(1) - loaderGate.resolve('shared') + loaderGate.resolve('shared data') await Promise.all([preload, navigation]) expect(router.state.matches.at(-1)?.context).toMatchObject({ authorization: 'new:false', }) - }) - - test('reruns beforeLoad when the route tree changes during an active preload', async () => { - const loaderGate = createControlledPromise() - const beforeLoad = vi.fn() - const loader = vi.fn(() => loaderGate) - const createRouteTree = () => { - const rootRoute = new BaseRootRoute({}) - const indexRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/', - }) - const guardedRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/guarded', - beforeLoad, - loader, - }) - return rootRoute.addChildren([indexRoute, guardedRoute]) - } - const router = createTestRouter({ - routeTree: createRouteTree(), - history: createMemoryHistory({ initialEntries: ['/'] }), - }) - - await router.load() - const preload = router.preloadRoute({ to: '/guarded' }) - await vi.waitFor(() => expect(loader).toHaveBeenCalledOnce()) - - router.update({ ...router.options, routeTree: createRouteTree() }) - const navigation = router.navigate({ to: '/guarded' }) - await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledTimes(2)) - - loaderGate.resolve('shared') - await Promise.all([preload, navigation]) - expect(loader).toHaveBeenCalledOnce() + expect(router.state.matches.at(-1)?.loaderData).toBe('shared data') }) }) diff --git a/packages/router-core/tests/preload-public-cache-behavior.test.ts b/packages/router-core/tests/preload-public-cache-behavior.test.ts index 5a7b6b2b98..54acdca68c 100644 --- a/packages/router-core/tests/preload-public-cache-behavior.test.ts +++ b/packages/router-core/tests/preload-public-cache-behavior.test.ts @@ -9,8 +9,8 @@ afterEach(() => { }) // https://github.com/TanStack/router/issues/2980 -// Repeated child preloads must borrow a stale active parent instead of rerunning -// its loader. +// Repeated child preloads must reuse data from the accepted active parent +// generation instead of rerunning its loader. test('#2980: repeated child preloads do not rerun a stale active parent loader', async () => { vi.useFakeTimers() vi.setSystemTime(1_000) @@ -115,7 +115,7 @@ test('fresh navigation data keeps its gc policy when a preload reuses it', async // Public contract: clearCache must remain authoritative even if an older // preload finishes unrelated asset work after the clear. -test('clearCache during an in-flight preload cannot resurrect its borrowed data', async () => { +test('clearCache during an in-flight preload cannot resurrect reused accepted data', async () => { const headGate = createControlledPromise<{ meta: Array<{ title: string }> }>() @@ -321,6 +321,128 @@ test('clearCache detaches every discarded flight before abort listeners reenter' expect(router.state.matches.at(-1)?.loaderData).toBe('generation 2') }) +test('a throwing clearCache filter leaves every preload owned', async () => { + const firstGate = createControlledPromise() + const secondGate = createControlledPromise() + let firstSignal: AbortSignal | undefined + let secondSignal: AbortSignal | undefined + const rootRoute = new BaseRootRoute({}) + const homeRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const firstRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/first', + loader: ({ abortController }) => { + firstSignal = abortController.signal + return firstGate + }, + }) + const secondRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/second', + loader: ({ abortController }) => { + secondSignal = abortController.signal + return secondGate + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([homeRoute, firstRoute, secondRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const firstPreload = router.preloadRoute({ to: '/first' }) + const secondPreload = router.preloadRoute({ to: '/second' }) + await vi.waitFor(() => { + expect(firstSignal).toBeDefined() + expect(secondSignal).toBeDefined() + }) + + const failure = new Error('filter failed') + expect(() => + router.clearCache({ + filter: (match) => { + if (match.routeId === firstRoute.id) { + return true + } + if (match.routeId === secondRoute.id) { + throw failure + } + return false + }, + }), + ).toThrow(failure) + + router.clearCache() + expect(firstSignal?.aborted).toBe(true) + expect(secondSignal?.aborted).toBe(true) + + firstGate.resolve('first') + secondGate.resolve('second') + await Promise.all([firstPreload, secondPreload]) +}) + +test('filtered clearCache preserves a parent flight owned by another preload', async () => { + const parentGate = createControlledPromise() + const parentError = new Error('shared parent failed') + const onError = vi.fn() + const parentLoader = vi.fn(() => parentGate) + const secondLoader = vi.fn(() => 'second') + const thirdLoader = vi.fn(() => 'third') + const rootRoute = new BaseRootRoute({}) + const homeRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: parentLoader, + onError, + }) + const firstRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/first', + }) + const secondRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/second', + loader: secondLoader, + }) + const thirdRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/third', + loader: thirdLoader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + homeRoute, + parentRoute.addChildren([firstRoute, secondRoute, thirdRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const firstPreload = router.preloadRoute({ to: '/parent/first' }) + await vi.waitFor(() => expect(parentLoader).toHaveBeenCalledOnce()) + const secondPreload = router.preloadRoute({ to: '/parent/second' }) + await vi.waitFor(() => expect(secondLoader).toHaveBeenCalledOnce()) + + router.clearCache({ + filter: (match) => match.routeId === firstRoute.id, + }) + const thirdPreload = router.preloadRoute({ to: '/parent/third' }) + await vi.waitFor(() => expect(thirdLoader).toHaveBeenCalledOnce()) + + expect(parentLoader).toHaveBeenCalledOnce() + + parentGate.reject(parentError) + await Promise.all([firstPreload, secondPreload, thirdPreload]) + expect(onError).toHaveBeenCalledExactlyOnceWith(parentError) +}) + test('independent concurrent preloads both populate the cache', async () => { const firstGate = createControlledPromise() const secondGate = createControlledPromise() @@ -367,46 +489,64 @@ test('independent concurrent preloads both populate the cache', async () => { expect(secondLoader).toHaveBeenCalledOnce() }) -// Probe, not a required cancellation policy: invalidating the accepted route -// need not cancel unrelated private preload work, but the public operations -// must both settle and leave navigation usable. -test('invalidate and an unrelated in-flight preload both settle cleanly', async () => { - const loaderGate = createControlledPromise() - const loader = vi.fn(() => loaderGate) - const rootRoute = new BaseRootRoute({}) - const homeRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/', - }) - const targetRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/target', - preloadStaleTime: Infinity, - staleTime: Infinity, - loader, - }) - const router = createTestRouter({ - routeTree: rootRoute.addChildren([homeRoute, targetRoute]), - history: createMemoryHistory({ initialEntries: ['/'] }), - }) +test.each([ + ['unfiltered', undefined, true], + ['filtered affected', 'target', true], + ['filtered unaffected', 'home', false], +] as const)( + '%s invalidation handles an active preload according to its filter scope', + async (_mode, selected, shouldRetire) => { + const oldLoaderGate = createControlledPromise() + const signals: Array = [] + const loader = vi.fn( + ({ abortController }: { abortController: AbortController }) => { + signals.push(abortController.signal) + return loader.mock.calls.length === 1 + ? oldLoaderGate + : 'new-generation' + }, + ) + const rootRoute = new BaseRootRoute({}) + const homeRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + preloadStaleTime: Infinity, + staleTime: Infinity, + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([homeRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) - await router.load() - const preload = router.preloadRoute({ to: '/target' }) - await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(1)) - expect(loaderGate.status).toBe('pending') - await router.invalidate() - expect(loaderGate.status).toBe('pending') - loaderGate.resolve('target data') - await preload + await router.load() + const preload = router.preloadRoute({ to: '/target' }) + await vi.waitFor(() => expect(loader).toHaveBeenCalledOnce()) - await router.navigate({ to: '/target' }) - expect(router.state.location.pathname).toBe('/target') - expect( - router.state.matches.find((match) => match.routeId === targetRoute.id) - ?.loaderData, - ).toBe('target data') - expect(loader).toHaveBeenCalledTimes(1) -}) + await (selected + ? router.invalidate({ + filter: (match) => + match.routeId === + (selected === 'target' ? targetRoute.id : homeRoute.id), + }) + : router.invalidate()) + const retired = signals[0]!.aborted + oldLoaderGate.resolve('old-generation') + await preload + await router.navigate({ to: '/target' }) + + expect(retired).toBe(shouldRetire) + expect(loader).toHaveBeenCalledTimes(shouldRetire ? 2 : 1) + expect(router.state.matches.at(-1)).toMatchObject({ + invalid: false, + loaderData: shouldRetire ? 'new-generation' : 'old-generation', + }) + }, +) // Preload lanes are not cancelled by unrelated navigations: an in-flight // async beforeLoad runs to completion, its loader still executes and seeds diff --git a/packages/router-core/tests/preload-public-signal-lifetime.test.ts b/packages/router-core/tests/preload-public-signal-lifetime.test.ts index b1bc87e65c..c83b6a54be 100644 --- a/packages/router-core/tests/preload-public-signal-lifetime.test.ts +++ b/packages/router-core/tests/preload-public-signal-lifetime.test.ts @@ -4,18 +4,18 @@ import { BaseRootRoute, BaseRoute, createControlledPromise } from '../src' import { createTestRouter } from './routerTestUtils' // Public contract: the AbortSignal supplied to loader code belongs to the -// accepted data generation. Adopting preloaded data keeps it alive; accepting +// accepted data generation. Reusing preloaded data keeps it alive; accepting // replacement data aborts it; unloading aborts the replacement generation. -test('an adopted loader signal lives until public replacement and unload', async () => { +test('a reused preload loader signal lives until public replacement and unload', async () => { const replacementGate = createControlledPromise<{ generation: number }>() let generation = 0 - let adoptedSignal: AbortSignal | undefined + let preloadSignal: AbortSignal | undefined let replacementSignal: AbortSignal | undefined const loader = vi.fn( ({ abortController }: { abortController: AbortController }) => { generation++ if (generation === 1) { - adoptedSignal = abortController.signal + preloadSignal = abortController.signal return { generation } } @@ -46,7 +46,7 @@ test('an adopted loader signal lives until public replacement and unload', async await router.load() await router.preloadRoute({ to: '/reports' }) - expect(adoptedSignal?.aborted).toBe(false) + expect(preloadSignal?.aborted).toBe(false) await router.navigate({ to: '/reports' }) expect(loader).toHaveBeenCalledTimes(1) @@ -54,15 +54,15 @@ test('an adopted loader signal lives until public replacement and unload', async router.state.matches.find((match) => match.routeId === reportsRoute.id) ?.loaderData, ).toEqual({ generation: 1 }) - expect(adoptedSignal?.aborted).toBe(false) + expect(preloadSignal?.aborted).toBe(false) const replacement = router.invalidate({ forcePending: true }) await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(2)) expect(replacementGate.status).toBe('pending') // Until replacement data is accepted, the currently rendered data still - // owns the adopted signal. - expect(adoptedSignal?.aborted).toBe(false) + // owns the preload generation's signal. + expect(preloadSignal?.aborted).toBe(false) expect(replacementSignal?.aborted).toBe(false) replacementGate.resolve({ generation: 2 }) @@ -71,14 +71,14 @@ test('an adopted loader signal lives until public replacement and unload', async router.state.matches.find((match) => match.routeId === reportsRoute.id) ?.loaderData, ).toEqual({ generation: 2 }) - expect(adoptedSignal?.aborted).toBe(true) + expect(preloadSignal?.aborted).toBe(true) expect(replacementSignal?.aborted).toBe(false) await router.navigate({ to: '/' }) expect(replacementSignal?.aborted).toBe(true) }) -test('a superseded preload releases its borrowed loader signal lease', async () => { +test('a superseded preload releases its lease on a reused loader generation', async () => { let parentSignal: AbortSignal | undefined let navigation!: Promise diff --git a/packages/router-core/tests/public-hydration-contract.test.ts b/packages/router-core/tests/public-hydration-contract.test.ts index b721135e2f..6d053b7cb9 100644 --- a/packages/router-core/tests/public-hydration-contract.test.ts +++ b/packages/router-core/tests/public-hydration-contract.test.ts @@ -1,6 +1,6 @@ import { runInNewContext } from 'node:vm' import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' -import { createMemoryHistory } from '@tanstack/history' +import { createBrowserHistory, createMemoryHistory } from '@tanstack/history' import { BaseRootRoute, BaseRoute, @@ -11,11 +11,12 @@ import { hydrate } from '../src/ssr/client' import { attachRouterServerSsrUtils } from '../src/ssr/ssr-server' import { dehydrateSsrMatchId } from '../src/ssr/ssr-match-id' import { createTestRouter } from './routerTestUtils' -import type { AnyRouteMatch, AnyRouter } from '../src' +import type { AnyRouteMatch, AnyRouter, LocationRewrite } from '../src' import type { DehydratedRouter, TsrSsrGlobal } from '../src/ssr/types' import type { ServerManifest } from '../src/manifest' const testManifest: ServerManifest = { routes: {} } +const browserWindow = window async function dehydrateToBootstrap(router: AnyRouter): Promise { attachRouterServerSsrUtils({ router, manifest: testManifest }) @@ -452,7 +453,7 @@ describe('public hydration contracts', () => { childRoute.id, ]) expect(router.state.matches[1]).toMatchObject({ - status: 'error', + status: 'pending', error: serverError, }) @@ -986,6 +987,77 @@ describe('public hydration contracts', () => { expect(router.state.matches.at(-1)?.loaderData).toBe('client new') }) + test('does not hand transported context to a replaced public URL generation', async () => { + vi.spyOn(browserWindow, 'scrollTo').mockImplementation(() => undefined) + browserWindow.history.replaceState({}, '', '/public-a') + const history = createBrowserHistory({ window: browserWindow }) + const rewrite: LocationRewrite = { + input: ({ url }) => { + if (url.pathname === '/public-a' || url.pathname === '/public-b') { + url.pathname = '/internal' + } + return url + }, + output: ({ url }) => url, + } + const beforeLoad = vi.fn(({ location }: { location: any }) => ({ + publicHref: location.publicHref, + })) + const loader = vi.fn( + ({ context: routeContext }: { context: { publicHref: string } }) => + routeContext.publicHref, + ) + const rootRoute = new BaseRootRoute({ beforeLoad }) + const internalRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/internal', + ssr: false, + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([internalRoute]), + history, + rewrite, + isServer: false, + }) + const matches = router.matchRoutes(router.stores.location.get()) + installHydrationPayload(mockWindow, [ + { + i: dehydrateSsrMatchId(matches[0]!.id), + s: 'success', + b: { publicHref: '/public-a' }, + ssr: true, + u: Date.now(), + }, + { + i: dehydrateSsrMatchId(matches[1]!.id), + s: 'pending', + ssr: false, + u: Date.now(), + }, + ]) + + try { + await hydrate(router) + browserWindow.history.replaceState( + browserWindow.history.state, + '', + '/public-b', + ) + + await router.load() + + expect( + beforeLoad.mock.calls.map(([options]) => options.location.publicHref), + ).toEqual(['/public-b']) + expect(loader).toHaveBeenCalledTimes(1) + expect(router.state.matches.at(-1)?.loaderData).toBe('/public-b') + } finally { + history.destroy() + browserWindow.history.replaceState({}, '', '/') + } + }) + test('keeps a hydration handoff when a provider initializes an empty context', async () => { const rootBeforeLoad = vi.fn(() => ({ source: 'client' })) const rootLoader = vi.fn(() => 'client root') @@ -1042,7 +1114,7 @@ describe('public hydration contracts', () => { expect(router.state.matches[1]).toMatchObject({ loaderData: 'server' }) }) - test('does not hand transported context across a router-context generation change', async () => { + test('does not hand transported context across an invalidation', async () => { const rootBeforeLoad = vi.fn(({ context }: { context: any }) => ({ auth: context.auth, })) @@ -1084,7 +1156,7 @@ describe('public hydration contracts', () => { ...router.options, context: { auth: 'client new' }, }) - await router.load() + await router.invalidate() expect(rootBeforeLoad).toHaveBeenCalledTimes(1) expect(pageLoader).toHaveBeenCalledTimes(1) @@ -1178,7 +1250,7 @@ describe('public hydration contracts', () => { expect(router.state.matches.at(-1)).toMatchObject({ routeId: pageRoute.id, - status: 'success', + status: 'pending', error: undefined, loaderData: 'server data', }) @@ -1233,7 +1305,7 @@ describe('public hydration contracts', () => { expect(router.state.location.pathname).toBe('/source') expect(router.state.matches.at(-1)).toMatchObject({ routeId: sourceRoute.id, - status: 'success', + status: 'pending', }) expect(router.state.resolvedLocation).toBeUndefined() @@ -1316,12 +1388,18 @@ describe('public hydration contracts', () => { }) }) - test('turns a hydrated normal-component chunk failure into a route error without rerunning loader data', async () => { + test('turns a hydrated normal-component chunk failure into a route error while retaining verified assets and loader data', async () => { const chunkError = new Error('page component failed to load') const componentPreload = vi.fn(() => Promise.reject(chunkError)) const Page = Object.assign(() => 'Page', { preload: componentPreload }) const loader = vi.fn(() => 'client data') const onError = vi.fn() + const head = vi.fn(({ loaderData }) => ({ + meta: [{ title: `Page: ${loaderData}` }], + })) + const scripts = vi.fn(({ loaderData }) => [ + { children: `window.pageData = ${JSON.stringify(loaderData)}` }, + ]) const rootRoute = new BaseRootRoute({}) const pageRoute = new BaseRoute({ getParentRoute: () => rootRoute, @@ -1330,6 +1408,8 @@ describe('public hydration contracts', () => { errorComponent: () => 'Page error', loader, onError, + head, + scripts, }) const router = createTestRouter({ routeTree: rootRoute.addChildren([pageRoute]), @@ -1352,9 +1432,11 @@ describe('public hydration contracts', () => { expect(router.state.matches.at(-1)).toMatchObject({ routeId: pageRoute.id, - status: 'success', + status: 'pending', error: undefined, loaderData: 'server data', + meta: [{ title: 'Page: server data' }], + scripts: [{ children: 'window.pageData = "server data"' }], }) expect(router.state.resolvedLocation).toBeUndefined() expect(onError).not.toHaveBeenCalled() @@ -1367,12 +1449,63 @@ describe('public hydration contracts', () => { status: 'error', error: chunkError, loaderData: 'server data', + meta: [{ title: 'Page: server data' }], + scripts: [{ children: 'window.pageData = "server data"' }], }) expect(onError).toHaveBeenCalledTimes(1) expect(onError).toHaveBeenCalledWith(chunkError) expect(loader).not.toHaveBeenCalled() }) + test('a context failure does not project assets for the failed hydrated route', async () => { + const contextError = new Error('root context failed') + const rootHead = vi.fn(() => ({ + meta: [{ title: 'Server-only root title' }], + })) + const rootScripts = vi.fn(() => [ + { children: 'window.serverOnlyRoot = true' }, + ]) + const rootRoute = new BaseRootRoute({ + context: () => { + throw contextError + }, + head: rootHead, + scripts: rootScripts, + }) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + component: () => 'Page', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + isServer: false, + }) + const matches = router.matchRoutes(router.stores.location.get()) + installHydrationPayload( + mockWindow, + matches.map((match) => ({ + i: dehydrateSsrMatchId(match.id), + s: 'success' as const, + ssr: true, + u: Date.now(), + })), + ) + + await hydrate(router) + + expect(rootHead).not.toHaveBeenCalled() + expect(rootScripts).not.toHaveBeenCalled() + expect(router.state.matches[0]).toMatchObject({ + routeId: rootRoute.id, + status: 'pending', + }) + expect(router.state.matches[0]).not.toHaveProperty('meta') + expect(router.state.matches[0]).not.toHaveProperty('scripts') + expect(router.state.resolvedLocation).toBeUndefined() + }) + test('retries from the earliest failed hydration chunk regardless of rejection order', async () => { const rootChunkError = new Error('root component failed to load') const childChunkError = new Error('child component failed to load') @@ -1388,10 +1521,9 @@ describe('public hydration contracts', () => { const ChildComponent = Object.assign(() => 'Child', { preload: childComponentPreload, }) - const rootContext = vi.fn(() => ({})) const rootRoute = new BaseRootRoute({ component: RootComponent, - context: rootContext, + context: () => ({}), }) const childRoute = new BaseRoute({ getParentRoute: () => rootRoute, @@ -1422,7 +1554,10 @@ describe('public hydration contracts', () => { rootChunkGate.reject(rootChunkError) await expect(hydration).resolves.toBeUndefined() - expect(rootContext).not.toHaveBeenCalled() + expect(router.state.matches[0]).toMatchObject({ + routeId: rootRoute.id, + status: 'pending', + }) expect(router.state.resolvedLocation).toBeUndefined() }) @@ -1439,10 +1574,9 @@ describe('public hydration contracts', () => { return childChunkGate }, }) - const rootContext = vi.fn(() => ({})) const rootRoute = new BaseRootRoute({ component: RootComponent, - context: rootContext, + context: () => ({}), }) const childRoute = new BaseRoute({ getParentRoute: () => rootRoute, @@ -1479,7 +1613,10 @@ describe('public hydration contracts', () => { await hydration } - expect(rootContext).not.toHaveBeenCalled() + expect(router.state.matches[0]).toMatchObject({ + routeId: rootRoute.id, + status: 'pending', + }) expect(router.state.resolvedLocation).toBeUndefined() }) }) diff --git a/packages/router-core/tests/public-preload-lane-contract.test.ts b/packages/router-core/tests/public-preload-lane-contract.test.ts index 7b13e6a0c9..4c8f7f0b56 100644 --- a/packages/router-core/tests/public-preload-lane-contract.test.ts +++ b/packages/router-core/tests/public-preload-lane-contract.test.ts @@ -13,10 +13,12 @@ afterEach(() => { vi.useRealTimers() }) -describe('public preload lane contracts', () => { - test('completed preload matches retain context without caching beforeLoad context', async () => { +describe('client loading contracts', () => { + test('completed preloads cache loader data without caching beforeLoad context', async () => { let beforeLoadGeneration = 0 - const loader = vi.fn(() => 'loader data') + const loader = vi.fn( + ({ context }: { context: { generation: number } }) => context.generation, + ) const rootRoute = new BaseRootRoute({}) const indexRoute = new BaseRoute({ getParentRoute: () => rootRoute, @@ -49,18 +51,26 @@ describe('public preload lane contracts', () => { generation: 2, }) expect(loader).toHaveBeenCalledTimes(1) + expect(router.state.matches.at(-1)?.loaderData).toBe(1) }) - test('active preloads share only an identical full lane', async () => { - const gates = new Map< - number, - ReturnType> - >() - const beforeLoad = vi.fn(({ search }: { search: { version: number } }) => { - const gate = createControlledPromise() - gates.set(search.version, gate) - return gate + test('navigation owns beforeLoad for equivalent Date search', async () => { + const beforeLoadGate = createControlledPromise() + const beforeLoad = vi.fn(async ({ preload }: { preload: boolean }) => { + await beforeLoadGate + return { source: preload ? 'preload' : 'navigation' } }) + const loader = vi.fn(() => 'loader data') + const parseSearch = (searchStr: string) => { + const day = new URLSearchParams(searchStr).get('day') + return day ? { day: new Date(day) } : {} + } + const stringifySearch = (search: Record) => { + const day = search.day + return day instanceof Date + ? `?day=${encodeURIComponent(day.toISOString())}` + : '' + } const rootRoute = new BaseRootRoute({}) const indexRoute = new BaseRoute({ getParentRoute: () => rootRoute, @@ -70,354 +80,65 @@ describe('public preload lane contracts', () => { getParentRoute: () => rootRoute, path: '/target', validateSearch: (search: Record) => ({ - version: Number(search.version), + day: + search.day instanceof Date + ? search.day + : new Date(String(search.day)), }), beforeLoad, - }) - const router = createTestRouter({ - routeTree: rootRoute.addChildren([indexRoute, targetRoute]), - history: createMemoryHistory({ initialEntries: ['/'] }), - stringifySearch: () => '', - }) - - await router.load() - const first = router.preloadRoute({ - to: '/target', - search: { version: 1 }, - }) - await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledTimes(1)) - const second = router.preloadRoute({ - to: '/target', - search: { version: 2 }, - }) - await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledTimes(2)) - gates.get(2)!.resolve(undefined) - await Promise.all([first, second]) - - const third = router.preloadRoute({ - to: '/target', - search: { version: 3 }, - }) - await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledTimes(3)) - const identical = router.preloadRoute({ - to: '/target', - search: { version: 3 }, - }) - await Promise.resolve() - expect(beforeLoad).toHaveBeenCalledTimes(3) - gates.get(3)!.resolve(undefined) - await Promise.all([third, identical]) - }) - - test('navigation adopts beforeLoad from an identical active preload lane', async () => { - const beforeLoadGate = createControlledPromise() - const beforeLoad = vi.fn(async ({ preload }: { preload: boolean }) => { - await beforeLoadGate - return { source: preload ? 'preload' : 'navigation' } - }) - const loader = vi.fn(() => 'loader data') - const rootRoute = new BaseRootRoute({}) - const indexRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/', - }) - const targetRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/target', - beforeLoad, loader, }) const router = createTestRouter({ routeTree: rootRoute.addChildren([indexRoute, targetRoute]), history: createMemoryHistory({ initialEntries: ['/'] }), + parseSearch, + stringifySearch, }) + const iso = '2026-07-24T10:00:00.000Z' + const options = () => ({ + to: '/target' as const, + search: { day: new Date(iso) }, + }) + const preloadOptions = options() + const navigationOptions = options() + + expect(preloadOptions.search.day).not.toBe(navigationOptions.search.day) await router.load() - const preload = router.preloadRoute({ to: '/target' }) - await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledTimes(1)) + const preload = router.preloadRoute(preloadOptions) + let navigation: ReturnType | undefined - const navigation = router.navigate({ to: '/target' }) - await Promise.resolve() - expect(beforeLoad).toHaveBeenCalledTimes(1) - - beforeLoadGate.resolve() - await Promise.all([preload, navigation]) - - expect(beforeLoad.mock.calls.map(([context]) => context.preload)).toEqual([ - true, - ]) - expect(loader).toHaveBeenCalledTimes(1) - expect(router.state.matches.at(-1)).toMatchObject({ - context: { source: 'preload' }, - loaderData: 'loader data', - }) - }) - - test('a depth-20 navigation does not adopt a depth-0 active preload redirect', async () => { - const redirectGate = createControlledPromise() - const sharedBeforeLoad = vi.fn(async (_context: { preload: boolean }) => { - await redirectGate - throw redirect({ to: '/target' }) - }) - const rootRoute = new BaseRootRoute({}) - const indexRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/', - }) - const hopRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/hop/$hop', - beforeLoad: ({ params }) => { - const hop = Number(params.hop) - if (hop < 19) { - throw redirect({ - to: '/hop/$hop', - params: { hop: String(hop + 1) }, - } as any) - } - throw redirect({ to: '/shared' }) - }, - }) - const sharedRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/shared', - beforeLoad: sharedBeforeLoad, - }) - const targetRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/target', - }) - const router = createTestRouter({ - routeTree: rootRoute.addChildren([ - indexRoute, - hopRoute, - sharedRoute, - targetRoute, - ]), - history: createMemoryHistory({ initialEntries: ['/'] }), - }) - - let preload: Promise | undefined - let navigation: Promise | undefined try { - await router.load() - preload = router.preloadRoute({ to: '/shared' }) - await vi.waitFor(() => expect(sharedBeforeLoad).toHaveBeenCalledOnce()) + await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledOnce()) - navigation = router.navigate({ - to: '/hop/$hop', - params: { hop: '0' }, - } as any) - await vi.waitFor(() => expect(sharedBeforeLoad).toHaveBeenCalledTimes(2)) + navigation = router.navigate(navigationOptions) + await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledTimes(2)) - redirectGate.resolve() + beforeLoadGate.resolve() await Promise.all([preload, navigation]) - expect( - sharedBeforeLoad.mock.calls.map(([context]) => context.preload), - ).toEqual([true, false]) - expect(router.state.location.pathname).toBe('/shared') - expect( - router.state.matches.find((match) => match.status !== 'success'), - ).toMatchObject({ - routeId: rootRoute.id, - status: 'error', - error: expect.objectContaining({ message: 'Too many redirects' }), + expect(beforeLoad.mock.calls.map(([context]) => context.preload)).toEqual( + [true, false], + ) + expect(loader).toHaveBeenCalledOnce() + expect(router.state.location.search).toEqual({ day: new Date(iso) }) + expect(router.state.matches.at(-1)).toMatchObject({ + context: { source: 'navigation' }, + loaderData: 'loader data', }) - expect(router.state.status).toBe('idle') } finally { - redirectGate.resolve() - const activeWork: Array> = [] - if (preload) { - activeWork.push(preload) - } - if (navigation) { - activeWork.push(navigation) - } - await Promise.allSettled(activeWork) + beforeLoadGate.resolve() + await Promise.allSettled([preload, navigation]) } }) - test.each([ - { - difference: 'pathname', - preloadMask: { to: '/mask-a' }, - navigationMask: { to: '/mask-b' }, - preloadPathname: '/mask-a', - navigationPathname: '/mask-b', - preloadUnmaskOnReload: undefined, - navigationUnmaskOnReload: undefined, - preloadSearchSource: undefined, - navigationSearchSource: undefined, - preloadStateSource: undefined, - navigationStateSource: undefined, - }, - { - difference: 'unmaskOnReload', - preloadMask: { to: '/mask-a' }, - navigationMask: { to: '/mask-a', unmaskOnReload: true }, - preloadPathname: '/mask-a', - navigationPathname: '/mask-a', - preloadUnmaskOnReload: undefined, - navigationUnmaskOnReload: true, - preloadSearchSource: undefined, - navigationSearchSource: undefined, - preloadStateSource: undefined, - navigationStateSource: undefined, - }, - { - difference: 'search', - preloadMask: { to: '/mask-a', search: { source: 'preload' } }, - navigationMask: { to: '/mask-a', search: { source: 'navigation' } }, - preloadPathname: '/mask-a', - navigationPathname: '/mask-a', - preloadUnmaskOnReload: undefined, - navigationUnmaskOnReload: undefined, - preloadSearchSource: 'preload', - navigationSearchSource: 'navigation', - preloadStateSource: undefined, - navigationStateSource: undefined, - }, - { - difference: 'state', - preloadMask: { to: '/mask-a', state: { source: 'preload' } }, - navigationMask: { to: '/mask-a', state: { source: 'navigation' } }, - preloadPathname: '/mask-a', - navigationPathname: '/mask-a', - preloadUnmaskOnReload: undefined, - navigationUnmaskOnReload: undefined, - preloadSearchSource: undefined, - navigationSearchSource: undefined, - preloadStateSource: 'preload', - navigationStateSource: 'navigation', - }, - ])( - 'navigation reruns beforeLoad for a different explicit mask $difference on the same destination', - async ({ - preloadMask, - navigationMask, - preloadPathname, - navigationPathname, - preloadUnmaskOnReload, - navigationUnmaskOnReload, - preloadSearchSource, - navigationSearchSource, - preloadStateSource, - navigationStateSource, - }) => { - const beforeLoadGate = createControlledPromise() - const loaderGate = createControlledPromise() - const beforeLoadCalls = vi.fn() - const loader = vi.fn(() => loaderGate) - const rootRoute = new BaseRootRoute({}) - const indexRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/', - }) - const targetRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/target', - beforeLoad: async (context) => { - const maskedLocation = context.location.maskedLocation - beforeLoadCalls({ - preload: context.preload, - pathname: maskedLocation?.pathname, - unmaskOnReload: maskedLocation?.unmaskOnReload, - searchSource: ( - maskedLocation?.search as { source?: string } | undefined - )?.source, - stateSource: ( - maskedLocation?.state as { source?: string } | undefined - )?.source, - }) - if (context.preload) { - await beforeLoadGate - } - return { source: context.preload ? 'preload' : 'navigation' } - }, - loader, - }) - const maskARoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/mask-a', - }) - const maskBRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/mask-b', - }) - const router = createTestRouter({ - routeTree: rootRoute.addChildren([ - indexRoute, - targetRoute, - maskARoute, - maskBRoute, - ]), - ...('search' in preloadMask ? { stringifySearch: () => '' } : {}), - history: createMemoryHistory({ initialEntries: ['/'] }), - }) - - let preload: Promise | undefined - let navigation: Promise | undefined - try { - await router.load() - preload = router.preloadRoute({ - to: '/target', - mask: preloadMask as any, - }) - await vi.waitFor(() => expect(beforeLoadCalls).toHaveBeenCalledTimes(1)) - - beforeLoadGate.resolve() - await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(1)) - - navigation = router.navigate({ - to: '/target', - mask: navigationMask as any, - }) - await vi.waitFor(() => - expect(beforeLoadCalls.mock.calls.map(([call]) => call)).toEqual([ - { - preload: true, - pathname: preloadPathname, - unmaskOnReload: preloadUnmaskOnReload, - searchSource: preloadSearchSource, - stateSource: preloadStateSource, - }, - { - preload: false, - pathname: navigationPathname, - unmaskOnReload: navigationUnmaskOnReload, - searchSource: navigationSearchSource, - stateSource: navigationStateSource, - }, - ]), - ) - - loaderGate.resolve('shared loader data') - await Promise.all([preload, navigation]) - - expect(router.state.matches.at(-1)?.context).toEqual({ - source: 'navigation', - }) - expect(router.history.location.pathname).toBe(navigationPathname) - expect(loader).toHaveBeenCalledTimes(1) - } finally { - beforeLoadGate.resolve() - loaderGate.resolve('shared loader data') - const activeWork: Array> = [] - if (preload) { - activeWork.push(preload) - } - if (navigation) { - activeWork.push(navigation) - } - await Promise.allSettled(activeWork) - } - }, - ) - - test('identical active preloads await the same redirect chain', async () => { + test('identical preloads rerun beforeLoad and share the redirected loader', async () => { const redirectGate = createControlledPromise() const loaderGate = createControlledPromise() + const sourceBeforeLoad = vi.fn(async () => { + await redirectGate + throw redirect({ to: '/target' }) + }) const redirectedLoader = vi.fn(() => loaderGate) const rootRoute = new BaseRootRoute({}) const indexRoute = new BaseRoute({ @@ -427,10 +148,7 @@ describe('public preload lane contracts', () => { const sourceRoute = new BaseRoute({ getParentRoute: () => rootRoute, path: '/source', - beforeLoad: async () => { - await redirectGate - throw redirect({ to: '/target' }) - }, + beforeLoad: sourceBeforeLoad, }) const targetRoute = new BaseRoute({ getParentRoute: () => rootRoute, @@ -445,6 +163,7 @@ describe('public preload lane contracts', () => { await router.load() const first = router.preloadRoute({ to: '/source' }) const second = router.preloadRoute({ to: '/source' }) + await vi.waitFor(() => expect(sourceBeforeLoad).toHaveBeenCalledTimes(2)) let secondSettled = false void second.then(() => { secondSettled = true @@ -459,6 +178,66 @@ describe('public preload lane contracts', () => { expect(secondSettled).toBe(true) }) + test('an unrelated navigation does not stop a preload redirect chain', async () => { + const redirectGate = createControlledPromise() + const navigationGate = createControlledPromise() + const targetGate = createControlledPromise() + const sourceBeforeLoad = vi.fn(async () => { + await redirectGate + throw redirect({ to: '/target' }) + }) + const navigationBeforeLoad = vi.fn(() => navigationGate) + const targetLoader = vi.fn(() => targetGate) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const sourceRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/source', + beforeLoad: sourceBeforeLoad, + }) + const navigationRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/navigation', + beforeLoad: navigationBeforeLoad, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + loader: targetLoader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + sourceRoute, + navigationRoute, + targetRoute, + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const first = router.preloadRoute({ to: '/source' }) + await vi.waitFor(() => expect(sourceBeforeLoad).toHaveBeenCalledOnce()) + + const navigation = router.navigate({ to: '/navigation' }) + await vi.waitFor(() => expect(navigationBeforeLoad).toHaveBeenCalledOnce()) + + expect(sourceBeforeLoad).toHaveBeenCalledOnce() + + redirectGate.resolve() + await vi.waitFor(() => expect(targetLoader).toHaveBeenCalledOnce()) + + targetGate.resolve('target') + const firstResult = await first + expect(firstResult?.at(-1)?.routeId).toBe(targetRoute.id) + + navigationGate.resolve() + await navigation + }) + test.each([ { name: 'route suffix', @@ -488,7 +267,7 @@ describe('public preload lane contracts', () => { search: { view: 'detail' }, }, ])( - 'navigation does not adopt beforeLoad from an active preload with different $name', + 'navigation owns beforeLoad with a different $name than an active preload', async ({ preload: preloadOptions, navigation: navigationOptions, @@ -545,12 +324,56 @@ describe('public preload lane contracts', () => { }, ) - test('a different full navigation lane reruns beforeLoad but reuses active same-id loader work', async () => { + test('equivalent serialized Date loader deps reuse stale-infinite data', async () => { + const loader = vi.fn(({ deps }: { deps: { day: Date } }) => + deps.day.toISOString(), + ) + const rootRoute = new BaseRootRoute({}) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + staleTime: Infinity, + validateSearch: (search: Record) => ({ + day: String(search.day), + layout: search.layout === 'grid' ? 'grid' : 'list', + }), + loaderDeps: ({ search }) => ({ + day: new Date(`${search.day}T00:00:00.000Z`), + }), + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([targetRoute]), + history: createMemoryHistory({ + initialEntries: ['/target?day=2026-07-24&layout=list'], + }), + }) + + await router.load() + await router.navigate({ + to: '/target', + search: { day: '2026-07-24', layout: 'grid' }, + }) + + expect(loader).toHaveBeenCalledTimes(1) + expect(router.state.location.search).toMatchObject({ layout: 'grid' }) + expect(router.state.matches.at(-1)?.loaderData).toBe( + '2026-07-24T00:00:00.000Z', + ) + }) + + test('a sibling navigation reruns beforeLoad but reuses the pending parent loader', async () => { const loaderGate = createControlledPromise() + let loaderSignal: AbortSignal | undefined const beforeLoad = vi.fn(({ preload }: { preload: boolean }) => ({ source: preload ? 'preload' : 'navigation', })) - const loader = vi.fn(() => loaderGate) + const loader = vi.fn( + ({ abortController }: { abortController: AbortController }) => { + loaderSignal = abortController.signal + return loaderGate + }, + ) const rootRoute = new BaseRootRoute({}) const indexRoute = new BaseRoute({ getParentRoute: () => rootRoute, @@ -601,9 +424,13 @@ describe('public preload lane contracts', () => { context: { source: 'navigation' }, loaderData: 'shared parent data', }) + expect(loaderSignal?.aborted).toBe(false) + + await router.navigate({ to: '/' }) + expect(loaderSignal?.aborted).toBe(true) }) - test('reserved preload loader work survives preload completion while navigation beforeLoad is pending', async () => { + test('a sibling navigation reuses parent data that settles while its beforeLoad is pending', async () => { const loaderGate = createControlledPromise() const navigationBeforeLoadGate = createControlledPromise() const beforeLoad = vi.fn(async ({ preload }: { preload: boolean }) => { @@ -647,7 +474,7 @@ describe('public preload lane contracts', () => { const navigation = router.navigate({ to: '/parent/second' }) await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledTimes(2)) - loaderGate.resolve('reserved parent data') + loaderGate.resolve('shared parent data') await preload expect(loader).toHaveBeenCalledTimes(1) @@ -664,12 +491,13 @@ describe('public preload lane contracts', () => { router.state.matches.find((match) => match.routeId === parentRoute.id), ).toMatchObject({ context: { source: 'navigation' }, - loaderData: 'reserved parent data', + loaderData: 'shared parent data', }) }) - test('a background refresh consumes reserved preload work after that preload completes', async () => { - const refreshGate = createControlledPromise() + test('a background shouldReload navigation starts fresh instead of joining a pending preload loader', async () => { + const preloadRefreshGate = createControlledPromise() + const navigationRefreshGate = createControlledPromise() const navigationBeforeLoadGate = createControlledPromise() const beforeLoad = vi.fn( async ({ @@ -685,9 +513,14 @@ describe('public preload lane contracts', () => { return { source: preload ? 'preload' : 'navigation' } }, ) - const loader = vi.fn(() => - loader.mock.calls.length === 1 ? 'initial data' : refreshGate, - ) + const loader = vi.fn(({ preload }: { preload: boolean }) => { + if (preload) { + return preloadRefreshGate + } + return loader.mock.calls.length === 1 + ? 'initial data' + : navigationRefreshGate + }) const rootRoute = new BaseRootRoute({}) const parentRoute = new BaseRoute({ getParentRoute: () => rootRoute, @@ -738,32 +571,45 @@ describe('public preload lane contracts', () => { }) await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledTimes(3)) - refreshGate.resolve('refreshed data') + preloadRefreshGate.resolve('preload refreshed data') await preload expect(loader).toHaveBeenCalledTimes(2) expect(navigationSettled).toBe(false) navigationBeforeLoadGate.resolve() + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(3)) + navigationRefreshGate.resolve('navigation refreshed data') await navigation + await vi.waitFor(() => { + expect( + router.state.matches.find( + (match) => match.routeId === parentRoute.id, + )?.loaderData, + ).toBe('navigation refreshed data') + }) expect(beforeLoad.mock.calls.map(([context]) => context.preload)).toEqual([ false, true, false, ]) - expect(loader).toHaveBeenCalledTimes(2) + expect(loader.mock.calls.map(([context]) => context.preload)).toEqual([ + false, + true, + false, + ]) expect(router.state.matches.at(-1)?.routeId).toBe(secondRoute.id) expect( router.state.matches.find((match) => match.routeId === parentRoute.id), ).toMatchObject({ context: { source: 'navigation' }, - loaderData: 'refreshed data', + loaderData: 'navigation refreshed data', preload: false, isFetching: false, }) }) - test('different same-href preload lanes rerun beforeLoad but share loader work by match id', async () => { + test('a sibling preload reruns beforeLoad but reuses the pending parent loader', async () => { const loaderGate = createControlledPromise() const beforeLoad = vi.fn() const loader = vi.fn(() => loaderGate) @@ -775,9 +621,6 @@ describe('public preload lane contracts', () => { const parentRoute = new BaseRoute({ getParentRoute: () => rootRoute, path: '/parent', - validateSearch: (search: Record) => ({ - version: Number(search.version), - }), beforeLoad, loader, }) @@ -795,67 +638,198 @@ describe('public preload lane contracts', () => { parentRoute.addChildren([firstRoute, secondRoute]), ]), history: createMemoryHistory({ initialEntries: ['/'] }), - stringifySearch: () => '', }) await router.load() - const first = router.preloadRoute({ - to: '/parent/first', - search: { version: 1 }, - }) + const first = router.preloadRoute({ to: '/parent/first' }) await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(1)) - const second = router.preloadRoute({ - to: '/parent/first', - search: { version: 2 }, - }) + const second = router.preloadRoute({ to: '/parent/second' }) await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledTimes(2)) expect(loader).toHaveBeenCalledTimes(1) - loaderGate.resolve('parent data') - await Promise.all([first, second]) + loaderGate.resolve('shared parent data') + const [firstMatches, secondMatches] = await Promise.all([first, second]) expect(beforeLoad).toHaveBeenCalledTimes(2) expect(loader).toHaveBeenCalledTimes(1) + expect( + firstMatches?.find((match) => match.routeId === parentRoute.id) + ?.loaderData, + ).toBe('shared parent data') + expect( + secondMatches?.find((match) => match.routeId === parentRoute.id) + ?.loaderData, + ).toBe('shared parent data') }) - test('completed preloads cache loader data but not beforeLoad context', async () => { - const beforeLoad = vi.fn(({ preload }: { preload: boolean }) => ({ - source: preload ? 'preload' : 'navigation', - })) - const loader = vi.fn( - ({ context }: { context: { source: string } }) => context.source, + test('sibling lanes reuse a pending stale parent refresh', async () => { + const refreshGate = createControlledPromise() + const beforeLoad = vi.fn() + const loader = vi.fn(() => + loader.mock.calls.length === 1 ? 'initial data' : refreshGate, ) const rootRoute = new BaseRootRoute({}) const indexRoute = new BaseRoute({ getParentRoute: () => rootRoute, path: '/', }) - const targetRoute = new BaseRoute({ + const parentRoute = new BaseRoute({ getParentRoute: () => rootRoute, - path: '/target', - staleTime: Infinity, - preloadStaleTime: Infinity, + path: '/parent', + preloadStaleTime: 0, beforeLoad, - loader, + loader: { + handler: loader, + staleReloadMode: 'blocking', + }, + }) + const firstRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/first', + }) + const secondRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/second', + }) + const thirdRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/third', }) const router = createTestRouter({ - routeTree: rootRoute.addChildren([indexRoute, targetRoute]), + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([firstRoute, secondRoute, thirdRoute]), + ]), history: createMemoryHistory({ initialEntries: ['/'] }), }) await router.load() - await router.preloadRoute({ to: '/target' }) - await router.navigate({ to: '/target' }) + await router.preloadRoute({ to: '/parent/first' }) + const refresh = router.preloadRoute({ to: '/parent/second' }) + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(2)) - expect(beforeLoad.mock.calls.map(([context]) => context.preload)).toEqual([ - true, - false, - ]) - expect(loader).toHaveBeenCalledTimes(1) - expect(router.state.matches.at(-1)).toMatchObject({ - context: { source: 'navigation' }, - loaderData: 'preload', + const navigation = router.navigate({ to: '/parent/third' }) + await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledTimes(3)) + expect(loader).toHaveBeenCalledTimes(2) + + refreshGate.resolve('refreshed data') + await Promise.all([refresh, navigation]) + + expect(loader).toHaveBeenCalledTimes(2) + expect( + router.state.matches.find((match) => match.routeId === parentRoute.id) + ?.loaderData, + ).toBe('refreshed data') + }) + + test('a sibling navigation shares a pending parent loader failure', async () => { + const loaderGate = createControlledPromise() + const beforeLoad = vi.fn() + const loader = vi.fn(() => loaderGate) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + beforeLoad, + loader, + }) + const firstRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/first', + }) + const secondRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/second', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([firstRoute, secondRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const preload = router.preloadRoute({ to: '/parent/first' }) + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(1)) + + const navigation = router.navigate({ to: '/parent/second' }) + await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledTimes(2)) + expect(loader).toHaveBeenCalledTimes(1) + + loaderGate.reject(new Error('preload failed')) + await Promise.all([preload, navigation]) + + expect(loader).toHaveBeenCalledTimes(1) + expect( + router.state.matches.find((match) => match.routeId === parentRoute.id), + ).toMatchObject({ + status: 'error', + error: expect.objectContaining({ message: 'preload failed' }), + }) + }) + + test('sibling lanes share one pending parent loader failure', async () => { + const firstLoaderGate = createControlledPromise() + const loader = vi.fn(() => firstLoaderGate) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader, + }) + const firstRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/first', + }) + const secondRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/second', + }) + const thirdRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/third', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([firstRoute, secondRoute, thirdRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const first = router.preloadRoute({ to: '/parent/first' }) + await vi.waitFor(() => expect(loader).toHaveBeenCalledOnce()) + const second = router.preloadRoute({ to: '/parent/second' }) + const third = router.preloadRoute({ to: '/parent/third' }) + await Promise.resolve() + expect(loader).toHaveBeenCalledOnce() + + firstLoaderGate.reject(new Error('first generation failed')) + const [, secondMatches, thirdMatches] = await Promise.all([ + first, + second, + third, + ]) + + expect(loader).toHaveBeenCalledOnce() + for (const matches of [secondMatches, thirdMatches]) { + expect( + matches?.find((match) => match.routeId === parentRoute.id), + ).toMatchObject({ + status: 'error', + error: expect.objectContaining({ message: 'first generation failed' }), + }) + } }) test('completed preloads reuse same-id route context and loader data', async () => { @@ -894,7 +868,7 @@ describe('public preload lane contracts', () => { }) }) - test('navigation retries an adopted preload lane that failed', async () => { + test('navigation succeeds independently of a failed preload beforeLoad', async () => { const preloadGate = createControlledPromise() const beforeLoad = vi.fn(async ({ preload }: { preload: boolean }) => { if (preload) { @@ -941,7 +915,7 @@ describe('public preload lane contracts', () => { }) }) - test('a retry reuses successful loader data from the failed preload lane', async () => { + test('a later retry reuses successful loader data from a failed preload lane', async () => { const childGate = createControlledPromise() const beforeLoad = vi.fn(({ preload }: { preload: boolean }) => ({ source: preload ? 'preload' : 'navigation', @@ -985,10 +959,10 @@ describe('public preload lane contracts', () => { await router.load() const preload = router.preloadRoute({ to: '/parent/child' }) await vi.waitFor(() => expect(childLoader).toHaveBeenCalledTimes(1)) - const navigation = router.navigate({ to: '/parent/child' }) childGate.resolve() - await Promise.all([preload, navigation]) + await preload + await router.navigate({ to: '/parent/child' }) expect(beforeLoad.mock.calls.map(([context]) => context.preload)).toEqual([ true, @@ -1071,11 +1045,15 @@ describe('public preload lane contracts', () => { }) }) - test('a terminal preload started during navigation borrows its loader generation', async () => { - const loaderGate = createControlledPromise() - const loader = vi.fn(() => - loader.mock.calls.length === 1 ? 'initial data' : loaderGate, - ) + test('a terminal preload with shouldReload starts fresh instead of joining a pending navigation loader', async () => { + const navigationLoaderGate = createControlledPromise() + const preloadLoaderGate = createControlledPromise() + const loader = vi.fn(({ preload }: { preload: boolean }) => { + if (loader.mock.calls.length === 1) { + return 'initial data' + } + return preload ? preloadLoaderGate : navigationLoaderGate + }) const rootRoute = new BaseRootRoute({ shouldReload: true, loader, @@ -1102,13 +1080,30 @@ describe('public preload lane contracts', () => { await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(2)) const preload = router.preloadRoute({ to: '/target' }) await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledTimes(2)) + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(3)) - expect(loader).toHaveBeenCalledTimes(2) - loaderGate.resolve('navigation data') - const [, terminal] = await Promise.all([navigation, preload]) + navigationLoaderGate.resolve('navigation data') + await navigation + expect(router.state.matches[0]).toMatchObject({ + routeId: rootRoute.id, + loaderData: 'navigation data', + }) - expect(loader).toHaveBeenCalledTimes(2) + preloadLoaderGate.resolve('preload data') + const terminal = await preload + + expect(loader.mock.calls.map(([context]) => context.preload)).toEqual([ + false, + false, + true, + ]) expect(terminal?.[0]).toMatchObject({ + routeId: rootRoute.id, + _notFound: true, + loaderData: 'preload data', + }) + + expect(router.state.matches[0]).toMatchObject({ routeId: rootRoute.id, _notFound: true, loaderData: 'navigation data', @@ -1195,7 +1190,7 @@ describe('public preload lane contracts', () => { expect(router.state.matches.at(-1)?.loaderData).toBe('loader data 1') }) - test('filtered invalidation invalidates active and cached generations of the selected route', async () => { + test('filtered invalidation invalidates committed and cached generations of the selected route', async () => { const loader = vi.fn(() => `loader data ${loader.mock.calls.length}`) const rootRoute = new BaseRootRoute({}) const targetRoute = new BaseRoute({ @@ -1319,9 +1314,21 @@ describe('public preload lane contracts', () => { }) }) - test('preload false skips speculation but performs a blocking navigation load', async () => { + test('preload false skips only that match while navigation loads it normally', async () => { const loaderGate = createControlledPromise() const loader = vi.fn(() => loaderGate) + const componentPreload = vi.fn(async () => {}) + const pendingComponentPreload = vi.fn(async () => {}) + const component = Object.assign(() => null, { + preload: componentPreload, + }) + const pendingComponent = Object.assign(() => null, { + preload: pendingComponentPreload, + }) + const lazyFn = vi.fn(async () => ({ options: {} }) as any) + const childLoader = vi.fn(() => 'child data') + const childComponentPreload = vi.fn(async () => {}) + const childPendingComponentPreload = vi.fn(async () => {}) const rootRoute = new BaseRootRoute({}) const indexRoute = new BaseRoute({ getParentRoute: () => rootRoute, @@ -1331,34 +1338,394 @@ describe('public preload lane contracts', () => { getParentRoute: () => rootRoute, path: '/target', preload: false, + component, + pendingComponent, loader, + }).lazy(lazyFn) + const childRoute = new BaseRoute({ + getParentRoute: () => targetRoute, + path: '/child', + preloadStaleTime: Infinity, + component: Object.assign(() => null, { + preload: childComponentPreload, + }), + pendingComponent: Object.assign(() => null, { + preload: childPendingComponentPreload, + }), + loader: childLoader, }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + targetRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.preloadRoute({ to: '/target/child' }) + + expect(loader).not.toHaveBeenCalled() + expect(lazyFn).not.toHaveBeenCalled() + expect(componentPreload).not.toHaveBeenCalled() + expect(pendingComponentPreload).not.toHaveBeenCalled() + expect(childLoader).toHaveBeenCalledOnce() + expect(childComponentPreload).toHaveBeenCalledOnce() + expect(childPendingComponentPreload).toHaveBeenCalledOnce() + + let settled = false + const navigation = router.navigate({ to: '/target/child' }).then(() => { + settled = true + }) + await vi.waitFor(() => { + expect(loader).toHaveBeenCalledOnce() + expect(lazyFn).toHaveBeenCalledOnce() + expect(componentPreload).toHaveBeenCalledOnce() + expect(pendingComponentPreload).toHaveBeenCalledOnce() + }) + expect(settled).toBe(false) + + loaderGate.resolve('target data') + await navigation + + expect(router.state.matches.at(-2)).toMatchObject({ + routeId: targetRoute.id, + status: 'success', + loaderData: 'target data', + }) + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: childRoute.id, + loaderData: 'child data', + }) + expect(childLoader).toHaveBeenCalledOnce() + }) + + test('a descendant background redirect beats an ancestor chunk failure', async () => { + const componentGate = createControlledPromise() + const componentStarted = createControlledPromise() + const redirectGate = createControlledPromise() + const redirectStarted = createControlledPromise() + const chunkError = new Error('parent component failed') + let childLoads = 0 + + const ParentComponent = Object.assign(() => null, { + preload: () => { + componentStarted.resolve() + return componentGate + }, + }) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + preload: false, + component: ParentComponent, + errorComponent: () => null, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + shouldReload: true, + loader: { + staleReloadMode: 'background', + handler: async () => { + childLoads++ + if (childLoads === 1) { + return 'preloaded child data' + } + redirectStarted.resolve() + await redirectGate + throw redirect({ to: '/target' }) + }, + }, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + targetRoute, + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.preloadRoute({ to: '/parent/child' }) + expect(componentStarted.status).toBe('pending') + expect(childLoads).toBe(1) + + const navigation = router.navigate({ to: '/parent/child' }) + await Promise.all([componentStarted, redirectStarted]) + redirectGate.resolve() + componentGate.reject(chunkError) + await navigation + + expect(router.state.location.pathname).toBe('/target') + }) + + test('a background redirect beats a descendant notFound targeted to its ancestor', async () => { + const redirectGate = createControlledPromise() + const redirectStarted = createControlledPromise() + const notFoundGate = createControlledPromise() + const notFoundStarted = createControlledPromise() + let middleLoads = 0 + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + notFoundComponent: () => null, + }) + const middleRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/middle', + shouldReload: true, + loader: { + staleReloadMode: 'background', + handler: async () => { + middleLoads++ + if (middleLoads === 1) { + return 'preloaded middle data' + } + redirectStarted.resolve() + await redirectGate + throw redirect({ to: '/target' }) + }, + }, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => middleRoute, + path: '/child', + preload: false, + loader: async () => { + notFoundStarted.resolve() + await notFoundGate + throw notFound({ routeId: parentRoute.id as never }) + }, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([ + middleRoute.addChildren([childRoute]), + ]), + targetRoute, + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.preloadRoute({ to: '/parent/middle/child' }) + expect(middleLoads).toBe(1) + expect(notFoundStarted.status).toBe('pending') + + const navigation = router.navigate({ to: '/parent/middle/child' }) + await Promise.all([redirectStarted, notFoundStarted]) + redirectGate.resolve() + notFoundGate.resolve() + await navigation + + expect(router.state.location.pathname).toBe('/target') + }) + + test('preload false skips a serial error boundary chunk until navigation', async () => { + const error = new Error('target failed') + const context = vi.fn(() => ({ targetContext: true })) + const beforeLoad = vi.fn(() => { + throw error + }) + const lazyFn = vi.fn(async () => ({ options: {} }) as any) + const errorComponentPreload = vi.fn(async () => {}) + const errorComponent = Object.assign(() => null, { + preload: errorComponentPreload, + }) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + preload: false, + context, + beforeLoad, + errorComponent, + }).lazy(lazyFn) const router = createTestRouter({ routeTree: rootRoute.addChildren([indexRoute, targetRoute]), history: createMemoryHistory({ initialEntries: ['/'] }), }) await router.load() - await router.preloadRoute({ to: '/target' }) - expect(loader).not.toHaveBeenCalled() + const preloaded = await router.preloadRoute({ to: '/target' }) - let settled = false - const navigation = router.navigate({ to: '/target' }).then(() => { - settled = true + expect(context).toHaveBeenCalledOnce() + expect(beforeLoad).toHaveBeenCalledOnce() + expect(lazyFn).not.toHaveBeenCalled() + expect(errorComponentPreload).not.toHaveBeenCalled() + expect(preloaded?.at(-1)).toMatchObject({ + routeId: targetRoute.id, + status: 'error', + error, }) - await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(1)) - expect(settled).toBe(false) - loaderGate.resolve('target data') - await navigation + await router.navigate({ to: '/target' }) + expect(context).toHaveBeenCalledTimes(2) + expect(beforeLoad).toHaveBeenCalledTimes(2) + expect(lazyFn).toHaveBeenCalledOnce() + expect(errorComponentPreload).toHaveBeenCalledOnce() expect(router.state.matches.at(-1)).toMatchObject({ routeId: targetRoute.id, - status: 'success', - loaderData: 'target data', + status: 'error', + error, }) }) + test('preload false skips its serial not-found boundary chunks', async () => { + const context = vi.fn(() => ({ targetContext: true })) + const lazyFn = vi.fn(async () => ({ options: {} }) as any) + const notFoundComponentPreload = vi.fn(async () => {}) + const notFoundComponent = Object.assign(() => null, { + preload: notFoundComponentPreload, + }) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + preload: false, + context, + beforeLoad: () => { + throw notFound({ routeId: targetRoute.id as never }) + }, + notFoundComponent, + }).lazy(lazyFn) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const preloaded = await router.preloadRoute({ to: '/target' }) + + expect(context).toHaveBeenCalledOnce() + expect(lazyFn).not.toHaveBeenCalled() + expect(notFoundComponentPreload).not.toHaveBeenCalled() + expect(preloaded?.at(-1)).toMatchObject({ + routeId: targetRoute.id, + status: 'notFound', + error: { isNotFound: true }, + }) + + await router.navigate({ to: '/target' }) + + expect(context).toHaveBeenCalledTimes(2) + expect(lazyFn).toHaveBeenCalledOnce() + expect(notFoundComponentPreload).toHaveBeenCalledOnce() + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: targetRoute.id, + status: 'notFound', + error: { isNotFound: true }, + }) + }) + + test('preload false still permits an enabled ancestor not-found boundary', async () => { + const targetLazyFn = vi.fn(async () => ({ options: {} }) as any) + const parentNotFoundPreload = vi.fn(async () => {}) + const ParentNotFound = Object.assign(() => null, { + preload: parentNotFoundPreload, + }) + const parentLazyFn = vi.fn( + async () => ({ options: { notFoundComponent: ParentNotFound } }) as any, + ) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + }).lazy(parentLazyFn) + const targetRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/target', + preload: false, + beforeLoad: () => { + throw notFound() + }, + }).lazy(targetLazyFn) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([targetRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const preloaded = await router.preloadRoute({ to: '/parent/target' }) + + expect(targetLazyFn).not.toHaveBeenCalled() + expect(parentLazyFn).toHaveBeenCalledOnce() + expect(parentNotFoundPreload).toHaveBeenCalledOnce() + expect(preloaded?.[1]).toMatchObject({ + routeId: parentRoute.id, + status: 'notFound', + error: { isNotFound: true }, + }) + }) + + test.each(['errorComponent', 'notFoundComponent'] as const)( + 'retries a failed on-demand %s chunk', + async (componentType) => { + const preload = vi + .fn<() => Promise>() + .mockRejectedValueOnce(new Error('boundary download failed')) + .mockResolvedValue(undefined) + const boundary = Object.assign(() => null, { preload }) + const rootRoute = new BaseRootRoute({}) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + [componentType]: boundary, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([targetRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await expect( + router.loadRouteChunk(targetRoute, componentType), + ).rejects.toThrow('boundary download failed') + await expect( + router.loadRouteChunk(targetRoute, componentType), + ).resolves.toBeUndefined() + + expect(preload).toHaveBeenCalledTimes(2) + }, + ) + test('preloads the target of a twenty-hop redirect chain', async () => { const beforeLoad = vi.fn(({ params }) => { const hop = Number(params.hop) @@ -1429,7 +1796,7 @@ describe('public preload lane contracts', () => { }) }) - test('forwards a document redirect at the redirect limit', async () => { + test('returns no preload matches for a document redirect at the limit', async () => { const beforeLoad = vi.fn(({ params }) => { const hop = Number(params.hop) throw redirect({ diff --git a/packages/router-core/tests/ssr-server-cleanup.test.ts b/packages/router-core/tests/ssr-server-cleanup.test.ts index d137fb3ae4..06e11c8119 100644 --- a/packages/router-core/tests/ssr-server-cleanup.test.ts +++ b/packages/router-core/tests/ssr-server-cleanup.test.ts @@ -1,10 +1,13 @@ import { createMemoryHistory } from '@tanstack/history' -import { afterEach, describe, expect, test, vi } from 'vitest' +import { afterEach, describe, expect, expectTypeOf, test, vi } from 'vitest' import { BaseRootRoute, BaseRoute } from '../src' import { createRequestHandler } from '../src/ssr/createRequestHandler' import { bindSsrResponseToRequest, createSsrStreamResponse, + replaceSsrResponse, + stripSsrResponseBody, + type SsrResponse, } from '../src/ssr/handlerCallback' import { attachRouterServerSsrUtils } from '../src/ssr/ssr-server' import { transformStreamWithRouter } from '../src/ssr/transformStreamWithRouter' @@ -391,10 +394,8 @@ describe('serverSsr.cleanup', () => { expect(router.serverSsr).toBeUndefined() renderResult.resolve(lateStreamResponse) - await Promise.resolve() - await Promise.resolve() + await vi.waitFor(() => expect(cancelCalls).toBe(1)) expect(cleanupCalls).toBe(1) - expect(cancelCalls).toBe(1) expect(router.serverSsr).toBeUndefined() }) @@ -479,11 +480,12 @@ describe('serverSsr.cleanup', () => { }, ) - test('request abort disposes a stream after response handoff', async () => { + test('request abort cancels a locked tagged stream after response handoff', async () => { const router = buildRouter() const requestController = new AbortController() + const cancellation = new Error('request disconnected') let cleanupCalls = 0 - let cancelCalls = 0 + const cancel = vi.fn(() => new Promise(() => {})) const handler = createRequestHandler({ createRouter: () => router, request: new Request('http://localhost/', { @@ -502,25 +504,223 @@ describe('serverSsr.cleanup', () => { requestRouter, new Response( new ReadableStream({ - cancel() { - cancelCalls++ - return new Promise(() => {}) - }, + cancel, }), ), ) }) - expect(response.body).not.toBeNull() + const reader = response.body!.getReader() + const read = expect(reader.read()).rejects.toBe(cancellation) expect(cleanupCalls).toBe(0) - requestController.abort(new Error('request disconnected')) - await Promise.resolve() + requestController.abort(cancellation) - expect(cleanupCalls).toBe(1) - expect(cancelCalls).toBe(1) - expect(router.serverSsr).toBeUndefined() + try { + await vi.waitFor(() => { + expect(cancel).toHaveBeenCalledWith(cancellation) + }) + await read + expect(cleanupCalls).toBe(1) + expect(router.serverSsr).toBeUndefined() + } finally { + reader.releaseLock() + } }) + test('request abort cancels a pre-enqueued plain stream after response handoff', async () => { + const router = buildRouter() + const requestController = new AbortController() + const cancellation = new Error('request disconnected') + const cancel = vi.fn() + const consoleError = vi + .spyOn(console, 'error') + .mockImplementation(() => undefined) + const handler = createRequestHandler({ + createRouter: () => router, + request: new Request('http://localhost/', { + signal: requestController.signal, + }), + }) + + const response = await handler(() => + Promise.resolve( + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array([1])) + }, + cancel, + }), + ), + ), + ) + const reader = response.body!.getReader() + requestController.abort(cancellation) + + try { + await vi.waitFor(() => { + expect(cancel).toHaveBeenCalledWith(cancellation) + }) + await expect(reader.read()).rejects.toBe(cancellation) + expect(consoleError).not.toHaveBeenCalled() + } finally { + reader.releaseLock() + consoleError.mockRestore() + } + }) + + test.each(['replace', 'strip'] as const)( + '%s remains Promise-returning without awaiting body cancellation', + async (operation) => { + const router = buildRouter() + attachRouterServerSsrUtils({ router, manifest: undefined }) + const cancel = vi.fn(() => new Promise(() => {})) + const result = createSsrStreamResponse( + router, + new Response(new ReadableStream({ cancel })), + ) + + const replacementPromise = + operation === 'replace' + ? replaceSsrResponse(result, new Response('replacement'), 'replaced') + : stripSsrResponseBody(result, 'stripped') + + expectTypeOf(replacementPromise).toEqualTypeOf>() + expect(replacementPromise).toBeInstanceOf(Promise) + const replacement = await replacementPromise + expect(replacement.serverSsrCleanup).toBe('none') + expect(router.serverSsr).toBeUndefined() + await vi.waitFor(() => expect(cancel).toHaveBeenCalledOnce()) + }, + ) + + test('stream response disposal remains Promise-returning', async () => { + const router = buildRouter() + attachRouterServerSsrUtils({ router, manifest: undefined }) + const result = createSsrStreamResponse( + router, + new Response(new ReadableStream()), + ) + + if (result.serverSsrCleanup !== 'stream') { + throw new Error('Expected a stream response') + } + + const disposal = result.dispose() + + expectTypeOf(disposal).toEqualTypeOf>() + expect(disposal).toBeInstanceOf(Promise) + await disposal + }) + + test('response body cancellation awaits upstream cancellation', async () => { + const router = buildRouter() + attachRouterServerSsrUtils({ router, manifest: undefined }) + const cancellation = deferred() + const cancel = vi.fn(() => cancellation.promise) + const result = createSsrStreamResponse( + router, + new Response(new ReadableStream({ cancel })), + ) + + const cancelled = result.response.body!.cancel('consumer cancelled') + expect(cancel).toHaveBeenCalledWith('consumer cancelled') + let settled = false + void cancelled.then(() => { + settled = true + }) + await Promise.resolve() + expect(settled).toBe(false) + + cancellation.resolve() + await cancelled + }) + + test('an SSR source error propagates and cleans router state', async () => { + const router = buildRouter() + attachRouterServerSsrUtils({ router, manifest: undefined }) + const cleanup = router.serverSsr!.cleanup + const cleanupSpy = vi.fn(() => cleanup()) + router.serverSsr!.cleanup = cleanupSpy + let source!: ReadableStreamDefaultController + const failure = new Error('renderer stream failed') + const result = createSsrStreamResponse( + router, + new Response( + new ReadableStream({ + start(controller) { + source = controller + }, + }), + ), + ) + const reader = result.response.body!.getReader() + const read = reader.read() + + source.error(failure) + + try { + await expect(read).rejects.toBe(failure) + expect(cleanupSpy).toHaveBeenCalledOnce() + expect(router.serverSsr).toBeUndefined() + } finally { + reader.releaseLock() + } + }) + + test.each(['replace', 'strip'] as const)( + '%s awaits custom asynchronous disposal', + async (operation) => { + const disposal = deferred() + const result = { + response: new Response('stream'), + serverSsrCleanup: 'stream' as const, + dispose: vi.fn(() => disposal.promise), + } + const replacementPromise = + operation === 'replace' + ? replaceSsrResponse(result, new Response('replacement'), 'replaced') + : stripSsrResponseBody(result, 'stripped') + + expect(replacementPromise).toBeInstanceOf(Promise) + await Promise.resolve() + expect(result.dispose).toHaveBeenCalledWith( + operation === 'replace' ? 'replaced' : 'stripped', + ) + + let settled = false + void replacementPromise.then(() => { + settled = true + }) + await Promise.resolve() + expect(settled).toBe(false) + + disposal.resolve() + const replacement = await replacementPromise + expect(replacement.serverSsrCleanup).toBe('none') + }, + ) + + test.each(['replace', 'strip'] as const)( + '%s cancels an abandoned plain response body', + async (operation) => { + const cancel = vi.fn() + const result = new Response(new ReadableStream({ cancel })) + + if (operation === 'replace') { + await replaceSsrResponse( + result, + new Response('replacement'), + 'replaced', + ) + } else { + await stripSsrResponseBody(result, 'stripped') + } + + expect(cancel).toHaveBeenCalledOnce() + }, + ) + test.each(['throw', 'reject'] as const)( 'reports a custom stream disposal %s after request abort', async (failureMode) => { @@ -564,6 +764,46 @@ describe('serverSsr.cleanup', () => { }, ) + test('immediately disposes a bodyless custom stream response', async () => { + const dispose = vi.fn(() => Promise.resolve()) + const result = bindSsrResponseToRequest( + undefined, + { + response: new Response(null, { status: 204 }), + serverSsrCleanup: 'stream', + dispose, + }, + new AbortController().signal, + ) + + expect(result).toMatchObject({ serverSsrCleanup: 'none' }) + expect(result.response.status).toBe(204) + await vi.waitFor(() => { + expect(dispose).toHaveBeenCalledWith(undefined) + }) + }) + + test('passes an existing request abort reason to a bodyless custom stream response', async () => { + const dispose = vi.fn(() => Promise.resolve()) + const request = new AbortController() + const reason = new Error('request disconnected') + request.abort(reason) + + bindSsrResponseToRequest( + undefined, + { + response: new Response(null, { status: 204 }), + serverSsrCleanup: 'stream', + dispose, + }, + request.signal, + ) + + await vi.waitFor(() => { + expect(dispose).toHaveBeenCalledWith(reason) + }) + }) + test('request handler defers cleanup for stream response metadata', async () => { const router = buildRouter() let cleanupCalls = 0 diff --git a/packages/solid-router/src/lazyRouteComponent.tsx b/packages/solid-router/src/lazyRouteComponent.tsx index 64bf129337..267548d2ab 100644 --- a/packages/solid-router/src/lazyRouteComponent.tsx +++ b/packages/solid-router/src/lazyRouteComponent.tsx @@ -13,29 +13,34 @@ export function lazyRouteComponent< ): T[TKey] extends (props: infer TProps) => any ? AsyncRouteComponent : never { - let loadPromise: Promise | undefined + let loadPromise: Promise | undefined let comp: T[TKey] | T['default'] let error: any const load = () => { - if (!loadPromise) { - error = undefined - loadPromise = importer() - .then((res) => { - // Keep browser preload behavior unchanged; SSR can reuse the import. - if (!(isServer ?? typeof window === 'undefined')) { - loadPromise = undefined - } - comp = res[exportName ?? 'default'] - return comp - }) - .catch((err) => { - loadPromise = undefined - error = err - }) + if (loadPromise) { + return loadPromise } - return loadPromise + error = undefined + return (loadPromise = importer() + .then((res) => { + // Keep browser preload behavior unchanged; SSR can reuse the import. + if ( + !((isServer as boolean | undefined) ?? typeof window === 'undefined') + ) { + loadPromise = undefined + } + comp = res[exportName ?? 'default'] + }) + .catch((err) => { + loadPromise = undefined + error = err + + if (!isModuleNotFoundError(err)) { + throw err + } + })) } const lazyComp = function Lazy(props: any) { @@ -47,30 +52,18 @@ export function lazyRouteComponent< // If this happens, the old version in the user's browser would have an outdated // URL to the lazy module. // In that case, we want to attempt one window refresh to get the latest. - if (isModuleNotFoundError(error)) { - // We don't want an error thrown from preload in this case, because - // there's nothing we want to do about module not found during preload. - // Record the error, recover the promise with a null return, - // and we will attempt module not found resolution during the render path. - - if ( - error instanceof Error && - typeof window !== 'undefined' && - typeof sessionStorage !== 'undefined' - ) { - // Again, we want to reload one time on module not found error and not enter - // a reload loop if there is some other issue besides an old deploy. - // That's why we store our reload attempt in sessionStorage. - // Use error.message as key because it contains the module path that failed. - const storageKey = `tanstack_router_reload:${error.message}` - if (!sessionStorage.getItem(storageKey)) { - sessionStorage.setItem(storageKey, '1') - window.location.reload() - - // Return empty component while we wait for window to reload - return { - default: () => null, - } + if ( + isModuleNotFoundError(error) && + error instanceof Error && + !((isServer as boolean | undefined) ?? typeof window === 'undefined') && + typeof sessionStorage !== 'undefined' + ) { + const storageKey = `tanstack_router_reload:${error.message}` + if (!sessionStorage.getItem(storageKey)) { + sessionStorage.setItem(storageKey, '1') + window.location.reload() + return { + default: () => null, } } } @@ -80,7 +73,7 @@ export function lazyRouteComponent< } if (!comp) { - const [compResource] = createResource(load, { + const [compResource] = createResource(() => load().then(() => comp), { initialValue: comp, ssrLoadFrom: 'initial', }) diff --git a/packages/solid-router/tests/component-preload-retry.test.tsx b/packages/solid-router/tests/component-preload-retry.test.tsx index 0a26f0af26..2ac1538d51 100644 --- a/packages/solid-router/tests/component-preload-retry.test.tsx +++ b/packages/solid-router/tests/component-preload-retry.test.tsx @@ -2,6 +2,7 @@ import { afterEach, expect, test, vi } from 'vitest' import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library' import { RouterProvider, + createControlledPromise, createMemoryHistory, createRootRoute, createRoute, @@ -15,6 +16,7 @@ afterEach(() => { cleanup() vi.restoreAllMocks() vi.unstubAllGlobals() + sessionStorage.clear() }) test('a successful server component download is reused', async () => { @@ -29,6 +31,21 @@ test('a successful server component download is reused', async () => { expect(importer).toHaveBeenCalledTimes(1) }) +test('concurrent component preloads share the import', async () => { + const componentImport = createControlledPromise<{ + default: () => null + }>() + const importer = vi.fn(() => componentImport) + const Page = lazyRouteComponent(importer) + + const first = Page.preload?.() + expect(Page.preload?.()).toBe(first) + expect(importer).toHaveBeenCalledOnce() + + componentImport.resolve({ default: () => null }) + await first +}) + test('a component loads when rendered before preload', async () => { const importer = vi.fn().mockResolvedValue({ default: () =>
Page content
, @@ -84,3 +101,52 @@ test('a failed component download is retried from the route error UI', async () expect(await screen.findByText('Page content')).toBeInTheDocument() }) + +test('retries a module download from the error UI after reloading once', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + + const failure = new TypeError( + 'Failed to fetch dynamically imported module: /assets/page.js', + ) + sessionStorage.setItem(`tanstack_router_reload:${failure.message}`, '1') + + const PageContent = () =>
Page content
+ const importer = vi + .fn<() => Promise<{ default: typeof PageContent }>>() + .mockRejectedValueOnce(failure) + .mockResolvedValue({ default: PageContent }) + const Page = lazyRouteComponent(importer) + + function RouteError(props: ErrorComponentProps) { + const router = useRouter() + return ( + + ) + } + + const rootRoute = createRootRoute() + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + component: Page, + errorComponent: RouteError, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + render(() => ) + fireEvent.click(await screen.findByRole('button', { name: 'Retry' })) + + expect(await screen.findByText('Page content')).toBeInTheDocument() + expect(importer).toHaveBeenCalledTimes(2) +}) diff --git a/packages/start-client-core/src/client-rpc/frame-decoder.ts b/packages/start-client-core/src/client-rpc/frame-decoder.ts index 9834b10a1b..263739fa13 100644 --- a/packages/start-client-core/src/client-rpc/frame-decoder.ts +++ b/packages/start-client-core/src/client-rpc/frame-decoder.ts @@ -2,11 +2,16 @@ * Client-side frame decoder for multiplexed responses. * * Decodes binary frame protocol and reconstructs: - * - JSON stream (NDJSON lines for seroval) + * - JSON stream (one complete Seroval value per frame) * - Raw streams (binary data as ReadableStream) */ -import { FRAME_HEADER_SIZE, FrameType } from '../constants' +import { + FRAME_HEADER_SIZE, + FrameType, + MAX_FRAMED_STREAMS, + MAX_FRAME_PAYLOAD_SIZE, +} from '../constants' /** Cached TextDecoder for frame decoding */ const textDecoder = new TextDecoder() @@ -14,11 +19,15 @@ const textDecoder = new TextDecoder() /** Shared empty buffer for empty buffer case - avoids allocation */ const EMPTY_BUFFER = new Uint8Array(0) -/** Hardening limits to prevent memory/CPU DoS */ -const MAX_FRAME_PAYLOAD_SIZE = 16 * 1024 * 1024 // 16MiB -const MAX_BUFFERED_BYTES = 32 * 1024 * 1024 // 32MiB -const MAX_STREAMS = 1024 -const MAX_FRAMES = 100_000 // Limit total frames to prevent CPU DoS +const MAX_QUEUED_BYTES = + FRAME_HEADER_SIZE + MAX_FRAME_PAYLOAD_SIZE * 2 + +type RawStreamState = [ + stream: ReadableStream, + controller: ReadableStreamDefaultController, + terminal: boolean | undefined, + queuedBytes: number, +] /** * Result of frame decoding. @@ -26,7 +35,7 @@ const MAX_FRAMES = 100_000 // Limit total frames to prevent CPU DoS export interface FrameDecoderResult { /** Gets or creates a raw stream by ID (for use by deserialize plugin) */ getOrCreateStream: (id: number) => ReadableStream - /** Stream of JSON strings (NDJSON lines) */ + /** Stream of complete JSON strings */ jsonChunks: ReadableStream } @@ -39,167 +48,138 @@ export interface FrameDecoderResult { export function createFrameDecoder( input: ReadableStream, ): FrameDecoderResult { - const streamControllers = new Map< - number, - ReadableStreamDefaultController - >() - const streams = new Map>() - const cancelledStreamIds = new Set() + const reader = input.getReader() + const streams = new Map() - let cancelled = false as boolean - let inputReader: ReadableStreamReader | null = null - let frameCount = 0 + let stopped: [unknown] | undefined + let queuedBytes = 0 - let jsonController!: ReadableStreamDefaultController - const jsonChunks = new ReadableStream({ - start(controller) { - jsonController = controller - }, - cancel() { - cancelled = true - try { - inputReader?.cancel() - } catch { - // Ignore + const updateQueuedBytes = ( + controller: ReadableStreamDefaultController, + previous: number, + ): number => { + const next = MAX_QUEUED_BYTES - controller.desiredSize! + queuedBytes += next - previous + return next + } + + const assertQueueBudget = (): void => { + if (queuedBytes > MAX_QUEUED_BYTES) { + throw new Error( + `Framed response queue exceeded ${MAX_QUEUED_BYTES} bytes`, + ) + } + } + + const errorStream = (state: RawStreamState, error: unknown): void => { + queuedBytes -= state[3] + state[3] = 0 + state[2] = true + state[1].error(error) + } + + const errorActiveStreams = (error: unknown): void => { + for (const state of streams.values()) { + if (!state[2]) { + errorStream(state, error) } + } + } - streamControllers.forEach((ctrl) => { - try { - ctrl.error(new Error('Framed response cancelled')) - } catch { - // Ignore - } - }) - streamControllers.clear() - streams.clear() - cancelledStreamIds.clear() - }, - }) - - /** - * Gets or creates a stream for a given stream ID. - * Called by deserialize plugin when it encounters a RawStream reference. - */ - function getOrCreateStream(id: number): ReadableStream { + function getOrCreateState(id: number): RawStreamState { const existing = streams.get(id) if (existing) { return existing } - // If we already received an END/ERROR for this streamId, returning a fresh stream - // would hang consumers. Return an already-closed stream instead. - if (cancelledStreamIds.has(id)) { - return new ReadableStream({ - start(controller) { - controller.close() - }, - }) - } - - if (streams.size >= MAX_STREAMS) { + if (streams.size >= MAX_FRAMED_STREAMS) { throw new Error( - `Too many raw streams in framed response (max ${MAX_STREAMS})`, + `Too many raw streams in framed response (max ${MAX_FRAMED_STREAMS})`, ) } - const stream = new ReadableStream({ - start(ctrl) { - streamControllers.set(id, ctrl) + const terminal = stopped + // Assigned after stream construction so its callbacks can close over it. + // eslint-disable-next-line prefer-const + let state!: RawStreamState + let controller!: ReadableStreamDefaultController + const stream = new ReadableStream( + { + start(ctrl) { + controller = ctrl + if (terminal) { + ctrl.error(terminal[0]) + } + }, + cancel() { + queuedBytes -= state[3] + state[3] = 0 + state[2] = true + }, + pull() { + state[3] = updateQueuedBytes(controller, state[3]) + if (state[2] && !state[3]) { + controller.close() + } + }, }, - cancel() { - cancelledStreamIds.add(id) - streamControllers.delete(id) - streams.delete(id) + { + highWaterMark: MAX_QUEUED_BYTES, + size(chunk) { + return FRAME_HEADER_SIZE + chunk.byteLength + }, }, - }) - streams.set(id, stream) - return stream + ) + state = [stream, controller, !!terminal, 0] + streams.set(id, state) + return state } - /** - * Ensures stream exists and returns its controller for enqueuing data. - * Used for CHUNK frames where we need to ensure stream is created. - */ - function ensureController( - id: number, - ): ReadableStreamDefaultController | undefined { - getOrCreateStream(id) - return streamControllers.get(id) + function getOrCreateStream(id: number): ReadableStream { + return getOrCreateState(id)[0] } + let jsonController!: ReadableStreamDefaultController + let queuedJSONBytes = 0 + const jsonChunks = new ReadableStream( + { + start(controller) { + jsonController = controller + }, + cancel(reason) { + const error = reason ?? new Error('Framed response cancelled') + stopped = [error] + errorActiveStreams(error) + streams.clear() + return reader.cancel(reason).catch(() => {}) + }, + pull() { + queuedJSONBytes = updateQueuedBytes(jsonController, queuedJSONBytes) + }, + }, + { + highWaterMark: MAX_QUEUED_BYTES, + size(value) { + return FRAME_HEADER_SIZE + value.length * 2 + }, + }, + ) + // Process frames asynchronously ;(async () => { - const reader = input.getReader() - inputReader = reader - const bufferList: Array = [] let totalLength = 0 - - /** - * Reads header bytes from buffer chunks without flattening. - * Returns header data or null if not enough bytes available. - */ - function readHeader(): { - type: number - streamId: number - length: number - } | null { - if (totalLength < FRAME_HEADER_SIZE) return null - - const first = bufferList[0]! - - // Fast path: header fits entirely in first chunk (common case) - if (first.length >= FRAME_HEADER_SIZE) { - const type = first[0]! - const streamId = - ((first[1]! << 24) | - (first[2]! << 16) | - (first[3]! << 8) | - first[4]!) >>> - 0 - const length = - ((first[5]! << 24) | - (first[6]! << 16) | - (first[7]! << 8) | - first[8]!) >>> - 0 - return { type, streamId, length } - } - - // Slow path: header spans multiple chunks - flatten header bytes only - const headerBytes = new Uint8Array(FRAME_HEADER_SIZE) - let offset = 0 - let remaining = FRAME_HEADER_SIZE - for (let i = 0; i < bufferList.length && remaining > 0; i++) { - const chunk = bufferList[i]! - const toCopy = Math.min(chunk.length, remaining) - headerBytes.set(chunk.subarray(0, toCopy), offset) - offset += toCopy - remaining -= toCopy - } - - const type = headerBytes[0]! - const streamId = - ((headerBytes[1]! << 24) | - (headerBytes[2]! << 16) | - (headerBytes[3]! << 8) | - headerBytes[4]!) >>> - 0 - const length = - ((headerBytes[5]! << 24) | - (headerBytes[6]! << 16) | - (headerBytes[7]! << 8) | - headerBytes[8]!) >>> - 0 - - return { type, streamId, length } - } + let pendingType = -1 + let pendingStreamId = 0 + let pendingLength = 0 /** * Flattens buffer list into single Uint8Array and removes from list. */ function extractFlattened(count: number): Uint8Array { - if (count === 0) return EMPTY_BUFFER + if (count === 0) { + return EMPTY_BUFFER + } // Fast path: the requested bytes are fully contained in the first buffered // chunk (the common case — most frames arrive within a single network @@ -207,8 +187,8 @@ export function createFrameDecoder( // copying `count` bytes. The view shares the chunk's backing ArrayBuffer, // which is safe because buffered chunks are never mutated in place after // being read from the network. - const first = bufferList[0] - if (first && first.length >= count) { + const first = bufferList[0]! + if (first.length >= count) { const result = first.subarray(0, count) if (first.length === count) { bufferList.shift() @@ -224,9 +204,8 @@ export function createFrameDecoder( let offset = 0 let remaining = count - while (remaining > 0 && bufferList.length > 0) { - const chunk = bufferList[0] - if (!chunk) break + while (remaining > 0) { + const chunk = bufferList[0]! const toCopy = Math.min(chunk.length, remaining) result.set(chunk.subarray(0, toCopy), offset) @@ -248,110 +227,111 @@ export function createFrameDecoder( // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition while (true) { const { done, value } = await reader.read() - if (cancelled) break - if (done) break - - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - if (!value) continue + if (stopped) { + break + } + if (done) { + break + } // Append incoming chunk to buffer list - if (totalLength + value.length > MAX_BUFFERED_BYTES) { - throw new Error( - `Framed response buffer exceeded ${MAX_BUFFERED_BYTES} bytes`, - ) - } bufferList.push(value) totalLength += value.length // Parse complete frames from buffer // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition while (true) { - const header = readHeader() - if (!header) break // Not enough bytes for header - - const { type, streamId, length } = header - - if ( - type !== FrameType.JSON && - type !== FrameType.CHUNK && - type !== FrameType.END && - type !== FrameType.ERROR - ) { - throw new Error(`Unknown frame type: ${type}`) - } - - // Enforce stream id conventions: JSON uses streamId 0, raw streams use non-zero ids - if (type === FrameType.JSON) { - if (streamId !== 0) { - throw new Error('Invalid JSON frame streamId (expected 0)') + if (pendingType < 0) { + if (totalLength < FRAME_HEADER_SIZE) { + break } - } else { - if (streamId === 0) { - throw new Error('Invalid raw frame streamId (expected non-zero)') + + const header = extractFlattened(FRAME_HEADER_SIZE) + pendingType = header[0]! + pendingStreamId = + ((header[1]! << 24) | + (header[2]! << 16) | + (header[3]! << 8) | + header[4]!) >>> + 0 + pendingLength = + ((header[5]! << 24) | + (header[6]! << 16) | + (header[7]! << 8) | + header[8]!) >>> + 0 + + if (pendingType > FrameType.ERROR) { + throw new Error(`Unknown frame type: ${pendingType}`) + } + + // JSON uses stream ID 0; raw streams use non-zero IDs. + if ( + pendingType === FrameType.JSON + ? pendingStreamId !== 0 + : pendingStreamId === 0 + ) { + throw new Error( + pendingType === FrameType.JSON + ? 'Invalid JSON frame streamId (expected 0)' + : 'Invalid raw frame streamId (expected non-zero)', + ) + } + + if (pendingLength > MAX_FRAME_PAYLOAD_SIZE) { + throw new Error( + `Frame payload too large: ${pendingLength} bytes (max ${MAX_FRAME_PAYLOAD_SIZE})`, + ) } } - if (length > MAX_FRAME_PAYLOAD_SIZE) { - throw new Error( - `Frame payload too large: ${length} bytes (max ${MAX_FRAME_PAYLOAD_SIZE})`, - ) + if (totalLength < pendingLength) { + break } - const frameSize = FRAME_HEADER_SIZE + length - if (totalLength < frameSize) break // Wait for more data - - if (++frameCount > MAX_FRAMES) { - throw new Error( - `Too many frames in framed response (max ${MAX_FRAMES})`, - ) - } - - // Extract and consume header bytes - extractFlattened(FRAME_HEADER_SIZE) - - // Extract payload - const payload = extractFlattened(length) + const type = pendingType + const streamId = pendingStreamId + pendingType = -1 + const payload = extractFlattened(pendingLength) // Process frame by type switch (type) { case FrameType.JSON: { - try { - jsonController.enqueue(textDecoder.decode(payload)) - } catch { - // JSON stream may be cancelled/closed - } + const value = textDecoder.decode(payload) + jsonController.enqueue(value) + queuedJSONBytes = updateQueuedBytes( + jsonController, + queuedJSONBytes, + ) + assertQueueBudget() break } case FrameType.CHUNK: { - const ctrl = ensureController(streamId) - if (ctrl) { - ctrl.enqueue(payload) + const state = getOrCreateState(streamId) + if (!state[2]) { + state[1].enqueue(payload.slice()) + state[3] = updateQueuedBytes(state[1], state[3]) + assertQueueBudget() } break } case FrameType.END: { - const ctrl = ensureController(streamId) - cancelledStreamIds.add(streamId) - if (ctrl) { - try { - ctrl.close() - } catch { - // Already closed + const state = getOrCreateState(streamId) + if (!state[2]) { + state[2] = true + if (!state[3]) { + state[1].close() } - streamControllers.delete(streamId) } break } case FrameType.ERROR: { - const ctrl = ensureController(streamId) - cancelledStreamIds.add(streamId) - if (ctrl) { - const message = textDecoder.decode(payload) - ctrl.error(new Error(message)) - streamControllers.delete(streamId) + const state = getOrCreateState(streamId) + if (!state[2]) { + errorStream(state, new Error(textDecoder.decode(payload))) } break } @@ -359,48 +339,30 @@ export function createFrameDecoder( } } - if (totalLength !== 0) { + if (stopped) { + return + } + + if (pendingType >= 0 || totalLength) { throw new Error('Incomplete frame at end of framed response') } - // Close JSON stream when done - try { - jsonController.close() - } catch { - // JSON stream may be cancelled/closed - } + const missingEnd = new Error( + 'Framed response ended before raw stream END', + ) + stopped = [missingEnd] + errorActiveStreams(missingEnd) - // Close any remaining streams (shouldn't happen in normal operation) - streamControllers.forEach((ctrl) => { - try { - ctrl.close() - } catch { - // Already closed - } - }) - streamControllers.clear() + // Close JSON stream when done + jsonController.close() } catch (error) { + stopped = [error] // Error reading - propagate to all streams - try { - jsonController.error(error) - } catch { - // Already errored/closed - } - streamControllers.forEach((ctrl) => { - try { - ctrl.error(error) - } catch { - // Already errored/closed - } - }) - streamControllers.clear() + jsonController.error(error) + errorActiveStreams(error) + void reader.cancel(error).catch(() => {}) } finally { - try { - reader.releaseLock() - } catch { - // Ignore - } - inputReader = null + reader.releaseLock() } })() diff --git a/packages/start-client-core/src/client-rpc/serverFnFetcher.ts b/packages/start-client-core/src/client-rpc/serverFnFetcher.ts index 2e993205bc..9b7bfbcf86 100644 --- a/packages/start-client-core/src/client-rpc/serverFnFetcher.ts +++ b/packages/start-client-core/src/client-rpc/serverFnFetcher.ts @@ -72,18 +72,6 @@ export function trackPostProcessPromise(promise: Promise): void { } } -/** - * Helper to await all post-processing promises. - * Uses Promise.allSettled to ensure all promises complete even if some reject. - */ -async function awaitPostProcessPromises( - promises: Array>, -): Promise { - if (promises.length > 0) { - await Promise.allSettled(promises) - } -} - /** * Checks if an object has at least one own enumerable property. * More efficient than Object.keys(obj).length > 0 as it short-circuits on first property. @@ -164,7 +152,7 @@ export async function serverFnFetcher( body = fetchBody?.body } - return await getResponse(async () => + return getResponse(async () => fetchImpl(url, { method: first.method, headers, @@ -197,9 +185,7 @@ async function serializePayload( } async function serialize(data: any) { - return JSON.stringify( - await Promise.resolve(toJSONAsync(data, { plugins: serovalPlugins! })), - ) + return JSON.stringify(await toJSONAsync(data, { plugins: serovalPlugins! })) } async function getFetchBody( @@ -268,7 +254,12 @@ async function getResponse(fn: () => Promise) { // If it's a framed response (contains RawStream), use frame decoder if (contentType.includes(TSS_CONTENT_TYPE_FRAMED)) { // Validate protocol version compatibility - validateFramedProtocolVersion(contentType) + try { + validateFramedProtocolVersion(contentType) + } catch (error) { + void response.body?.cancel(error).catch(() => {}) + throw error + } if (!response.body) { throw new Error('No response body for framed response') @@ -281,16 +272,9 @@ async function getResponse(fn: () => Promise) { // Create deserialize plugin that wires up the raw streams const rawStreamPlugin = createRawStreamDeserializePlugin(getOrCreateStream) - const plugins = [rawStreamPlugin, ...(serovalPlugins || [])] + const plugins = [rawStreamPlugin, ...serovalPlugins!] - const refs = new Map() - result = await processFramedResponse({ - jsonStream: jsonChunks, - onMessage: (msg: any) => fromCrossJSON(msg, { refs, plugins }), - onError(msg, error) { - console.error(msg, error) - }, - }) + result = await processFramedResponse(jsonChunks, plugins) } // If it's a JSON response, it can be simpler else if (contentType.includes('application/json')) { @@ -304,7 +288,9 @@ async function getResponse(fn: () => Promise) { setPostProcessContext(null) } // Await any async post-processing before returning - await awaitPostProcessPromises(postProcessPromises) + if (postProcessPromises.length) { + await Promise.allSettled(postProcessPromises) + } } if (!result) { @@ -352,94 +338,77 @@ async function getResponse(fn: () => Promise) { * completes before the next chunk is processed. This prevents issues when * streaming values require async post-processing (e.g., RSC decoding). */ -async function processFramedResponse({ - jsonStream, - onMessage, - onError, -}: { - jsonStream: ReadableStream - onMessage: (msg: any) => any - onError?: (msg: string, error?: any) => void -}) { +async function processFramedResponse( + jsonStream: ReadableStream, + plugins: Array>, +) { const reader = jsonStream.getReader() + const refs = new Map() + const transportFailure = new Promise((_, reject) => { + void reader.closed.catch(reject) + }) + void transportFailure.catch(() => {}) - // Read first JSON frame - this is the main result - const { value: firstValue, done: firstDone } = await reader.read() - if (firstDone || !firstValue) { - throw new Error('Stream ended before first object') + const deserialize = (json: string) => { + const postProcessPromises: Array> = [] + setPostProcessContext(postProcessPromises) + let result + try { + result = fromCrossJSON(JSON.parse(json), { refs, plugins }) + } finally { + setPostProcessContext(null) + } + return postProcessPromises.length + ? Promise.race([ + Promise.allSettled(postProcessPromises), + transportFailure, + ]).then(() => result) + : result } - // Each frame is a complete JSON string - const firstObject = JSON.parse(firstValue) + // Read and deserialize the first frame before starting the detached drain so + // its refs exist before the drain can observe a terminal transport error. + let initial: Promise + try { + const { value, done } = await reader.read() + if (done || !value) { + throw new Error('Stream ended before first object') + } + initial = Promise.resolve(deserialize(value)) + } catch (error) { + reader.cancel(error).catch(() => {}) + reader.releaseLock() + throw error + } // Process remaining frames for streaming refs like RawStream. // Keep draining until the server closes the stream. // Each chunk gets its own post-processing context to properly scope async work. - let drainCancelled = false as boolean const drain = (async () => { try { // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition while (true) { const { value, done } = await reader.read() - if (done) break + if (done) { + break + } if (value) { - try { - // Set up post-processing context for this chunk - const chunkPostProcessPromises: Array> = [] - setPostProcessContext(chunkPostProcessPromises) - try { - onMessage(JSON.parse(value)) - } finally { - setPostProcessContext(null) - } - // Await any async post-processing from this chunk before processing next. - // This ensures values requiring async work are ready before their - // containing Promise/Stream resolves/emits to consumers. - await awaitPostProcessPromises(chunkPostProcessPromises) - } catch (e) { - onError?.(`Invalid JSON: ${value}`, e) - } + await deserialize(value) } } } catch (err) { - if (!drainCancelled) { - onError?.('Stream processing error:', err) - } + reader.cancel(err).catch(() => {}) + throw err + } finally { + reader.releaseLock() } })() - // Process first object with its own post-processing context - let result: any - const initialPostProcessPromises: Array> = [] - setPostProcessContext(initialPostProcessPromises) try { - result = onMessage(firstObject) + await Promise.race([initial, drain]) + return await initial } catch (err) { - setPostProcessContext(null) - drainCancelled = true - reader.cancel().catch(() => {}) + reader.cancel(err).catch(() => {}) throw err } - setPostProcessContext(null) - - // Await initial post-processing promises before returning result - await awaitPostProcessPromises(initialPostProcessPromises) - - // If the initial decode fails async, stop draining to avoid holding - // onto the response body and raw stream buffers unnecessarily. - Promise.resolve(result).catch(() => { - drainCancelled = true - reader.cancel().catch(() => {}) - }) - - // Detach reader once draining completes. - drain.finally(() => { - try { - reader.releaseLock() - } catch { - // Ignore - } - }) - - return result } diff --git a/packages/start-client-core/src/constants.ts b/packages/start-client-core/src/constants.ts index 3df983dfe7..01c71ca96f 100644 --- a/packages/start-client-core/src/constants.ts +++ b/packages/start-client-core/src/constants.ts @@ -15,7 +15,7 @@ export const TSS_CONTENT_TYPE_FRAMED = 'application/x-tss-framed' * Frame types for binary multiplexing protocol. */ export const FrameType = { - /** Seroval JSON chunk (NDJSON line) */ + /** Seroval JSON value */ JSON: 0, /** Raw stream data chunk */ CHUNK: 1, @@ -30,6 +30,12 @@ export type FrameType = (typeof FrameType)[keyof typeof FrameType] /** Header size in bytes: type(1) + streamId(4) + length(4) */ export const FRAME_HEADER_SIZE = 9 +/** Maximum payload size accepted by the framed response decoder (16 MiB). */ +export const MAX_FRAME_PAYLOAD_SIZE = 16 * 1024 * 1024 + +/** Maximum number of raw streams accepted in one framed response. */ +export const MAX_FRAMED_STREAMS = 1024 + /** Current protocol version for framed responses */ export const TSS_FRAMED_PROTOCOL_VERSION = 1 diff --git a/packages/start-client-core/src/index.tsx b/packages/start-client-core/src/index.tsx index 5bf09c4440..6c79b366ab 100644 --- a/packages/start-client-core/src/index.tsx +++ b/packages/start-client-core/src/index.tsx @@ -104,6 +104,8 @@ export { TSS_FRAMED_PROTOCOL_VERSION, FrameType, FRAME_HEADER_SIZE, + MAX_FRAME_PAYLOAD_SIZE, + MAX_FRAMED_STREAMS, X_TSS_SERIALIZED, X_TSS_RAW_RESPONSE, X_TSS_CONTEXT, diff --git a/packages/start-client-core/tests/frame-decoder.test.ts b/packages/start-client-core/tests/frame-decoder.test.ts index 3a05611392..ab9cdbe364 100644 --- a/packages/start-client-core/tests/frame-decoder.test.ts +++ b/packages/start-client-core/tests/frame-decoder.test.ts @@ -1,6 +1,11 @@ -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { createFrameDecoder } from '../src/client-rpc/frame-decoder' -import { FRAME_HEADER_SIZE, FrameType } from '../src/constants' +import { + FRAME_HEADER_SIZE, + MAX_FRAME_PAYLOAD_SIZE, + MAX_FRAMED_STREAMS, + FrameType, +} from '../src/constants' /** * Helper to encode a frame for testing @@ -96,7 +101,7 @@ describe('frame-decoder', () => { const view = new DataView(headerOnly.buffer) view.setUint8(0, FrameType.JSON) view.setUint32(1, 0, false) - view.setUint32(5, 16 * 1024 * 1024 + 1, false) + view.setUint32(5, MAX_FRAME_PAYLOAD_SIZE + 1, false) const input = new ReadableStream({ start(controller) { @@ -131,26 +136,150 @@ describe('frame-decoder', () => { await expect(reader.read()).rejects.toThrow('Incomplete frame') }) - it('should cancel input when jsonChunks cancelled', async () => { - let cancelled = false + it('should error a raw stream that reaches transport EOF without END', async () => { + const chunk = encodeChunkFrame(1, new Uint8Array([1, 2, 3])) + const input = new ReadableStream({ + start(controller) { + controller.enqueue(chunk) + controller.close() + }, + }) + const { getOrCreateStream, jsonChunks } = createFrameDecoder(input) + const rawReader = getOrCreateStream(1).getReader() + + await expect(jsonChunks.getReader().read()).resolves.toEqual({ + done: true, + value: undefined, + }) + await expect(rawReader.read()).rejects.toThrow( + 'ended before raw stream END', + ) + }) + + it('should error an unknown raw stream requested after transport EOF', async () => { + const { getOrCreateStream, jsonChunks } = createFrameDecoder( + new ReadableStream({ + start(controller) { + controller.close() + }, + }), + ) + await jsonChunks.getReader().read() + + const read = getOrCreateStream(1).getReader().read() + const result = await Promise.race([ + read.then( + () => undefined, + (error: unknown) => error, + ), + new Promise<'pending'>((resolve) => { + setTimeout(() => resolve('pending'), 0) + }), + ]) + + expect(result).toBeInstanceOf(Error) + expect((result as Error).message).toContain('ended before raw stream END') + }) + + it('should deliver a raw chunk to an already waiting reader', async () => { + let inputController!: ReadableStreamDefaultController + const input = new ReadableStream({ + start(controller) { + inputController = controller + }, + }) + const { getOrCreateStream } = createFrameDecoder(input) + const reader = getOrCreateStream(1).getReader() + const firstRead = reader.read() + + await new Promise((resolve) => setTimeout(resolve, 0)) + inputController.enqueue(encodeChunkFrame(1, new Uint8Array([1, 2, 3]))) + inputController.enqueue(encodeEndFrame(1)) + inputController.close() + + await expect(firstRead).resolves.toEqual({ + done: false, + value: new Uint8Array([1, 2, 3]), + }) + await expect(reader.read()).resolves.toEqual({ + done: true, + value: undefined, + }) + }) + + it('should preserve a queued empty raw chunk before END', async () => { + const input = new ReadableStream({ + start(controller) { + controller.enqueue(encodeChunkFrame(1, new Uint8Array())) + controller.enqueue(encodeEndFrame(1)) + controller.close() + }, + }) + const { getOrCreateStream, jsonChunks } = createFrameDecoder(input) + + await expect(jsonChunks.getReader().read()).resolves.toEqual({ + done: true, + value: undefined, + }) + const reader = getOrCreateStream(1).getReader() + await expect(reader.read()).resolves.toEqual({ + done: false, + value: new Uint8Array(), + }) + await expect(reader.read()).resolves.toEqual({ + done: true, + value: undefined, + }) + }) + + it('should forward cancellation and swallow input cleanup failures', async () => { + let cancelReason: unknown const input = new ReadableStream({ pull() {}, - cancel() { - cancelled = true + cancel(reason) { + cancelReason = reason + return Promise.reject(new Error('input cleanup failed')) }, }) const { jsonChunks } = createFrameDecoder(input) - const reader = jsonChunks.getReader() + const reason = new Error('consumer cancelled') - await reader.cancel() - expect(cancelled).toBe(true) + await expect(jsonChunks.cancel(reason)).resolves.toBeUndefined() + expect(cancelReason).toBe(reason) + }) + + it('should cancel the input after a protocol error', async () => { + const badFrame = encodeFrame(99, 0, new Uint8Array(0)) + let cancelReason: unknown + const input = new ReadableStream({ + start(controller) { + controller.enqueue(badFrame) + }, + cancel(reason) { + cancelReason = reason + }, + }) + const { jsonChunks } = createFrameDecoder(input) + + const error = await jsonChunks + .getReader() + .read() + .then( + () => undefined, + (cause: unknown) => cause, + ) + + expect(error).toBeInstanceOf(Error) + await vi.waitFor(() => { + expect(cancelReason).toBe(error) + }) }) it('should reject too many raw streams', async () => { // END frames create streams via ensureController, even with no CHUNKs. const frames: Array = [] - for (let i = 1; i <= 1025; i++) { + for (let i = 1; i <= MAX_FRAMED_STREAMS + 1; i++) { frames.push(encodeEndFrame(i)) } @@ -175,21 +304,212 @@ describe('frame-decoder', () => { await expect(reader.read()).rejects.toThrow('Too many raw streams') }) - it('should reject when buffered bytes exceed limit', async () => { - // No valid frame can be parsed from this; we just want to exceed MAX_BUFFERED_BYTES. - const tooLarge = new Uint8Array(32 * 1024 * 1024 + 1) + it('should count cancelled raw stream IDs toward the response limit', async () => { + const { getOrCreateStream, jsonChunks } = createFrameDecoder( + new ReadableStream(), + ) + for (let id = 1; id <= MAX_FRAMED_STREAMS; id++) { + await getOrCreateStream(id).cancel() + } + + expect(() => getOrCreateStream(MAX_FRAMED_STREAMS + 1)).toThrow( + `Too many raw streams in framed response (max ${MAX_FRAMED_STREAMS})`, + ) + await jsonChunks.cancel() + }) + + it('should allow a consumed raw stream to exceed 100,000 frames', async () => { + const frameCount = 100_001 + const frame = encodeChunkFrame(1, new Uint8Array([1])) + const end = encodeEndFrame(1) + const combined = new Uint8Array(frame.length * frameCount + end.length) + for (let index = 0; index < frameCount; index++) { + combined.set(frame, index * frame.length) + } + combined.set(end, frame.length * frameCount) const input = new ReadableStream({ start(controller) { - controller.enqueue(tooLarge) + controller.enqueue(combined) controller.close() }, }) + const { getOrCreateStream, jsonChunks } = createFrameDecoder(input) + const received = await new Response( + getOrCreateStream(1), + ).arrayBuffer() + expect(received.byteLength).toBe(frameCount) + await expect(jsonChunks.getReader().read()).resolves.toEqual({ + done: true, + value: undefined, + }) + }) + + it('should decode valid frames coalesced into one large transport chunk', async () => { + const frame = encodeChunkFrame(1, new Uint8Array(MAX_FRAME_PAYLOAD_SIZE)) + const tail = encodeChunkFrame( + 1, + new Uint8Array(MAX_FRAME_PAYLOAD_SIZE - FRAME_HEADER_SIZE), + ) + const end = encodeEndFrame(1) + const combined = new Uint8Array(frame.length + tail.length + end.length) + combined.set(frame) + combined.set(tail, frame.length) + combined.set(end, frame.length + tail.length) + const input = new ReadableStream({ + start(controller) { + controller.enqueue(combined) + controller.close() + }, + }) + const { getOrCreateStream, jsonChunks } = createFrameDecoder(input) + const rawReader = getOrCreateStream(1).getReader() + + await expect(jsonChunks.getReader().read()).resolves.toEqual({ + done: true, + value: undefined, + }) + await expect(rawReader.read()).resolves.toMatchObject({ + done: false, + value: { byteLength: MAX_FRAME_PAYLOAD_SIZE }, + }) + await expect(rawReader.read()).resolves.toMatchObject({ + done: false, + value: { + byteLength: MAX_FRAME_PAYLOAD_SIZE - FRAME_HEADER_SIZE, + }, + }) + await expect(rawReader.read()).resolves.toEqual({ + done: true, + value: undefined, + }) + }) + + it('accepts one maximum-size JSON frame while its consumer is stalled', async () => { + const json = 'x'.repeat(MAX_FRAME_PAYLOAD_SIZE) + const input = new ReadableStream({ + start(controller) { + controller.enqueue(encodeJSONFrame(json)) + controller.close() + }, + }) const { jsonChunks } = createFrameDecoder(input) - const reader = jsonChunks.getReader() - await expect(reader.read()).rejects.toThrow('buffer exceeded') + await new Promise((resolve) => setTimeout(resolve, 0)) + const result = await jsonChunks.getReader().read() + expect(result.done).toBe(false) + expect(result.value?.length).toBe(MAX_FRAME_PAYLOAD_SIZE) + }) + + it('delivers later JSON before an unconsumed large raw stream is read', async () => { + const payload = new Uint8Array(MAX_FRAME_PAYLOAD_SIZE) + const input = new ReadableStream({ + start(controller) { + controller.enqueue(encodeJSONFrame('{"ref":1}')) + controller.enqueue(encodeChunkFrame(1, payload)) + controller.enqueue(encodeChunkFrame(1, new Uint8Array([1]))) + controller.enqueue(encodeJSONFrame('{"later":true}')) + controller.enqueue(encodeEndFrame(1)) + controller.close() + }, + }) + const { getOrCreateStream, jsonChunks } = createFrameDecoder(input) + const rawReader = getOrCreateStream(1).getReader() + const jsonReader = jsonChunks.getReader() + + await expect(jsonReader.read()).resolves.toMatchObject({ + value: '{"ref":1}', + }) + const laterJSON = jsonReader.read() + await expect(laterJSON).resolves.toMatchObject({ + value: '{"later":true}', + }) + await expect(rawReader.read()).resolves.toMatchObject({ + value: { byteLength: payload.byteLength }, + }) + await expect(rawReader.read()).resolves.toMatchObject({ + value: new Uint8Array([1]), + }) + await expect(rawReader.read()).resolves.toMatchObject({ done: true }) + }) + + it('rejects when unread decoded output queues exceed the byte budget', async () => { + const cancel = vi.fn() + let frame = 0 + const input = new ReadableStream({ + pull(controller) { + if (frame++ === 0) { + controller.enqueue(encodeJSONFrame('{"ref":1}')) + } else if (frame < 4) { + controller.enqueue( + encodeChunkFrame(1, new Uint8Array(MAX_FRAME_PAYLOAD_SIZE)), + ) + } else { + controller.enqueue(encodeEndFrame(1)) + controller.close() + } + }, + cancel, + }) + const { jsonChunks } = createFrameDecoder(input) + + await vi.waitFor(() => { + expect(cancel).toHaveBeenCalledOnce() + }) + await expect(jsonChunks.getReader().read()).rejects.toThrow( + 'Framed response queue exceeded', + ) + }) + + it('allows consumed traffic to exceed the cumulative queue budget', async () => { + let frame = 0 + const input = new ReadableStream({ + pull(controller) { + if (frame++ < 3) { + controller.enqueue( + encodeChunkFrame(1, new Uint8Array(MAX_FRAME_PAYLOAD_SIZE)), + ) + } else { + controller.enqueue(encodeEndFrame(1)) + controller.close() + } + }, + }) + const { getOrCreateStream, jsonChunks } = createFrameDecoder(input) + const reader = getOrCreateStream(1).getReader() + let received = 0 + + while (true) { + const chunk = await reader.read() + if (chunk.done) { + break + } + received += chunk.value.byteLength + } + + expect(received).toBe(MAX_FRAME_PAYLOAD_SIZE * 3) + await expect(jsonChunks.getReader().read()).resolves.toMatchObject({ + done: true, + }) + }) + + it('surfaces a transport failure after JSON was queued', async () => { + const sourceError = new Error('transport failed') + let inputController!: ReadableStreamDefaultController + const input = new ReadableStream({ + start(controller) { + inputController = controller + controller.enqueue(encodeJSONFrame('{"queued":true}')) + }, + }) + const { jsonChunks } = createFrameDecoder(input) + + await new Promise((resolve) => setTimeout(resolve, 0)) + inputController.error(sourceError) + await new Promise((resolve) => setTimeout(resolve, 0)) + + await expect(jsonChunks.getReader().read()).rejects.toBe(sourceError) }) it('should decode JSON frames', async () => { diff --git a/packages/start-client-core/tests/serverFnFetcher.test.ts b/packages/start-client-core/tests/serverFnFetcher.test.ts new file mode 100644 index 0000000000..72df1804da --- /dev/null +++ b/packages/start-client-core/tests/serverFnFetcher.test.ts @@ -0,0 +1,395 @@ +import { describe, expect, it, vi } from 'vitest' +import { toCrossJSONStream } from 'seroval' +import { + RawStream, + createRawStreamRPCPlugin, + createSerializationAdapter, + makeSerovalPlugin, +} from '@tanstack/router-core' +import { + serverFnFetcher, + trackPostProcessPromise, +} from '../src/client-rpc/serverFnFetcher' +import { + FRAME_HEADER_SIZE, + FrameType, + MAX_FRAME_PAYLOAD_SIZE, + TSS_CONTENT_TYPE_FRAMED, + TSS_CONTENT_TYPE_FRAMED_VERSIONED, + X_TSS_SERIALIZED, +} from '../src/constants' +import type { SerovalNode } from 'seroval' +import type { Plugin as SerovalPlugin } from 'seroval' + +const mocks = vi.hoisted(() => ({ plugins: [] as Array })) +vi.mock('../src/getDefaultSerovalPlugins', () => ({ + getDefaultSerovalPlugins: () => mocks.plugins, +})) + +const textEncoder = new TextEncoder() + +function encodeFrame( + type: FrameType, + streamId: number, + payload: Uint8Array, +): Uint8Array { + const frame = new Uint8Array(FRAME_HEADER_SIZE + payload.length) + const view = new DataView(frame.buffer) + view.setUint8(0, type) + view.setUint32(1, streamId, false) + view.setUint32(5, payload.length, false) + frame.set(payload, FRAME_HEADER_SIZE) + return frame +} + +function encodeJSONPayload(json: string): Uint8Array { + return encodeFrame(FrameType.JSON, 0, textEncoder.encode(json)) +} + +function encodeJSONFrame(value: SerovalNode): Uint8Array { + return encodeJSONPayload(JSON.stringify(value)) +} + +function serializeInitial(value: unknown): SerovalNode { + let initial!: SerovalNode + const destroy = toCrossJSONStream(value, { + refs: new Map(), + plugins: mocks.plugins as Array>, + onParse(value) { + initial ??= value + }, + onDone() {}, + onError(error) { + throw error + }, + }) + destroy() + return initial +} + +function createDeferred() { + let resolve!: () => void + const promise = new Promise((done) => { + resolve = done + }) + return { promise, resolve } +} + +function createFramedResponse(value: unknown) { + let controller!: ReadableStreamDefaultController + const body = new ReadableStream({ + start(ctrl) { + controller = ctrl + controller.enqueue(encodeJSONFrame(serializeInitial(value))) + }, + }) + const response = new Response(body, { + headers: { + 'content-type': TSS_CONTENT_TYPE_FRAMED_VERSIONED, + [X_TSS_SERIALIZED]: 'true', + }, + }) + return { controller, response } +} + +function createStreamingFramedResponse(value: unknown) { + let controller!: ReadableStreamDefaultController + let destroy!: () => void + const body = new ReadableStream({ + start(ctrl) { + controller = ctrl + destroy = toCrossJSONStream(value, { + refs: new Map(), + plugins: mocks.plugins as Array>, + onParse(value) { + controller.enqueue(encodeJSONFrame(value)) + }, + onDone() {}, + onError(error) { + controller.error(error) + }, + }) + }, + cancel() { + destroy() + }, + }) + const response = new Response(body, { + headers: { + 'content-type': TSS_CONTENT_TYPE_FRAMED_VERSIONED, + [X_TSS_SERIALIZED]: 'true', + }, + }) + return { controller, destroy, response } +} + +function createRawPromiseFramedResponse() { + let destroy!: () => void + const body = new ReadableStream({ + start(controller) { + let resolveLater!: (value: string) => void + const later = new Promise((resolve) => { + resolveLater = resolve + }) + let rawId!: number + let initial = true + destroy = toCrossJSONStream( + { + raw: new RawStream(new ReadableStream()), + later, + }, + { + refs: new Map(), + plugins: [ + createRawStreamRPCPlugin((id) => { + rawId = id + }), + ], + onParse(value) { + controller.enqueue(encodeJSONFrame(value)) + if (initial) { + initial = false + const chunk = new Uint8Array(MAX_FRAME_PAYLOAD_SIZE) + controller.enqueue(encodeFrame(FrameType.CHUNK, rawId, chunk)) + setTimeout(() => resolveLater('resolved'), 0) + } + }, + onDone() { + controller.enqueue( + encodeFrame(FrameType.END, rawId, new Uint8Array()), + ) + controller.close() + }, + onError(error) { + controller.error(error) + }, + }, + ) + }, + cancel() { + destroy() + }, + }) + return new Response(body, { + headers: { + 'content-type': TSS_CONTENT_TYPE_FRAMED_VERSIONED, + [X_TSS_SERIALIZED]: 'true', + }, + }) +} + +async function observe(promise: Promise) { + return Promise.race([ + promise.then( + (value) => ({ status: 'resolved' as const, value }), + (error: unknown) => ({ status: 'rejected' as const, error }), + ), + new Promise<{ status: 'pending' }>((resolve) => { + setTimeout(() => resolve({ status: 'pending' }), 50) + }), + ]) +} + +describe('serverFnFetcher framed responses', () => { + it('cancels a response body rejected for an incompatible protocol version', async () => { + let cancelReason: unknown + const body = new ReadableStream({ + cancel(reason) { + cancelReason = reason + }, + }) + const response = new Response(body, { + headers: { + 'content-type': `${TSS_CONTENT_TYPE_FRAMED}; v=999`, + [X_TSS_SERIALIZED]: 'true', + }, + }) + + await expect( + serverFnFetcher( + '/server-fn', + [{ method: 'GET', context: {} }], + async () => response, + ), + ).rejects.toThrow('Incompatible framed protocol version') + await vi.waitFor(() => { + expect(cancelReason).toBeInstanceOf(Error) + expect(body.locked).toBe(false) + }) + }) + + it('cancels and unlocks the body after malformed initial JSON', async () => { + let cancelReason: unknown + const body = new ReadableStream({ + start(controller) { + controller.enqueue(encodeJSONPayload('{')) + }, + cancel(reason) { + cancelReason = reason + }, + }) + const response = new Response(body, { + headers: { + 'content-type': TSS_CONTENT_TYPE_FRAMED_VERSIONED, + [X_TSS_SERIALIZED]: 'true', + }, + }) + + await expect( + serverFnFetcher( + '/server-fn', + [{ method: 'GET', context: {} }], + async () => response, + ), + ).rejects.toBeInstanceOf(SyntaxError) + await vi.waitFor(() => { + expect(cancelReason).toBeInstanceOf(SyntaxError) + expect(body.locked).toBe(false) + }) + }) + + it('cancels and unlocks the body when initial deserialization throws', async () => { + class ThrowingValue {} + class LaterValue {} + const failure = new Error('deserialization failed') + let laterDeserializations = 0 + const plugin = makeSerovalPlugin( + createSerializationAdapter({ + key: 'throwing-deserializer-test', + test: (value): value is ThrowingValue | LaterValue => + value instanceof ThrowingValue || value instanceof LaterValue, + toSerializable: (value) => value instanceof LaterValue, + fromSerializable: (later) => { + if (later) { + laterDeserializations++ + return new LaterValue() + } + throw failure + }, + }), + ) + mocks.plugins.push(plugin) + let cancelReason: unknown + const body = new ReadableStream({ + start(controller) { + controller.enqueue( + encodeJSONFrame(serializeInitial(new ThrowingValue())), + ) + controller.enqueue(encodeJSONFrame(serializeInitial(new LaterValue()))) + }, + cancel(reason) { + cancelReason = reason + }, + }) + const response = new Response(body, { + headers: { + 'content-type': TSS_CONTENT_TYPE_FRAMED_VERSIONED, + [X_TSS_SERIALIZED]: 'true', + }, + }) + + try { + await expect( + serverFnFetcher( + '/server-fn', + [{ method: 'GET', context: {} }], + async () => response, + ), + ).rejects.toMatchObject({ cause: failure }) + await vi.waitFor(() => { + expect(cancelReason).toBeInstanceOf(Error) + expect(body.locked).toBe(false) + }) + expect(laterDeserializations).toBe(0) + } finally { + mocks.plugins.pop() + } + }) + + it('forwards a server-side Promise rejection', async () => { + let rejectLater!: (error: unknown) => void + const later = new Promise((_, reject) => { + rejectLater = reject + }) + const { controller, destroy, response } = createStreamingFramedResponse({ + later, + }) + + try { + const result = (await serverFnFetcher( + '/server-fn', + [{ method: 'GET', context: {} }], + async () => response, + )) as { later: Promise } + const error = new Error('server rejected') + + rejectLater(error) + + await expect(result.later).rejects.toMatchObject({ + message: 'server rejected', + }) + } finally { + destroy() + controller.close() + } + }) + + it('rejects when transport fails during initial post-processing', async () => { + class PostProcessedValue {} + const started = createDeferred() + const postProcess = createDeferred() + const plugin = makeSerovalPlugin( + createSerializationAdapter({ + key: 'pending-post-process-test', + test: (value): value is PostProcessedValue => + value instanceof PostProcessedValue, + toSerializable: () => null, + fromSerializable: () => { + trackPostProcessPromise(postProcess.promise) + started.resolve() + return 'decoded' + }, + }), + ) + mocks.plugins.push(plugin) + const { controller, response } = createFramedResponse( + new PostProcessedValue(), + ) + const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}) + + try { + const result = serverFnFetcher( + '/server-fn', + [{ method: 'GET', context: {} }], + async () => response, + ) + await started.promise + const transportError = new Error('transport failed') + + controller.error(transportError) + + await expect(observe(result)).resolves.toEqual({ + status: 'rejected', + error: transportError, + }) + } finally { + postProcess.resolve() + mocks.plugins.pop() + consoleError.mockRestore() + } + }) + + it('resolves a sibling Promise without consuming an eager RawStream', async () => { + const result = (await serverFnFetcher( + '/server-fn', + [{ method: 'GET', context: {} }], + async () => createRawPromiseFramedResponse(), + )) as { raw: ReadableStream; later: Promise } + + try { + await expect(result.later).resolves.toBe('resolved') + } finally { + await result.raw.cancel() + } + }) +}) diff --git a/packages/start-server-core/src/createStartHandler.ts b/packages/start-server-core/src/createStartHandler.ts index 20c4763137..ff67afd432 100644 --- a/packages/start-server-core/src/createStartHandler.ts +++ b/packages/start-server-core/src/createStartHandler.ts @@ -21,8 +21,7 @@ import { getOrigin, isSsrResponse, normalizeSsrResponse, - replaceSsrResponse, - stripSsrResponseBody, + _transferSsrResponse, waitForRequest, } from '@tanstack/router-core/ssr/server' import { @@ -199,7 +198,7 @@ function throwIfMayNotDefer(): never { * Check if a value is a special response (Response or Redirect) */ function isSpecialResponse(value: unknown): value is Response { - return value instanceof Response || isRedirect(value) + return value instanceof Response } /** @@ -219,10 +218,6 @@ function disposeLateResponse(result: TODO, signal: AbortSignal): void { } } -function isSignalAborted(signal: AbortSignal): boolean { - return signal.aborted -} - /** * Execute a middleware chain */ @@ -232,10 +227,16 @@ async function executeMiddleware( signal: AbortSignal, ): Promise<{ ctx: TODO; response: HandlerCallbackResult }> { let index = -1 - let streamResponse: - | Extract - | undefined - let retiredStreamIdentities: WeakSet | undefined + let responseOwner: HandlerCallbackResult | undefined + let responseOwnerBody: ReadableStream | null | undefined + let retiredResponseIdentities: WeakSet | undefined + + const getResponse = (value: unknown) => + isSsrResponse(value) + ? value.response + : value instanceof Response + ? value + : undefined const isResponseAlias = (candidate: unknown, response: Response) => candidate === response || @@ -243,49 +244,77 @@ async function executeMiddleware( response.body !== null && candidate.body === response.body) - const setResponse = (response: TODO) => { - if (isSsrResponse(response)) { - if (response.serverSsrCleanup === 'stream') { - streamResponse = response - } - ctx.response = response.response + const retireResponse = (reason: unknown) => { + const owner = responseOwner + if (!owner) { return } - ctx.response = response - } - - const disposeStreamResponse = async (reason: unknown) => { - const response = streamResponse - if (!response) { - return + responseOwner = undefined + responseOwnerBody = undefined + const response = getResponse(owner)! + retiredResponseIdentities ??= new WeakSet() + retiredResponseIdentities.add(response) + if (response.body) { + retiredResponseIdentities.add(response.body) } - - streamResponse = undefined - retiredStreamIdentities ??= new WeakSet() - retiredStreamIdentities.add(response.response) - if (response.response.body) { - retiredStreamIdentities.add(response.response.body) - } - const currentResponse = ctx.response - if (isResponseAlias(currentResponse, response.response)) { + if (isResponseAlias(ctx.response, response)) { ctx.response = undefined } - await response.dispose(reason) + disposeSsrResponseDetached(owner, reason) + } + + const setResponse = (value: TODO) => { + const owned = getResponse(value) + let response = owned ?? value + const owner = responseOwner + const ownedResponse = getResponse(responseOwner) + if (ownedResponse && !isResponseAlias(response, ownedResponse)) { + if ( + response instanceof Response && + response.body && + isSsrResponse(owner) && + owner.serverSsrCleanup === 'stream' && + responseOwnerBody && + (responseOwnerBody.locked || ownedResponse.body !== responseOwnerBody) + ) { + if (ownedResponse.body !== responseOwnerBody) { + disposeSsrResponseDetached( + ownedResponse, + 'middleware response transferred', + ) + } + responseOwner = _transferSsrResponse( + owner, + response as Response & { body: ReadableStream }, + ) + response = responseOwner.response + responseOwnerBody = response.body + } else { + retireResponse('middleware response replaced') + } + } + if (!responseOwner && owned) { + responseOwner = value + responseOwnerBody = owned.body + } + ctx.response = response } const disposeAbandonedResult = (result: TODO) => { const exposed = handleCtxResult(result)?.response - const response = isSsrResponse(exposed) ? exposed.response : exposed - if (streamResponse && isResponseAlias(response, streamResponse.response)) { - void disposeStreamResponse(signal.reason).catch(console.error) + const response = getResponse(exposed) + const ownedResponse = getResponse(responseOwner) + if (ownedResponse && isResponseAlias(response, ownedResponse)) { + retireResponse(signal.reason) return } if ( - response instanceof Response && - retiredStreamIdentities && - (retiredStreamIdentities.has(response) || - (response.body !== null && retiredStreamIdentities.has(response.body))) + response && + retiredResponseIdentities && + (retiredResponseIdentities.has(response) || + (response.body !== null && + retiredResponseIdentities.has(response.body))) ) { return } @@ -293,39 +322,29 @@ async function executeMiddleware( disposeLateResponse(result, signal) } - const getFinalResponse = async (): Promise => { + const getFinalResponse = (): HandlerCallbackResult => { const response = ctx.response if (!response) { throwRouteHandlerError() } - if (!streamResponse) { + const owner = responseOwner + const ownedResponse = getResponse(owner) + if (!ownedResponse) { return response } - if (response === streamResponse.response) { - return streamResponse + if (isResponseAlias(response, ownedResponse)) { + if (isSsrResponse(owner) && owner.serverSsrCleanup === 'stream') { + return response === ownedResponse ? owner : { ...owner, response } + } + return response } - if ( - streamResponse.response.body !== null && - response.body === streamResponse.response.body - ) { - return { ...streamResponse, response } - } - - await disposeStreamResponse('middleware response replaced') + retireResponse('middleware response replaced') return response } - let nextPromise: Promise | undefined - - function next(nextCtx?: TODO): Promise { - const result = runNext(nextCtx) - nextPromise = result - return result - } - async function runNext(nextCtx?: TODO): Promise { if (signal.aborted) { throw signal.reason @@ -352,20 +371,13 @@ async function executeMiddleware( let result: TODO try { - const pending = middleware({ ...ctx, next }) - // A directly returned next() promise already propagates request aborts. - if (pending === nextPromise) { - nextPromise = undefined - result = await pending - if (isSignalAborted(signal)) { - disposeAbandonedResult(result) - throw signal.reason - } - } else { - result = await waitForRequest(pending, signal, disposeAbandonedResult) - } + result = await waitForRequest( + middleware({ ...ctx, next: runNext }), + signal, + disposeAbandonedResult, + ) } catch (err) { - if (isSignalAborted(signal)) { + if (signal.aborted) { throw signal.reason } if (isSpecialResponse(err)) { @@ -390,23 +402,14 @@ async function executeMiddleware( try { await runNext() - const response = await waitForRequest( - getFinalResponse(), - signal, - disposeAbandonedResult, - ) + const response = getFinalResponse() if (signal.aborted) { disposeAbandonedResult(response) throw signal.reason } return { ctx, response } } catch (err) { - const disposal = disposeStreamResponse(signal.aborted ? signal.reason : err) - if (signal.aborted) { - void disposal.catch(console.error) - } else { - await disposal - } + retireResponse(signal.aborted ? signal.reason : err) throw err } } @@ -624,16 +627,19 @@ export function createStartHandler( request.signal, ) - const result = await handleRedirectResponse( + const result = await finalizeResponse( middlewareResponse, request, getRouter, + ) + const bound = bindSsrResponseToRequest( + router ?? undefined, + result, request.signal, ) - bindSsrResponseToRequest(router ?? undefined, result, request.signal) request.signal.throwIfAborted() - responseOwnsCleanup = result.serverSsrCleanup === 'stream' - return result.response + responseOwnsCleanup = bound.serverSsrCleanup === 'stream' + return bound.response } // Router execution function @@ -769,16 +775,19 @@ export function createStartHandler( request.signal, ) - const response = await handleRedirectResponse( + const response = await finalizeResponse( middlewareResponse, request, getRouter, + ) + const bound = bindSsrResponseToRequest( + router ?? undefined, + response, request.signal, ) - bindSsrResponseToRequest(router ?? undefined, response, request.signal) request.signal.throwIfAborted() - responseOwnsCleanup = response.serverSsrCleanup === 'stream' - return response.response + responseOwnsCleanup = bound.serverSsrCleanup === 'stream' + return bound.response } finally { if (router?.serverSsr && !responseOwnsCleanup) { // Clean up router SSR state if it was set up but won't be cleaned up by the callback @@ -793,6 +802,37 @@ export function createStartHandler( return requestHandler(startRequestResolver) } +async function finalizeResponse( + response: HandlerCallbackResult, + request: Request, + getRouter: () => Promise, +): Promise { + const signal = request.signal + // Resolve redirects before stripping so HEAD preserves the final Location. + const resolved = await handleRedirectResponse( + response, + request, + getRouter, + signal, + ) + return request.method === 'HEAD' + ? replaceSsrResponseDetached( + resolved, + new Response(null, resolved.response), + 'HEAD body stripped', + ) + : resolved +} + +function replaceSsrResponseDetached( + result: SsrResponse, + response: Response, + reason: unknown, +): SsrResponse { + disposeSsrResponseDetached(result, reason) + return { response, serverSsrCleanup: 'none' } +} + async function handleRedirectResponse( response: HandlerCallbackResult, request: Request, @@ -807,16 +847,13 @@ async function handleRedirectResponse( if (isResolvedRedirect(ssrResponse.response)) { if (request.headers.get('x-tsr-serverFn') === 'true') { - return waitForRequest( - replaceSsrResponse( - ssrResponse, - Response.json( - { ...ssrResponse.response.options, isSerializedRedirect: true }, - { headers: ssrResponse.response.headers }, - ), - 'redirect response replaced', + return replaceSsrResponseDetached( + ssrResponse, + Response.json( + { ...ssrResponse.response.options, isSerializedRedirect: true }, + { headers: ssrResponse.response.headers }, ), - signal, + 'redirect response replaced', ) } return ssrResponse @@ -850,22 +887,20 @@ async function handleRedirectResponse( const redirect = router.resolveRedirect(ssrResponse.response) if (request.headers.get('x-tsr-serverFn') === 'true') { - return waitForRequest( - replaceSsrResponse( - ssrResponse, - Response.json( - { ...ssrResponse.response.options, isSerializedRedirect: true }, - { headers: ssrResponse.response.headers }, - ), - 'redirect response replaced', + return replaceSsrResponseDetached( + ssrResponse, + Response.json( + { ...ssrResponse.response.options, isSerializedRedirect: true }, + { headers: ssrResponse.response.headers }, ), - signal, + 'redirect response replaced', ) } - return waitForRequest( - replaceSsrResponse(ssrResponse, redirect, 'redirect response replaced'), - signal, + return replaceSsrResponseDetached( + ssrResponse, + redirect, + 'redirect response replaced', ) } @@ -919,7 +954,6 @@ async function handleServerRoutes({ // Add handler middleware if exact match const server = foundRoute?.options.server - let isHeadFallback = false if (server?.handlers && isExactMatch) { const handlers = typeof server.handlers === 'function' @@ -933,9 +967,6 @@ async function handleServerRoutes({ requestMethod === 'HEAD' ? (handlers['HEAD'] ?? handlers['GET'] ?? handlers['ANY']) : (handlers[requestMethod] ?? handlers['ANY']) - isHeadFallback = - requestMethod === 'HEAD' && handler !== undefined && !handlers['HEAD'] - if (handler) { const mayDefer = !!foundRoute.options.component @@ -959,7 +990,7 @@ async function handleServerRoutes({ routeMiddlewares.push(((ctx: TODO) => executeRouter(ctx.context, matchedRoutes)) as TODO) - const { ctx, response } = await executeMiddleware( + const { response } = await executeMiddleware( routeMiddlewares, { request, @@ -971,24 +1002,5 @@ async function handleServerRoutes({ request.signal, ) - // RFC 9110 §9.3.2: HEAD must carry the same header fields as GET but no body. - // Resolve any redirect before stripping so the Location header survives. - if (isHeadFallback) { - if (!ctx.response) { - throwRouteHandlerError() - } - - const resolved = await handleRedirectResponse( - response, - request, - getRouter, - request.signal, - ) - return waitForRequest( - stripSsrResponseBody(resolved, 'HEAD body stripped'), - request.signal, - ) - } - return normalizeSsrResponse(response) } diff --git a/packages/start-server-core/src/frame-protocol.ts b/packages/start-server-core/src/frame-protocol.ts index e96275c0bb..1d4c8e63be 100644 --- a/packages/start-server-core/src/frame-protocol.ts +++ b/packages/start-server-core/src/frame-protocol.ts @@ -9,10 +9,16 @@ */ // Re-export constants from shared location -import { FRAME_HEADER_SIZE, FrameType } from '@tanstack/start-client-core' +import { + FRAME_HEADER_SIZE, + FrameType, + MAX_FRAME_PAYLOAD_SIZE, +} from '@tanstack/start-client-core' export { FRAME_HEADER_SIZE, + MAX_FRAME_PAYLOAD_SIZE, + MAX_FRAMED_STREAMS, FrameType, TSS_CONTENT_TYPE_FRAMED, TSS_CONTENT_TYPE_FRAMED_VERSIONED, @@ -22,9 +28,6 @@ export { /** Cached TextEncoder for frame encoding */ const textEncoder = new TextEncoder() -/** Shared empty payload for END frames - avoids allocation per call */ -const EMPTY_PAYLOAD = new Uint8Array(0) - /** * Encodes a single frame with header and payload. */ @@ -37,14 +40,14 @@ export function encodeFrame( // Write header bytes directly to avoid DataView allocation per frame // Frame format: [type:1][streamId:4 BE][length:4 BE] frame[0] = type - frame[1] = (streamId >>> 24) & 0xff - frame[2] = (streamId >>> 16) & 0xff - frame[3] = (streamId >>> 8) & 0xff - frame[4] = streamId & 0xff - frame[5] = (payload.length >>> 24) & 0xff - frame[6] = (payload.length >>> 16) & 0xff - frame[7] = (payload.length >>> 8) & 0xff - frame[8] = payload.length & 0xff + frame[1] = streamId >>> 24 + frame[2] = streamId >>> 16 + frame[3] = streamId >>> 8 + frame[4] = streamId + frame[5] = payload.length >>> 24 + frame[6] = payload.length >>> 16 + frame[7] = payload.length >>> 8 + frame[8] = payload.length frame.set(payload, FRAME_HEADER_SIZE) return frame } @@ -53,24 +56,13 @@ export function encodeFrame( * Encodes a JSON frame (type 0, streamId 0). */ export function encodeJSONFrame(json: string): Uint8Array { - return encodeFrame(FrameType.JSON, 0, textEncoder.encode(json)) -} - -/** - * Encodes a raw stream chunk frame. - */ -export function encodeChunkFrame( - streamId: number, - chunk: Uint8Array, -): Uint8Array { - return encodeFrame(FrameType.CHUNK, streamId, chunk) -} - -/** - * Encodes a raw stream end frame. - */ -export function encodeEndFrame(streamId: number): Uint8Array { - return encodeFrame(FrameType.END, streamId, EMPTY_PAYLOAD) + const payload = textEncoder.encode(json) + if (payload.length > MAX_FRAME_PAYLOAD_SIZE) { + throw new RangeError( + `Frame payload too large: ${payload.length} bytes (max ${MAX_FRAME_PAYLOAD_SIZE})`, + ) + } + return encodeFrame(FrameType.JSON, 0, payload) } /** @@ -79,65 +71,72 @@ export function encodeEndFrame(streamId: number): Uint8Array { export function encodeErrorFrame(streamId: number, error: unknown): Uint8Array { const message = error instanceof Error ? error.message : String(error ?? 'Unknown error') - return encodeFrame(FrameType.ERROR, streamId, textEncoder.encode(message)) + const payload = new Uint8Array( + Math.min(MAX_FRAME_PAYLOAD_SIZE, message.length * 3), + ) + const { written } = textEncoder.encodeInto(message, payload) + return encodeFrame(FrameType.ERROR, streamId, payload.subarray(0, written)) } -/** - * Late stream registration for RawStreams discovered after serialization starts. - * Used when Promise resolves after the initial synchronous pass. - */ -export interface LateStreamRegistration { - id: number - stream: ReadableStream +export function cancelReadableStream( + stream: ReadableStream, + reason?: unknown, +): void { + void stream.cancel(reason).catch(() => {}) } /** * Creates a multiplexed ReadableStream from JSON stream and raw streams. * - * The JSON stream emits NDJSON lines (from seroval's toCrossJSONStream). + * The JSON stream emits pre-encoded JSON frames. * Raw streams are pumped concurrently, interleaved with JSON frames. - * - * Supports late stream registration for RawStreams discovered after initial - * serialization (e.g., from resolved Promises). - * - * @param jsonStream Stream of JSON strings (each string is one NDJSON line) - * @param rawStreams Map of stream IDs to raw binary streams (known at start) - * @param lateStreamSource Optional stream of late registrations for streams discovered later */ export function createMultiplexedStream( - jsonStream: ReadableStream, + jsonStream: ReadableStream, rawStreams: Map>, - lateStreamSource?: ReadableStream, -): ReadableStream { - // Shared state for the multiplexed stream - let controller: ReadableStreamDefaultController - let cancelled = false - const readers: Array> = [] +): [ + stream: ReadableStream, + registerRaw: (id: number, stream: ReadableStream) => void, +] { + const transform = new TransformStream() + const writer = transform.writable.getWriter() + let terminal = false + const readers = new Set>() + let active = 0 - // Helper to enqueue a frame, ignoring errors if stream is closed/cancelled - const enqueue = (frame: Uint8Array): boolean => { - if (cancelled) return false - try { - controller.enqueue(frame) - return true - } catch { - return false + const stop = (error: unknown): void => { + if (terminal) { + return } + + terminal = true + for (const reader of readers) { + void reader.cancel(error).catch(() => {}) + } + readers.clear() + void writer.abort(error).catch(() => {}) } - // Helper to error the output stream (for fatal errors like JSON stream failure) - const errorOutput = (error: unknown): void => { - if (cancelled) return - cancelled = true - try { - controller.error(error) - } catch { - // Already errored - } - // Cancel all readers to stop other pumps - for (const reader of readers) { - reader.cancel().catch(() => {}) - } + void writer.closed.catch(stop) + + const write = (frame: Uint8Array): Promise => { + return writer.write(frame).then( + () => true, + (error) => { + stop(error) + return false + }, + ) + } + + const track = (pump: Promise): void => { + active++ + void pump.then(() => { + if (!--active && !terminal) { + terminal = true + void writer.close().catch(() => {}) + } + }, stop) } // Pumps a raw stream, sending CHUNK frames and END/ERROR on completion @@ -145,22 +144,47 @@ export function createMultiplexedStream( streamId: number, stream: ReadableStream, ): Promise { - const reader = stream.getReader() - readers.push(reader) + let reader: ReadableStreamDefaultReader | undefined try { - while (!cancelled) { + reader = stream.getReader() + readers.add(reader) + + while (!terminal) { const { done, value } = await reader.read() - if (done) { - enqueue(encodeEndFrame(streamId)) + // Cancellation can happen while the read is pending. + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + if (terminal) { return } - if (!enqueue(encodeChunkFrame(streamId, value))) return + if (done) { + await write( + encodeFrame(FrameType.END, streamId, new Uint8Array()), + ) + return + } + + let offset = 0 + do { + const chunk = value.subarray( + offset, + Math.min(offset + MAX_FRAME_PAYLOAD_SIZE, value.length), + ) + if (!(await write(encodeFrame(FrameType.CHUNK, streamId, chunk)))) { + return + } + offset += MAX_FRAME_PAYLOAD_SIZE + } while (offset < value.length) } } catch (error) { // Raw stream error - send ERROR frame, don't fail entire response - enqueue(encodeErrorFrame(streamId, error)) + if (!terminal) { + await write(encodeErrorFrame(streamId, error)) + } } finally { - reader.releaseLock() + if (reader) { + readers.delete(reader) + reader.releaseLock() + } } } @@ -168,91 +192,43 @@ export function createMultiplexedStream( // JSON stream errors are fatal - they error the entire output async function pumpJSON(): Promise { const reader = jsonStream.getReader() - readers.push(reader) + readers.add(reader) try { - while (!cancelled) { + while (!terminal) { const { done, value } = await reader.read() - if (done) return - if (!enqueue(encodeJSONFrame(value))) return + // Cancellation can happen while the read is pending. + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + if (terminal) { + return + } + if (done) { + return + } + + if (!(await write(value))) { + return + } } - } catch (error) { - // JSON stream error is fatal - error the entire output - errorOutput(error) - throw error // Re-throw to signal failure to Promise.all } finally { + readers.delete(reader) reader.releaseLock() } } - // Pumps late stream registrations, spawning raw stream pumps as they arrive - async function pumpLateStreams(): Promise>> { - if (!lateStreamSource) return [] - - const lateStreamPumps: Array> = [] - const reader = lateStreamSource.getReader() - readers.push(reader) - try { - while (!cancelled) { - const { done, value } = await reader.read() - if (done) break - // Start pumping this late stream and track it - lateStreamPumps.push(pumpRawStream(value.id, value.stream)) - } - } finally { - reader.releaseLock() - } - return lateStreamPumps + const registerRaw = ( + id: number, + stream: ReadableStream, + ): void => { + // Start immediately so output cancellation owns the raw reader. Raw and + // JSON frame order is intentionally independent. + track(pumpRawStream(id, stream)) } - return new ReadableStream({ - async start(ctrl) { - controller = ctrl + track(pumpJSON()) + for (const [id, stream] of rawStreams) { + track(pumpRawStream(id, stream)) + } + rawStreams.clear() - // Collect all pump promises - const pumps: Array>>> = [pumpJSON()] - - for (const [streamId, stream] of rawStreams) { - pumps.push(pumpRawStream(streamId, stream)) - } - - // Add late stream pump (returns array of spawned pump promises) - if (lateStreamSource) { - pumps.push(pumpLateStreams()) - } - - try { - // Wait for initial pumps to complete - const results = await Promise.all(pumps) - - // Wait for any late stream pumps that were spawned - const latePumps = results.find(Array.isArray) as - | Array> - | undefined - if (latePumps && latePumps.length > 0) { - await Promise.all(latePumps) - } - - // All pumps done - close the output stream - if (!cancelled) { - try { - controller.close() - } catch { - // Already closed - } - } - } catch { - // Error already handled by errorOutput in pumpJSON - // or was a raw stream error (non-fatal, already sent ERROR frame) - } - }, - - cancel() { - cancelled = true - // Cancel all readers to stop pumps quickly - for (const reader of readers) { - reader.cancel().catch(() => {}) - } - readers.length = 0 - }, - }) + return [transform.readable, registerRaw] } diff --git a/packages/start-server-core/src/server-functions-handler.ts b/packages/start-server-core/src/server-functions-handler.ts index e7d961decf..e054b45391 100644 --- a/packages/start-server-core/src/server-functions-handler.ts +++ b/packages/start-server-core/src/server-functions-handler.ts @@ -15,10 +15,14 @@ import { fromJSON, toCrossJSONAsync, toCrossJSONStream } from 'seroval' import { getResponse } from './request-response' import { getServerFnById } from './getServerFnById' import { + FRAME_HEADER_SIZE, + MAX_FRAME_PAYLOAD_SIZE, + MAX_FRAMED_STREAMS, TSS_CONTENT_TYPE_FRAMED_VERSIONED, + cancelReadableStream, createMultiplexedStream, + encodeJSONFrame, } from './frame-protocol' -import type { LateStreamRegistration } from './frame-protocol' import type { Plugin as SerovalPlugin } from 'seroval' // Cache serovalPlugins at module level to avoid repeated calls @@ -33,6 +37,8 @@ const FORM_DATA_CONTENT_TYPES = [ // Maximum payload size for GET requests (1MB) const MAX_PAYLOAD_SIZE = 1_000_000 +const MAX_JSON_FRAME_SIZE = FRAME_HEADER_SIZE + MAX_FRAME_PAYLOAD_SIZE + export const handleServerAction = async ({ request, context, @@ -180,87 +186,79 @@ export const handleServerAction = async ({ return serializeResult(res) function serializeResult(res: unknown): Response { - let nonStreamingBody: any = undefined + let nonStreamingBody: any const alsResponse = getResponse() if (res !== undefined) { // Collect raw streams encountered during initial synchronous serialization const rawStreams = new Map>() - // Track whether we're still in the initial synchronous phase - // After initial phase, new RawStreams go to lateStreamWriter - let initialPhase = true - - // Late stream registration for RawStreams discovered after initial pass - // (e.g., from resolved Promises) - let lateStreamWriter: - | WritableStreamDefaultWriter + let registerRaw: + | ((id: number, stream: ReadableStream) => void) | undefined - let lateStreamReadable: - | ReadableStream - | undefined = undefined - const pendingLateStreams: Array = [] const rawStreamPlugin = createRawStreamRPCPlugin( (id: number, stream: ReadableStream) => { - if (initialPhase) { - rawStreams.set(id, stream) + if (id > MAX_FRAMED_STREAMS) { + const error = new Error( + `Too many raw streams in framed response (max ${MAX_FRAMED_STREAMS})`, + ) + cancelReadableStream(stream, error) + throw error + } + if (registerRaw) { + registerRaw(id, stream) return } - - if (lateStreamWriter) { - // Late stream - write to the late stream channel - lateStreamWriter.write({ id, stream }).catch(() => { - // Ignore write errors - stream may be closed - }) - return - } - - // Discovered after initial phase but before writer exists. - pendingLateStreams.push({ id, stream }) + rawStreams.set(id, stream) }, ) // Build plugins with RawStreamRPCPlugin first (before default SSR plugin) - const plugins = [rawStreamPlugin, ...(serovalPlugins || [])] + const plugins = [rawStreamPlugin, ...serovalPlugins!] // first run without the stream in case `result` does not need streaming - let done = false as boolean - const callbacks: { - onParse: (value: any) => void - onDone: () => void - onError: (error: any) => void - } = { - onParse: (value) => { - nonStreamingBody = value - }, - onDone: () => { - done = true - }, - onError: (error) => { - throw error - }, + let done = false + let initialError: [unknown] | undefined + let onParse = (value: any): void => { + nonStreamingBody = value + } + let onDone = (): void => { + done = true + } + let onError = (error: unknown): void => { + initialError ??= [error] + } + let destroySerialization: (() => void) | undefined + const stopSerialization = (): void => { + const destroy = destroySerialization + destroySerialization = undefined + destroy?.() + } + try { + destroySerialization = toCrossJSONStream(res, { + refs: new Map(), + plugins, + onParse(value) { + onParse(value) + }, + onDone() { + onDone() + }, + onError(error) { + onError(error) + }, + }) + if (initialError) { + throw initialError[0] + } + } catch (error) { + stopSerialization() + for (const stream of rawStreams.values()) { + cancelReadableStream(stream, error) + } + throw error } - toCrossJSONStream(res, { - refs: new Map(), - plugins, - onParse(value) { - callbacks.onParse(value) - }, - onDone() { - callbacks.onDone() - }, - onError: (error) => { - callbacks.onError(error) - }, - }) - - // End of initial synchronous phase - any new RawStreams are "late" - initialPhase = false - - // If any RawStreams are discovered after this point but before the - // late-stream writer exists, we buffer them and flush once the writer - // is ready. This avoids an occasional missed-stream race. // If no raw streams and done synchronously, return simple JSON if (done && rawStreams.size === 0) { @@ -277,83 +275,65 @@ export const handleServerAction = async ({ ) } - // Not done synchronously or has raw streams - use framed protocol - // This supports late RawStreams from resolved Promises - const { readable, writable } = - new TransformStream() - lateStreamReadable = readable - lateStreamWriter = writable.getWriter() - - // Flush any late streams that were discovered in the small window - // between end of initial serialization and writer setup. - for (const registration of pendingLateStreams) { - lateStreamWriter.write(registration).catch(() => { - // Ignore write errors - stream may be closed - }) - } - pendingLateStreams.length = 0 - - // Create a stream of JSON chunks - const jsonStream = new ReadableStream({ - start(controller) { - callbacks.onParse = (value) => { - controller.enqueue(JSON.stringify(value) + '\n') - } - callbacks.onDone = () => { - try { - controller.close() - } catch { - // Already closed - } - // Close late stream writer when JSON serialization is done - // Any RawStreams not yet discovered won't be sent - lateStreamWriter - ?.close() - .catch(() => { - // Ignore close errors - }) - .finally(() => { - lateStreamWriter = undefined - }) - } - - callbacks.onError = (error) => { - controller.error(error) - lateStreamWriter - ?.abort(error) - .catch(() => { - // Ignore abort errors - }) - .finally(() => { - lateStreamWriter = undefined - }) - } - - // Emit initial body if we have one - if (nonStreamingBody !== undefined) { - callbacks.onParse(nonStreamingBody) - } - // If serialization already completed synchronously, close now - // This handles the case where onDone was called during toCrossJSONStream - // before we overwrote callbacks.onDone - if (done) { - callbacks.onDone() - } + let jsonController!: ReadableStreamDefaultController + const jsonStream = new ReadableStream( + { + start(controller) { + jsonController = controller + }, + cancel() { + stopSerialization() + }, }, - cancel() { - lateStreamWriter?.abort().catch(() => {}) - lateStreamWriter = undefined + { + highWaterMark: MAX_JSON_FRAME_SIZE, + size(frame) { + return frame!.byteLength + }, }, - }) - - // Create multiplexed stream with JSON, initial raw streams, and late streams - const multiplexedStream = createMultiplexedStream( - jsonStream, - rawStreams, - lateStreamReadable, ) - return new Response(multiplexedStream, { + const multiplexed = createMultiplexedStream(jsonStream, rawStreams) + registerRaw = multiplexed[1] + + const failSerialization = (error: unknown): void => { + if (!destroySerialization) { + return + } + stopSerialization() + jsonController.error(error) + } + + onParse = (value) => { + try { + const frame = encodeJSONFrame(JSON.stringify(value)) + if (jsonController.desiredSize! < frame.byteLength) { + throw new Error( + `Framed JSON queue exceeded ${MAX_JSON_FRAME_SIZE} bytes`, + ) + } + jsonController.enqueue(frame) + } catch (error) { + failSerialization(error) + } + } + onDone = () => { + if (!destroySerialization) { + return + } + destroySerialization = undefined + jsonController.close() + } + onError = failSerialization + + if (nonStreamingBody !== undefined) { + onParse(nonStreamingBody) + } + if (done) { + onDone() + } + + return new Response(multiplexed[0], { status: alsResponse.status, statusText: alsResponse.statusText, headers: { @@ -396,12 +376,10 @@ export const handleServerAction = async ({ console.info() const serializedError = JSON.stringify( - await Promise.resolve( - toCrossJSONAsync(error, { - refs: new Map(), - plugins: serovalPlugins, - }), - ), + await toCrossJSONAsync(error, { + refs: new Map(), + plugins: serovalPlugins, + }), ) const response = getResponse() return new Response(serializedError, { diff --git a/packages/start-server-core/tests/createStartHandler.test.ts b/packages/start-server-core/tests/createStartHandler.test.ts index a4c8dc16f6..447af79885 100644 --- a/packages/start-server-core/tests/createStartHandler.test.ts +++ b/packages/start-server-core/tests/createStartHandler.test.ts @@ -7,6 +7,7 @@ import { BaseRootRoute, BaseRoute, RouterCore, + redirect, type AnyRouter, } from '@tanstack/router-core' import { @@ -107,13 +108,17 @@ function waitForAbortOrRelease(signal: AbortSignal) { }) } -function makeStreamResponse(router: ReturnType) { +function makeStreamResponse( + router: ReturnType, + onCancel?: (reason: unknown) => void, +) { attachRouterServerSsrUtils({ router: router as any, manifest: undefined }) const stream = new ReadableStream({ start(controller) { controller.enqueue(new TextEncoder().encode('stream')) }, - cancel() { + cancel(reason) { + onCancel?.(reason) router.serverSsr?.cleanup() }, }) @@ -182,11 +187,71 @@ describe('createStartHandler SSR cleanup ownership', () => { {}, ) - expect(response).toBe(replacement) + expect(await response.text()).toBe('replacement') expect(dispose).toHaveBeenCalledOnce() expect(router.serverSsr).toBeUndefined() }) + it('cancels a plain response body replaced by middleware', async () => { + const router = makeRouter() + startMocks.router = router + const cancel = vi.fn() + startMocks.serverFnResult = new Response( + new ReadableStream({ cancel }), + ) + startMocks.requestMiddleware = [ + createMiddleware().server(async ({ next }) => { + await next() + return new Response('replacement') + }), + ] + + const handler = createStartHandler(() => new Response('unused')) + const response = await handler( + new Request('http://localhost/_serverFn/test', { + headers: { 'x-tsr-serverFn': 'true' }, + }), + {}, + ) + + expect(await response.text()).toBe('replacement') + expect(cancel).toHaveBeenCalledOnce() + }) + + it('does not await a replaced stream owner', async () => { + const router = makeRouter() + startMocks.router = router + const dispose = vi.fn(() => new Promise(() => {})) + startMocks.serverFnResult = { + response: new Response('stream'), + serverSsrCleanup: 'stream', + dispose, + } + startMocks.requestMiddleware = [ + createMiddleware().server(async ({ next }) => { + await next() + return new Response('replacement') + }), + ] + + const handler = createStartHandler(() => new Response('unused')) + const response = handler( + new Request('http://localhost/_serverFn/test', { + headers: { 'x-tsr-serverFn': 'true' }, + }), + {}, + ) + const outcome = await Promise.race([ + Promise.resolve(response).then(() => 'settled'), + new Promise<'pending'>((resolve) => { + setTimeout(() => resolve('pending'), 20) + }), + ]) + + expect(outcome).toBe('settled') + expect(dispose).toHaveBeenCalledOnce() + }) + it('exposes Response to middleware while preserving stream ownership', async () => { startMocks.requestMiddleware = [] const router = makeRouter() @@ -282,6 +347,227 @@ describe('createStartHandler SSR cleanup ownership', () => { expect(router.serverSsr).toBeUndefined() }) + it.each(['pipeThrough', 'clone'] as const)( + 'preserves stream ownership when middleware returns a %s response', + async (operation) => { + const router = makeRouter() + startMocks.router = router + let release!: () => void + const gate = new Promise((resolve) => { + release = resolve + }) + attachRouterServerSsrUtils({ router: router as any, manifest: undefined }) + const ssrResponse = createSsrStreamResponse( + router as any, + new Response( + new ReadableStream({ + async pull(controller) { + await gate + controller.enqueue(new TextEncoder().encode('stream')) + controller.close() + }, + }), + ), + ) + const dispose = vi.spyOn(ssrResponse as any, 'dispose') + startMocks.serverFnResult = ssrResponse + startMocks.requestMiddleware = [ + createMiddleware().server(async ({ next }) => { + const result = await next() + return operation === 'clone' + ? result.response.clone() + : new Response( + result.response.body!.pipeThrough(new TransformStream()), + result.response, + ) + }), + ] + + const handler = createStartHandler(() => new Response('unused')) + const response = await handler( + new Request('http://localhost/_serverFn/test', { + headers: { 'x-tsr-serverFn': 'true' }, + }), + {}, + ) + release() + + expect(dispose).not.toHaveBeenCalled() + await expect(response.text()).resolves.toBe('stream') + expect(router.serverSsr).toBeUndefined() + }, + ) + + it.each(['pipeThrough', 'clone'] as const)( + 'request abort cancels a locked %s response and its SSR source', + async (operation) => { + const router = makeRouter() + startMocks.router = router + attachRouterServerSsrUtils({ router: router as any, manifest: undefined }) + const cleanup = router.serverSsr!.cleanup + const cleanupSpy = vi.fn(() => cleanup()) + router.serverSsr!.cleanup = cleanupSpy + const sourceCancel = vi.fn() + startMocks.serverFnResult = createSsrStreamResponse( + router as any, + new Response(new ReadableStream({ cancel: sourceCancel })), + ) + startMocks.requestMiddleware = [ + createMiddleware().server(async ({ next }) => { + const result = await next() + return operation === 'clone' + ? result.response.clone() + : new Response( + result.response.body!.pipeThrough(new TransformStream()), + result.response, + ) + }), + ] + const requestController = new AbortController() + const cancellation = new Error('request disconnected') + const response = await createStartHandler(() => + new Response('unused'), + )( + new Request('http://localhost/_serverFn/test', { + headers: { 'x-tsr-serverFn': 'true' }, + signal: requestController.signal, + }), + {}, + ) + const reader = response.body!.getReader() + const read = reader.read() + + expect(response.body!.locked).toBe(true) + requestController.abort(cancellation) + + try { + await expect(read).rejects.toBe(cancellation) + await vi.waitFor(() => expect(sourceCancel).toHaveBeenCalledOnce()) + expect(cleanupSpy).toHaveBeenCalledOnce() + expect(router.serverSsr).toBeUndefined() + } finally { + reader.releaseLock() + } + }, + ) + + it('cancels a replacement stream after middleware buffers the SSR response', async () => { + const router = makeRouter() + startMocks.router = router + attachRouterServerSsrUtils({ router: router as any, manifest: undefined }) + startMocks.serverFnResult = createSsrStreamResponse( + router as any, + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode('stream')) + controller.close() + }, + }), + ), + ) + const requestController = new AbortController() + const cancellation = new Error('request disconnected') + const cancel = vi.fn() + startMocks.requestMiddleware = [ + createMiddleware().server(async ({ next }) => { + const result = await next() + await expect(result.response.text()).resolves.toBe('stream') + return new Response(new ReadableStream({ cancel })) + }), + ] + + const response = await createStartHandler(() => new Response('unused'))( + new Request('http://localhost/_serverFn/test', { + headers: { 'x-tsr-serverFn': 'true' }, + signal: requestController.signal, + }), + {}, + ) + try { + requestController.abort(cancellation) + await vi.waitFor(() => { + expect(cancel).toHaveBeenCalledOnce() + }) + } finally { + void response.body!.cancel('test cleanup').catch(() => {}) + } + }) + + it('does not report a cleanup error for a transformed plain response', async () => { + const router = makeRouter() + startMocks.router = router + startMocks.serverFnResult = new Response('plain') + startMocks.requestMiddleware = [ + createMiddleware().server(async ({ next }) => { + const result = await next() + return new Response( + result.response.body!.pipeThrough(new TransformStream()), + result.response, + ) + }), + ] + const consoleError = vi + .spyOn(console, 'error') + .mockImplementation(() => undefined) + + try { + const response = await createStartHandler(() => new Response('unused'))( + new Request('http://localhost/_serverFn/test', { + headers: { 'x-tsr-serverFn': 'true' }, + }), + {}, + ) + + await expect(response.text()).resolves.toBe('plain') + expect(consoleError).not.toHaveBeenCalled() + } finally { + consoleError.mockRestore() + } + }) + + it('retires a locked stream owner replaced by a bodyless response', async () => { + const router = makeRouter() + startMocks.router = router + const cancel = vi.fn() + attachRouterServerSsrUtils({ router: router as any, manifest: undefined }) + const ssrResponse = createSsrStreamResponse( + router as any, + new Response(new ReadableStream({ cancel })), + ) + const dispose = vi.spyOn(ssrResponse as any, 'dispose') + startMocks.serverFnResult = ssrResponse + let lockedReader: ReadableStreamDefaultReader | undefined + startMocks.requestMiddleware = [ + createMiddleware().server(async ({ next }) => { + const result = await next() + lockedReader = result.response.body!.getReader() + void lockedReader.closed.catch(() => {}) + return new Response(null, { status: 204 }) + }), + ] + + try { + const response = await createStartHandler(() => new Response('unused'))( + new Request('http://localhost/_serverFn/test', { + headers: { 'x-tsr-serverFn': 'true' }, + }), + {}, + ) + + expect(response.status).toBe(204) + expect(response.body).toBeNull() + expect(dispose).toHaveBeenCalledOnce() + expect(cancel).toHaveBeenCalledOnce() + expect(router.serverSsr).toBeUndefined() + } finally { + lockedReader?.releaseLock() + if (router.serverSsr) { + await ssrResponse.dispose('test cleanup') + } + } + }) + it('disposes stream response on middleware error after next', async () => { const router = makeRouter() startMocks.router = router @@ -330,7 +616,8 @@ describe('createStartHandler SSR cleanup ownership', () => { {}, ) - expect(response).toBe(replacement) + expect(response.status).toBe(418) + expect(await response.text()).toBe('handled') expect(dispose).toHaveBeenCalledOnce() expect(router.serverSsr).toBeUndefined() }) @@ -358,12 +645,161 @@ describe('createStartHandler SSR cleanup ownership', () => { {}, ) - expect(response).toBe(replacement) + expect(await response.text()).toBe('replacement') expect(dispose).toHaveBeenCalledOnce() expect(router.serverSsr).toBeUndefined() }) }) +describe('createStartHandler HEAD responses', () => { + it('strips and cancels an application document body', async () => { + const router = makeRouter() + startMocks.router = router + const cancel = vi.fn() + const render = vi.fn( + () => + new Response(new ReadableStream({ cancel }), { + headers: { 'x-rendered': 'true' }, + }), + ) + const handler = createStartHandler(render) + + const response = await handler( + new Request('http://localhost/', { method: 'HEAD' }), + {}, + ) + + expect(render).toHaveBeenCalledOnce() + expect(response.headers.get('x-rendered')).toBe('true') + expect(response.body).toBeNull() + expect(cancel).toHaveBeenCalledOnce() + }) + + it('strips and cancels a body returned by an explicit HEAD handler', async () => { + const rootRoute = new BaseRootRoute({}) + const cancel = vi.fn() + const headHandler = vi.fn( + () => + new Response(new ReadableStream({ cancel }), { + status: 202, + headers: { 'x-handler': 'HEAD' }, + }), + ) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + server: { handlers: { HEAD: headHandler } }, + }) + const router = new RouterCore( + { + history: createMemoryHistory({ initialEntries: ['/target'] }), + routeTree: rootRoute.addChildren([targetRoute]), + }, + getStoreConfig, + ) + router.isServer = true + startMocks.router = router + const render = vi.fn(() => new Response('must not render')) + const handler = createStartHandler(render) + + const response = await handler( + new Request('http://localhost/target', { method: 'HEAD' }), + {}, + ) + + expect(headHandler).toHaveBeenCalledOnce() + expect(render).not.toHaveBeenCalled() + expect(response.status).toBe(202) + expect(response.headers.get('x-handler')).toBe('HEAD') + expect(response.body).toBeNull() + expect(cancel).toHaveBeenCalledOnce() + }) + + it('resolves a redirect before stripping its HEAD body', async () => { + const rootRoute = new BaseRootRoute({}) + const sourceRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/source', + server: { + handlers: { + HEAD: () => redirect({ to: '/target' }), + }, + }, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const router = new RouterCore( + { + history: createMemoryHistory({ initialEntries: ['/source'] }), + routeTree: rootRoute.addChildren([sourceRoute, targetRoute]), + }, + getStoreConfig, + ) + router.isServer = true + startMocks.router = router + + const response = await createStartHandler(() => + new Response('must not render'), + )(new Request('http://localhost/source', { method: 'HEAD' }), {}) + + expect(response.status).toBe(307) + expect(response.headers.get('Location')).toBe('/target') + expect(response.body).toBeNull() + }) + + it('strips and cancels a body returned early by request middleware', async () => { + const router = makeRouter() + startMocks.router = router + const cancel = vi.fn() + startMocks.requestMiddleware = [ + createMiddleware().server( + () => + new Response(new ReadableStream({ cancel }), { + status: 202, + headers: { 'x-middleware': 'true' }, + }), + ), + ] + const render = vi.fn(() => new Response('must not render')) + + const response = await createStartHandler(render)( + new Request('http://localhost/', { method: 'HEAD' }), + {}, + ) + + expect(render).not.toHaveBeenCalled() + expect(response.status).toBe(202) + expect(response.headers.get('x-middleware')).toBe('true') + expect(response.body).toBeNull() + expect(cancel).toHaveBeenCalledOnce() + }) + + it('strips a server-function HEAD error body', async () => { + const router = makeRouter() + startMocks.router = router + startMocks.serverFnResult = new Response('method not allowed', { + status: 405, + headers: { Allow: 'POST' }, + }) + + const response = await createStartHandler(() => + new Response('must not render'), + )( + new Request('http://localhost/_serverFn/test', { + method: 'HEAD', + headers: { 'x-tsr-serverFn': 'true' }, + }), + {}, + ) + + expect(response.status).toBe(405) + expect(response.headers.get('Allow')).toBe('POST') + expect(response.body).toBeNull() + }) +}) + describe('createStartHandler request cancellation', () => { it.each(['beforeLoad', 'loader'] as const)( 'aborts route %s work and does not render HTML', @@ -460,10 +896,8 @@ describe('createStartHandler request cancellation', () => { expect(router.serverSsr).toBeUndefined() resolveRender(lateStreamResponse) - await Promise.resolve() - await Promise.resolve() + await vi.waitFor(() => expect(cancelCalls).toBe(1)) expect(cleanupCalls).toBe(1) - expect(cancelCalls).toBe(1) expect(router.serverSsr).toBeUndefined() }) @@ -655,20 +1089,18 @@ describe('createStartHandler request cancellation', () => { }, ) - it('disposes a stream when the request aborts after response handoff', async () => { + it('cancels a locked tagged stream when the request aborts after handoff', async () => { const router = makeRouter() startMocks.router = router const requestController = new AbortController() - let cancelCalls = 0 + const cancellation = new Error('request disconnected') + const cancel = vi.fn(() => new Promise(() => {})) const handler = createStartHandler(({ router: requestRouter }) => createSsrStreamResponse( requestRouter, new Response( new ReadableStream({ - cancel() { - cancelCalls++ - return new Promise(() => {}) - }, + cancel, }), ), ), @@ -680,16 +1112,66 @@ describe('createStartHandler request cancellation', () => { }), {}, ) - expect(response.body).not.toBeNull() + const reader = response.body!.getReader() + const read = expect(reader.read()).rejects.toBe(cancellation) expect(router.serverSsr).toBeDefined() - requestController.abort(new Error('request disconnected')) - await Promise.resolve() + requestController.abort(cancellation) - expect(cancelCalls).toBe(1) - expect(router.serverSsr).toBeUndefined() + try { + await vi.waitFor(() => { + expect(cancel).toHaveBeenCalledWith(cancellation) + }) + await read + expect(router.serverSsr).toBeUndefined() + } finally { + reader.releaseLock() + } }) + it.each(['router', 'serverFn'] as const)( + 'cancels a locked plain %s response after handoff', + async (handlerType) => { + const router = makeRouter() + startMocks.router = router + const requestController = new AbortController() + const cancellation = new Error('request disconnected') + const cancel = vi.fn() + const plainResponse = new Response(new ReadableStream({ cancel })) + if (handlerType === 'serverFn') { + startMocks.serverFnResult = plainResponse + } + const handler = createStartHandler(() => plainResponse) + const response = await handler( + new Request( + handlerType === 'serverFn' + ? 'http://localhost/_serverFn/test' + : 'http://localhost/', + { + headers: + handlerType === 'serverFn' + ? { 'x-tsr-serverFn': 'true' } + : undefined, + signal: requestController.signal, + }, + ), + {}, + ) + const reader = response.body!.getReader() + + requestController.abort(cancellation) + + try { + await vi.waitFor(() => { + expect(cancel).toHaveBeenCalledWith(cancellation) + }) + await expect(reader.read()).rejects.toBe(cancellation) + } finally { + reader.releaseLock() + } + }, + ) + it('settles when request middleware ignores cancellation', async () => { const router = makeRouter() startMocks.router = router @@ -839,9 +1321,9 @@ describe('createStartHandler request cancellation', () => { const reason = new Error('request disconnected') const observedErrors: Array = [] const afterNext = vi.fn() - const ssrResponse = makeStreamResponse(router) + const cancel = vi.fn() + const ssrResponse = makeStreamResponse(router, cancel) const dispose = vi.spyOn(ssrResponse as any, 'dispose') - const cancel = vi.spyOn(ssrResponse.response.body!, 'cancel') startMocks.requestMiddleware = [ createMiddleware().server(async ({ next }) => { try { @@ -860,9 +1342,8 @@ describe('createStartHandler request cancellation', () => { ) return pending }), - createMiddleware().server(() => ssrResponse as any), ] - const render = vi.fn(() => new Response('must not render')) + const render = vi.fn(() => ssrResponse) const handler = createStartHandler(render) const response = await handler( @@ -881,44 +1362,7 @@ describe('createStartHandler request cancellation', () => { expect(cancel).toHaveBeenCalledWith(reason) }) expect(afterNext).not.toHaveBeenCalled() - expect(render).not.toHaveBeenCalled() - }) - - it('disposes a tagged final response once when abort wins handoff', async () => { - const router = makeRouter() - startMocks.router = router - const requestController = new AbortController() - const reason = new Error('request disconnected') - const ssrResponse = makeStreamResponse(router) - const dispose = vi.spyOn(ssrResponse as any, 'dispose') - const cancel = vi.spyOn(ssrResponse.response.body!, 'cancel') - startMocks.requestMiddleware = [ - createMiddleware().server(() => { - queueMicrotask(() => { - queueMicrotask(() => requestController.abort(reason)) - }) - return ssrResponse as any - }), - ] - const render = vi.fn(() => new Response('must not render')) - const handler = createStartHandler(render) - - const response = await handler( - new Request('http://localhost/', { - signal: requestController.signal, - }), - {}, - ) - - expect(response.status).toBe(500) - await vi.waitFor(() => { - expect(dispose).toHaveBeenCalledOnce() - expect(dispose).toHaveBeenCalledWith(reason) - expect(cancel).toHaveBeenCalledOnce() - expect(cancel).toHaveBeenCalledWith(reason) - }) - expect(router.serverSsr).toBeUndefined() - expect(render).not.toHaveBeenCalled() + expect(render).toHaveBeenCalledOnce() }) it('ignores a late same-body alias after catch disposes its owner', async () => { @@ -950,14 +1394,15 @@ describe('createStartHandler request cancellation', () => { return wrapped }), ] + const cancel = vi.fn() const response = new Response( new ReadableStream({ start(controller) { controller.enqueue(new TextEncoder().encode('stream')) }, + cancel, }), ) - const cancel = vi.spyOn(response.body!, 'cancel') let ssrResponse!: ReturnType const render = vi.fn(({ router: requestRouter }) => { ssrResponse = createSsrStreamResponse(requestRouter, response) diff --git a/packages/start-server-core/tests/frame-protocol.test.ts b/packages/start-server-core/tests/frame-protocol.test.ts index 380f3a8351..4d5a13f301 100644 --- a/packages/start-server-core/tests/frame-protocol.test.ts +++ b/packages/start-server-core/tests/frame-protocol.test.ts @@ -1,15 +1,19 @@ -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { FRAME_HEADER_SIZE, + MAX_FRAME_PAYLOAD_SIZE, FrameType, createMultiplexedStream, - encodeChunkFrame, - encodeEndFrame, encodeErrorFrame, encodeFrame, encodeJSONFrame, } from '../src/frame-protocol' +const encodeChunkFrame = (streamId: number, chunk: Uint8Array) => + encodeFrame(FrameType.CHUNK, streamId, chunk) +const encodeEndFrame = (streamId: number) => + encodeFrame(FrameType.END, streamId, new Uint8Array()) + describe('frame-protocol', () => { describe('encodeFrame', () => { it('should encode frame with header and payload', () => { @@ -55,32 +59,13 @@ describe('frame-protocol', () => { const payload = frame.slice(FRAME_HEADER_SIZE) expect(new TextDecoder().decode(payload)).toBe(json) }) - }) - describe('encodeChunkFrame', () => { - it('should encode binary chunk with frame type CHUNK', () => { - const chunk = new Uint8Array([0xff, 0xfe, 0xfd]) - const frame = encodeChunkFrame(123, chunk) + it('should reject payloads larger than the client decoder limit', () => { + const json = 'x'.repeat(MAX_FRAME_PAYLOAD_SIZE + 1) - const view = new DataView(frame.buffer) - expect(view.getUint8(0)).toBe(FrameType.CHUNK) - expect(view.getUint32(1, false)).toBe(123) - expect(view.getUint32(5, false)).toBe(3) - - expect(frame.slice(FRAME_HEADER_SIZE)).toEqual(chunk) - }) - }) - - describe('encodeEndFrame', () => { - it('should encode end frame with empty payload', () => { - const frame = encodeEndFrame(456) - - expect(frame.length).toBe(FRAME_HEADER_SIZE) - - const view = new DataView(frame.buffer) - expect(view.getUint8(0)).toBe(FrameType.END) - expect(view.getUint32(1, false)).toBe(456) - expect(view.getUint32(5, false)).toBe(0) + expect(() => encodeJSONFrame(json)).toThrow( + `Frame payload too large: ${json.length} bytes (max ${MAX_FRAME_PAYLOAD_SIZE})`, + ) }) }) @@ -109,19 +94,30 @@ describe('frame-protocol', () => { const payload = frame.slice(FRAME_HEADER_SIZE) expect(new TextDecoder().decode(payload)).toBe('Unknown error') }) + + it('should truncate error payloads to the client decoder limit', () => { + const frame = encodeErrorFrame( + 1, + new Error('x'.repeat(MAX_FRAME_PAYLOAD_SIZE + 1)), + ) + const view = new DataView(frame.buffer, frame.byteOffset) + + expect(view.getUint32(5, false)).toBe(MAX_FRAME_PAYLOAD_SIZE) + expect(frame.length).toBe(FRAME_HEADER_SIZE + MAX_FRAME_PAYLOAD_SIZE) + }) }) describe('createMultiplexedStream', () => { it('should multiplex JSON stream only', async () => { - const jsonStream = new ReadableStream({ + const jsonStream = new ReadableStream({ start(controller) { - controller.enqueue('{"data":1}') - controller.enqueue('{"data":2}') + controller.enqueue(encodeJSONFrame('{"data":1}')) + controller.enqueue(encodeJSONFrame('{"data":2}')) controller.close() }, }) - const multiplexed = createMultiplexedStream( + const [multiplexed] = createMultiplexedStream( jsonStream, new Map(), // no raw streams ) @@ -145,9 +141,9 @@ describe('frame-protocol', () => { }) it('should multiplex JSON and raw streams', async () => { - const jsonStream = new ReadableStream({ + const jsonStream = new ReadableStream({ start(controller) { - controller.enqueue('{"result":"ok"}') + controller.enqueue(encodeJSONFrame('{"result":"ok"}')) controller.close() }, }) @@ -162,7 +158,7 @@ describe('frame-protocol', () => { const rawStreams = new Map>() rawStreams.set(5, rawStream) - const multiplexed = createMultiplexedStream(jsonStream, rawStreams) + const [multiplexed] = createMultiplexedStream(jsonStream, rawStreams) const reader = multiplexed.getReader() const chunks: Array = [] @@ -191,10 +187,10 @@ describe('frame-protocol', () => { let jsonCancelled = false let rawCancelled = false - const jsonStream = new ReadableStream({ + const jsonStream = new ReadableStream({ async start(controller) { await new Promise((r) => setTimeout(r, 100)) - controller.enqueue('{}\n') + controller.enqueue(encodeJSONFrame('{}\n')) controller.close() }, cancel() { @@ -216,7 +212,7 @@ describe('frame-protocol', () => { const rawStreams = new Map>() rawStreams.set(1, rawStream) - const multiplexed = createMultiplexedStream(jsonStream, rawStreams) + const [multiplexed] = createMultiplexedStream(jsonStream, rawStreams) const reader = multiplexed.getReader() // Cancel immediately before streams complete @@ -224,8 +220,186 @@ describe('frame-protocol', () => { await reader.cancel() // Underlying reader.cancel should propagate to sources - expect(jsonCancelled).toBe(true) - expect(rawCancelled).toBe(true) + await vi.waitFor(() => { + expect(jsonCancelled).toBe(true) + expect(rawCancelled).toBe(true) + }) + }) + + it('should cancel a registered raw stream with the output cancellation reason', async () => { + let rawCancelReason: unknown + const rawStream = new ReadableStream({ + cancel(reason) { + rawCancelReason = reason + }, + }) + const [output, registerRaw] = createMultiplexedStream( + new ReadableStream(), + new Map(), + ) + const reason = new Error('output cancelled') + + registerRaw(1, rawStream) + await output.cancel(reason) + + await vi.waitFor(() => { + expect(rawCancelReason).toBe(reason) + }) + }) + + it('should isolate a reused raw stream failure from healthy frames', async () => { + const reusedStream = new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array([1])) + controller.close() + }, + }) + const healthyStream = new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array([3])) + controller.close() + }, + }) + const jsonStream = new ReadableStream({ + start(controller) { + controller.enqueue(encodeJSONFrame('{}')) + controller.close() + }, + }) + const reader = createMultiplexedStream( + jsonStream, + new Map([ + [1, reusedStream], + [2, reusedStream], + [3, healthyStream], + ]), + )[0].getReader() + const frames: Array = [] + + while (true) { + const { done, value } = await reader.read() + if (done) { + break + } + frames.push(value) + } + + const frameMetadata = frames.map((frame) => { + const view = new DataView(frame.buffer, frame.byteOffset) + return { + type: view.getUint8(0), + streamId: view.getUint32(1, false), + } + }) + + expect(frameMetadata).toContainEqual({ + type: FrameType.JSON, + streamId: 0, + }) + expect(frameMetadata).toContainEqual({ + type: FrameType.CHUNK, + streamId: 1, + }) + expect(frameMetadata).toContainEqual({ + type: FrameType.END, + streamId: 1, + }) + expect(frameMetadata).toContainEqual({ + type: FrameType.ERROR, + streamId: 2, + }) + expect(frameMetadata).toContainEqual({ + type: FrameType.CHUNK, + streamId: 3, + }) + expect(frameMetadata).toContainEqual({ + type: FrameType.END, + streamId: 3, + }) + }) + + it('should split oversized raw chunks into client-decodable frames', async () => { + const oversizedChunk = new Uint8Array(MAX_FRAME_PAYLOAD_SIZE + 1) + oversizedChunk[0] = 1 + oversizedChunk[MAX_FRAME_PAYLOAD_SIZE] = 2 + const rawStream = new ReadableStream({ + start(controller) { + controller.enqueue(oversizedChunk) + controller.close() + }, + }) + const jsonStream = new ReadableStream({ + start(controller) { + controller.close() + }, + }) + const reader = createMultiplexedStream( + jsonStream, + new Map([[1, rawStream]]), + )[0].getReader() + const frames: Array = [] + + while (true) { + const { done, value } = await reader.read() + if (done) { + break + } + frames.push(value) + } + + const chunkFrames = frames.filter((frame) => { + return frame[0] === FrameType.CHUNK + }) + expect(chunkFrames).toHaveLength(2) + expect( + chunkFrames.map((frame) => { + return new DataView(frame.buffer, frame.byteOffset).getUint32( + 5, + false, + ) + }), + ).toEqual([MAX_FRAME_PAYLOAD_SIZE, 1]) + expect(chunkFrames[0]![FRAME_HEADER_SIZE]).toBe(1) + expect(chunkFrames[1]![FRAME_HEADER_SIZE]).toBe(2) + expect(frames.at(-1)?.[0]).toBe(FrameType.END) + }) + + it('should stop pulling inputs while the output is backpressured', async () => { + let pulls = 0 + let rawCancelled = false + const rawStream = new ReadableStream({ + pull(controller) { + pulls++ + controller.enqueue(new Uint8Array(1024)) + if (pulls === 100) { + controller.close() + } + }, + cancel() { + rawCancelled = true + }, + }) + + const jsonStream = new ReadableStream({ + start(controller) { + controller.close() + }, + }) + const [multiplexed] = createMultiplexedStream( + jsonStream, + new Map([[1, rawStream]]), + ) + + await new Promise((resolve) => setTimeout(resolve, 0)) + + // One frame may be queued, one held by the pump, and one prefetched by + // the input stream. The remaining chunks must wait for output demand. + expect(pulls).toBeLessThanOrEqual(3) + + await multiplexed.cancel() + await vi.waitFor(() => { + expect(rawCancelled).toBe(true) + }) }) it('should interleave multiple raw streams correctly', async () => { @@ -235,9 +409,9 @@ describe('frame-protocol', () => { const gate1 = new Promise((r) => (resolve1 = r)) const gate2 = new Promise((r) => (resolve2 = r)) - const jsonStream = new ReadableStream({ + const jsonStream = new ReadableStream({ start(controller) { - controller.enqueue('{"streams":[1,2]}') + controller.enqueue(encodeJSONFrame('{"streams":[1,2]}')) controller.close() }, }) @@ -264,7 +438,7 @@ describe('frame-protocol', () => { rawStreams.set(1, rawStream1) rawStreams.set(2, rawStream2) - const multiplexed = createMultiplexedStream(jsonStream, rawStreams) + const [multiplexed] = createMultiplexedStream(jsonStream, rawStreams) const reader = multiplexed.getReader() const chunks: Array = [] @@ -301,42 +475,32 @@ describe('frame-protocol', () => { }) it('should handle late stream registration', async () => { - const jsonStream = new ReadableStream({ + let jsonController!: ReadableStreamDefaultController + const jsonStream = new ReadableStream({ start(controller) { - controller.enqueue('{"ref":99}') - controller.close() + jsonController = controller + controller.enqueue(encodeJSONFrame('{"ref":99}')) }, }) - // Late stream source that emits a registration after a delay - // (ensures framed protocol doesn't miss late-stream messages) let resolveGate: () => void const gate = new Promise((r) => (resolveGate = r)) - - const lateStreamSource = new ReadableStream<{ - id: number - stream: ReadableStream - }>({ - async start(controller) { - await gate - controller.enqueue({ - id: 99, - stream: new ReadableStream({ - start(c) { - c.enqueue(new Uint8Array([0xaa, 0xbb])) - c.close() - }, - }), - }) - controller.close() - }, - }) - - const multiplexed = createMultiplexedStream( + const [multiplexed, registerRaw] = createMultiplexedStream( jsonStream, new Map(), - lateStreamSource, ) + const register = gate.then(() => { + registerRaw( + 99, + new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array([0xaa, 0xbb])) + controller.close() + }, + }), + ) + jsonController.close() + }) const reader = multiplexed.getReader() const chunks: Array = [] @@ -347,6 +511,7 @@ describe('frame-protocol', () => { // Release gate to let late stream arrive resolveGate!() + await register // Read remaining frames while (true) { @@ -378,37 +543,26 @@ describe('frame-protocol', () => { let startJson: () => void const jsonGate = new Promise((r) => (startJson = r)) - const jsonStream = new ReadableStream({ + const jsonStream = new ReadableStream({ async start(controller) { await jsonGate - controller.enqueue('{"ref":1}') + controller.enqueue(encodeJSONFrame('{"ref":1}')) controller.close() }, }) - // Late stream registers immediately (before JSON starts) - const lateStreamSource = new ReadableStream<{ - id: number - stream: ReadableStream - }>({ - start(controller) { - controller.enqueue({ - id: 1, - stream: new ReadableStream({ - start(c) { - c.enqueue(new Uint8Array([0x01])) - c.close() - }, - }), - }) - controller.close() - }, - }) - - const multiplexed = createMultiplexedStream( + const [multiplexed, registerRaw] = createMultiplexedStream( jsonStream, new Map(), - lateStreamSource, + ) + registerRaw( + 1, + new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array([0x01])) + controller.close() + }, + }), ) const reader = multiplexed.getReader() @@ -436,46 +590,37 @@ describe('frame-protocol', () => { }) it('should handle multiple late stream registrations', async () => { - const jsonStream = new ReadableStream({ + let jsonController!: ReadableStreamDefaultController + const jsonStream = new ReadableStream({ start(controller) { - controller.enqueue('{}') - controller.close() + jsonController = controller + controller.enqueue(encodeJSONFrame('{}')) }, }) - const lateStreamSource = new ReadableStream<{ - id: number - stream: ReadableStream - }>({ - start(controller) { - // Register two streams - controller.enqueue({ - id: 10, - stream: new ReadableStream({ - start(c) { - c.enqueue(new Uint8Array([10])) - c.close() - }, - }), - }) - controller.enqueue({ - id: 20, - stream: new ReadableStream({ - start(c) { - c.enqueue(new Uint8Array([20])) - c.close() - }, - }), - }) - controller.close() - }, - }) - - const multiplexed = createMultiplexedStream( + const [multiplexed, registerRaw] = createMultiplexedStream( jsonStream, new Map(), - lateStreamSource, ) + registerRaw( + 10, + new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array([10])) + controller.close() + }, + }), + ) + registerRaw( + 20, + new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array([20])) + controller.close() + }, + }), + ) + jsonController.close() const reader = multiplexed.getReader() const chunks: Array = [] @@ -504,11 +649,11 @@ describe('frame-protocol', () => { let resolveJson: () => void const jsonGate = new Promise((r) => (resolveJson = r)) - const jsonStream = new ReadableStream({ + const jsonStream = new ReadableStream({ async start(controller) { - controller.enqueue('{"first":true}') + controller.enqueue(encodeJSONFrame('{"first":true}')) await jsonGate - controller.enqueue('{"second":true}') + controller.enqueue(encodeJSONFrame('{"second":true}')) controller.close() }, }) @@ -524,29 +669,18 @@ describe('frame-protocol', () => { const rawStreams = new Map>() rawStreams.set(1, initialRaw) - // Late stream arrives after first JSON - const lateStreamSource = new ReadableStream<{ - id: number - stream: ReadableStream - }>({ - start(controller) { - controller.enqueue({ - id: 2, - stream: new ReadableStream({ - start(c) { - c.enqueue(new Uint8Array([2])) - c.close() - }, - }), - }) - controller.close() - }, - }) - - const multiplexed = createMultiplexedStream( + const [multiplexed, registerRaw] = createMultiplexedStream( jsonStream, rawStreams, - lateStreamSource, + ) + registerRaw( + 2, + new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array([2])) + controller.close() + }, + }), ) const reader = multiplexed.getReader() @@ -583,9 +717,9 @@ describe('frame-protocol', () => { }) it('should handle raw stream error', async () => { - const jsonStream = new ReadableStream({ + const jsonStream = new ReadableStream({ start(controller) { - controller.enqueue('{}') + controller.enqueue(encodeJSONFrame('{}')) controller.close() }, }) @@ -599,7 +733,7 @@ describe('frame-protocol', () => { const rawStreams = new Map>() rawStreams.set(10, errorStream) - const multiplexed = createMultiplexedStream(jsonStream, rawStreams) + const [multiplexed] = createMultiplexedStream(jsonStream, rawStreams) const reader = multiplexed.getReader() const chunks: Array = [] @@ -631,11 +765,11 @@ describe('frame-protocol', () => { }) it('should propagate JSON stream error to output (fatal)', async () => { - let errorController: ReadableStreamDefaultController - const jsonStream = new ReadableStream({ + let errorController: ReadableStreamDefaultController + const jsonStream = new ReadableStream({ start(controller) { errorController = controller - controller.enqueue('{"first":true}') + controller.enqueue(encodeJSONFrame('{"first":true}')) }, }) @@ -651,7 +785,7 @@ describe('frame-protocol', () => { const rawStreams = new Map>() rawStreams.set(1, rawStream) - const multiplexed = createMultiplexedStream(jsonStream, rawStreams) + const [multiplexed] = createMultiplexedStream(jsonStream, rawStreams) const reader = multiplexed.getReader() // Should be able to read first JSON frame @@ -669,9 +803,9 @@ describe('frame-protocol', () => { it('should not hang when raw stream never ends', async () => { // This tests the fix for hanging requests - const jsonStream = new ReadableStream({ + const jsonStream = new ReadableStream({ start(controller) { - controller.enqueue('{}') + controller.enqueue(encodeJSONFrame('{}')) controller.close() }, }) @@ -690,7 +824,7 @@ describe('frame-protocol', () => { const rawStreams = new Map>() rawStreams.set(1, neverEndingStream) - const multiplexed = createMultiplexedStream(jsonStream, rawStreams) + const [multiplexed] = createMultiplexedStream(jsonStream, rawStreams) const reader = multiplexed.getReader() // Read first two frames (JSON and CHUNK) @@ -704,7 +838,9 @@ describe('frame-protocol', () => { await reader.cancel() // The underlying raw stream should be cancelled - expect(rawStreamCancelled).toBe(true) + await vi.waitFor(() => { + expect(rawStreamCancelled).toBe(true) + }) }) }) }) diff --git a/packages/start-server-core/tests/server-functions-handler.test.ts b/packages/start-server-core/tests/server-functions-handler.test.ts new file mode 100644 index 0000000000..593f9284e0 --- /dev/null +++ b/packages/start-server-core/tests/server-functions-handler.test.ts @@ -0,0 +1,247 @@ +// @vitest-environment node + +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { + RawStream, + createSerializationAdapter, + defaultSerovalPlugins, + makeSerovalPlugin, +} from '@tanstack/router-core' +import { + FRAME_HEADER_SIZE, + MAX_FRAME_PAYLOAD_SIZE, + MAX_FRAMED_STREAMS, + TSS_CONTENT_TYPE_FRAMED_VERSIONED, +} from '@tanstack/start-client-core' +import { handleServerAction } from '../src/server-functions-handler' + +const handlerMocks = vi.hoisted(() => ({ + action: vi.fn(), + serializationDestroyed: vi.fn(), + serializationPlugins: [] as Array, +})) + +vi.mock('../src/getServerFnById', () => ({ + getServerFnById: async () => handlerMocks.action, +})) + +vi.mock('../src/request-response', () => ({ + getResponse: () => ({ status: 200, statusText: 'OK' }), +})) + +vi.mock('@tanstack/start-client-core', async (importOriginal) => { + const actual = + await importOriginal() + return { + ...actual, + getDefaultSerovalPlugins: () => [ + ...handlerMocks.serializationPlugins, + ...defaultSerovalPlugins, + ], + } +}) + +vi.mock('seroval', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + toCrossJSONStream( + ...args: Parameters + ): ReturnType { + const destroy = actual.toCrossJSONStream(...args) + return (() => { + handlerMocks.serializationDestroyed() + destroy() + }) as ReturnType + }, + } +}) + +function createDeferred() { + let resolve!: (value: T) => void + const promise = new Promise((promiseResolve) => { + resolve = promiseResolve + }) + return { promise, resolve } +} + +class ThrowDuringSerialization {} + +const serializationFailure = new Error('custom serialization failed') +handlerMocks.serializationPlugins.push( + makeSerovalPlugin( + createSerializationAdapter({ + key: 'throw-during-serialization-test', + test: (value): value is ThrowDuringSerialization => { + return value instanceof ThrowDuringSerialization + }, + toSerializable: (): unknown => { + throw serializationFailure + }, + fromSerializable: () => new ThrowDuringSerialization(), + }), + ), +) + +async function createServerFnResponse(result: unknown): Promise { + handlerMocks.action.mockResolvedValue({ result }) + const response = await handleServerAction({ + request: new Request('http://localhost/_serverFn/test', { + method: 'POST', + headers: { 'x-tsr-serverFn': 'true' }, + }), + context: {}, + serverFnId: 'test', + }) + + expect(response.headers.get('Content-Type')).toBe( + TSS_CONTENT_TYPE_FRAMED_VERSIONED, + ) + return response +} + +describe('server-functions-handler framed responses', () => { + beforeEach(() => { + handlerMocks.action.mockReset() + handlerMocks.serializationDestroyed.mockClear() + }) + + it('destroys pending Seroval work when the response is cancelled', async () => { + const pendingResult = createDeferred() + const response = await createServerFnResponse(pendingResult.promise) + const reason = new Error('consumer disconnected') + + await response.body!.cancel(reason) + + await vi.waitFor(() => { + expect(handlerMocks.serializationDestroyed).toHaveBeenCalledTimes(1) + }) + }) + + it('destroys pending work and cancels raw streams when initial serialization fails', async () => { + const cancel = vi.fn() + const pending = new Promise(() => {}) + const consoleError = vi + .spyOn(console, 'error') + .mockImplementation(() => undefined) + handlerMocks.action.mockResolvedValue({ + result: [ + pending, + new RawStream(new ReadableStream({ cancel })), + new ThrowDuringSerialization(), + ], + }) + try { + const response = await handleServerAction({ + request: new Request('http://localhost/_serverFn/test', { + method: 'POST', + headers: { 'x-tsr-serverFn': 'true' }, + }), + context: {}, + serverFnId: 'test', + }) + + expect(response.headers.get('Content-Type')).toBe('application/json') + expect(handlerMocks.serializationDestroyed).toHaveBeenCalledOnce() + expect(cancel).toHaveBeenCalledOnce() + expect(cancel).toHaveBeenCalledWith(serializationFailure) + } finally { + consoleError.mockRestore() + } + }) + + it('cancels every late raw stream when the output is cancelled', async () => { + const pendingResult = createDeferred>() + const cancelReasons: Array> = [[], [], []] + let resolveFirstPull!: () => void + const firstPull = new Promise((resolve) => { + resolveFirstPull = resolve + }) + let firstStream!: ReadableStream + firstStream = new ReadableStream({ + pull() { + if (firstStream.locked) { + resolveFirstPull() + } + }, + cancel(reason) { + cancelReasons[0]!.push(reason) + }, + }) + const streams = [ + firstStream, + ...cancelReasons.slice(1).map((reasons) => { + return new ReadableStream({ + cancel(reason) { + reasons.push(reason) + }, + }) + }), + ] + const reason = new Error('consumer disconnected') + + const response = await createServerFnResponse(pendingResult.promise) + pendingResult.resolve( + streams.map((stream) => { + return new RawStream(stream) + }), + ) + + await firstPull + await response.body!.cancel(reason) + + await vi.waitFor(() => { + expect(cancelReasons).toEqual([[reason], [reason], [reason]]) + }) + }) + + it('rejects excess raw streams discovered after the response starts', async () => { + const pendingResult = createDeferred>() + const response = await createServerFnResponse(pendingResult.promise) + let cancellations = 0 + pendingResult.resolve( + Array.from({ length: MAX_FRAMED_STREAMS + 1 }, () => { + return new RawStream( + new ReadableStream({ + cancel() { + cancellations++ + }, + }), + ) + }), + ) + + await expect(response.text()).rejects.toThrow( + `Too many raw streams in framed response (max ${MAX_FRAMED_STREAMS})`, + ) + await vi.waitFor(() => { + expect(cancellations).toBe(MAX_FRAMED_STREAMS + 1) + }) + }) + + it('bounds queued JSON while the response consumer is stalled', async () => { + const pendingValues = [ + createDeferred(), + createDeferred(), + createDeferred(), + ] + const response = await createServerFnResponse( + pendingValues.map(({ promise }) => promise), + ) + const largeValue = 'x'.repeat( + Math.floor(MAX_FRAME_PAYLOAD_SIZE / 2) + 1024, + ) + + for (const pendingValue of pendingValues) { + pendingValue.resolve(largeValue) + await new Promise((resolve) => { + setTimeout(resolve, 0) + }) + } + + await expect(response.text()).rejects.toThrow( + `Framed JSON queue exceeded ${FRAME_HEADER_SIZE + MAX_FRAME_PAYLOAD_SIZE} bytes`, + ) + expect(handlerMocks.serializationDestroyed).toHaveBeenCalledOnce() + }) +}) diff --git a/packages/vue-router/src/CatchBoundary.tsx b/packages/vue-router/src/CatchBoundary.tsx index e912445158..96ff495228 100644 --- a/packages/vue-router/src/CatchBoundary.tsx +++ b/packages/vue-router/src/CatchBoundary.tsx @@ -8,6 +8,25 @@ type CatchBoundaryProps = { onCatch?: (error: Error) => void } +const ErrorCatcher = Vue.defineComponent({ + props: { + onError: Function, + children: null, + }, + setup(props) { + Vue.onErrorCaptured((err: Error) => { + if (typeof (err as any).then === 'function') { + return false + } + + props.onError?.(err) + return false + }) + + return () => props.children as Vue.VNode + }, +}) + const VueErrorBoundary = Vue.defineComponent({ name: 'VueErrorBoundary', props: { @@ -23,6 +42,13 @@ const VueErrorBoundary = Vue.defineComponent({ error.value = null } + const onError = (err: Error) => { + if (!error.value) { + error.value = err + props.onError?.(err) + } + } + Vue.watch( () => props.resetKey, (newKey, oldKey) => { @@ -32,30 +58,13 @@ const VueErrorBoundary = Vue.defineComponent({ }, ) - Vue.onErrorCaptured((err: Error) => { - if ( - err instanceof Promise || - (err && typeof (err as any).then === 'function') - ) { - return false - } - - error.value = err - - if (props.onError) { - props.onError(err) - } - - return false - }) - return () => error.value ? Vue.h(props.errorComponent ?? ErrorComponent, { error: error.value, reset, }) - : (props.children as Vue.VNode) + : Vue.h(ErrorCatcher, { onError, children: props.children }) }, }) diff --git a/packages/vue-router/src/headContentUtils.tsx b/packages/vue-router/src/headContentUtils.tsx index adfc156c72..9ec5453b10 100644 --- a/packages/vue-router/src/headContentUtils.tsx +++ b/packages/vue-router/src/headContentUtils.tsx @@ -22,30 +22,6 @@ export const useTags = (assetCrossOrigin?: AssetCrossOriginConfig) => { const currentMatches = matches.value const tags: Array = [] const manifest = router.ssr?.manifest - for (const match of currentMatches) { - for (const link of manifest?.routes[match.routeId]?.css ?? []) { - const resolvedLink = resolveManifestCssLink(link) - tags.push({ - tag: 'link', - attrs: { - rel: 'stylesheet', - ...resolvedLink, - crossOrigin: - getAssetCrossOrigin(assetCrossOrigin, 'stylesheet') ?? - resolvedLink.crossOrigin, - }, - }) - } - } - if (manifest?.inlineStyle) { - tags.push({ - tag: 'style', - attrs: manifest.inlineStyle.attrs, - children: manifest.inlineStyle.children, - inlineCss: true, - }) - } - const resultMeta: Array = [] const metaByAttribute: Record = {} let title: RouterManagedTag | undefined @@ -101,21 +77,36 @@ export const useTags = (assetCrossOrigin?: AssetCrossOriginConfig) => { resultMeta.push(title) } resultMeta.reverse() - appendUniqueUserTags(tags, resultMeta) const preloads: Array = [] const links: Array = [] const headScripts: Array = [] for (const match of currentMatches) { - for (const preload of manifest?.routes[match.routeId]?.preloads ?? []) { - if (preload) { - preloads.push({ + const manifestRoute = manifest?.routes[match.routeId] + if (manifestRoute) { + for (const link of manifestRoute.css ?? []) { + const resolvedLink = resolveManifestCssLink(link) + tags.push({ tag: 'link', attrs: { - ...getScriptPreloadAttrs(manifest, preload, assetCrossOrigin), + rel: 'stylesheet', + ...resolvedLink, + crossOrigin: + getAssetCrossOrigin(assetCrossOrigin, 'stylesheet') ?? + resolvedLink.crossOrigin, }, }) } + for (const preload of manifestRoute.preloads ?? []) { + if (preload) { + preloads.push({ + tag: 'link', + attrs: { + ...getScriptPreloadAttrs(manifest, preload, assetCrossOrigin), + }, + }) + } + } } for (const link of match.links ?? []) { if (link) { @@ -133,6 +124,15 @@ export const useTags = (assetCrossOrigin?: AssetCrossOriginConfig) => { } } } + if (manifest?.inlineStyle) { + tags.push({ + tag: 'style', + attrs: manifest.inlineStyle.attrs, + children: manifest.inlineStyle.children, + inlineCss: true, + }) + } + appendUniqueUserTags(tags, resultMeta) tags.push(...preloads) appendUniqueUserTags(tags, links) appendUniqueUserTags(tags, headScripts) diff --git a/packages/vue-router/src/lazyRouteComponent.tsx b/packages/vue-router/src/lazyRouteComponent.tsx index 527f3d15ad..a9d2b8bec1 100644 --- a/packages/vue-router/src/lazyRouteComponent.tsx +++ b/packages/vue-router/src/lazyRouteComponent.tsx @@ -1,25 +1,10 @@ import * as Vue from 'vue' +import { isModuleNotFoundError } from '@tanstack/router-core' +import { isServer } from '@tanstack/router-core/isServer' import { Outlet } from './Match' import { ClientOnly } from './ClientOnly' import type { AsyncRouteComponent } from './route' -// If the load fails due to module not found, it may mean a new version of -// the build was deployed and the user's browser is still using an old version. -// If this happens, the old version in the user's browser would have an outdated -// URL to the lazy module. -// In that case, we want to attempt one window refresh to get the latest. -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." - if (typeof error?.message !== 'string') return false - return ( - error.message.startsWith('Failed to fetch dynamically imported module') || - error.message.startsWith('error loading dynamically imported module') || - error.message.startsWith('Importing a module script failed') - ) -} - export function lazyRouteComponent< T extends Record, TKey extends keyof T = 'default', @@ -30,41 +15,36 @@ export function lazyRouteComponent< ): T[TKey] extends (props: infer TProps) => any ? AsyncRouteComponent : never { - let loadPromise: Promise | undefined + let loadPromise: Promise | undefined let comp: T[TKey] | T['default'] | null = null let error: any = null - let attemptedReload = false const load = () => { // If we're on the server and SSR is disabled for this component - if (typeof document === 'undefined' && ssr?.() === false) { + if ((isServer ?? typeof document === 'undefined') && ssr?.() === false) { comp = (() => null) as any - return Promise.resolve(comp) + return Promise.resolve() } - // Use existing promise or create new one - if (!loadPromise) { - error = undefined - loadPromise = importer() - .then((res) => { - loadPromise = undefined - comp = res[exportName ?? 'default'] - return comp - }) - .catch((err) => { - error = err - loadPromise = undefined + if (loadPromise) { + return loadPromise + } - // If it's a module not found error, we'll try to handle it in the component - if (isModuleNotFoundError(error)) { - return null - } + error = null + return (loadPromise = importer() + .then((res) => { + loadPromise = undefined + comp = res[exportName ?? 'default'] + }) + .catch((err) => { + error = err + loadPromise = undefined + // Missing modules are handled when the component renders. + if (!isModuleNotFoundError(err)) { throw err - }) - } - - return loadPromise + } + })) } // Create a lazy component wrapper using defineComponent so it works in Vue SFC templates @@ -72,59 +52,43 @@ export function lazyRouteComponent< name: 'LazyRouteComponent', setup(props: any) { // Create refs to track component state - // Use shallowRef for component to avoid making it reactive (Vue warning) - const component = Vue.shallowRef(comp ? Vue.markRaw(comp) : comp) + const component = Vue.shallowRef(comp) const errorState = Vue.ref(error) - const loading = Vue.ref(!component.value && !errorState.value) // Setup effect to load the component when this component is used Vue.onMounted(() => { if (!component.value && !errorState.value) { - loading.value = true - load() - .then((result) => { - // Use markRaw to prevent Vue from making the component reactive - component.value = result ? Vue.markRaw(result) : result - loading.value = false + .then(() => { + errorState.value = error + component.value = comp }) .catch((err) => { errorState.value = err - loading.value = false }) } }) - // Handle module not found error with reload attempt - if ( - errorState.value && - isModuleNotFoundError(errorState.value) && - !attemptedReload - ) { - if ( - typeof window !== 'undefined' && - typeof sessionStorage !== 'undefined' - ) { - // Try to reload once on module not found error - const storageKey = `tanstack_router_reload:${errorState.value.message}` - if (!sessionStorage.getItem(storageKey)) { - sessionStorage.setItem(storageKey, '1') - attemptedReload = true - window.location.reload() - return () => null // Return empty while reloading - } - } - } - - // If we have a non-module-not-found error, throw it - if (errorState.value && !isModuleNotFoundError(errorState.value)) { - throw errorState.value - } - // Return a render function return () => { + if (errorState.value) { + if ( + isModuleNotFoundError(errorState.value) && + !(isServer ?? typeof window === 'undefined') && + typeof sessionStorage !== 'undefined' + ) { + const storageKey = `tanstack_router_reload:${errorState.value.message}` + if (!sessionStorage.getItem(storageKey)) { + sessionStorage.setItem(storageKey, '1') + window.location.reload() + return null + } + } + throw errorState.value + } + // If we're still loading or don't have a component yet, use a suspense pattern - if (loading.value || !component.value) { + if (!component.value) { return Vue.h('div', null) // Empty div while loading } diff --git a/packages/vue-router/tests/CatchBoundary.test.tsx b/packages/vue-router/tests/CatchBoundary.test.tsx new file mode 100644 index 0000000000..a792ec7684 --- /dev/null +++ b/packages/vue-router/tests/CatchBoundary.test.tsx @@ -0,0 +1,144 @@ +import { afterEach, expect, test, vi } from 'vitest' +import * as Vue from 'vue' +import { cleanup, fireEvent, render, screen } from '@testing-library/vue' +import { CatchBoundary } from '../src' +import type { ErrorComponentProps } from '../src' + +afterEach(() => { + cleanup() + vi.restoreAllMocks() +}) + +const unmountHooks = [ + ['before unmount', Vue.onBeforeUnmount], + ['after unmount', Vue.onUnmounted], +] as const + +test.each(unmountHooks)( + 'keeps ownership of errors thrown by the failed child tree %s hook', + async (_, onUnmount) => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + + const shouldThrow = Vue.ref(false) + const cleanupChild = vi.fn(() => { + throw new Error('child cleanup failed') + }) + const innerCatch = vi.fn() + const Child = Vue.defineComponent({ + setup() { + onUnmount(cleanupChild) + return () => { + if (shouldThrow.value) { + throw new Error('child render failed') + } + return Vue.h('p', null, 'child content') + } + }, + }) + const InnerError = (props: ErrorComponentProps) => ( +

inner: {props.error.message}

+ ) + const OuterError = (props: ErrorComponentProps) => ( +

outer: {props.error.message}

+ ) + const App = Vue.defineComponent({ + setup() { + return () => + CatchBoundary({ + getResetKey: () => 0, + errorComponent: OuterError, + children: CatchBoundary({ + getResetKey: () => 0, + errorComponent: InnerError, + onCatch: innerCatch, + children: Vue.h(Child), + }), + }) + }, + }) + + render() + expect(await screen.findByText('child content')).toBeInTheDocument() + + shouldThrow.value = true + + expect( + await screen.findByText('inner: child render failed'), + ).toBeInTheDocument() + expect(cleanupChild).toHaveBeenCalledOnce() + expect(innerCatch).toHaveBeenCalledOnce() + expect(innerCatch.mock.calls[0]![0]).toMatchObject({ + message: 'child render failed', + }) + expect(screen.queryByRole('alert')).not.toBeInTheDocument() + }, +) + +test.each(unmountHooks)( + 'propagates errors thrown by the fallback %s hook during reset', + async (_, onUnmount) => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + + const shouldThrow = Vue.ref(true) + const cleanupFallback = vi.fn(() => { + throw new Error('fallback cleanup failed') + }) + const Child = Vue.defineComponent({ + setup() { + return () => { + if (shouldThrow.value) { + throw new Error('child render failed') + } + return Vue.h('p', null, 'child content') + } + }, + }) + const InnerError = Vue.defineComponent({ + props: { + error: { type: Error, required: true }, + reset: { type: Function, required: true }, + }, + setup(props) { + onUnmount(cleanupFallback) + return () => + Vue.h( + 'button', + { + onClick: () => { + shouldThrow.value = false + props.reset() + }, + }, + `inner: ${props.error.message}`, + ) + }, + }) + const OuterError = (props: ErrorComponentProps) => ( +

outer: {props.error.message}

+ ) + const App = Vue.defineComponent({ + setup() { + return () => + CatchBoundary({ + getResetKey: () => 0, + errorComponent: OuterError, + children: CatchBoundary({ + getResetKey: () => 0, + errorComponent: InnerError, + children: Vue.h(Child), + }), + }) + }, + }) + + render() + await fireEvent.click( + await screen.findByRole('button', { name: 'inner: child render failed' }), + ) + + expect(await screen.findByRole('alert')).toHaveTextContent( + 'outer: fallback cleanup failed', + ) + expect(cleanupFallback).toHaveBeenCalledOnce() + }, +) diff --git a/packages/vue-router/tests/component-preload-retry.test.tsx b/packages/vue-router/tests/component-preload-retry.test.tsx index 9fb8ad5f5a..c2c7526459 100644 --- a/packages/vue-router/tests/component-preload-retry.test.tsx +++ b/packages/vue-router/tests/component-preload-retry.test.tsx @@ -1,7 +1,16 @@ import { afterEach, expect, test, vi } from 'vitest' -import { cleanup, fireEvent, render, screen } from '@testing-library/vue' import { + cleanup, + fireEvent, + render, + screen, + waitFor, +} from '@testing-library/vue' +import { + Outlet, RouterProvider, + createControlledPromise, + createLazyRoute, createMemoryHistory, createRootRoute, createRoute, @@ -14,6 +23,48 @@ import type { ErrorComponentProps } from '../src' afterEach(() => { cleanup() vi.restoreAllMocks() + vi.unstubAllGlobals() + sessionStorage.clear() +}) + +test('concurrent component preloads share the import', async () => { + const componentImport = createControlledPromise<{ + default: () => null + }>() + const importer = vi.fn(() => componentImport) + const Page = lazyRouteComponent(importer) + + const first = Page.preload?.() + expect(Page.preload?.()).toBe(first) + expect(importer).toHaveBeenCalledOnce() + + componentImport.resolve({ default: () => null }) + await first +}) + +test('a component loads when rendered before preload', async () => { + const importer = vi.fn().mockResolvedValue({ + default: () =>
Page content
, + }) + const Page = lazyRouteComponent(importer) + + render() + + expect(await screen.findByText('Page content')).toBeInTheDocument() + expect(importer).toHaveBeenCalledOnce() +}) + +test('a preloaded component renders without another import', async () => { + const importer = vi.fn().mockResolvedValue({ + default: () =>
Page content
, + }) + const Page = lazyRouteComponent(importer) + + await Page.preload?.() + render() + + expect(await screen.findByText('Page content')).toBeInTheDocument() + expect(importer).toHaveBeenCalledOnce() }) test('a failed component download is retried from the route error UI', async () => { @@ -63,3 +114,184 @@ test('a failed component download is retried from the route error UI', async () expect(await screen.findByText('Page content')).toBeInTheDocument() expect(importer).toHaveBeenCalledTimes(2) }) + +test('a lazy error component failure after reload reaches the global error boundary', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + + const importFailure = new TypeError( + 'Failed to fetch dynamically imported module: /assets/error.js', + ) + sessionStorage.setItem(`tanstack_router_reload:${importFailure.message}`, '1') + const ErrorPage = () =>

Unreachable error page

+ const importer = vi + .fn<() => Promise<{ default: typeof ErrorPage }>>() + .mockRejectedValue(importFailure) + const LazyErrorPage = lazyRouteComponent(importer) + const rootRoute = createRootRoute() + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + component: () => { + throw new Error('page render failed') + }, + errorComponent: LazyErrorPage, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + render() + + expect(await screen.findByText(importFailure.message)).toBeInTheDocument() + expect(screen.getByRole('heading', { name: 'Error' })).toBeInTheDocument() + expect(importer).toHaveBeenCalledOnce() +}) + +test('reloads once when a route component preload reports a missing module', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + + const failure = new TypeError( + 'Failed to fetch dynamically imported module: /assets/page.js', + ) + const storageKey = `tanstack_router_reload:${failure.message}` + const importer = vi.fn().mockRejectedValue(failure) + const Page = lazyRouteComponent(importer) + const rootRoute = createRootRoute() + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + component: Page, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + const reload = vi.fn() + vi.stubGlobal('window', { document, location: { reload } }) + + render() + + await waitFor(() => { + expect(sessionStorage.getItem(storageKey)).toBe('1') + }) + expect(importer).toHaveBeenCalledOnce() + expect(reload).toHaveBeenCalledOnce() +}) + +test('retries a module download from the error UI after reloading once', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + + const failure = new TypeError( + 'Failed to fetch dynamically imported module: /assets/page.js', + ) + sessionStorage.setItem(`tanstack_router_reload:${failure.message}`, '1') + + const PageContent = () =>
Page content
+ const importer = vi + .fn<() => Promise<{ default: typeof PageContent }>>() + .mockRejectedValueOnce(failure) + .mockResolvedValue({ default: PageContent }) + const Page = lazyRouteComponent(importer) + + function RouteError(props: ErrorComponentProps) { + const router = useRouter() + return ( + + ) + } + + const rootRoute = createRootRoute() + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + component: Page, + errorComponent: RouteError, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + const reload = vi.fn() + vi.stubGlobal('window', { document, location: { reload } }) + + render() + await fireEvent.click(await screen.findByRole('button', { name: 'Retry' })) + + expect(await screen.findByText('Page content')).toBeInTheDocument() + expect(importer).toHaveBeenCalledTimes(2) + expect(reload).not.toHaveBeenCalled() +}) + +test('delayed lazy options replace default pending UI before the page component loads', async () => { + const loader = createControlledPromise() + const componentPreload = createControlledPromise() + const preloadComponent = vi.fn(() => componentPreload) + const Page = Object.assign(() =>

Page

, { + preload: preloadComponent, + }) + const lazyPageOptions = createLazyRoute('/page')({ + pendingComponent: () =>

Loading lazy page

, + component: Page, + }) + const lazyOptions = createControlledPromise() + const rootRoute = createRootRoute({ component: Outlet }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>

Index page

, + }) + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + loader: () => loader, + }).lazy(() => lazyOptions) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, pageRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + defaultPendingMs: 0, + defaultPendingMinMs: 0, + defaultPendingComponent: () =>

Loading default

, + }) + let navigation: Promise | undefined + + try { + render() + expect(await screen.findByText('Index page')).toBeInTheDocument() + + navigation = router.navigate({ to: '/page' }) + expect(await screen.findByRole('status')).toHaveTextContent( + 'Loading default', + ) + + lazyOptions.resolve(lazyPageOptions) + await waitFor(() => { + expect(screen.getByRole('status')).toHaveTextContent('Loading lazy page') + }) + expect(preloadComponent).toHaveBeenCalledOnce() + expect(componentPreload.status).toBe('pending') + expect(screen.queryByText('Page')).not.toBeInTheDocument() + + componentPreload.resolve() + loader.resolve() + await navigation + + expect(await screen.findByText('Page')).toBeInTheDocument() + } finally { + lazyOptions.resolve(lazyPageOptions) + componentPreload.resolve() + loader.resolve() + if (navigation) { + await Promise.allSettled([navigation]) + } + } +}) From 7b8cdfbe4f89cd862e33d8644cae7882be83df8a Mon Sep 17 00:00:00 2001 From: Manuel Schiller <6340397+schiller-manuel@users.noreply.github.com> Date: Thu, 30 Jul 2026 22:05:03 +0200 Subject: [PATCH 59/59] fix --- e2e/react-start/hmr/tests/app.spec.ts | 248 +++++- packages/react-router/src/Matches.tsx | 32 +- packages/react-router/src/Transitioner.tsx | 208 ++--- .../tests/component-preload-retry.test.tsx | 10 +- .../tests/errorComponent.test.tsx | 48 +- .../tests/preloaded-mount-resolution.test.tsx | 110 +-- .../react-render-owner-contract.test.tsx | 140 --- .../tests/transitioner-remount.test.tsx | 141 --- .../tests/transitioner-render-ack.test.tsx | 264 ++---- packages/router-core/INTERNALS.md | 56 +- packages/router-core/src/load-client.ts | 835 +++++++++--------- packages/router-core/src/router.ts | 11 +- .../tests/boundary-component-chunk.test.ts | 15 +- .../tests/hmr-refresh-lifecycle.test.ts | 385 +------- .../tests/pending-terminal-boundary.test.ts | 20 +- .../preload-public-signal-lifetime.test.ts | 31 + 16 files changed, 969 insertions(+), 1585 deletions(-) delete mode 100644 packages/react-router/tests/react-render-owner-contract.test.tsx delete mode 100644 packages/react-router/tests/transitioner-remount.test.tsx diff --git a/e2e/react-start/hmr/tests/app.spec.ts b/e2e/react-start/hmr/tests/app.spec.ts index 6c70843c04..81d367de7f 100644 --- a/e2e/react-start/hmr/tests/app.spec.ts +++ b/e2e/react-start/hmr/tests/app.spec.ts @@ -1,10 +1,10 @@ +import path from 'node:path' import { expect } from '@playwright/test' import { createHmrFileEditor, replaceAll, test, } from '@tanstack/router-e2e-utils' -import path from 'node:path' import type { Page } from '@playwright/test' @@ -38,6 +38,21 @@ const routeFilePaths = { type RouteFileKey = keyof typeof routeFilePaths +const rootLoaderBlock = " loader: () => ({\n crumb: 'Home',\n }),\n" +const redirectRootLoaderBlock = + " staleTime: Infinity,\n loader: () => ({\n crumb:\n typeof window === 'undefined'\n ? 'Home Armed'\n : (window.sessionStorage.getItem('hmr-root-crumb') ?? 'Home Armed'),\n }),\n" +const childBeforeLoadBlock = + " beforeLoad: () => ({\n greeting: 'Hello',\n }),\n" +const childLoaderBlock = " loader: () => ({\n crumb: 'Child',\n }),\n" +const failingChildOnStayBlock = + " onStay: () => {\n const match = (window as any).__TSR_ROUTER__.stores.matches\n .get()\n .find((candidate: any) => candidate.routeId === '/child')\n ;(window as any).__TSR_HMR_FAILED_SIGNAL__ = match.abortController.signal\n ;(window as any).__TSR_HMR_FAILURE_RAN__ = true\n throw new Error('intentional HMR lifecycle failure')\n },\n" +const pendingNavigationChildLoaderBlock = + " loader: async () => {\n if (typeof window !== 'undefined') {\n const gate = (window as any).__TSR_HMR_PENDING_NAV_GATE__\n if (gate) {\n ;(window as any).__TSR_HMR_PENDING_NAV_GATE__ = undefined\n ;(window as any).__TSR_HMR_PENDING_NAV_EVENTS__.push('loader-start')\n await gate\n ;(window as any).__TSR_HMR_PENDING_NAV_EVENTS__.push('loader-end')\n }\n }\n return { crumb: 'Child' }\n },\n" +const pendingNavigationChildOnStayBlock = + " onStay: () => {\n ;(window as any).__TSR_HMR_PENDING_NAV_EVENTS__.push('onStay')\n throw new Error('intentional HMR failure after pending navigation')\n },\n" +const redirectChildBeforeLoadBlock = + " beforeLoad: () => {\n throw redirect({ to: '/' })\n },\n" + const routeFiles = Object.fromEntries( Object.entries(routeFilePaths).map(([key, relativePath]) => [ key, @@ -141,6 +156,8 @@ function normalizeRouteSource(routeFileKey: RouteFileKey, source: string) { } if (routeFileKey === 'root') { + next = next.replace(redirectRootLoaderBlock, rootLoaderBlock) + for (const marker of [ 'root-component-inline-baseline', 'root-component-inline-updated', @@ -209,30 +226,36 @@ function normalizeRouteSource(routeFileKey: RouteFileKey, source: string) { } if (routeFileKey === 'child') { - const beforeLoadBlock = - " beforeLoad: () => ({\n greeting: 'Hello',\n }),\n" - const loaderBlock = " loader: () => ({\n crumb: 'Child',\n }),\n" - next = replaceAll(next, "greeting: 'Hi'", "greeting: 'Hello'") + next = next.replace(failingChildOnStayBlock, '') + next = next.replace(pendingNavigationChildOnStayBlock, '') + next = next.replace(pendingNavigationChildLoaderBlock, childLoaderBlock) + next = next.replace(redirectChildBeforeLoadBlock, childBeforeLoadBlock) + next = next.replace( + "import { createFileRoute, redirect } from '@tanstack/react-router'", + "import { createFileRoute } from '@tanstack/react-router'", + ) + next = replaceAll(next, "crumb: 'Child Recovered'", "crumb: 'Child'") + next = replaceAll(next, "crumb: 'Child Failed'", "crumb: 'Child'") next = replaceAll(next, "crumb: 'Child Updated Again'", "crumb: 'Child'") next = replaceAll(next, "crumb: 'Child Updated'", "crumb: 'Child'") - if (!next.includes(beforeLoadBlock)) { + if (!next.includes(childBeforeLoadBlock)) { next = next.replace( ' component: Child,\n', - `${beforeLoadBlock} component: Child,\n`, + `${childBeforeLoadBlock} component: Child,\n`, ) } - if (!next.includes(loaderBlock)) { + if (!next.includes(childLoaderBlock)) { const withLoaderAfterBeforeLoad = next.replace( - `${beforeLoadBlock} component: Child,\n`, - `${beforeLoadBlock}${loaderBlock} component: Child,\n`, + `${childBeforeLoadBlock} component: Child,\n`, + `${childBeforeLoadBlock}${childLoaderBlock} component: Child,\n`, ) next = withLoaderAfterBeforeLoad === next ? next.replace( ' component: Child,\n', - `${loaderBlock} component: Child,\n`, + `${childLoaderBlock} component: Child,\n`, ) : withLoaderAfterBeforeLoad } @@ -659,6 +682,209 @@ test.describe('react-start hmr', () => { 'child preserved', ) await expect(page.getByTestId('child')).toHaveText('child') + + const preloadedRouteId = await page.evaluate(async () => { + const matches = await (window as any).__TSR_ROUTER__.preloadRoute({ + to: '/inputs', + }) + return matches?.at(-1)?.routeId + }) + expect(preloadedRouteId).toBe('/inputs') + }) + + test('rolls back a failed route refresh and accepts the next HMR update', async ({ + page, + }) => { + await page.goto('/child') + await page.getByTestId('hydrated').waitFor({ state: 'visible' }) + await page.getByTestId('root-message').fill('preserved through failure') + await expect(page.getByTestId('crumb-/child')).toHaveText('Child') + + await page.evaluate(() => { + const match = (window as any).__TSR_ROUTER__.stores.matches + .get() + .find((candidate: any) => candidate.routeId === '/child') + ;(window as any).__TSR_HMR_COMMITTED_SIGNAL__ = + match.abortController.signal + ;(window as any).__TSR_HMR_FAILURE_RAN__ = false + }) + + await rewriteRouteFile( + page, + 'child', + (source) => + source.replace( + childLoaderBlock, + `${failingChildOnStayBlock} loader: () => ({\n crumb: 'Child Failed',\n }),\n`, + ), + async () => { + await waitForRouteModuleUpdate(page, '/child', 'Child Failed') + await page.waitForFunction( + () => (window as any).__TSR_HMR_FAILURE_RAN__ === true, + ) + }, + ) + + await expect(page.getByTestId('crumb-/child')).toHaveText('Child') + await expect(page.getByTestId('root-message')).toHaveValue( + 'preserved through failure', + ) + expect( + await page.evaluate(() => ({ + committed: (window as any).__TSR_HMR_COMMITTED_SIGNAL__.aborted, + failed: (window as any).__TSR_HMR_FAILED_SIGNAL__.aborted, + })), + ).toEqual({ committed: false, failed: true }) + + await rewriteRouteFile( + page, + 'child', + (source) => + source + .replace(failingChildOnStayBlock, '') + .replace("crumb: 'Child Failed'", "crumb: 'Child Recovered'"), + async () => { + await waitForRouteModuleUpdate(page, '/child', 'Child Recovered') + await hmrExpect(page.getByTestId('crumb-/child')).toHaveText( + 'Child Recovered', + ) + }, + ) + + await expect(page.getByTestId('root-message')).toHaveValue( + 'preserved through failure', + ) + expect( + await page.evaluate(() => { + const router = (window as any).__TSR_ROUTER__ + const current = router.stores.matches + .get() + .find((candidate: any) => candidate.routeId === '/child') + return { + previous: (window as any).__TSR_HMR_COMMITTED_SIGNAL__.aborted, + current: current.abortController.signal.aborted, + } + }), + ).toEqual({ previous: true, current: false }) + }) + + test('rematerializes retained routes when an HMR update redirects', async ({ + page, + }) => { + await page.goto('/child') + await page.getByTestId('hydrated').waitFor({ state: 'visible' }) + await page.getByTestId('root-message').fill('preserved through redirect') + + await rewriteRouteFile( + page, + 'root', + (source) => source.replace(rootLoaderBlock, redirectRootLoaderBlock), + async () => { + await waitForRouteModuleUpdate(page, '__root__', 'Home Armed') + await hmrExpect(page.getByTestId('crumb-__root__')).toHaveText( + 'Home Armed', + ) + }, + ) + + await page.evaluate(() => { + window.sessionStorage.setItem('hmr-root-crumb', 'Home Redirected') + }) + + await rewriteRouteFile( + page, + 'child', + (source) => + source + .replace( + "import { createFileRoute } from '@tanstack/react-router'", + "import { createFileRoute, redirect } from '@tanstack/react-router'", + ) + .replace(childBeforeLoadBlock, redirectChildBeforeLoadBlock), + async () => { + await hmrExpect(page).toHaveURL((url) => url.pathname === '/') + await hmrExpect(page.getByTestId('crumb-__root__')).toHaveText( + 'Home Redirected', + ) + }, + ) + + await expect(page.getByTestId('root-message')).toHaveValue( + 'preserved through redirect', + ) + }) + + test('waits for a pending navigation before applying an HMR refresh', async ({ + page, + }) => { + await page.goto('/') + await page.getByTestId('hydrated').waitFor({ state: 'visible' }) + await page.getByTestId('root-message').fill('preserved while pending') + + await page.evaluate(() => { + let release!: () => void + const gate = new Promise((resolve) => { + release = resolve + }) + ;(window as any).__TSR_HMR_PENDING_NAV_EVENTS__ = [] + ;(window as any).__TSR_HMR_PENDING_NAV_GATE__ = gate + ;(window as any).__TSR_HMR_RELEASE_PENDING_NAV__ = release + }) + + await rewriteRouteFile( + page, + 'child', + (source) => + source.replace(childLoaderBlock, pendingNavigationChildLoaderBlock), + async () => { + await page.waitForFunction(() => { + const loader = (window as any).__TSR_ROUTER__?.routesById?.['/child'] + ?.options?.loader + return String(loader).includes('__TSR_HMR_PENDING_NAV_GATE__') + }) + }, + ) + + await page.getByTestId('child-link').click() + await page.waitForFunction( + () => + (window as any).__TSR_HMR_PENDING_NAV_EVENTS__?.[0] === 'loader-start', + ) + + await rewriteRouteFile( + page, + 'child', + (source) => + source.replace( + pendingNavigationChildLoaderBlock, + `${pendingNavigationChildOnStayBlock}${pendingNavigationChildLoaderBlock}`, + ), + async () => { + await page.waitForFunction(() => { + const onStay = (window as any).__TSR_ROUTER__?.routesById?.['/child'] + ?.options?.onStay + return String(onStay).includes( + 'intentional HMR failure after pending navigation', + ) + }) + }, + ) + + await page.evaluate(() => { + ;(window as any).__TSR_HMR_RELEASE_PENDING_NAV__() + }) + + await page.waitForFunction(() => + (window as any).__TSR_HMR_PENDING_NAV_EVENTS__?.includes('onStay'), + ) + await hmrExpect(page.getByTestId('child')).toHaveText('child') + await hmrExpect(page.getByTestId('crumb-/child')).toHaveText('Child') + expect( + await page.evaluate(() => (window as any).__TSR_HMR_PENDING_NAV_EVENTS__), + ).toEqual(['loader-start', 'loader-end', 'onStay']) + await expect(page.getByTestId('root-message')).toHaveValue( + 'preserved while pending', + ) }) test('adds a createFileRoute property during HMR', async ({ page }) => { diff --git a/packages/react-router/src/Matches.tsx b/packages/react-router/src/Matches.tsx index a555848535..218039be34 100644 --- a/packages/react-router/src/Matches.tsx +++ b/packages/react-router/src/Matches.tsx @@ -8,11 +8,10 @@ import { CatchBoundary } from './CatchBoundary' import { useRouter } from './useRouter' import { useStructuralSharing } from './useMatch' import { useLayoutEffect } from './utils' -import { Transitioner, clearOwner } from './Transitioner' +import { Transitioner } from './Transitioner' import { matchContext } from './matchContext' import { Match, renderPending } from './Match' import { SafeFragment } from './SafeFragment' -import type { ReactRenderOwner } from './Transitioner' import type { StructuralSharingOption, ValidateSelected, @@ -48,9 +47,6 @@ declare module '@tanstack/router-core' { */ export function Matches() { const router = useRouter() - // Stable render receipt: Transitioner offers a generation and MatchesInner - // acknowledges that exact array after it commits. - const [owner] = React.useState([]) const rootRoute: AnyRoute = router.routesById[rootRouteId] const pendingElement = renderPending(router, rootRoute) @@ -61,9 +57,9 @@ export function Matches() { const inner = ( <> - {!(isServer ?? router.isServer) && } + {!(isServer ?? router.isServer) && } - + ) @@ -75,24 +71,22 @@ export function Matches() { ) } -function MatchesInner({ owner }: { owner: ReactRenderOwner }) { +function MatchesInner() { const router = useRouter() - const presentation = + const matches = (isServer ?? router.isServer) ? router.stores.matches.get() - : // eslint-disable-next-line react-hooks/rules-of-hooks - useStore( - router.stores.ids, - () => owner[0] ?? router.stores.matches.get(), - ) - const match = presentation[0] + : // IDs change for every publication, but not for fetching alone. + // eslint-disable-next-line react-hooks/rules-of-hooks + useStore(router.stores.ids, router.stores.matches.get) + const match = matches[0] const routeId = match?.routeId useLayoutEffect(() => { - if (owner[0] === presentation) { - clearOwner(owner)?.(true) - } - }, [owner, presentation]) + const rendered = router._rendered + router._rendered = undefined + rendered?.(true) + }, [matches, router]) const matchComponent = routeId ? : null diff --git a/packages/react-router/src/Transitioner.tsx b/packages/react-router/src/Transitioner.tsx index e65d76012e..dc3f30691a 100644 --- a/packages/react-router/src/Transitioner.tsx +++ b/packages/react-router/src/Transitioner.tsx @@ -4,132 +4,114 @@ import * as React from 'react' import { getLocationChangeInfo, trimPathRight } from '@tanstack/router-core' import { useLayoutEffect } from './utils' import { useRouter } from './useRouter' -import type { AnyRouteMatch } from '@tanstack/router-core' -export type ReactRenderOwner = [ - offered?: Array, - settle?: (rendered: boolean) => void, - active?: boolean, -] - -export function clearOwner( - owner: ReactRenderOwner, - current = owner[1], -): typeof current { - if (owner[1] === current) { - owner[0] = owner[1] = undefined - return current - } - return undefined -} - -export function Transitioner({ owner }: { owner: ReactRenderOwner }) { +/** + * Bridges router-core's awaitable transition contract to React: + * + * 1. Core gives `startTransition` a callback that publishes to the store. + * 2. We remember its resolver and schedule the publication with React. + * 3. `MatchesInner` acknowledges the committed route tree from its layout effect. + * 4. Core resumes and can finish pending timing, events, and background work. + * + * If another publication starts first, the older one resolves `false` because + * it was superseded rather than rendered. + */ +export function Transitioner() { const router = useRouter() + // StrictMode replays mount effects in development. This only prevents a + // duplicate initial load/event during that replay; it is not remount state. + const initialized = + process.env.NODE_ENV !== 'production' + ? // eslint-disable-next-line react-hooks/rules-of-hooks + React.useRef(false) + : undefined + + // React.startTransition returns void, so core waits for MatchesInner's + // layout effect to resolve the publication after its route tree commits. + router.startTransition = (fn) => + new Promise((resolve, reject) => { + // A newer publication owns the next commit. Retire the previous one so + // its transaction cannot report itself as rendered later. + router._rendered?.(false) + router._rendered = resolve + React.startTransition( + process.env.NODE_ENV === 'production' + ? fn + : () => { + // React captures action errors. Catch inside the action so an + // HMR failure rejects and core can roll back its publication. + try { + fn() + } catch (cause) { + router._rendered = undefined + reject(cause) + } + }, + ) + }) // Subscribe before canonicalizing so the initial URL has exactly one load. useLayoutEffect(() => { - // Suspense and Activity can reconnect effects without rendering again. - const initialized = owner[2] !== undefined - owner[2] = true - router.startTransition = async (fn, expected) => { - if (!owner[2]) { - fn() - return false - } - - return new Promise((resolve, reject) => { - clearOwner(owner)?.(false) - owner[0] = expected - owner[1] = resolve - if (process.env.NODE_ENV === 'production') { - React.startTransition(fn) - } else { - // React captures transition-action errors, so HMR must catch inside it. - React.startTransition(() => { - try { - fn() - } catch (cause) { - clearOwner(owner, resolve) - reject(cause) - } - }) - } - }) - } - ;( - router as typeof router & { _cancelTransition?: () => void } - )._cancelTransition = () => clearOwner(owner)?.(false) const unsub = router.history.subscribe(router.load) - if ( - !initialized || - router.history.location.state.__TSR_key !== - router.latestLocation.state.__TSR_key - ) { - router.updateLatestLocation() - const location = router.latestLocation - const nextLocation = router.buildLocation({ - to: location.pathname, - search: true, - params: true, - hash: true, - state: true, - _includeValidateSearch: true, - }) + if (initialized) { + if (initialized.current) { + return unsub + } + initialized.current = true + } - // Check if the current URL matches the canonical form. - // Compare publicHref (browser-facing URL) consistently with server - // canonicalization. - if ( - trimPathRight(location.publicHref) !== - trimPathRight(nextLocation.publicHref) - ) { - router.commitLocation({ - ...nextLocation, - replace: true, - ignoreBlocker: true, - }) - } else { - const resolvedLocation = router.stores.resolvedLocation.get() - if ( - resolvedLocation?.href === location.href && - resolvedLocation.state.__TSR_key === location.state.__TSR_key - ) { - if (!owner[1]) { - owner[0] = router.stores.matches.get() - owner[1] = (rendered) => { - if (rendered) { - router.emit({ - type: 'onRendered', - ...getLocationChangeInfo(resolvedLocation, resolvedLocation), - }) - } - } - } - } else if (initialized || !router._tx) { - router.load().catch(console.error) + router.updateLatestLocation() + const location = router.latestLocation + const nextLocation = router.buildLocation({ + to: location.pathname, + search: true, + params: true, + hash: true, + state: true, + _includeValidateSearch: true, + }) + + // Check if the current URL matches the canonical form. + // Compare publicHref (browser-facing URL) consistently with server + // canonicalization. + if ( + trimPathRight(location.publicHref) !== + trimPathRight(nextLocation.publicHref) + ) { + router.commitLocation({ + ...nextLocation, + replace: true, + ignoreBlocker: true, + }) + return unsub + } + + const resolvedLocation = router.stores.resolvedLocation.get() + if ( + resolvedLocation?.href === location.href && + resolvedLocation.state.__TSR_key === location.state.__TSR_key + ) { + // Hydration or a pre-mount load may already have resolved this location. + // Arm the same commit receipt so its first real route-tree commit emits + // the initial onRendered event at the correct time. + router._rendered = (rendered) => { + if (rendered) { + router.emit({ + type: 'onRendered', + ...getLocationChangeInfo(resolvedLocation, resolvedLocation), + }) } } + } else if (!router._tx) { + // Otherwise begin the initial load unless one is already in flight. + router.load().catch(console.error) } - return () => { - unsub() - owner[2] = false - if (process.env.NODE_ENV === 'production') { - clearOwner(owner)?.(false) - } else { - const current = owner[1] - // StrictMode replays effects without another render. Its second setup - // reactivates this owner before the microtask; a real unmount does not. - queueMicrotask(() => { - if (!owner[2]) { - clearOwner(owner, current)?.(false) - } - }) - } - } + return unsub + // `initialized` exists only in development and is stable when present. // eslint-disable-next-line react-hooks/exhaustive-deps - }, [owner, router, router.history]) + }, [router, router.history]) return null } diff --git a/packages/react-router/tests/component-preload-retry.test.tsx b/packages/react-router/tests/component-preload-retry.test.tsx index 26cf472602..7ded6ff858 100644 --- a/packages/react-router/tests/component-preload-retry.test.tsx +++ b/packages/react-router/tests/component-preload-retry.test.tsx @@ -25,10 +25,8 @@ test('a successful server component download is reused', async () => { const importer = vi.fn().mockResolvedValue({ default: () => null }) const Page = lazyRouteComponent(importer) - const preload = Page.preload?.() - await preload - - expect(Page.preload?.()).toBe(preload) + await Page.preload?.() + await Page.preload?.() expect(importer).toHaveBeenCalledTimes(1) }) @@ -40,11 +38,11 @@ test('concurrent component preloads share the import', async () => { const Page = lazyRouteComponent(importer) const first = Page.preload?.() - expect(Page.preload?.()).toBe(first) + const second = Page.preload?.() expect(importer).toHaveBeenCalledOnce() componentImport.resolve({ default: () => null }) - await first + await Promise.all([first, second]) }) test('a failed component download is retried from the route error UI', async () => { diff --git a/packages/react-router/tests/errorComponent.test.tsx b/packages/react-router/tests/errorComponent.test.tsx index 25e52259a4..41f12561cb 100644 --- a/packages/react-router/tests/errorComponent.test.tsx +++ b/packages/react-router/tests/errorComponent.test.tsx @@ -871,32 +871,32 @@ describe('notFoundComponent is rendered when an error is thrown in params.parse' expect(rootLoader).toHaveBeenCalledTimes(1) expect(linkToRottenPizza).toBeInTheDocument() - await act(() => fireEvent.mouseOver(linkToRottenPizza)) - await vi.waitFor(() => expect(rootLoader).toHaveBeenCalledTimes(2)) - await act(() => fireEvent.click(linkToRottenPizza)) - await vi.waitFor(() => expect(router.state.status).toBe('pending')) + try { + await act(() => fireEvent.mouseOver(linkToRottenPizza)) + await vi.waitFor(() => expect(rootLoader).toHaveBeenCalledTimes(2)) + await act(() => fireEvent.click(linkToRottenPizza)) + await vi.waitFor(() => expect(router.state.status).toBe('pending')) - expect(preloadGate.status).toBe('pending') - expect(preloadController?.signal.aborted).toBe(false) + expect(preloadGate.status).toBe('pending') + expect(preloadController?.signal.aborted).toBe(false) - await vi.waitFor(() => expect(rootLoader).toHaveBeenCalledTimes(3)) - expect(rootLoader.mock.calls.map(([context]) => context.preload)).toEqual([ - false, - true, - false, - ]) + await vi.waitFor(() => expect(rootLoader).toHaveBeenCalledTimes(3)) + expect(rootLoader.mock.calls.map(([context]) => context.preload)).toEqual( + [false, true, false], + ) - const notFoundComponent = await screen.findByText('No pizza', undefined, { - timeout: 750, - }) - expect(router.state.status).toBe('idle') - expect(preloadGate.status).toBe('pending') - expect(preloadController?.signal.aborted).toBe(false) - expect(notFoundComponent).toBeInTheDocument() - - await act(async () => { - preloadGate.resolve() - await Promise.resolve() - }) + const notFoundComponent = await screen.findByText('No pizza', undefined, { + timeout: 750, + }) + expect(router.state.status).toBe('idle') + expect(preloadGate.status).toBe('pending') + expect(preloadController?.signal.aborted).toBe(false) + expect(notFoundComponent).toBeInTheDocument() + } finally { + await act(async () => { + preloadGate.resolve() + await Promise.resolve() + }) + } }) }) diff --git a/packages/react-router/tests/preloaded-mount-resolution.test.tsx b/packages/react-router/tests/preloaded-mount-resolution.test.tsx index b7527beb3e..51dae3b3c3 100644 --- a/packages/react-router/tests/preloaded-mount-resolution.test.tsx +++ b/packages/react-router/tests/preloaded-mount-resolution.test.tsx @@ -1,44 +1,21 @@ -import { afterEach, beforeEach, expect, test, vi } from 'vitest' +import { expect, test, vi } from 'vitest' import * as React from 'react' -import { createRoot } from 'react-dom/client' +import { render, screen, waitFor } from '@testing-library/react' import { createMemoryHistory } from '@tanstack/history' import { Outlet, RouterProvider, - createControlledPromise, 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. + * Start hydrates the router before RouterProvider renders it. Build that same + * resolved state through the public load API, then verify the first StrictMode + * commit emits one onRendered event after the route tree's layout effects. */ - -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 -}) - -test('mounting after a settled load still resolves status and fires onRendered', async () => { +test('StrictMode emits one post-commit onRendered for an already resolved router', async () => { const lifecycle: Array<'layout' | 'rendered'> = [] const Home = () => { React.useLayoutEffect(() => { @@ -75,15 +52,8 @@ test('mounting after a settled load still resolves status and fires 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) - let renderedTimeout: ReturnType | undefined try { - // Load fully settles before the provider mounts — the exact shape of the - // memory benchmark's mount/unmount cycle. await router.load() expect(router.state.status).toBe('idle') expect(router.state.resolvedLocation?.pathname).toBe('/') @@ -91,64 +61,22 @@ test('mounting after a settled load still resolves status and fires onRendered', expect(onResolved).toHaveBeenCalledTimes(1) expect(onRendered).not.toHaveBeenCalled() - reactRoot.render() - await Promise.race([ - rendered, - new Promise((_, reject) => { - renderedTimeout = setTimeout(() => { - reject(new Error('Timed out waiting for onRendered')) - }, 2000) - }), - ]) + render( + + + , + ) + await screen.findByTestId('home') + await rendered + await new Promise((resolve) => setTimeout(resolve, 0)) - expect(container.querySelector('[data-testid="home"]')).not.toBeNull() - expect(onRendered).toHaveBeenCalledTimes(1) - expect(lifecycle).toEqual(['layout', 'rendered']) + await waitFor(() => expect(onRendered).toHaveBeenCalledTimes(1)) + expect(lifecycle.indexOf('layout')).toBeLessThan( + lifecycle.indexOf('rendered'), + ) expect(router.state.status).toBe('idle') expect(router.state.resolvedLocation?.pathname).toBe('/') } finally { - clearTimeout(renderedTimeout) - unsubscribe() - reactRoot.unmount() - container.remove() - } -}) - -test('mounting during a load keeps the existing generation', async () => { - const gate = createControlledPromise() - const beforeLoad = vi.fn() - const loader = vi.fn(() => gate) - const rootRoute = createRootRoute({ component: () => }) - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - beforeLoad, - loader, - component: () =>
Home
, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute]), - history: createMemoryHistory({ initialEntries: ['/'] }), - }) - const load = router.load() - await vi.waitFor(() => expect(loader).toHaveBeenCalledOnce()) - - const container = document.createElement('div') - document.body.appendChild(container) - const reactRoot = createRoot(container) - try { - reactRoot.render() - await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledOnce()) - gate.resolve() - await load - await vi.waitFor(() => { - expect(container.querySelector('[data-testid="home"]')).not.toBeNull() - }) - - expect(beforeLoad).toHaveBeenCalledOnce() - expect(loader).toHaveBeenCalledOnce() - } finally { - reactRoot.unmount() - container.remove() + unsubscribers.forEach((unsubscribe) => unsubscribe()) } }) diff --git a/packages/react-router/tests/react-render-owner-contract.test.tsx b/packages/react-router/tests/react-render-owner-contract.test.tsx deleted file mode 100644 index 0324ae38c3..0000000000 --- a/packages/react-router/tests/react-render-owner-contract.test.tsx +++ /dev/null @@ -1,140 +0,0 @@ -import { act } from 'react' -import { cleanup, render, screen, waitFor } from '@testing-library/react' -import { afterEach, expect, test, vi } from 'vitest' -import { - Outlet, - RouterProvider, - createControlledPromise, - createMemoryHistory, - createRootRoute, - createRoute, - createRouter, -} from '../src' - -const testCleanups: Array<() => void> = [] - -afterEach(() => { - while (testCleanups.length) { - testCleanups.pop()!() - } - cleanup() -}) - -test('a suspended same-membership publication cannot acknowledge its successor', async () => { - const firstRenderStarted = createControlledPromise() - const firstRenderGate = createControlledPromise() - let signaledFirstRender = false - - const rootRoute = createRootRoute({ - validateSearch: (search: Record) => ({ - revision: Number(search.revision), - }), - component: () => { - const revision = rootRoute.useSearch().revision - if (revision === 1 && firstRenderGate.status === 'pending') { - if (!signaledFirstRender) { - signaledFirstRender = true - firstRenderStarted.resolve() - } - throw firstRenderGate - } - return
Root revision {revision}
- }, - }) - const router = createRouter({ - routeTree: rootRoute, - history: createMemoryHistory({ initialEntries: ['/?revision=0'] }), - }) - - render() - expect(await screen.findByText('Root revision 0')).toBeInTheDocument() - await waitFor(() => expect(router.state.status).toBe('idle')) - const initialIds = router.state.matches.map((match) => match.routeId) - - const renderedRevisions: Array = [] - testCleanups.push( - router.subscribe('onRendered', (event) => { - renderedRevisions.push( - Number((event.toLocation.search as Record).revision), - ) - }), - ) - - let firstNavigation!: Promise - await act(async () => { - firstNavigation = router.navigate({ - to: '/', - search: { revision: 1 }, - }) - await firstRenderStarted - }) - - const firstSettled = vi.fn() - void firstNavigation.then(firstSettled) - expect(router.state.matches.map((match) => match.routeId)).toEqual(initialIds) - expect(router.state.matches[0]?.search.revision).toBe(1) - expect(screen.getByText('Root revision 0')).toBeInTheDocument() - expect(firstSettled).not.toHaveBeenCalled() - expect(renderedRevisions).toEqual([]) - - try { - await act(() => - router.navigate({ - to: '/', - search: { revision: 2 }, - }), - ) - await firstNavigation - - expect(screen.getByText('Root revision 2')).toBeInTheDocument() - expect(router.state.matches.map((match) => match.routeId)).toEqual( - initialIds, - ) - expect(renderedRevisions).toEqual([2]) - expect(firstSettled).toHaveBeenCalledOnce() - } finally { - await act(async () => { - firstRenderGate.resolve() - await Promise.resolve() - }) - } - - expect(screen.getByText('Root revision 2')).toBeInTheDocument() - expect(renderedRevisions).toEqual([2]) -}) - -test('a development HMR lifecycle failure rolls back before recovery', async () => { - let generation = 1 - const rootRoute = createRootRoute({ component: Outlet }) - const pageRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/page', - loader: () => generation, - component: () =>
Page generation {pageRoute.useLoaderData()}
, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([pageRoute]), - history: createMemoryHistory({ initialEntries: ['/page'] }), - }) - - render() - expect(await screen.findByText('Page generation 1')).toBeInTheDocument() - await waitFor(() => expect(router.state.status).toBe('idle')) - - generation = 2 - pageRoute.options.onStay = () => { - throw new Error('hot route failed') - } - await act(() => router._refreshRoute!()) - - expect(screen.getByText('Page generation 1')).toBeInTheDocument() - expect(router.state.matches.at(-1)?.loaderData).toBe(1) - expect(router.state.status).toBe('idle') - - pageRoute.options.onStay = undefined - generation = 3 - await act(() => router._refreshRoute!()) - - expect(screen.getByText('Page generation 3')).toBeInTheDocument() - expect(router.state.matches.at(-1)?.loaderData).toBe(3) -}) diff --git a/packages/react-router/tests/transitioner-remount.test.tsx b/packages/react-router/tests/transitioner-remount.test.tsx deleted file mode 100644 index e0b6122ec6..0000000000 --- a/packages/react-router/tests/transitioner-remount.test.tsx +++ /dev/null @@ -1,141 +0,0 @@ -import { useState } from 'react' -import { flushSync } from 'react-dom' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { act, cleanup, render, screen, waitFor } from '@testing-library/react' -import { - Outlet, - RouterProvider, - createMemoryHistory, - createRootRoute, - createRoute, - createRouter, -} from '../src' - -afterEach(() => { - cleanup() - vi.unstubAllEnvs() -}) - -function setup() { - const rootRoute = createRootRoute({ component: () => }) - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: () =>
Index
, - }) - const nextRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/next', - component: () =>
Next
, - }) - const history = createMemoryHistory({ initialEntries: ['/'] }) - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute, nextRoute]), - history, - }) - return { history, router } -} - -describe('Transitioner remount', () => { - // Zombie-router pin: once the provider unmounts, the history subscription - // must be torn down so a later history change never re-drives the router. - it('does not load after the provider unmounts', async () => { - const { history, router } = setup() - const loadSpy = vi.spyOn(router, 'load') - - const first = render() - expect(await screen.findByText('Index')).toBeInTheDocument() - await waitFor(() => expect(router.state.status).toBe('idle')) - - first.unmount() - loadSpy.mockClear() - - // A history change while unmounted must not reach the router. - history.push('/next') - await new Promise((resolve) => setTimeout(resolve, 0)) - - expect(loadSpy).not.toHaveBeenCalled() - // Raw history advanced... - expect(router.history.location.pathname).toBe('/next') - // ...but the router never processed it, so its committed state stayed put. - expect(router.state.location.pathname).toBe('/') - - loadSpy.mockRestore() - }) - - // Remounting the same router instance must re-establish the subscription so - // navigation keeps working, without leaving a stale duplicate behind. - it('re-subscribes and loads on remount with the same router', async () => { - const { history, router } = setup() - // Spy before the first mount so the subscription captures the spy by - // reference - both the first and second mounts subscribe with it. - const loadSpy = vi.spyOn(router, 'load') - - const first = render() - expect(await screen.findByText('Index')).toBeInTheDocument() - await waitFor(() => expect(router.state.status).toBe('idle')) - - first.unmount() - - render() - expect(await screen.findByText('Index')).toBeInTheDocument() - await waitFor(() => expect(router.state.status).toBe('idle')) - - // A push on the remounted provider must drive exactly one load, proving - // the subscription was re-established (and is singular). - loadSpy.mockClear() - history.push('/next') - expect(await screen.findByText('Next')).toBeInTheDocument() - expect(router.state.location.pathname).toBe('/next') - await waitFor(() => expect(loadSpy).toHaveBeenCalledTimes(1)) - - loadSpy.mockRestore() - }) - - it.each(['development', 'production'] as const)( - 'settles an outstanding render when the provider unmounts in %s', - async (nodeEnv) => { - vi.stubEnv('NODE_ENV', nodeEnv) - - const { router } = setup() - let setMounted!: (mounted: boolean) => void - function Harness() { - const [mounted, set] = useState(true) - setMounted = set - return mounted ? : null - } - - render() - expect(await screen.findByText('Index')).toBeInTheDocument() - await waitFor(() => expect(router.state.status).toBe('idle')) - - const rendered = vi.fn() - const navigationSettled = vi.fn() - const unsubscribers = [ - router.subscribe('onRendered', (event) => { - if (event.toLocation.pathname === '/next') { - rendered() - } - }), - router.subscribe('onBeforeRouteMount', (event) => { - if (event.toLocation.pathname === '/next') { - expect(navigationSettled).not.toHaveBeenCalled() - flushSync(() => setMounted(false)) - } - }), - ] - - void router.navigate({ to: '/next' }).then(navigationSettled) - await waitFor(() => expect(navigationSettled).toHaveBeenCalledOnce()) - expect(rendered).not.toHaveBeenCalled() - - await act(() => setMounted(true)) - expect(await screen.findByText('Next')).toBeInTheDocument() - await waitFor(() => expect(rendered).toHaveBeenCalledOnce()) - - for (const unsubscribe of unsubscribers) { - unsubscribe() - } - }, - ) -}) diff --git a/packages/react-router/tests/transitioner-render-ack.test.tsx b/packages/react-router/tests/transitioner-render-ack.test.tsx index 29c3b05554..46296da9e5 100644 --- a/packages/react-router/tests/transitioner-render-ack.test.tsx +++ b/packages/react-router/tests/transitioner-render-ack.test.tsx @@ -1,4 +1,4 @@ -import { Activity, StrictMode, act, lazy } from 'react' +import { StrictMode, act } from 'react' import { cleanup, render, screen, waitFor } from '@testing-library/react' import { afterEach, expect, test, vi } from 'vitest' import { @@ -19,7 +19,6 @@ afterEach(() => { } cleanup() vi.useRealTimers() - vi.unstubAllEnvs() }) test('same-location invalidation emits onResolved after its refreshed DOM commits', async () => { @@ -58,6 +57,83 @@ test('same-location invalidation emits onResolved after its refreshed DOM commit expect(refreshedDomWasVisible).toEqual([true]) }) +test('a navigation superseding a suspended render acknowledges only the latest route', async () => { + const renderStarted = createControlledPromise() + const renderGate = createControlledPromise() + let signaled = false + + const rootRoute = createRootRoute({ + validateSearch: (search: Record) => ({ + revision: Number(search.revision), + }), + component: () => { + const revision = rootRoute.useSearch().revision + if (revision === 1 && renderGate.status === 'pending') { + if (!signaled) { + signaled = true + renderStarted.resolve() + } + throw renderGate + } + return
Root revision {revision}
+ }, + }) + const router = createRouter({ + routeTree: rootRoute, + history: createMemoryHistory({ initialEntries: ['/?revision=0'] }), + }) + + render() + expect(await screen.findByText('Root revision 0')).toBeInTheDocument() + await waitFor(() => expect(router.state.status).toBe('idle')) + + const renderedRevisions: Array = [] + testCleanups.push( + router.subscribe('onRendered', (event) => { + renderedRevisions.push( + Number((event.toLocation.search as Record).revision), + ) + }), + ) + + let suspendedNavigation!: Promise + await act(async () => { + suspendedNavigation = router.navigate({ + to: '/', + search: { revision: 1 }, + }) + await renderStarted + }) + + const suspendedSettled = vi.fn() + void suspendedNavigation.then(suspendedSettled) + expect(screen.getByText('Root revision 0')).toBeInTheDocument() + expect(suspendedSettled).not.toHaveBeenCalled() + expect(renderedRevisions).toEqual([]) + + try { + await act(() => + router.navigate({ + to: '/', + search: { revision: 2 }, + }), + ) + await suspendedNavigation + + expect(screen.getByText('Root revision 2')).toBeInTheDocument() + expect(renderedRevisions).toEqual([2]) + expect(suspendedSettled).toHaveBeenCalledOnce() + } finally { + await act(async () => { + renderGate.resolve() + await Promise.resolve() + }) + } + + expect(screen.getByText('Root revision 2')).toBeInTheDocument() + expect(renderedRevisions).toEqual([2]) +}) + test('a late background refresh is discarded after foreground navigation commits', async () => { const backgroundRefresh = createControlledPromise() let sourceGeneration = 0 @@ -97,17 +173,6 @@ test('a late background refresh is discarded after foreground navigation commits ).toBeInTheDocument() await waitFor(() => expect(router.state.status).toBe('idle')) - const eventLog: Array = [] - const unsubscribers = [ - router.subscribe('onResolved', (event) => { - eventLog.push(`onResolved:${event.toLocation.pathname}`) - }), - router.subscribe('onRendered', (event) => { - eventLog.push(`onRendered:${event.toLocation.pathname}`) - }), - ] - testCleanups.push(...unsubscribers) - await act(() => router.invalidate()) expect(itemLoader).toHaveBeenCalledTimes(2) @@ -120,12 +185,6 @@ test('a late background refresh is discarded after foreground navigation commits expect( screen.getByText('Item target: foreground target data'), ).toBeInTheDocument() - expect(eventLog.filter((event) => event.endsWith('/items/target'))).toEqual([ - 'onResolved:/items/target', - 'onRendered:/items/target', - ]) - expect(router.state.resolvedLocation?.pathname).toBe('/items/target') - const eventCountAfterForegroundCommit = eventLog.length await act(async () => { backgroundRefresh.resolve('obsolete source data') @@ -138,17 +197,6 @@ test('a late background refresh is discarded after foreground navigation commits expect( screen.queryByText('Item source: obsolete source data'), ).not.toBeInTheDocument() - expect(router.state.location.pathname).toBe('/items/target') - expect(router.state.resolvedLocation?.pathname).toBe('/items/target') - expect(router.state.matches.at(-1)?.routeId).toBe(itemRoute.id) - expect(router.state.matches.at(-1)?.params).toEqual({ itemId: 'target' }) - expect(router.state.matches.at(-1)?.loaderData).toBe('foreground target data') - expect(router.state.status).toBe('idle') - expect( - eventLog - .slice(eventCountAfterForegroundCommit) - .every((event) => event.endsWith('/items/target')), - ).toBe(true) await act(() => router.navigate({ @@ -274,159 +322,3 @@ test('StrictMode effect replay preserves renderer commit sequencing', async () = expect(screen.getByText('Next')).toBeInTheDocument() expect(screen.queryByText('Index')).not.toBeInTheDocument() }) - -test('Activity reconnects render acknowledgement before the next navigation', async () => { - vi.stubEnv('NODE_ENV', 'production') - - const rootRoute = createRootRoute({ component: Outlet }) - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: () =>
Index
, - }) - const nextRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/next', - component: () =>
Next
, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute, nextRoute]), - history: createMemoryHistory({ initialEntries: ['/'] }), - }) - const provider = - const view = render({provider}) - - expect(await screen.findByText('Index')).toBeInTheDocument() - await waitFor(() => expect(router.state.status).toBe('idle')) - - const rendered = vi.fn() - const unsubscribe = router.subscribe('onRendered', (event) => { - if (event.toLocation.pathname === '/next') { - rendered(screen.queryByText('Next') !== null) - } - }) - testCleanups.push(unsubscribe) - - view.rerender({provider}) - expect(screen.getByText('Index')).not.toBeVisible() - view.rerender({provider}) - expect(screen.getByText('Index')).toBeVisible() - - await act(() => router.navigate({ to: '/next' })) - - expect(screen.getByText('Next')).toBeVisible() - expect(rendered).toHaveBeenCalledOnce() - expect(rendered).toHaveBeenCalledWith(true) - - view.unmount() - vi.unstubAllEnvs() -}) - -test('Activity catches up with history changes made while hidden', async () => { - const rootRoute = createRootRoute({ component: Outlet }) - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: () =>
Index
, - }) - const nextRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/next', - component: () =>
Next
, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute, nextRoute]), - history: createMemoryHistory({ initialEntries: ['/'] }), - }) - const provider = - const view = render({provider}) - - expect(await screen.findByText('Index')).toBeInTheDocument() - await waitFor(() => expect(router.state.status).toBe('idle')) - - view.rerender({provider}) - expect(screen.getByText('Index')).not.toBeVisible() - - await act(() => router.history.push('/next')) - expect(router.history.location.href).toBe('/next') - expect(router.latestLocation.pathname).toBe('/') - - view.rerender({provider}) - - expect(await screen.findByText('Next')).toBeVisible() - expect(router.latestLocation.pathname).toBe('/next') -}) - -test('Activity does not restart a navigation observed before it was hidden', async () => { - const next = createControlledPromise() - const loader = vi.fn(() => next) - const rootRoute = createRootRoute({ component: Outlet }) - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: () =>
Index
, - }) - const nextRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/next', - loader, - component: () =>
Next
, - }) - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute, nextRoute]), - history: createMemoryHistory({ initialEntries: ['/'] }), - }) - const provider = - const view = render({provider}) - - expect(await screen.findByText('Index')).toBeInTheDocument() - await waitFor(() => expect(router.state.status).toBe('idle')) - - let navigation!: Promise - act(() => { - navigation = router.navigate({ to: '/next' }) - }) - await waitFor(() => expect(loader).toHaveBeenCalledOnce()) - - view.rerender({provider}) - view.rerender({provider}) - expect(loader).toHaveBeenCalledOnce() - - await act(async () => { - next.resolve() - await navigation - }) - expect(screen.getByText('Next')).toBeVisible() -}) - -test('an initial canceled pending publication restores the empty presentation', async () => { - let offeredRouteId: string | undefined - const offeredRoute = { readId: (): string | undefined => undefined } - const suspendedPending = createControlledPromise() - const Pending = lazy(async () => { - await suspendedPending - return { default: () =>
Initial pending
} - }) - const rootRoute = createRootRoute({ - pendingMs: 0, - pendingMinMs: 0, - pendingComponent: Pending, - beforeLoad: ({ abortController }) => { - offeredRouteId = offeredRoute.readId() - abortController.abort() - }, - component: () =>
Ready
, - }) - const router = createRouter({ - routeTree: rootRoute, - history: createMemoryHistory({ initialEntries: ['/'] }), - }) - offeredRoute.readId = () => router.state.matches[0]?.routeId - - render() - - await waitFor(() => expect(offeredRouteId).toBe(rootRoute.id)) - await waitFor(() => expect(router.state.status).toBe('idle')) - expect(router.state.matches).toEqual([]) - expect(screen.queryByText('Something went wrong!')).not.toBeInTheDocument() -}) diff --git a/packages/router-core/INTERNALS.md b/packages/router-core/INTERNALS.md index 5a8dc15597..826578d240 100644 --- a/packages/router-core/INTERNALS.md +++ b/packages/router-core/INTERNALS.md @@ -62,7 +62,7 @@ to publish. - `src/ssr/handlerCallback.ts`, `ssr-server.ts`, and `transformStreamWithRouter.ts` transfer stream ownership and coordinate serialization, injection, abort, and cleanup. -- Framework `Transitioner` and `Matches` implementations acknowledge exact +- Framework `Transitioner` and `Matches` implementations acknowledge committed publications and render only through the selected boundary. Framework `RouterClient` and render-to-stream implementations complete hydration and connect request abort to their renderer. @@ -686,21 +686,17 @@ its previous child DOM while the surrounding `MatchesInner` publication commits and acknowledges. Review code that uses `onRendered` for descendant DOM work with that distinction in mind. -React cannot await `React.startTransition` directly. Its adapter has one current -acknowledgement slot, and `Matches` settles that slot from a layout effect. A new -expected publication first settles the previous slot as `false`, then installs -itself before the transition callback runs. This ordering matters because -publication can invoke a route lifecycle callback that synchronously starts and -publishes a successor navigation. Installing the expectation after the callback -would let the superseded publication replace the successor's slot. -The mounted-tree-owned Transitioner precedes the sibling match tree, so its -layout effect installs these callbacks before the match tree can acknowledge. +React cannot await `React.startTransition` directly. Its adapter stores one +resolver on the router. A new publication settles the previous resolver as +`false`, stores its own resolver, and starts the React transition. `MatchesInner` +takes and clears the current resolver in its layout effect, then settles it as +`true`. There is no generation token, match-array comparison, or separate owner. In development HMR, the transition callback is wrapped by a `try`/`catch` inside the function passed to `React.startTransition`. React 19 captures callback throws instead of rethrowing them from the outer `React.startTransition` call. -The development-only wrapper therefore clears only its exact owner and rejects -the adapter promise so the HMR transaction can restore `_committed`. Ordinary +The development-only wrapper therefore clears the resolver and rejects the +adapter promise so the HMR transaction can restore `_committed`. Ordinary production lifecycle and router-event callbacks are already isolated, so the production adapter calls `React.startTransition` directly. @@ -716,28 +712,12 @@ renderers. Every publication writes its already-created route-ID array, even when membership is unchanged. Per-route stores can still replace live match objects for `isFetching` without acknowledging another semantic publication. -React keeps the exact offered match-array pointer in a small owner local to the -mounted `Matches` tree. It captures that pointer during render and compares it -by identity in a layout effect. An exact render settles the current slot as -`true`; a mismatched render is ignored. This pointer is neither public match -state nor semantic authority, and it does not exist in router-core. - -Direct core restoration clears an outstanding React offer before publishing -the restored stores. This matters on a canceled first load: the accepted lane -is empty, so leaving the offered root armed while tombstoning its route atom -would make React try to render a route that no longer has a presented match. - Solid awaits its transition, and Vue awaits its render tick. For an already-settled Solid mount, history subscription remains before the route tree while a post-match notifier emits the initial `onRendered` event after -descendant mount effects. The architecture supports one committed `Matches` -owner per router at a time. Unmounting it unsubscribes from history and retires -any outstanding acknowledgement as `false`; a later mount creates a new owner -and synchronizes with the router's current presented matches. Development -defers only that retirement through the StrictMode effect replay turn, while -production cleanup is synchronous. Effect setup always reactivates the owner: -React Suspense and Activity can disconnect and reconnect layout effects without -rendering the preserved child tree again. +descendant mount effects. The React contract assumes one continuously mounted +`RouterProvider` per router. Continuing transactions across provider remounts, +swapping router instances, and mounting the same router twice are unsupported. Every core publication passed to `startTransition` must publish the route-ID generation signal even if route membership is unchanged. Suppressing that @@ -1207,13 +1187,13 @@ When changing this architecture, verify all of the following: is retained across that wait so chronological failure/control selection is not recomputed later. 19. `isFetching` clears for success, failure, cancellation, and supersession. -20. Transition acknowledgement settlement gates resolved/idle completion; React - identifies the exact generation by presentation-array identity and installs - it in one superseding slot before running the possibly reentrant transition - callback. Only `true` gates `onRendered` and pending minimum timing. -21. Exactly one mounted `Matches` tree owns a router's React acknowledgement at - a time. Final unmount retires it, and a later mount creates a new owner from - the router's current presentation. +20. Transition acknowledgement settlement gates resolved/idle completion. React + uses one superseding resolver slot; `MatchesInner` clears and settles it + after the route tree commits. Only `true` gates `onRendered` and pending + minimum timing. +21. React assumes one continuously mounted `RouterProvider` per router; provider + remount continuation, router swapping, and duplicate providers are outside + the transaction contract. 22. Reentrant callbacks suppress every stale later event or publication. 23. Canonicalization compares browser-facing `publicHref`; semantic `href` is not a symmetric canonical key across input and output rewrites. diff --git a/packages/router-core/src/load-client.ts b/packages/router-core/src/load-client.ts index f0c7432128..ea926db9ce 100644 --- a/packages/router-core/src/load-client.ts +++ b/packages/router-core/src/load-client.ts @@ -147,25 +147,17 @@ const REDIRECTED = 3 const CANCELED = 4 type SharedLoaderFailure = - | [typeof ERROR, error: unknown] - | [typeof NOT_FOUND, error: NotFoundError] - | [typeof REDIRECTED, redirect: AnyRedirect] + | [kind: typeof ERROR, error: unknown] + | [kind: typeof NOT_FOUND, error: NotFoundError] + | [kind: typeof REDIRECTED, redirect: AnyRedirect] -type LoaderFailure = SharedLoaderFailure | [typeof CANCELED] +type LoaderFailure = SharedLoaderFailure | [kind: typeof CANCELED] type LoaderOutcome = - | [ - typeof SUCCESS, - data: unknown, - updatedAt?: number, - ] + | [kind: typeof SUCCESS, data: unknown, updatedAt?: number] | SharedLoaderFailure -type LoaderSuccess = [ - typeof SUCCESS, - data: unknown, - updatedAt: number, -] +type LoaderSuccess = [kind: typeof SUCCESS, data: unknown, updatedAt: number] type LoaderResult = LoaderSuccess | LoaderFailure type LoaderFlightResult = LoaderSuccess | SharedLoaderFailure @@ -201,11 +193,13 @@ export type LoadTransaction = [ /** * Dev-only HMR refresh mode. Presence is the mode flag; a refresh always * carries the presentation it started from, while the hydration handoff is - * genuinely optional — the tuple makes a half-armed refresh unrepresentable. + * genuinely optional. The rollback exists only while its publication awaits + * render acknowledgement. */ refresh?: [ presentation: Array, handoff: NonNullable | undefined, + rollback?: () => boolean, ], ] @@ -221,29 +215,19 @@ export type PendingSession = [ type CoordinatorRouter = AnyRouter & { _refreshNextLoad?: boolean - _rollbackRefresh?: () => void - _cancelTransition?: () => void -} - -type PublicationCheckpoint = { - previousMatches: Array - previousPresentation: Array - previousCache: Map - commitPromise: CoordinatorRouter['_commitPromise'] - published: boolean } type LoaderTask = [ index: number, outcome: Promise, - ready: Promise, + chunkFailure: Promise, candidate?: WorkMatch, ] type BackgroundLoaderTask = [ index: number, outcome: Promise, - ready: Promise, + chunkFailure: Promise, candidate: WorkMatch, ] @@ -260,15 +244,15 @@ type ExecuteLaneOptions = [ ] type ControlOutcome = - | [typeof REDIRECTED, redirect: AnyRedirect] - | [typeof CANCELED] + | [kind: typeof REDIRECTED, redirect: AnyRedirect] + | [kind: typeof CANCELED] type LaneResult = ProjectedLane | ControlOutcome function isControl( result: Lane | ControlOutcome, ): result is ControlOutcome { - return typeof result[0] === 'number' + return typeof result[0 /* location or kind */] === 'number' } export function waitFor( @@ -287,7 +271,7 @@ export function waitFor( }) } -export function getRoute(router: AnyRouter, match: WorkMatch): AnyRoute { +function getRoute(router: AnyRouter, match: WorkMatch): AnyRoute { return (router.routesById as Record)[match.routeId]! } @@ -321,11 +305,11 @@ function normalize( function normalizeError(route: AnyRoute, cause: unknown): SharedLoaderFailure { let outcome = normalize(cause, true, route.id) - if (outcome[0] !== ERROR) { + if (outcome[0 /* kind */] !== ERROR) { return outcome } try { - route.options.onError?.(outcome[1]) + route.options.onError?.(outcome[1 /* error */]) } catch (onErrorCause) { outcome = normalize(onErrorCause, true, route.id) } @@ -337,14 +321,17 @@ function normalizeLaneError( cause: unknown, options: ExecuteLaneOptions, ): LoaderFailure { - if (options[0].signal.aborted || !options[2]()) { - options[0].abort() + if ( + options[0 /* controller */].signal.aborted || + !options[2 /* isCurrent */]() + ) { + options[0 /* controller */].abort() return [CANCELED] } return normalizeError(route, cause) } -export function navigateFrom(router: AnyRouter, location: ParsedLocation) { +function navigateFrom(router: AnyRouter, location: ParsedLocation) { return (opts: any) => router.navigate({ ...opts, @@ -359,13 +346,13 @@ async function contextualize( end: number, ): Promise { const [location, matches] = lane - const signal = options[0].signal - const preload = options[4] - for (let index = options[7] ?? 0; index < end; index++) { + const signal = options[0 /* controller */].signal + const preload = options[4 /* preload */] + for (let index = options[7 /* resolvedPrefix */] ?? 0; index < end; index++) { const match = matches[index]! const route = getRoute(router, match) - match.abortController = options[0] + match.abortController = options[0 /* controller */] // Contextualization is serial, so the previous match already contains the // complete parent context for this route. const parentContext = @@ -376,7 +363,7 @@ async function contextualize( navigate: navigateFrom(router, location), buildLocation: router.buildLocation, cause: preload ? ('preload' as const) : match.cause, - abortController: options[0], + abortController: options[0 /* controller */], preload, matches, routeId: route.id, @@ -401,8 +388,8 @@ async function contextualize( releaseFlight(match) return [index, normalizeLaneError(route, cause, options)] } - if (signal.aborted || !options[2]()) { - options[0].abort() + if (signal.aborted || !options[2 /* isCurrent */]()) { + options[0 /* controller */].abort() return [index, [CANCELED]] } const validationError = match.paramsError ?? match.searchError @@ -436,16 +423,16 @@ async function contextualize( if (previousStatus === 'success') { match.status = 'pending' } - options[8]?.() + options[8 /* onReady */]?.() try { - setFetching(router, match, 'beforeLoad', options[0]) + setFetching(router, match, 'beforeLoad', options[0 /* controller */]) const result = await waitFor(beforeLoad(beforeLoadContext), signal) - if (!options[2]()) { - options[0].abort() + if (!options[2 /* isCurrent */]()) { + options[0 /* controller */].abort() return [index, [CANCELED]] } const outcome = normalize(result, false, route.id) - if (outcome[0] !== SUCCESS) { + if (outcome[0 /* kind */] !== SUCCESS) { releaseFlight(match) return [index, outcome] } @@ -460,7 +447,7 @@ async function contextualize( if (previousStatus === 'success' && match.status === 'pending') { match.status = 'success' } - setFetching(router, match, false, options[0]) + setFetching(router, match, false, options[0 /* controller */]) } } @@ -471,11 +458,11 @@ function detachOwnedFlight( matchId: string, flight: LoaderFlight | undefined, ): AbortController | undefined { - if (flight && !--flight[2]) { - if (flight[3].get(matchId) === flight) { - flight[3].delete(matchId) + if (flight && !--flight[2 /* leases */]) { + if (flight[3 /* registry */].get(matchId) === flight) { + flight[3 /* registry */].delete(matchId) } - return flight[1] + return flight[1 /* controller */] } return } @@ -500,15 +487,13 @@ function releaseFlight(match: WorkMatch): void { } function retireFlight(matchId: string, flight: LoaderFlight): void { - if (flight[3].get(matchId) === flight) { - flight[3].delete(matchId) + if (flight[3 /* registry */].get(matchId) === flight) { + flight[3 /* registry */].delete(matchId) } } /** Release every loader-flight lease owned by a discarded match set. */ -export function transferMatchResources( - previous: Array, -): void { +export function transferMatchResources(previous: Array): void { const abort: Array = [] for (const match of previous as Array) { const claimed = detachClaim(match) @@ -532,7 +517,7 @@ function claimPendingFlights( for (const match of matches as Array) { const flight = router._flights.get(match.id) if (flight && flight !== match._flight) { - flight[2]++ + flight[2 /* leases */]++ match._claimedFlight = flight } } @@ -542,10 +527,10 @@ function setFetching( router: AnyRouter, match: WorkMatch, value: AnyRouteMatch['isFetching'], - owner?: AbortController, + owner: AbortController, ): void { match.isFetching = value - if (owner && router._tx?.[0] !== owner) { + if (router._tx?.[0 /* controller */] !== owner) { return } const store = router.stores.byRoute.get(match.routeId) @@ -564,7 +549,7 @@ function getLoaderContext( parentMatchPromise: Promise | undefined, preload: boolean, ): LoaderFnContext { - const location = lane[0] + const location = lane[0 /* location */] return { params: match.params, location, @@ -603,7 +588,7 @@ async function loadResource( if (!flight) { flight = registry.get(match.id) if (flight) { - flight[2]++ + flight[2 /* leases */]++ } } if (!flight) { @@ -625,8 +610,8 @@ async function loadResource( .then( (value): LoaderFlightResult => { const result = normalize(value, false, route.id) - if (result[0] === SUCCESS) { - result[2] = Date.now() + if (result[0 /* kind */] === SUCCESS) { + result[2 /* updatedAt */] = Date.now() } else { retireFlight(match.id, flight!) } @@ -634,18 +619,18 @@ async function loadResource( }, (cause) => { retireFlight(match.id, flight!) - return flight![2] + return flight![2 /* leases */] ? normalizeError(route, cause) : normalize(cause, true, route.id) }, - ) + ) flight = [outcome, controller, 1, registry] as LoaderFlight registry.set(match.id, flight) } match._flight = flight - match.abortController = flight[1] + match.abortController = flight[1 /* controller */] try { - return await waitFor(flight[0], signal) + return await waitFor(flight[0 /* outcome */], signal) } catch (cause) { if (cause !== signal) { throw cause @@ -663,21 +648,21 @@ function settle( result: LoaderResult, preload: boolean, ): match is SettledMatch { - const success = result[0] === SUCCESS - if (result[0] < REDIRECTED) { + const success = result[0 /* kind */] === SUCCESS + if (result[0 /* kind */] < REDIRECTED) { match.error = undefined match.status = 'success' match.invalid = !success if (success) { - match.loaderData = result[1] - match.updatedAt = result[2] + match.loaderData = result[1 /* data */] + match.updatedAt = result[2 /* updatedAt */] match.preload = preload } } return success } -export function cacheLoaderMatch( +function cacheLoaderMatch( router: CoordinatorRouter, match: SettledMatch, planned: AnyRouteMatch | undefined, @@ -687,12 +672,10 @@ export function cacheLoaderMatch( if ( current !== planned || (flight && - (flight[3].get(match.id) !== flight || - ( - router._committed.find((candidate) => candidate.id === match.id) as - | WorkMatch - | undefined - )?._flight === flight)) + (flight[3 /* registry */].get(match.id) !== flight || + router._committed.some( + (candidate) => (candidate as WorkMatch)._flight === flight, + ))) ) { return } @@ -702,7 +685,7 @@ export function cacheLoaderMatch( context: {}, } as WorkMatch if (cached._flight) { - cached._flight[2]++ + cached._flight[2 /* leases */]++ } router._cache.set(match.id, cached) if (current) { @@ -710,15 +693,12 @@ export function cacheLoaderMatch( } } -function getParentSnapshot( - match: WorkMatch, - outcome: LoaderResult, -): WorkMatch { - if (outcome[0] === ERROR || outcome[0] === NOT_FOUND) { +function getParentSnapshot(match: WorkMatch, outcome: LoaderResult): WorkMatch { + if (outcome[0 /* kind */] === ERROR || outcome[0 /* kind */] === NOT_FOUND) { return { ...match, - status: outcome[0] === ERROR ? 'error' : 'notFound', - error: outcome[1], + status: outcome[0 /* kind */] === ERROR ? 'error' : 'notFound', + error: outcome[1 /* error */], _flight: undefined, } } @@ -733,19 +713,19 @@ function createLoaderTask( semanticParent: Promise | undefined, options: ExecuteLaneOptions, ): Promise { - const match = lane[1][index]! + const match = lane[1 /* matches */][index]! const route = getRoute(router, match) - const preload = options[4] + const preload = options[4 /* preload */] if (preload && route.options.preload === false) { match.isFetching = false return Promise.resolve(match) } const plannedCacheMatch = preload ? router._cache.get(match.id) : undefined let configured - let reload = false + let reload = match.status !== 'success' let reloadFailure: LoaderFailure | undefined - try { - if (match.status === 'success') { + if (!reload) { + try { configured = route.options.shouldReload if (typeof configured === 'function') { configured = configured( @@ -754,48 +734,42 @@ function createLoaderTask( lane, match, route, - options[0], + options[0 /* controller */], semanticParent, preload, ), ) } - if (!options[2]()) { - options[0].abort() + if (!options[2 /* isCurrent */]()) { + options[0 /* controller */].abort() reloadFailure = [CANCELED] } - } - if (!reloadFailure) { - if (match.status !== 'success') { - reload = true - } else { + if (!reloadFailure) { const staleAge = preload || match.preload ? (route.options.preloadStaleTime ?? router.options.defaultPreloadStaleTime ?? 30_000) - : (route.options.staleTime ?? - router.options.defaultStaleTime ?? - 0) + : (route.options.staleTime ?? router.options.defaultStaleTime ?? 0) reload = !!( match.invalid || configured || (configured === undefined && Date.now() - match.updatedAt >= staleAge && - (options[6] || + (options[6 /* forceStaleReload */] || match.cause === 'enter' || - options[3].some( + options[3 /* base */].some( (candidate) => candidate.routeId === match.routeId && candidate.id !== match.id, ))) ) } + } catch (cause) { + match.invalid = true + releaseFlight(match) + reloadFailure = normalizeLaneError(route, cause, options) } - } catch (cause) { - match.invalid = true - releaseFlight(match) - reloadFailure = normalizeLaneError(route, cause, options) } const routeLoader = route.options.loader const loader = @@ -814,7 +788,7 @@ function createLoaderTask( reload && match.status === 'success' && !preload && - !options[5] && + !options[5 /* sync */] && ((typeof routeLoader === 'function' ? undefined : routeLoader?.staleReloadMode) ?? @@ -850,16 +824,12 @@ function createLoaderTask( if (match.status === 'success') { match.status = 'pending' } - options[8]?.() + options[8 /* onReady */]?.() } const rawOutcome: Promise = reloadFailure ? Promise.resolve(reloadFailure) : !blocking || !loader - ? Promise.resolve([ - SUCCESS, - match.loaderData, - match.updatedAt, - ]) + ? Promise.resolve([SUCCESS, match.loaderData, match.updatedAt]) : loadResource( router, lane, @@ -868,7 +838,7 @@ function createLoaderTask( loader, semanticParent, preload, - options[0], + options[0 /* controller */], ) const outcome = rawOutcome.then((result) => { if (blocking && settle(match, result, preload)) { @@ -884,9 +854,9 @@ function createLoaderTask( const rawChunkFailure = waitFor( Promise.resolve().then(() => - loadRouteChunk(route, undefined, options[8]), + loadRouteChunk(route, undefined, options[8 /* onReady */]), ), - options[0].signal, + options[0 /* controller */].signal, ).catch( (cause): IndexedOutcome => [ index, @@ -898,12 +868,12 @@ function createLoaderTask( if ( blocking && !failure && - result[0] === SUCCESS && + result[0 /* kind */] === SUCCESS && match.status === 'pending' && - options[2]() + options[2 /* isCurrent */]() ) { match.status = 'success' - options[8]?.() + options[8 /* onReady */]?.() } return failure }), @@ -930,16 +900,21 @@ function createLoaderTask( loader, semanticParent, false, - options[0], + options[0 /* controller */], ).then((result) => { match.isFetching = false - if (result[0] === SUCCESS) { + if (result[0 /* kind */] === SUCCESS) { retireFlight(match.id, candidate._flight!) } settle(candidate, result, false) return result }) - ;(lane[2] ??= []).push([index, backgroundOutcome, chunkFailure, candidate]) + ;(lane[2 /* background */] ??= []).push([ + index, + backgroundOutcome, + chunkFailure, + candidate, + ]) return backgroundOutcome.then((result) => getParentSnapshot(candidate, result), ) @@ -953,10 +928,12 @@ async function getNotFoundBoundary( fallback = 0, preload?: boolean, ): Promise { - const cause = indexed?.[1][1] as NotFoundError | undefined + const cause = indexed?.[1 /* outcome */][1 /* error or redirect */] as + | NotFoundError + | undefined let index = cause?.routeId ? matches.findIndex((match) => match.routeId === cause.routeId) - : (indexed?.[0] ?? matches.length - 1) + : (indexed?.[0 /* index */] ?? matches.length - 1) if (index < 0) { index = 0 } @@ -982,9 +959,11 @@ async function getNotFoundBoundary( } function discardBackground(lane: Lane): void { - if (lane[2]) { - transferMatchResources(lane[2].map((task) => task[3])) - lane[2] = undefined + if (lane[2 /* background */]) { + transferMatchResources( + lane[2 /* background */].map((task) => task[3 /* candidate */]), + ) + lane[2 /* background */] = undefined } } @@ -995,10 +974,10 @@ function waitForDescendantRedirects( return Promise.all( (tasks ?? []).map( (task) => - task[0] > boundary && - task[1].then((outcome) => { - if (outcome[0] === REDIRECTED) { - throw [task[0], outcome] as IndexedOutcome + task[0 /* index */] > boundary && + task[1 /* outcome */].then((outcome) => { + if (outcome[0 /* kind */] === REDIRECTED) { + throw [task[0 /* index */], outcome] as IndexedOutcome } }), ), @@ -1016,15 +995,15 @@ async function settleTasks( try { await Promise.all( tasks.map((task) => - task[1].then(async (outcome) => { - const taskIndex = task[0] + task[1 /* outcome */].then(async (outcome) => { + const taskIndex = task[0 /* index */] if (gate && taskIndex >= (await gate)) { return } - if (outcome[0] >= REDIRECTED) { + if (outcome[0 /* kind */] >= REDIRECTED) { throw [taskIndex, outcome] as IndexedOutcome } - if (outcome[0] !== SUCCESS) { + if (outcome[0 /* kind */] !== SUCCESS) { loaderFailure ||= [taskIndex, outcome] // Every started descendant must settle before an ordinary failure // wins because a redirect from any of them remains control flow. @@ -1049,12 +1028,12 @@ async function reduceLane( onReady?: () => void, preload?: boolean, ): Promise { - const matches = lane[1] + const matches = lane[1 /* matches */] let failure = await settlement let redirectLimitExceeded = false const plannedBoundary = matches.findIndex((match) => match._notFound) const boundaryOf = (found: IndexedOutcome) => - found[1][0] === NOT_FOUND + found[1 /* outcome */][0 /* kind */] === NOT_FOUND ? getNotFoundBoundary( router, matches, @@ -1063,36 +1042,36 @@ async function reduceLane( 0, preload, ) - : found[0] + : found[0 /* index */] let readinessEnd = plannedBoundary < 0 ? matches.length : plannedBoundary - if ((failure?.[1][0] ?? 0) >= REDIRECTED) { + if ((failure?.[1 /* outcome */][0 /* kind */] ?? 0) >= REDIRECTED) { readinessEnd = 0 } else if (failure) { - readinessEnd = failure[2] ??= await boundaryOf(failure) + readinessEnd = failure[2 /* boundary */] ??= await boundaryOf(failure) for (const task of tasks) { - if (task[0] >= readinessEnd) { + if (task[0 /* index */] >= readinessEnd) { break } - const outcome = await task[1] + const outcome = await task[1 /* outcome */] // Presence means a loader previously succeeded, even with `undefined`. if ( - outcome[0] !== SUCCESS && - outcome[0] < REDIRECTED && - !('loaderData' in matches[task[0]]!) + outcome[0 /* kind */] !== SUCCESS && + outcome[0 /* kind */] < REDIRECTED && + !('loaderData' in matches[task[0 /* index */]]!) ) { - failure = [task[0], outcome] - readinessEnd = failure[2] = await boundaryOf(failure) + failure = [task[0 /* index */], outcome] + readinessEnd = failure[2 /* boundary */] = await boundaryOf(failure) break } } } for (const task of tasks) { - if (task[0] >= readinessEnd) { + if (task[0 /* index */] >= readinessEnd) { break } - const chunkFailure = await task[2] + const chunkFailure = await task[2 /* chunkFailure */] if (!chunkFailure) { continue } @@ -1100,22 +1079,22 @@ async function reduceLane( break } - if (failure && failure[1][0] < REDIRECTED) { + if (failure && failure[1 /* outcome */][0 /* kind */] < REDIRECTED) { try { await waitForDescendantRedirects( - lane[2], - (failure[2] ??= await boundaryOf(failure)), + lane[2 /* background */], + (failure[2 /* boundary */] ??= await boundaryOf(failure)), ) } catch (cause) { failure = cause as IndexedOutcome } } - if ((failure?.[1][0] ?? 0) >= REDIRECTED) { - const outcome = failure![1] + if ((failure?.[1 /* outcome */][0 /* kind */] ?? 0) >= REDIRECTED) { + const outcome = failure![1 /* outcome */] if ( - outcome[0] !== REDIRECTED || - outcome[1].options.reloadDocument || + outcome[0 /* kind */] !== REDIRECTED || + outcome[1 /* redirect */].options.reloadDocument || redirects < 20 ) { discardBackground(lane) @@ -1126,13 +1105,13 @@ async function reduceLane( } const boundary = failure - ? (failure[2] ?? (await boundaryOf(failure))) + ? (failure[2 /* boundary */] ?? (await boundaryOf(failure))) : plannedBoundary if (boundary >= 0) { - const outcome = failure?.[1] - const kind = outcome?.[0] + const outcome = failure?.[1 /* outcome */] + const kind = outcome?.[0 /* kind */] const match = matches[boundary]! - const cause = outcome?.[1] + const cause = outcome?.[1 /* error or redirect */] const route = getRoute(router, match) if (outcome) { match._notFound = undefined @@ -1179,9 +1158,11 @@ async function reduceLane( } else if (redirectLimitExceeded) { controller.abort() await Promise.all([ - ...tasks.map((task) => task[1]), - ...tasks.map((task) => task[2]), - ...(lane[2] ?? []).map((task) => task[1]), + ...tasks.map((task) => task[1 /* outcome */]), + ...tasks.map((task) => task[2 /* chunkFailure */]), + ...(lane[2 /* background */] ?? []).map( + (task) => task[1 /* outcome */], + ), ]) discardBackground(lane) transferMatchResources(matches) @@ -1191,14 +1172,14 @@ async function reduceLane( return lane as unknown as ReducedLane } -export async function projectLane( +async function projectLane( router: AnyRouter, lane: ReducedLane, signal: AbortSignal, start = 0, - end = lane[1].length, + end = lane[1 /* matches */].length, ): Promise { - const matches = lane[1] + const matches = lane[1 /* matches */] for (let index = start; index < end; index++) { const match = matches[index]! const routeOptions = getRoute(router, match).options @@ -1248,11 +1229,11 @@ async function executeClientLane( if (router.options.notFoundMode !== 'root' && plannedBoundary >= 0) { const boundary = await getNotFoundBoundary( router, - matched[1], + matched[1 /* matches */], undefined, - options[0].signal, + options[0 /* controller */].signal, plannedBoundary, - options[4], + options[4 /* preload */], ) if (boundary !== plannedBoundary) { matches[plannedBoundary]!._notFound = undefined @@ -1266,29 +1247,29 @@ async function executeClientLane( // the two use sites below rather than granted by a (byte-costing) return. const failure = await contextualize(router, matched, options, end) if (failure) { - options[5] = true + options[5 /* sync */] = true } const tasks: Array = [] - const start = options[7] ?? 0 + const start = options[7 /* resolvedPrefix */] ?? 0 let semanticParent = start - ? Promise.resolve(matched[1][start - 1]!) + ? Promise.resolve(matched[1 /* matches */][start - 1]!) : undefined - end = failure?.[0] ?? end - if (failure?.[1][0] === NOT_FOUND) { - failure[2] = await getNotFoundBoundary( + end = failure?.[0 /* index */] ?? end + if (failure?.[1 /* outcome */][0 /* kind */] === NOT_FOUND) { + failure[2 /* boundary */] = await getNotFoundBoundary( router, - matched[1], + matched[1 /* matches */], failure, - options[0].signal, + options[0 /* controller */].signal, 0, - options[4], + options[4 /* preload */], ) - end = Math.min(end, failure[2] + 1) - } else if ((failure?.[1][0] ?? 0) >= REDIRECTED) { + end = Math.min(end, failure[2 /* boundary */] + 1) + } else if ((failure?.[1 /* outcome */][0 /* kind */] ?? 0) >= REDIRECTED) { end = 0 } for (let index = start; index < end; index++) { - if (options[0].signal.aborted) { + if (options[0 /* controller */].signal.aborted) { break } semanticParent = createLoaderTask( @@ -1300,7 +1281,7 @@ async function executeClientLane( options, ) } - for (const match of matched[1]) { + for (const match of matched[1 /* matches */]) { detachClaim(match)?.abort() } let reduced: ReducedLane | ControlOutcome @@ -1309,22 +1290,22 @@ async function executeClientLane( router, matched as unknown as ContextualizedLane, tasks, - options[0], - options[1], - settleTasks(tasks, failure, matched[2]), - options[8], - options[4], + options[0 /* controller */], + options[1 /* redirects */], + settleTasks(tasks, failure, matched[2 /* background */]), + options[8 /* onReady */], + options[4 /* preload */], ) - if (matched[2]?.length) { - matched[3] = settleTasks( - matched[2], + if (matched[2 /* background */]?.length) { + matched[3 /* backgroundSettlement */] = settleTasks( + matched[2 /* background */], undefined, undefined, reduction.then( (foreground) => isControl(foreground) ? 0 - : _getRenderedMatches(foreground[1]).length, + : _getRenderedMatches(foreground[1 /* matches */]).length, () => 0, ), ) @@ -1340,8 +1321,10 @@ async function executeClientLane( return projectLane( router, reduced, - options[0].signal, - options[7] === reduced[1].length ? options[7] : 0, + options[0 /* controller */].signal, + options[7 /* resolvedPrefix */] === reduced[1 /* matches */].length + ? options[7 /* resolvedPrefix */] + : 0, ) } @@ -1357,13 +1340,17 @@ function offerPending(router: CoordinatorRouter, tx: LoadTransaction): void { } let session = router._pending let tookOver = false - const sessionMatchId = session?.[0][3][session[1]]?.id - if (session?.[0] !== tx) { - if (session && tx[3][session[1]]?.id === sessionMatchId) { - session[0] = tx + const sessionMatchId = + session?.[0 /* owner */][3 /* matches */][session[1 /* boundary */]]?.id + if (session?.[0 /* owner */] !== tx) { + if ( + session && + tx[3 /* matches */][session[1 /* boundary */]]?.id === sessionMatchId + ) { + session[0 /* owner */] = tx tookOver = true } else { - clearTimeout(session?.[3]) + clearTimeout(session?.[3 /* timer */]) router._pending = session = undefined } } @@ -1374,8 +1361,8 @@ function offerPending(router: CoordinatorRouter, tx: LoadTransaction): void { let delay: number | undefined let min = 0 let component: unknown - for (; boundary < tx[3].length; boundary++) { - const match = tx[3][boundary]! + for (; boundary < tx[3 /* matches */].length; boundary++) { + const match = tx[3 /* matches */][boundary]! const success = match.status === 'success' const visible = success && @@ -1395,64 +1382,71 @@ function offerPending(router: CoordinatorRouter, tx: LoadTransaction): void { if (!component || typeof delay !== 'number' || delay === Infinity) { return } - min = - route.options.pendingMinMs ?? router.options.defaultPendingMinMs ?? 0 + min = route.options.pendingMinMs ?? router.options.defaultPendingMinMs ?? 0 break } if (delay === undefined) { return } - const matchId = tx[3][boundary]!.id - if (!session || session[1] !== boundary || sessionMatchId !== matchId) { + const matchId = tx[3 /* matches */][boundary]!.id + if ( + !session || + session[1 /* boundary */] !== boundary || + sessionMatchId !== matchId + ) { // Hydration and redirects can preserve pending presentation without a session. // Do not delay it again; conservatively start pendingMinMs from now. - clearTimeout(session?.[3]) + clearTimeout(session?.[3 /* timer */]) const presentedMatch = presented[boundary] const visible = presentedMatch?.id === matchId && presentedMatch.status === 'pending' router._pending = session = [ tx, boundary, - visible ? Date.now() + min : tx[4] + delay, + visible ? Date.now() + min : tx[4 /* startedAt */] + delay, undefined, visible ? Promise.resolve(true) : undefined, component, ] } - if (session[4] && !tookOver && session[5] === component) { + if ( + session[4 /* ack */] && + !tookOver && + session[5 /* component */] === component + ) { return } - session[5] = component - if (!session[4]) { - clearTimeout(session[3]) - const remaining = session[2] - Date.now() + session[5 /* component */] = component + if (!session[4 /* ack */]) { + clearTimeout(session[3 /* timer */]) + const remaining = session[2 /* deadline */] - Date.now() if (remaining > 0) { - session[3] = setTimeout(() => { + session[3 /* timer */] = setTimeout(() => { offerPending(router, tx) }, remaining) return } - session[2] = 0 + session[2 /* deadline */] = 0 } - const offered = tx[3].map((match) => ({ + const offered = tx[3 /* matches */].map((match) => ({ ...match, _flight: undefined, })) offered[boundary]!.status = 'pending' const ack = router - .startTransition(() => router.stores.setMatches(offered), offered) + .startTransition(() => router.stores.setMatches(offered)) .then((rendered) => { if ( rendered && router._pending === session && - session[4] === ack && - !session[2] + session[4 /* ack */] === ack && + !session[2 /* deadline */] ) { - session[2] = Date.now() + min + session[2 /* deadline */] = Date.now() + min } return rendered }) - session[4] = ack + session[4 /* ack */] = ack } /** @@ -1461,8 +1455,8 @@ function offerPending(router: CoordinatorRouter, tx: LoadTransaction): void { */ function finishPending(router: CoordinatorRouter, tx: LoadTransaction): void { const session = router._pending - if (session?.[0] === tx) { - clearTimeout(session[3]) + if (session?.[0 /* owner */] === tx) { + clearTimeout(session[3 /* timer */]) router._pending = undefined } } @@ -1476,7 +1470,7 @@ function publishMatches( } function discardLane(lane: ProjectedLane): void { - transferMatchResources(lane[1]) + transferMatchResources(lane[1 /* matches */]) discardBackground(lane) } @@ -1541,115 +1535,69 @@ function commitMatches( } } // The lane becomes committed before publication can synchronously reenter. - tx[3] = [] + tx[3 /* matches */] = [] router._cache = cached publishMatches(router, matches) transferMatchResources(discarded) runRouteLifecycle(router, previous, matches, () => router._tx === tx) } -function commitRefreshMatches( - router: CoordinatorRouter, - tx: LoadTransaction, - matches: LaneMatches<'projected'>, - checkpoint: PublicationCheckpoint, -): void { - const previous = router._committed - const previousCached = router._cache - for (const match of matches) { - match.preload = false - } - const cached = new Map() - // Delay releasing the previous owners until the HMR render is acknowledged. - // Old generations must not become reusable cache entries after refresh. - tx[3] = [] - router._cache = cached - checkpoint.previousMatches = previous - checkpoint.previousCache = previousCached - checkpoint.published = true - publishMatches(router, matches) - if (!checkpoint.published || router._tx !== tx) { - return - } - runRouteLifecycle(router, previous, matches, () => router._tx === tx, true) -} - -function settlePublication( - router: CoordinatorRouter, - checkpoint: PublicationCheckpoint, -): void { - if (!checkpoint.published) { - return - } - checkpoint.published = false - const retained = [...router._cache.values(), ...router._committed] - transferMatchResources( - [...checkpoint.previousCache.values(), ...checkpoint.previousMatches].filter( - (match) => !retained.includes(match), - ), - ) -} - -function rollbackPublication( - router: CoordinatorRouter, - tx: LoadTransaction, - lane: ProjectedLane, - checkpoint: PublicationCheckpoint, -): boolean { - if ( - !checkpoint.published || - router._tx !== tx || - router._committed !== lane[1] - ) { - settlePublication(router, checkpoint) - return false - } - - router._cancelTransition?.() - const discarded = [...router._cache.values(), ...router._committed] - const restored = [ - ...checkpoint.previousCache.values(), - ...checkpoint.previousMatches, - ] - router._cache = checkpoint.previousCache - router._committed = checkpoint.previousMatches - checkpoint.published = false - - finishPending(router, tx) - router.batch(() => { - router.stores.status.set('idle') - router.stores.setMatches(checkpoint.previousPresentation) - }) - tx[0].abort() - transferMatchResources( - discarded.filter((match) => !restored.includes(match)), - ) - discardBackground(lane) - if (router._tx === tx && router._commitPromise === checkpoint.commitPromise) { - router._commitPromise?.resolve() - router._commitPromise = undefined - } - return true -} - async function transitionRefresh( router: CoordinatorRouter, tx: LoadTransaction, - lane: ProjectedLane, + matches: LaneMatches<'projected'>, changeInfo: ReturnType, ): Promise { - const checkpoint: PublicationCheckpoint = { - previousMatches: router._committed, - previousPresentation: tx[6]?.[0] ?? router.stores.matches.get(), - previousCache: router._cache, - commitPromise: router._commitPromise, - published: false, + const refresh = tx[6 /* refresh */]! + const commitPromise = router._commitPromise + // Presence means this refresh is published but not yet acknowledged. + let previousMatches: Array | undefined + + const settle = () => { + const previous = previousMatches + previousMatches = undefined + if (previous) { + transferMatchResources(previous) + } + } + const rollback = () => { + refresh[2 /* rollback */] = undefined + const previous = previousMatches + if ( + previous === undefined || + router._tx !== tx || + router._committed !== matches + ) { + settle() + return false + } + + previousMatches = undefined + router._committed = previous + router.batch(() => { + router.stores.status.set('idle') + router.stores.setMatches(refresh[0 /* presentation */]) + }) + tx[0 /* controller */].abort() + transferMatchResources(matches) + if (router._tx === tx && router._commitPromise === commitPromise) { + commitPromise?.resolve() + router._commitPromise = undefined + } + return true } const commit = () => { finishPending(router, tx) - router._rollbackRefresh = rollback - commitRefreshMatches(router, tx, lane[1], checkpoint) - if (!checkpoint.published || router._tx !== tx) { + refresh[2 /* rollback */] = rollback + tx[3 /* matches */] = [] + const previous = router._committed + previousMatches = previous + publishMatches(router, matches) + if (previousMatches === undefined || router._tx !== tx) { + return + } + runRouteLifecycle(router, previous, matches, () => router._tx === tx, true) + if (previousMatches === undefined || router._tx !== tx) { return } router.emit({ type: 'onLoad', ...changeInfo }) @@ -1657,27 +1605,19 @@ async function transitionRefresh( router.emit({ type: 'onBeforeRouteMount', ...changeInfo }) } } - const rollback = () => { - if (router._rollbackRefresh === rollback) { - router._rollbackRefresh = undefined - } - return rollbackPublication(router, tx, lane, checkpoint) - } try { - const rendered = await router.startTransition(commit, lane[1]) - if (router._rollbackRefresh === rollback) { - router._rollbackRefresh = undefined - } - if (checkpoint.published) { - const handoff = tx[6]?.[1] + const rendered = await router.startTransition(commit) + refresh[2 /* rollback */] = undefined + if (previousMatches !== undefined) { + const handoff = refresh[1 /* handoff */] if (handoff && router._handoff === handoff) { - handoff[1]() + handoff[1 /* finish */]() } if (router._tx === tx) { - tx[6] = undefined + tx[6 /* refresh */] = undefined } } - settlePublication(router, checkpoint) + settle() return rendered } catch (cause) { if (rollback()) { @@ -1693,7 +1633,7 @@ async function awaitCurrent( ): Promise { let current = router._tx while (current && current !== owner) { - await current[5] + await current[5 /* done */] if (router._tx === current) { return } @@ -1710,7 +1650,7 @@ async function followRedirect( ...redirect.options, replace: true, ignoreBlocker: true, - _redirects: tx[1] + 1, + _redirects: tx[1 /* redirects */] + 1, } as any) } @@ -1719,13 +1659,12 @@ function restoreCommitted( tx: LoadTransaction, ): void { finishPending(router, tx) - tx[0].abort() - transferMatchResources(tx[3]) - tx[3] = [] + tx[0 /* controller */].abort() + transferMatchResources(tx[3 /* matches */]) + tx[3 /* matches */] = [] if (router._tx !== tx) { return } - router._cancelTransition?.() router.batch(() => { router.stores.status.set('idle') router.stores.setMatches(router._committed) @@ -1748,22 +1687,29 @@ async function runBackground( let taskIndex = 0 const next = base.map((match, index) => { const task = tasks[taskIndex] - if (task?.[0] === index) { + if (task?.[0 /* index */] === index) { taskIndex++ - return task[3] + return task[3 /* candidate */] } const clone = { ...match } as WorkMatch if (clone._flight) { - clone._flight[2]++ + clone._flight[2 /* leases */]++ } return clone }) // Phase jump: the clones inherit beforeLoad context from the committed // foreground lane, which already ran `contextualize` for these matches. - const lane = [tx[2], next] as ContextualizedLane + const lane = [tx[2 /* location */], next] as ContextualizedLane let reduced: ReducedLane | ControlOutcome try { - reduced = await reduceLane(router, lane, tasks, tx[0], tx[1], settlement) + reduced = await reduceLane( + router, + lane, + tasks, + tx[0 /* controller */], + tx[1 /* redirects */], + settlement, + ) } catch (cause) { transferMatchResources(next) throw cause @@ -1771,28 +1717,32 @@ async function runBackground( if (isControl(reduced)) { transferMatchResources(next) if ( - reduced[0] === REDIRECTED && + reduced[0 /* kind */] === REDIRECTED && router._tx === tx && router._committed === base ) { - await followRedirect(router, tx, reduced[1]) + await followRedirect(router, tx, reduced[1 /* redirect */]) } return } - const projected = await projectLane(router, reduced, tx[0].signal) + const projected = await projectLane( + router, + reduced, + tx[0 /* controller */].signal, + ) if (router._tx !== tx || router._committed !== base) { - transferMatchResources(projected[1]) + transferMatchResources(projected[1 /* matches */]) return } for (const task of tasks) { - const match = task[3] + const match = task[3 /* candidate */] const cached = router._cache.get(match.id) as WorkMatch | undefined if (cached?._flight && cached._flight === match._flight) { router._cache.delete(match.id) releaseFlight(cached) } } - publishMatches(router, projected[1]) + publishMatches(router, projected[1 /* matches */]) transferMatchResources(base) } @@ -1805,9 +1755,9 @@ async function runClientTransaction( resolvedPrefix?: number, ): Promise { const options: ExecuteLaneOptions = [ - tx[0], - tx[1], - () => router._tx === tx && !!tx[3].length, + tx[0 /* controller */], + tx[1 /* redirects */], + () => router._tx === tx && !!tx[3 /* matches */].length, router._committed, false, sync, @@ -1815,18 +1765,23 @@ async function runClientTransaction( resolvedPrefix, onReady, ] - const result = await executeClientLane(router, tx[2], tx[3], options) + const result = await executeClientLane( + router, + tx[2 /* location */], + tx[3 /* matches */], + options, + ) if (isControl(result)) { - if (result[0] === REDIRECTED && router._tx === tx) { + if (result[0 /* kind */] === REDIRECTED && router._tx === tx) { finishPending(router, tx) - transferMatchResources(tx[3]) - tx[3] = [] + transferMatchResources(tx[3 /* matches */]) + tx[3 /* matches */] = [] if (router._tx === tx) { - if (process.env.NODE_ENV !== 'production' && tx[6]) { + if (process.env.NODE_ENV !== 'production' && tx[6 /* refresh */]) { router._refreshNextLoad = true } - await followRedirect(router, tx, result[1]) + await followRedirect(router, tx, result[1 /* redirect */]) } } else { restoreCommitted(router, tx) @@ -1834,36 +1789,40 @@ async function runClientTransaction( return } const pending = router._pending - if (pending?.[0] === tx) { + if (pending?.[0 /* owner */] === tx) { /** * Loading finished, so cancel any pending reveal. If the fallback rendered, * wait out the rest of `pendingMinMs` before replacing it. If it never * rendered, there is no minimum wait; if another load took it over, that * load owns the deadline. */ - clearTimeout(pending[3]) - if (pending[4]) { - const signal = tx[0].signal + clearTimeout(pending[3 /* timer */]) + if (pending[4 /* ack */]) { + const signal = tx[0 /* controller */].signal let rendered = false try { - rendered = await waitFor(pending[4], signal) + rendered = await waitFor(pending[4 /* ack */], signal) } catch (cause) { if (cause !== signal) { throw cause } } - if (rendered && router._pending === pending && pending[0] === tx) { - const remaining = pending[2] - Date.now() + if ( + rendered && + router._pending === pending && + pending[0 /* owner */] === tx + ) { + const remaining = pending[2 /* deadline */] - Date.now() if (remaining > 0) { try { await waitFor( new Promise((resolve) => { - pending[3] = setTimeout(resolve, remaining) + pending[3 /* timer */] = setTimeout(resolve, remaining) }), signal, ) } catch {} - clearTimeout(pending[3]) + clearTimeout(pending[3 /* timer */]) } } } @@ -1873,12 +1832,12 @@ async function runClientTransaction( discardLane(result) return } - const toLocation = tx[2] + const toLocation = tx[2 /* location */] const changeInfo = getLocationChangeInfo( toLocation, router.stores.resolvedLocation.get(), ) - const background = result[2] + const background = result[2 /* background */] await router.startViewTransition(async () => { if (router._tx !== tx) { discardLane(result) @@ -1886,7 +1845,7 @@ async function runClientTransaction( } const commit = () => { finishPending(router, tx) - commitMatches(router, tx, result[1], resolvedPrefix) + commitMatches(router, tx, result[1 /* matches */], resolvedPrefix) if (router._tx !== tx) { return } @@ -1896,12 +1855,17 @@ async function runClientTransaction( } } const rendered = - process.env.NODE_ENV !== 'production' && tx[6] - ? await transitionRefresh(router, tx, result, changeInfo) - : await router.startTransition(commit, result[1]) + process.env.NODE_ENV !== 'production' && tx[6 /* refresh */] + ? await transitionRefresh( + router, + tx, + result[1 /* matches */], + changeInfo, + ) + : await router.startTransition(commit) if ( process.env.NODE_ENV !== 'production' && - tx[6] && + tx[6 /* refresh */] && rendered === undefined ) { return @@ -1914,9 +1878,13 @@ async function runClientTransaction( // Publish refreshes only after the foreground render acknowledgement. // Otherwise a fast refresh can replace the acknowledged generation // before the framework commits it and strand the navigation. - runBackground(router, tx, result[1], background, result[3]!).catch( - console.error, - ) + runBackground( + router, + tx, + result[1 /* matches */], + background, + result[3 /* backgroundSettlement */]!, + ).catch(console.error) } router.batch(() => { router.stores.resolvedLocation.set(toLocation) @@ -1942,8 +1910,8 @@ export async function loadClientRoute( ): Promise { let rematerialize = false if (process.env.NODE_ENV !== 'production') { - router._rollbackRefresh?.() - rematerialize = !!router._refreshNextLoad || !!router._tx?.[6] + router._tx?.[6 /* refresh */]?.[2 /* rollback */]?.() + rematerialize = !!router._refreshNextLoad || !!router._tx?.[6 /* refresh */] } const refreshPresentation = rematerialize ? router.stores.matches.get() @@ -1967,32 +1935,34 @@ export async function loadClientRoute( !redirects && previousOwner && !rematerialize && - previousOwner[2].href === location.href && + previousOwner[2 /* location */].href === location.href && router.stores.status.get() === 'pending' ) { await awaitCurrent(router) return } const handoff = router._handoff - const hydrationController = rematerialize ? undefined : handoff?.[0]() + const hydrationController = rematerialize + ? undefined + : handoff?.[0 /* claim */]() const preflight = new AbortController() const previousPreflight = router._preflight router._preflight = preflight if (!rematerialize && !hydrationController) { - handoff?.[1]() + handoff?.[1 /* finish */]() } previousPreflight?.abort() - if (preflight.signal.aborted || router._tx !== previousOwner) { + if (router._preflight !== preflight) { await awaitCurrent(router, previousOwner) return } const changeInfo = getLocationChangeInfo(location, resolvedLocation) router.emit({ type: 'onBeforeNavigate', ...changeInfo }) - if (!preflight.signal.aborted && router._tx === previousOwner) { + if (router._preflight === preflight) { router.emit({ type: 'onBeforeLoad', ...changeInfo }) } - if (preflight.signal.aborted || router._tx !== previousOwner) { + if (router._preflight !== preflight) { preflight.abort() await awaitCurrent(router, previousOwner) return @@ -2000,7 +1970,6 @@ export async function loadClientRoute( const sameHref = previousLocation.href === location.href let matches: Array let controller = preflight - let resolvedPrefix: number | undefined try { matches = process.env.NODE_ENV !== 'production' && rematerialize @@ -2028,13 +1997,15 @@ export async function loadClientRoute( await awaitCurrent(router, previousOwner) return } - resolvedPrefix = hydrationController ? handoff![1](matches) : undefined + const resolvedPrefix = hydrationController + ? handoff![1 /* finish */](matches) + : undefined if (resolvedPrefix) { controller = hydrationController! } else { hydrationController?.abort() } - if (router._preflight !== preflight || router._tx !== previousOwner) { + if (router._preflight !== preflight) { preflight.abort() transferMatchResources(matches) await awaitCurrent(router, previousOwner) @@ -2070,7 +2041,7 @@ export async function loadClientRoute( ] if (process.env.NODE_ENV !== 'production' && rematerialize) { // `refreshPresentation` is always captured when `rematerialize` is set. - tx[6] = [refreshPresentation!, handoff] + tx[6 /* refresh */] = [refreshPresentation!, handoff] router._refreshNextLoad = undefined } router._tx = tx @@ -2083,15 +2054,15 @@ export async function loadClientRoute( break } if (match.isFetching) { - setFetching(router, match, false) + setFetching(router, match, false, tx[0 /* controller */]) } } - previousOwner[0].abort() - transferMatchResources(previousOwner[3]) + previousOwner[0 /* controller */].abort() + transferMatchResources(previousOwner[3 /* matches */]) } if (router._tx !== tx) { - transferMatchResources(tx[3]) - tx[3] = [] + transferMatchResources(tx[3 /* matches */]) + tx[3 /* matches */] = [] await awaitCurrent(router, tx) return } @@ -2102,7 +2073,7 @@ export async function loadClientRoute( }) offerPending(router, tx) try { - await tx[5] + await tx[5 /* done */] } finally { await awaitCurrent(router, tx) } @@ -2112,10 +2083,14 @@ export async function refreshClientRoute( router: CoordinatorRouter, ): Promise { router._refreshNextLoad = true - router._rollbackRefresh?.() + router._tx?.[6 /* refresh */]?.[2 /* rollback */]?.() const pending = router._tx - if (pending && !pending[6] && router.stores.status.get() === 'pending') { - await pending[5] + if ( + pending && + !pending[6 /* refresh */] && + router.stores.status.get() === 'pending' + ) { + await pending[5 /* done */] if (router._tx !== pending) { await awaitCurrent(router, pending) } @@ -2134,7 +2109,7 @@ export async function preloadClientRoute( ): Promise | undefined> { if ( process.env.NODE_ENV !== 'production' && - (router._refreshNextLoad || router._tx?.[6]) + (router._refreshNextLoad || router._tx?.[6 /* refresh */]) ) { return } @@ -2154,46 +2129,47 @@ export async function preloadClientRoute( return } router._preloads.set(controller, matches) + let active: boolean try { - const result = await executeClientLane(router, location, matches, [ - controller, - redirects, - // Preload lanes run to completion even when unrelated navigations - // commit: finished work seeds the cache. - () => true, - base, - true, - ]) - const control = isControl(result) - if (!router._preloads.delete(controller)) { - return control ? undefined : matches + let result: LaneResult + try { + result = await executeClientLane(router, location, matches, [ + controller, + redirects, + // Preload lanes run to completion even when unrelated navigations + // commit: finished work seeds the cache. + () => true, + base, + true, + ]) + } finally { + active = router._preloads.delete(controller) + transferMatchResources(matches) + controller.abort() } - transferMatchResources(matches) - controller.abort() - if (!control) { + if (!isControl(result)) { return matches } - if (result[0] === REDIRECTED && !result[1].options.reloadDocument) { + if ( + active && + result[0 /* kind */] === REDIRECTED && + !result[1 /* redirect */].options.reloadDocument + ) { return preloadClientRoute( router, { - ...result[1].options, + ...result[1 /* redirect */].options, _fromLocation: location, }, redirects + 1, ) } - return } catch (cause) { - if (router._preloads.delete(controller)) { - transferMatchResources(matches) - controller.abort() - } if (!isNotFound(cause)) { console.error(cause) } - return } + return } // --- SSR hydration (client entry via @tanstack/router-core/ssr/client) --- @@ -2252,10 +2228,7 @@ export async function hydrate(router: AnyRouter): Promise { return false } const isCurrent = () => - (!router._tx && - router._preflight === controller && - !controller.signal.aborted) || - retire() + (router._preflight === controller && !controller.signal.aborted) || retire() let location!: AnyRouter['latestLocation'] let candidates!: Array @@ -2307,7 +2280,7 @@ export async function hydrate(router: AnyRouter): Promise { router, // Phase jump: dehydrated server data is already past the loader // phase — the guard above verified a settled success (or transported - // loaderData), so this clone is settled without a client settleInto. + // loaderData), so this clone is settled without a client settle. { ...match, status: 'success', diff --git a/packages/router-core/src/router.ts b/packages/router-core/src/router.ts index e18269802a..428fd31765 100644 --- a/packages/router-core/src/router.ts +++ b/packages/router-core/src/router.ts @@ -774,10 +774,7 @@ export type CommitLocationFn = ({ ...next }: ParsedLocation & CommitLocationOptions) => Promise -export type StartTransitionFn = ( - fn: () => void, - expected: Array, -) => Promise +export type StartTransitionFn = (fn: () => void) => Promise export interface MatchRoutesFn { ( @@ -934,6 +931,10 @@ export function _getUserHistoryState({ return state } +/** + * User callbacks cannot interrupt router control flow. Development HMR lets + * lifecycle errors escape so its unacknowledged publication can roll back. + */ function runCallback( callback: ((arg: T) => void) | undefined, arg: T, @@ -1059,6 +1060,8 @@ export interface RouterCore< _pending?: PendingSession /** Result of the latest server load, used to render or redirect. */ _serverResult?: ServerLoadResult + /** Resolves the framework's pending matches publication. */ + _rendered?: (rendered: boolean) => void /** Development-only HMR reload for a route and its descendants. */ _refreshRoute: (() => Promise) | undefined /** Development-only replacement for a route's lazy chunk owner. */ diff --git a/packages/router-core/tests/boundary-component-chunk.test.ts b/packages/router-core/tests/boundary-component-chunk.test.ts index 06953b4543..2e85096b32 100644 --- a/packages/router-core/tests/boundary-component-chunk.test.ts +++ b/packages/router-core/tests/boundary-component-chunk.test.ts @@ -34,10 +34,12 @@ afterEach(async () => { }) describe('route boundary component preloads', () => { - test('errorComponent preload resolves without waiting for a pending route component preload', async () => { + test('an error boundary ignores a late normal component failure', async () => { const componentGate = createControlledPromise() const errorComponentGate = createControlledPromise() const routeError = new Error('loader failed') + const componentError = new Error('component chunk failed') + const onError = vi.fn() let errorComponentPreloadCalls = 0 pendingGates.push(componentGate, errorComponentGate) @@ -58,6 +60,7 @@ describe('route boundary component preloads', () => { loader: () => { throw routeError }, + onError, component: SlowRouteComponent as any, errorComponent: ErrorBoundary as any, }) @@ -79,8 +82,16 @@ describe('route boundary component preloads', () => { const match = router.state.matches.find((item) => item.routeId === route.id) expect(match?.status).toBe('error') expect(match?.error).toBe(routeError) + expect(onError).toHaveBeenCalledOnce() - componentGate.resolve() + // The committed loader error makes the unused normal component stale even + // though this transaction's AbortController remains live after commit. + componentGate.reject(componentError) + await expect(componentGate).rejects.toBe(componentError) + await new Promise((resolve) => setTimeout(resolve, 0)) + + expect(onError).toHaveBeenCalledOnce() + expect(match?.error).toBe(routeError) }) test('global notFound does not wait for component chunks below its boundary', async () => { diff --git a/packages/router-core/tests/hmr-refresh-lifecycle.test.ts b/packages/router-core/tests/hmr-refresh-lifecycle.test.ts index cac5e942d1..7576d08c1a 100644 --- a/packages/router-core/tests/hmr-refresh-lifecycle.test.ts +++ b/packages/router-core/tests/hmr-refresh-lifecycle.test.ts @@ -1,11 +1,6 @@ import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' import { createMemoryHistory } from '@tanstack/history' -import { - BaseRootRoute, - BaseRoute, - createControlledPromise, - redirect, -} from '../src' +import { BaseRootRoute, BaseRoute, createControlledPromise } from '../src' import { createTestRouter } from './routerTestUtils' beforeEach(() => { @@ -56,211 +51,6 @@ describe('HMR route refresh', () => { unsubMount() }) - test('retires refresh mode after an acknowledged publication', async () => { - const otherLoader = vi.fn(() => 'other data') - const rootRoute = new BaseRootRoute({}) - const pageRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/page', - }) - const otherRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/other', - loader: otherLoader, - }) - const router = createTestRouter({ - routeTree: rootRoute.addChildren([pageRoute, otherRoute]), - history: createMemoryHistory({ initialEntries: ['/page'] }), - }) - - await router.load() - await router._refreshRoute!() - await router.preloadRoute({ to: '/other' }) - - expect(router._tx?.[6]).toBeUndefined() - expect(otherLoader).toHaveBeenCalledOnce() - }) - - test('passes rematerialization to a reentrant preflight load', async () => { - let generation = 1 - const loader = vi.fn(() => generation) - const rootRoute = new BaseRootRoute({}) - const pageRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/page', - staleTime: Infinity, - loader, - }) - const router = createTestRouter({ - routeTree: rootRoute.addChildren([pageRoute]), - history: createMemoryHistory({ initialEntries: ['/page'] }), - }) - - await router.load() - generation = 2 - let reenter = true - let reentrantLoad: Promise | undefined - const unsubscribe = router.subscribe('onBeforeNavigate', () => { - if (reenter) { - reenter = false - reentrantLoad = router.load({ sync: true }) - } - }) - try { - await router._refreshRoute!() - await reentrantLoad - } finally { - unsubscribe() - } - - expect(loader).toHaveBeenCalledTimes(2) - expect(router.state.matches.at(-1)?.loaderData).toBe(2) - }) - - test('passes rematerialization to a load that supersedes refresh work', async () => { - let generation = 1 - let reenter = false - let reentrantLoad: Promise | undefined - let router!: ReturnType - const loader = vi.fn(() => { - if (reenter) { - reenter = false - reentrantLoad = router.load({ sync: true }) - } - return generation - }) - const rootRoute = new BaseRootRoute({}) - const pageRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/page', - staleTime: Infinity, - loader, - }) - router = createTestRouter({ - routeTree: rootRoute.addChildren([pageRoute]), - history: createMemoryHistory({ initialEntries: ['/page'] }), - }) - - await router.load() - generation = 2 - reenter = true - await router._refreshRoute!() - await reentrantLoad - - expect(loader).toHaveBeenCalledTimes(3) - expect(router.state.matches.at(-1)?.loaderData).toBe(2) - }) - - test('passes rematerialization through a refresh redirect', async () => { - let generation = 1 - let shouldRedirect = false - const rootLoader = vi.fn(() => generation) - const rootRoute = new BaseRootRoute({ - staleTime: Infinity, - loader: rootLoader, - }) - const sourceRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/source', - beforeLoad: () => { - if (shouldRedirect) { - throw redirect({ to: '/target' }) - } - }, - }) - const targetRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/target', - }) - const router = createTestRouter({ - routeTree: rootRoute.addChildren([sourceRoute, targetRoute]), - history: createMemoryHistory({ initialEntries: ['/source'] }), - }) - - await router.load() - generation = 2 - shouldRedirect = true - await router._refreshRoute!() - - expect(router.state.location.pathname).toBe('/target') - expect(rootLoader).toHaveBeenCalledTimes(2) - expect(router.state.matches[0]?.loaderData).toBe(2) - }) - - test('restores the committed presentation when publication fails', async () => { - let generation = 1 - const rootRoute = new BaseRootRoute({}) - const pageRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/page', - loader: () => generation, - }) - const router = createTestRouter({ - routeTree: rootRoute.addChildren([pageRoute]), - history: createMemoryHistory({ initialEntries: ['/page'] }), - }) - - await router.load() - const previousMatches = router.state.matches - generation = 2 - const startTransition = router.startTransition - router.startTransition = async (fn) => { - fn() - router.clearCache() - throw new Error('render failed') - } - - await router._refreshRoute!() - - expect(router.state.status).toBe('idle') - expect(router.state.matches).toHaveLength(previousMatches.length) - expect(router.state.matches.at(-1)?.loaderData).toBe(1) - - router.startTransition = startTransition - generation = 3 - await router._refreshRoute!() - expect(router.state.matches.at(-1)?.loaderData).toBe(3) - }) - - test('keeps the rendered generation alive until refresh is acknowledged', async () => { - let generation = 1 - const signals: Array = [] - const rootRoute = new BaseRootRoute({}) - const pageRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/page', - loader: ({ abortController }) => { - signals.push(abortController.signal) - return generation - }, - }) - const router = createTestRouter({ - routeTree: rootRoute.addChildren([pageRoute]), - history: createMemoryHistory({ initialEntries: ['/page'] }), - }) - - await router.load() - const renderedSignal = signals[0]! - generation = 2 - const startTransition = router.startTransition - router.startTransition = async (fn) => { - fn() - throw new Error('render failed') - } - - await router._refreshRoute!() - - expect(renderedSignal.aborted).toBe(false) - expect(signals[1]?.aborted).toBe(true) - expect(router.state.matches.at(-1)?.loaderData).toBe(1) - - router.startTransition = startTransition - generation = 3 - await router._refreshRoute!() - expect(renderedSignal.aborted).toBe(true) - expect(router.state.matches.at(-1)?.loaderData).toBe(3) - }) - test('rolls overlapping refreshes back to the last acknowledged generation', async () => { let generation = 1 const rootRoute = new BaseRootRoute({}) @@ -268,6 +58,11 @@ describe('HMR route refresh', () => { getParentRoute: () => rootRoute, path: '/page', loader: () => generation, + onStay: () => { + if (generation === 3) { + throw new Error('replacement lifecycle failed') + } + }, }) const router = createTestRouter({ routeTree: rootRoute.addChildren([pageRoute]), @@ -276,20 +71,19 @@ describe('HMR route refresh', () => { await router.load() let transitionCount = 0 - let supersedeFirst!: () => void + let pending: ((rendered: boolean) => void) | undefined router.startTransition = (fn) => { transitionCount++ + pending?.(false) + pending = undefined fn() if (transitionCount === 1) { return new Promise((resolve) => { - supersedeFirst = () => resolve(false) + pending = resolve }) } - return Promise.reject(new Error('replacement render failed')) + return Promise.resolve(true) } - ;( - router as typeof router & { _cancelTransition?: () => void } - )._cancelTransition = () => supersedeFirst() generation = 2 const firstRefresh = router._refreshRoute!() @@ -324,20 +118,19 @@ describe('HMR route refresh', () => { await router.load() let transitionCount = 0 - let cancelRefresh!: () => void + let pending: ((rendered: boolean) => void) | undefined router.startTransition = (fn) => { transitionCount++ + pending?.(false) + pending = undefined fn() if (transitionCount === 1) { return new Promise((resolve) => { - cancelRefresh = () => resolve(false) + pending = resolve }) } return Promise.resolve(true) } - ;( - router as typeof router & { _cancelTransition?: () => void } - )._cancelTransition = () => cancelRefresh() generation = 2 const refresh = router._refreshRoute!() @@ -357,152 +150,4 @@ describe('HMR route refresh', () => { expect(navigationSettled).toHaveBeenCalledOnce() expect(router.state.matches.at(-1)?.routeId).toBe(destinationRoute.id) }) - - test('waits for an ordinary pending navigation before refreshing', async () => { - const destinationGate = createControlledPromise() - const rootRoute = new BaseRootRoute({}) - const pageRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/page', - }) - const destinationRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/destination', - pendingMs: 0, - pendingMinMs: 0, - pendingComponent: () => null, - loader: () => destinationGate, - }) - const router = createTestRouter({ - routeTree: rootRoute.addChildren([pageRoute, destinationRoute]), - history: createMemoryHistory({ initialEntries: ['/page'] }), - }) - - await router.load() - const navigation = router.navigate({ to: '/destination' }) - await vi.waitFor(() => { - expect(router.state.status).toBe('pending') - expect(router.state.matches.at(-1)?.routeId).toBe(destinationRoute.id) - }) - destinationRoute.options.onStay = () => { - throw new Error('refreshed destination failed') - } - const refreshSettled = vi.fn() - const refresh = router._refreshRoute!().then(refreshSettled) - await Promise.resolve() - expect(refreshSettled).not.toHaveBeenCalled() - - destinationGate.resolve() - await Promise.all([navigation, refresh]) - - expect(router.state.status).toBe('idle') - expect(router.state.matches.at(-1)).toMatchObject({ - routeId: destinationRoute.id, - status: 'success', - }) - expect(refreshSettled).toHaveBeenCalledOnce() - }) - - test('rolls back when an HMR lifecycle callback throws', async () => { - let generation = 1 - const rootRoute = new BaseRootRoute({}) - const pageRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/page', - loader: () => generation, - }) - const router = createTestRouter({ - routeTree: rootRoute.addChildren([pageRoute]), - history: createMemoryHistory({ initialEntries: ['/page'] }), - }) - - await router.load() - generation = 2 - pageRoute.options.onStay = () => { - throw new Error('lifecycle failed') - } - - await router._refreshRoute!() - - expect(router.state.status).toBe('idle') - expect(router.state.matches.at(-1)?.loaderData).toBe(1) - - pageRoute.options.onStay = undefined - generation = 3 - await router._refreshRoute!() - expect(router.state.matches.at(-1)?.loaderData).toBe(3) - }) - - test('ignores preloads triggered by HMR preflight hooks', async () => { - let generation = 1 - const rootRoute = new BaseRootRoute({}) - const pageRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/page', - loader: () => generation, - }) - const router = createTestRouter({ - routeTree: rootRoute.addChildren([pageRoute]), - history: createMemoryHistory({ initialEntries: ['/page'] }), - }) - - await router.load() - generation = 2 - const unsubscribe = router.subscribe('onBeforeLoad', () => { - void router.preloadRoute({ to: '/page' }) - }) - try { - await router._refreshRoute!() - } finally { - unsubscribe() - } - - expect(router.state.matches.at(-1)?.loaderData).toBe(2) - }) - - test('ignores a preload reentered from cache cleanup during HMR', async () => { - let reentrantPreload: Promise | undefined - let router!: ReturnType - const reentrantLoader = vi.fn(() => 'reentrant data') - const rootRoute = new BaseRootRoute({}) - const pageRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/page', - }) - const cachedRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/cached', - loader: ({ abortController }) => { - abortController.signal.addEventListener( - 'abort', - () => { - reentrantPreload = router.preloadRoute({ to: '/reentrant' }) - }, - { once: true }, - ) - return 'cached data' - }, - }) - const reentrantRoute = new BaseRoute({ - getParentRoute: () => rootRoute, - path: '/reentrant', - loader: reentrantLoader, - }) - router = createTestRouter({ - routeTree: rootRoute.addChildren([ - pageRoute, - cachedRoute, - reentrantRoute, - ]), - history: createMemoryHistory({ initialEntries: ['/page'] }), - }) - - await router.load() - await router.preloadRoute({ to: '/cached' }) - await router._refreshRoute!() - expect(reentrantPreload).toBeDefined() - await reentrantPreload - - expect(reentrantLoader).not.toHaveBeenCalled() - }) }) diff --git a/packages/router-core/tests/pending-terminal-boundary.test.ts b/packages/router-core/tests/pending-terminal-boundary.test.ts index 3d7959998d..aead36d383 100644 --- a/packages/router-core/tests/pending-terminal-boundary.test.ts +++ b/packages/router-core/tests/pending-terminal-boundary.test.ts @@ -66,15 +66,17 @@ test('a known parent error does not offer a descendant pending boundary while it Array<{ routeId: string; status: string; error: unknown }> > = [] const startTransition = router.startTransition - router.startTransition = (commit, expected) => { - transitions.push( - expected.map((match) => ({ - routeId: match.routeId, - status: match.status, - error: match.error, - })), - ) - return startTransition(commit, expected) + router.startTransition = (commit) => { + return startTransition(() => { + commit() + transitions.push( + router.stores.matches.get().map((match) => ({ + routeId: match.routeId, + status: match.status, + error: match.error, + })), + ) + }) } const navigation = router.navigate({ to: '/parent/child' }) diff --git a/packages/router-core/tests/preload-public-signal-lifetime.test.ts b/packages/router-core/tests/preload-public-signal-lifetime.test.ts index c83b6a54be..489cba702a 100644 --- a/packages/router-core/tests/preload-public-signal-lifetime.test.ts +++ b/packages/router-core/tests/preload-public-signal-lifetime.test.ts @@ -122,3 +122,34 @@ test('a superseded preload releases its lease on a reused loader generation', as expect(router.state.location.pathname).toBe('/') expect(parentSignal?.aborted).toBe(true) }) + +test('a terminal preload aborts its loader generation', async () => { + const routeError = new Error('preload failed') + let signal: AbortSignal | undefined + + const rootRoute = new BaseRootRoute({}) + const homeRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const reportsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/reports', + loader: ({ abortController }) => { + signal = abortController.signal + throw routeError + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([homeRoute, reportsRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const matches = await router.preloadRoute({ to: '/reports' }) + + expect( + matches?.find((match) => match.routeId === reportsRoute.id), + ).toMatchObject({ status: 'error', error: routeError }) + expect(signal?.aborted).toBe(true) +})