From 73ce10478466afd12a376f52f27a641216cdc032 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Sat, 5 Sep 2026 13:36:41 +0200 Subject: [PATCH 1/3] test(router): cover cached link pathname semantics --- .../tests/link-build-cache.test.tsx | 258 +++++++++ .../build-location-cache-regressions.test.ts | 293 ++++++++++ .../tests/build-location-cache.bench.ts | 111 ++++ .../tests/build-location-cache.test.ts | 536 ++++++++++++++++++ 4 files changed, 1198 insertions(+) create mode 100644 packages/react-router/tests/link-build-cache.test.tsx create mode 100644 packages/router-core/tests/build-location-cache-regressions.test.ts create mode 100644 packages/router-core/tests/build-location-cache.bench.ts create mode 100644 packages/router-core/tests/build-location-cache.test.ts diff --git a/packages/react-router/tests/link-build-cache.test.tsx b/packages/react-router/tests/link-build-cache.test.tsx new file mode 100644 index 0000000000..9306cc7712 --- /dev/null +++ b/packages/react-router/tests/link-build-cache.test.tsx @@ -0,0 +1,258 @@ +import React from 'react' +import { afterEach, expect, test, vi } from 'vitest' +import { + act, + cleanup, + fireEvent, + render, + screen, + waitFor, +} from '@testing-library/react' +import { + Link, + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, + retainSearchParams, +} from '../src' +import type { AnyRouter } from '../src' + +afterEach(cleanup) + +function setup(links: () => React.ReactNode) { + const root = createRootRoute({ + component: () => ( + <> + + + + ), + }) + const index = createRoute({ getParentRoute: () => root, path: '/' }) + const item = createRoute({ getParentRoute: () => root, path: '/items/$id' }) + const optional = createRoute({ + getParentRoute: () => root, + path: '/optional/{-$id}', + }) + const router = createRouter({ + routeTree: root.addChildren([index, item, optional]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + const build = router.buildLocation + let hits = 0 + vi.spyOn(router, 'buildLocation').mockImplementation((options) => { + const cache = (options as { _buildCache?: { value?: unknown } })._buildCache + const entry = cache?.value + const result = build(options) + if (entry && entry === cache?.value) { + hits++ + } + return result + }) + return { router, item, hits: () => hits } +} + +async function mount(router: AnyRouter) { + await act(async () => { + render() + await router.load() + }) +} + +function href() { + return screen.getByTestId('link').getAttribute('href') +} + +test('a cached destination keeps its href while active state follows navigation', async () => { + const { router, hits } = setup(() => ( + + item + + )) + await mount(router) + const before = hits() + expect(href()).toBe('/items/9') + expect(screen.getByTestId('link').className).not.toContain('active') + await act(() => router.navigate({ to: '/items/$id', params: { id: '9' } })) + expect(hits()).toBeGreaterThan(before) + expect(href()).toBe('/items/9') + expect(screen.getByTestId('link').className).toContain('active') + await act(() => router.navigate({ to: '/' })) + expect(screen.getByTestId('link').className).not.toContain('active') +}) + +test('changed link options discard the previous cache', async () => { + function Links() { + const [id, setId] = React.useState('1') + return ( + <> + + + item + + + ) + } + const { router, hits } = setup(() => ) + await mount(router) + await act(() => router.navigate({ to: '/items/$id', params: { id: '9' } })) + expect(hits()).toBeGreaterThan(0) + expect(href()).toBe('/items/1?tab=1#1') + fireEvent.click(screen.getByText('change')) + expect(href()).toBe('/items/2?tab=2#2') +}) + +test('cache hits still apply changed locale rewrites', async () => { + const { router, hits } = setup(() => ( + + item + + )) + let locale = 'en' + router.update({ + rewrite: { + input: ({ url }) => { + url.pathname = url.pathname.replace(/^\/(en|fr)(?=\/|$)/, '') || '/' + return url + }, + output: ({ url }) => { + url.pathname = `/${locale}${url.pathname}` + return url + }, + }, + }) + await mount(router) + expect(href()).toBe('/en/items/9') + const before = hits() + locale = 'fr' + await act(() => router.navigate({ to: '/items/$id', params: { id: '2' } })) + expect(hits()).toBeGreaterThan(before) + expect(href()).toBe('/fr/items/9') +}) + +test('an absent optional param is inherited after navigation', async () => { + const { router } = setup(() => ( + + optional + + )) + await mount(router) + expect(href()).toBe('/optional') + await act(() => router.navigate({ to: '/items/$id', params: { id: '2' } })) + expect(href()).toBe('/optional/2') +}) + +test('route.update can add middleware after the link has served cache hits', async () => { + const { router, item, hits } = setup(() => ( + + item + + )) + await mount(router) + await act(() => router.navigate({ to: '/items/$id', params: { id: '2' } })) + expect(hits()).toBeGreaterThan(0) + item.update({ search: { middlewares: [retainSearchParams(true)] } }) + await act(() => router.navigate({ to: '/', search: { tab: 'new' } } as any)) + expect(href()).toBe('/items/9?tab=new') +}) + +test('clicking a cached link still validates search during navigation', async () => { + const { router, item, hits } = setup(() => ( + + item + + )) + item.update({ + validateSearch: (search: Record) => ({ + page: Number(search.page ?? 1), + }), + } as any) + await mount(router) + await act(() => router.navigate({ to: '/items/$id', params: { id: '2' } })) + expect(hits()).toBeGreaterThan(0) + expect(href()).toBe('/items/9') + await act(async () => { + fireEvent.click(screen.getByTestId('link')) + }) + expect(router.state.location.href).toBe('/items/9?page=1') +}) + +test('intent preloading validates search after cache hits', async () => { + const { router, item, hits } = setup(() => ( + + item + + )) + const loader = vi.fn(() => null) + item.update({ + validateSearch: (search: Record) => ({ + page: Number(search.page ?? 1), + }), + loaderDeps: ({ search }: any) => ({ page: search.page }), + loader, + } as any) + const preload = vi.spyOn(router, 'preloadRoute') + await mount(router) + await act(() => router.navigate({ to: '/items/$id', params: { id: '2' } })) + expect(hits()).toBeGreaterThan(0) + loader.mockClear() + fireEvent.focus(screen.getByTestId('link')) + await waitFor(() => expect(loader).toHaveBeenCalled()) + expect(preload.mock.calls[0]![0]).not.toHaveProperty('_buildCache') + expect(loader).toHaveBeenCalledWith( + expect.objectContaining({ deps: { page: 1 }, params: { id: '9' } }), + ) +}) + +test('hash-only navigation updates href and active state on cache hits', async () => { + const { router, hits } = setup(() => ( + <> + + inherited + + + fixed + + + )) + await mount(router) + await act(() => + router.navigate({ to: '/items/$id', params: { id: '9' }, hash: 'one' }), + ) + expect(href()).toBe('/items/9#one') + expect(screen.getByTestId('fixed').className).toContain('active') + const before = hits() + await act(() => + router.navigate({ to: '/items/$id', params: { id: '9' }, hash: 'two' }), + ) + expect(hits()).toBeGreaterThan(before) + expect(href()).toBe('/items/9#two') + expect(screen.getByTestId('fixed').className).not.toContain('active') +}) diff --git a/packages/router-core/tests/build-location-cache-regressions.test.ts b/packages/router-core/tests/build-location-cache-regressions.test.ts new file mode 100644 index 0000000000..cfc1fbeef0 --- /dev/null +++ b/packages/router-core/tests/build-location-cache-regressions.test.ts @@ -0,0 +1,293 @@ +import { expect, test } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, retainSearchParams } from '../src' +import { createTestRouter } from './routerTestUtils' + +function setup(stringify = false) { + const root = new BaseRootRoute({}) + const index = new BaseRoute({ getParentRoute: () => root, path: '/' }) + const item = new BaseRoute({ getParentRoute: () => root, path: '/items/$id' }) + const optional = new BaseRoute({ + getParentRoute: () => root, + path: '/optional/{-$id}', + ...(stringify + ? { + params: { + stringify: (p: any) => ({ id: p.id ? `s${p.id}` : 'fallback' }), + }, + } + : {}), + }) + const router = createTestRouter({ + routeTree: root.addChildren([index, item, optional]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + return { router, optional, item } +} + +test('an initially absent optional param can become inherited', async () => { + const { router } = setup() + await router.load() + const cache = {} + const opts = { to: '/optional/{-$id}', params: {} } + expect(router.buildLocation({ ...opts, _buildCache: cache }).href).toBe( + '/optional', + ) + await router.navigate({ to: '/items/$id', params: { id: '2' } }) + const fresh = router.buildLocation(opts).href + expect(fresh).toBe('/optional/2') + expect(router.buildLocation({ ...opts, _buildCache: cache }).href).toBe(fresh) +}) + +test('a stringify skipped for empty params must be reconsidered', async () => { + const { router } = setup(true) + await router.load() + const cache = {} + const opts = { to: '/optional/{-$id}', params: {} } + expect(router.buildLocation({ ...opts, _buildCache: cache }).href).toBe( + '/optional', + ) + await router.navigate({ to: '/items/$id', params: { id: '2' } }) + const fresh = router.buildLocation(opts).href + expect(fresh).toBe('/optional/s2') + expect(router.buildLocation({ ...opts, _buildCache: cache }).href).toBe(fresh) +}) + +test('route.update invalidates newly installed search middleware', async () => { + const { router, item } = setup() + await router.load() + const cache = {} + const opts = { to: '/items/$id', params: { id: 'fixed' } } + expect(router.buildLocation({ ...opts, _buildCache: cache }).href).toBe( + '/items/fixed', + ) + item.update({ search: { middlewares: [retainSearchParams(true)] } }) + await router.navigate({ to: '/', search: { tab: 'new' } } as any) + const fresh = router.buildLocation(opts).href + expect(fresh).toBe('/items/fixed?tab=new') + expect(router.buildLocation({ ...opts, _buildCache: cache }).href).toBe(fresh) +}) + +test('output rewrites observe a changed locale with stable router options', async () => { + const { router } = setup() + let locale = 'en' + router.update({ + rewrite: { + input: ({ url }) => { + url.pathname = url.pathname.replace(/^\/(en|fr)(?=\/|$)/, '') || '/' + return url + }, + output: ({ url }) => { + url.pathname = `/${locale}${url.pathname}` + return url + }, + }, + }) + await router.load() + const cache = {} + const opts = { to: '/items/$id', params: { id: '9' } } + expect(router.buildLocation({ ...opts, _buildCache: cache }).publicHref).toBe( + '/en/items/9', + ) + locale = 'fr' + await router.navigate({ to: '/items/$id', params: { id: '2' } }) + const fresh = router.buildLocation(opts).publicHref + expect(fresh).toBe('/fr/items/9') + expect(router.buildLocation({ ...opts, _buildCache: cache }).publicHref).toBe( + fresh, + ) +}) + +test.each([ + ['prototype property', () => Object.create({ id: '1' })], + [ + 'non-enumerable property', + () => Object.defineProperty({}, 'id', { value: '1' }), + ], +])('params with a %s still inherit the current value', async (_, params) => { + const { router } = setup() + await router.load() + await router.navigate({ to: '/items/$id', params: { id: '1' } }) + const options = { to: '/items/$id', params: params() } + const cache = {} + expect(router.buildLocation({ ...options, _buildCache: cache }).href).toBe( + '/items/1', + ) + await router.navigate({ to: '/items/$id', params: { id: '2' } }) + expect(router.buildLocation({ ...options, _buildCache: cache }).href).toBe( + '/items/2', + ) +}) + +test('cache hits still invoke a custom search serializer', async () => { + const { router } = setup() + let locale = 'en' + router.update({ stringifySearch: () => `?locale=${locale}` }) + await router.load() + const cache: import('../src').BuildLocationCache = {} + const options = { to: '/items/$id', params: { id: '9' } } + expect(router.buildLocation({ ...options, _buildCache: cache }).href).toBe( + '/items/9?locale=en', + ) + const entry = cache.value + expect(entry).toBeDefined() + locale = 'fr' + expect(router.buildLocation({ ...options, _buildCache: cache }).href).toBe( + '/items/9?locale=fr', + ) + expect(cache.value).toBe(entry) +}) + +test('a newly installed params stringifier invalidates a cache hit', async () => { + const { router, item } = setup() + await router.load() + const cache: import('../src').BuildLocationCache = {} + const options = { to: '/items/$id', params: { id: '9' } } + router.buildLocation({ ...options, _buildCache: cache }) + expect(cache.value).toBeDefined() + item.options.params = { stringify: (params) => ({ id: `x${params.id}` }) } + expect(router.buildLocation({ ...options, _buildCache: cache }).href).toBe( + '/items/x9', + ) + expect(cache.value).toBeUndefined() +}) + +test('a link cache cannot bypass navigation validation or template matching', async () => { + const { router, item } = setup() + item.update({ + validateSearch: (search: Record) => ({ + page: search.page ?? 1, + }), + } as any) + await router.load() + const options = { to: '/items/$id', params: { id: '9' } } + const cache: import('../src').BuildLocationCache = {} + expect(router.buildLocation({ ...options, _buildCache: cache }).href).toBe( + '/items/9', + ) + expect(cache.value).toBeDefined() + expect( + router.buildLocation({ + ...options, + _buildCache: cache, + _includeValidateSearch: true, + }).href, + ).toBe('/items/9?page=1') + expect( + router.buildLocation({ ...options, _buildCache: cache, leaveParams: true }) + .pathname, + ).toBe('/items/$id') +}) + +test('cache hits build fresh state and continue applying state updaters', async () => { + const { router } = setup() + await router.load() + const cache: import('../src').BuildLocationCache = {} + const options = { + to: '/items/$id', + params: { id: '9' }, + state: (previous: any): any => ({ count: (previous.count ?? 0) + 1 }), + } + const first = router.buildLocation({ ...options, _buildCache: cache }) + const entry = cache.value + expect(entry).toBeDefined() + await router.navigate({ to: '/', state: { count: 4 } } as any) + const second = router.buildLocation({ ...options, _buildCache: cache }) + expect(second).not.toBe(first) + expect(second.state).toEqual({ count: 5 }) + expect(cache.value).toBe(entry) +}) + +test('a frozen params getter is evaluated on each build', async () => { + const { router } = setup() + await router.load() + let id = '1' + const params = Object.freeze({ + get id() { + return id + }, + }) + const cache = {} + const options = { to: '/items/$id', params, _buildCache: cache } + expect(router.buildLocation(options).href).toBe('/items/1') + id = '2' + expect(router.buildLocation(options).href).toBe('/items/2') +}) + +test('object-valued params are not assumed to have a constant string representation', async () => { + const { router } = setup() + await router.load() + let id = '1' + const params = { id: { toString: () => id } } + const options = { to: '/items/$id', params, _buildCache: {} } + expect(router.buildLocation(options as any).href).toBe('/items/1') + id = '2' + expect(router.buildLocation(options as any).href).toBe('/items/2') +}) + +test('search accessors and nested accessors are evaluated on pathname cache hits', async () => { + const { router } = setup() + await router.load() + let locale = 'en' + const search = Object.freeze({ + get locale() { + return locale + }, + nested: Object.freeze({ + get locale() { + return locale + }, + }), + }) + const cache: import('../src').BuildLocationCache = {} + const options = { to: '/items/$id', params: { id: '9' }, search } + router.buildLocation({ ...options, _buildCache: cache }) + const entry = cache.value + expect(entry).toBeDefined() + locale = 'fr' + const cached = router.buildLocation({ ...options, _buildCache: cache }) + expect(cached).toEqual(router.buildLocation(options)) + expect(cached.search).toEqual({ locale: 'fr', nested: { locale: 'fr' } }) + expect(cache.value).toBe(entry) +}) + +test('a mutating serializer does not accumulate mutations in a pathname cache', async () => { + const { router } = setup() + router.update({ + stringifySearch: (search) => { + search.count = (search.count ?? 0) + 1 + return `?count=${search.count}` + }, + }) + await router.load() + const cache: import('../src').BuildLocationCache = {} + const options = { to: '/items/$id', params: { id: '9' } } + router.buildLocation({ ...options, _buildCache: cache }) + expect(cache.value).toBeDefined() + expect(router.buildLocation({ ...options, _buildCache: cache })).toEqual( + router.buildLocation(options), + ) +}) + +test.each(['/items/$*', '/items/$*/$'])( + 'a parameter named star in %s is not mistaken for the splat alias', + async (path) => { + const root = new BaseRootRoute({}) + const route = new BaseRoute({ getParentRoute: () => root, path }) + const router = createTestRouter({ + routeTree: root.addChildren([route]), + history: createMemoryHistory({ initialEntries: ['/items/1/tail'] }), + }) + await router.load() + const options = { to: path, params: { _splat: 'tail' } } + const cache = {} + router.buildLocation({ ...options, _buildCache: cache } as any) + await router.navigate({ + to: path, + params: { '*': '2', _splat: 'tail' }, + } as any) + expect( + router.buildLocation({ ...options, _buildCache: cache } as any), + ).toEqual(router.buildLocation(options as any)) + }, +) diff --git a/packages/router-core/tests/build-location-cache.bench.ts b/packages/router-core/tests/build-location-cache.bench.ts new file mode 100644 index 0000000000..7d57eef412 --- /dev/null +++ b/packages/router-core/tests/build-location-cache.bench.ts @@ -0,0 +1,111 @@ +import { bench, describe, expect } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, retainSearchParams } from '../src' +import { createTestRouter } from './routerTestUtils' + +function setup(middleware = false) { + const root = new BaseRootRoute({ + ...(middleware + ? { search: { middlewares: [retainSearchParams(true)] } } + : {}), + }) + const index = new BaseRoute({ getParentRoute: () => root, path: '/' }) + const item = new BaseRoute({ getParentRoute: () => root, path: '/items/$id' }) + const optional = new BaseRoute({ + getParentRoute: () => root, + path: '/optional/{-$id}', + }) + return createTestRouter({ + routeTree: root.addChildren([index, item, optional]), + history: createMemoryHistory({ initialEntries: ['/items/1'] }), + }) +} + +const batchSize = 100 +const plain = setup() +const middleware = setup(true) +await plain.load() +await middleware.load() +const locations = ['1', '2'].map((id) => + plain.buildLocation({ + to: '/items/$id', + params: { id }, + search: { tab: id }, + }), +) +const literal = { + to: '/items/$id', + params: { id: '9' }, + search: { tab: 'specs', page: 2 }, +} +const inherited = { to: '/items/$id', params: {} } +const optional = { to: '/optional/{-$id}', params: {} } + +// These inputs intentionally work on the parent commit, where the private slot +// is ignored, so the same fixture measures the ordinary build and its cache. +for (const [name, router, options, useCache] of [ + ['uncached literal', plain, literal, false], + ['cached literal', plain, literal, true], + ['uncached inherited', plain, inherited, false], + ['cache miss inherited', plain, inherited, true], + ['cache miss optional', plain, optional, true], + ['uncached middleware', middleware, literal, false], + ['cached middleware', middleware, literal, true], +] as const) { + const cache = {} + const inputs = locations.map((location) => ({ + ...options, + _fromLocation: location, + ...(useCache ? { _buildCache: cache } : {}), + })) + for (const input of inputs) { + const { _buildCache: _, ...fresh } = input as any + expect(router.buildLocation(input as any)).toEqual( + router.buildLocation(fresh), + ) + } + describe(name, () => { + bench( + '100 alternating builds', + () => { + for (let i = 0; i < batchSize; i++) { + router.buildLocation(inputs[i % 2]! as any) + } + }, + { time: 1_000, warmupTime: 300 }, + ) + }) +} + +const mixed = [literal, literal, inherited, optional].map((options) => ({ + ...options, + _buildCache: {}, +})) +for (const [name, cold] of [ + ['mixed warm slots', false], + ['cold literal slots', true], +] as const) { + for (const options of mixed) { + const { _buildCache: _, ...fresh } = options + expect(plain.buildLocation(options as any)).toEqual( + plain.buildLocation(fresh as any), + ) + } + describe(name, () => { + bench( + '100 alternating builds', + () => { + for (let i = 0; i < batchSize; i++) { + const options = cold + ? { ...literal, _buildCache: {} } + : mixed[i % mixed.length]! + plain.buildLocation({ + ...options, + _fromLocation: locations[i % 2], + } as any) + } + }, + { time: 1_000, warmupTime: 300 }, + ) + }) +} diff --git a/packages/router-core/tests/build-location-cache.test.ts b/packages/router-core/tests/build-location-cache.test.ts new file mode 100644 index 0000000000..d34eb92f2b --- /dev/null +++ b/packages/router-core/tests/build-location-cache.test.ts @@ -0,0 +1,536 @@ +import { describe, expect, test } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, retainSearchParams } from '../src' +import { createTestRouter } from './routerTestUtils' +import type { AnyRouter, BuildLocationCache, ParsedLocation } from '../src' + +function makeRouter(initialEntry = '/items/1') { + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const itemsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/items/$id', + }) + const itemsDetailRoute = new BaseRoute({ + getParentRoute: () => itemsRoute, + path: '/detail', + }) + const aboutRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/about', + }) + const routeTree = rootRoute.addChildren([ + indexRoute, + itemsRoute.addChildren([itemsDetailRoute]), + aboutRoute, + ]) + + return createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: [initialEntry] }), + }) +} + +/** + * Build `opts` with and without a memo slot and assert the memo did not change + * the answer. Returns whether the pathname cache reused its previous entry, + * which happens only for location-independent pathnames, so both + * the fast path and the correctness of the classification are pinned. + */ +function buildBoth( + router: AnyRouter, + cache: BuildLocationCache, + opts: Record, +) { + const previous = cache.value + const cached: ParsedLocation = router.buildLocation({ + ...opts, + _buildCache: cache, + } as any) + const fresh: ParsedLocation = router.buildLocation({ ...opts } as any) + + expect(cached.href).toBe(fresh.href) + expect(cached.publicHref).toBe(fresh.publicHref) + expect(cached.pathname).toBe(fresh.pathname) + expect(cached.searchStr).toBe(fresh.searchStr) + expect(cached.hash).toBe(fresh.hash) + expect(cached.search).toEqual(fresh.search) + expect(cached.state).toEqual(fresh.state) + expect(cached.maskedLocation?.href).toBe(fresh.maskedLocation?.href) + + return { + location: cached, + hit: previous !== undefined && cache.value === previous, + } +} + +describe('buildLocation memo (_buildCache)', () => { + test('a location-independent destination is served from the memo across navigations', async () => { + const router = makeRouter('/items/1') + await router.load() + const cache: BuildLocationCache = {} + const opts = { to: '/items/$id', params: { id: '9' } } + + expect(buildBoth(router, cache, opts).location.href).toBe('/items/9') + + await router.navigate({ to: '/items/$id', params: { id: '2' } }) + const second = buildBoth(router, cache, opts) + expect(second.hit).toBe(true) + expect(second.location.href).toBe('/items/9') + + await router.navigate({ to: '/about' }) + const third = buildBoth(router, cache, opts) + expect(third.hit).toBe(true) + expect(third.location.href).toBe('/items/9') + }) + + test('a literal search and hash stay location-independent', async () => { + const router = makeRouter('/items/1') + await router.load() + const cache: BuildLocationCache = {} + const opts = { + to: '/items/$id', + params: { id: '9' }, + search: { tab: 'specs' }, + hash: 'section-9', + } + + expect(buildBoth(router, cache, opts).location.href).toBe( + '/items/9?tab=specs#section-9', + ) + + await router.navigate({ + to: '/items/$id', + params: { id: '2' }, + search: { q: 'x' }, + }) + const second = buildBoth(router, cache, opts) + expect(second.hit).toBe(true) + expect(second.location.href).toBe('/items/9?tab=specs#section-9') + }) + + // A plain `params` object does not have to be complete: `resolveNextParams` + // merges it over the current location's params, so anything it leaves out is + // inherited. Skipping the `usedParams` check and treating every plain object + // as self-sufficient would memoize these links and freeze their href. + test('a plain `params` object that omits a needed param still follows the current location', async () => { + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const postRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts/$postId', + }) + const editRoute = new BaseRoute({ + getParentRoute: () => postRoute, + path: '/edit', + }) + const tabRoute = new BaseRoute({ + getParentRoute: () => postRoute, + path: '/tab/$tab', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + postRoute.addChildren([editRoute, tabRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/posts/1'] }), + }) + await router.load() + + const empty: BuildLocationCache = {} + const partial: BuildLocationCache = {} + const emptyOpts = { to: '/posts/$postId/edit', params: {} } + const partialOpts = { + to: '/posts/$postId/tab/$tab', + params: { tab: 'stats' }, + } + + expect(buildBoth(router, empty, emptyOpts).location.href).toBe( + '/posts/1/edit', + ) + expect(buildBoth(router, partial, partialOpts).location.href).toBe( + '/posts/1/tab/stats', + ) + + await router.navigate({ to: '/posts/$postId', params: { postId: '2' } }) + + const emptyAfter = buildBoth(router, empty, emptyOpts) + expect(emptyAfter.hit).toBe(false) + expect(emptyAfter.location.href).toBe('/posts/2/edit') + + const partialAfter = buildBoth(router, partial, partialOpts) + expect(partialAfter.hit).toBe(false) + expect(partialAfter.location.href).toBe('/posts/2/tab/stats') + }) + + test('inherited params (`params` omitted) follow the current location', async () => { + const router = makeRouter('/items/1') + await router.load() + const cache: BuildLocationCache = {} + const opts = { to: '/items/$id/detail' } + + expect(buildBoth(router, cache, opts).location.href).toBe('/items/1/detail') + + await router.navigate({ to: '/items/$id', params: { id: '2' } }) + const second = buildBoth(router, cache, opts) + expect(second.hit).toBe(false) + expect(second.location.href).toBe('/items/2/detail') + }) + + test('`params: true` follows the current location', async () => { + const router = makeRouter('/items/1') + await router.load() + const cache: BuildLocationCache = {} + const opts = { to: '/items/$id/detail', params: true } + + expect(buildBoth(router, cache, opts).location.href).toBe('/items/1/detail') + await router.navigate({ to: '/items/$id', params: { id: '7' } }) + expect(buildBoth(router, cache, opts).location.href).toBe('/items/7/detail') + }) + + test('a params updater function follows the current location', async () => { + const router = makeRouter('/items/1') + await router.load() + const cache: BuildLocationCache = {} + const opts = { + to: '/items/$id/detail', + params: (prev: any) => ({ id: `${prev.id}-x` }), + } + + expect(buildBoth(router, cache, opts).location.href).toBe( + '/items/1-x/detail', + ) + await router.navigate({ to: '/items/$id', params: { id: '7' } }) + expect(buildBoth(router, cache, opts).location.href).toBe( + '/items/7-x/detail', + ) + }) + + test('a relative `to` follows the current location', async () => { + const router = makeRouter('/items/1') + await router.load() + const cache: BuildLocationCache = {} + const opts = { to: 'detail' } + + expect(buildBoth(router, cache, opts).location.href).toBe('/items/1/detail') + await router.navigate({ to: '/about' }) + const second = buildBoth(router, cache, opts) + expect(second.hit).toBe(false) + expect(second.location.href).toBe('/about/detail') + }) + + test('`unsafeRelative: path` follows the current pathname', async () => { + const router = makeRouter('/items/1') + await router.load() + const cache: BuildLocationCache = {} + const opts = { to: 'detail', unsafeRelative: 'path' as const } + + expect(buildBoth(router, cache, opts).location.href).toBe('/items/1/detail') + await router.navigate({ to: '/items/$id', params: { id: '5' } }) + const second = buildBoth(router, cache, opts) + expect(second.hit).toBe(false) + expect(second.location.href).toBe('/items/5/detail') + }) + + test('`search: true` follows the current search', async () => { + const router = makeRouter('/items/1?tab=a') + await router.load() + const cache: BuildLocationCache = {} + const opts = { to: '/about', search: true } + + expect(buildBoth(router, cache, opts).location.href).toBe('/about?tab=a') + await router.navigate({ + to: '/items/$id', + params: { id: '2' }, + search: { tab: 'b' }, + }) + const second = buildBoth(router, cache, opts) + expect(second.hit).toBe(true) + expect(second.location.href).toBe('/about?tab=b') + }) + + test('a search updater function follows the current search', async () => { + const router = makeRouter('/items/1?tab=a') + await router.load() + const cache: BuildLocationCache = {} + const opts = { + to: '/about', + search: (prev: any) => ({ tab: prev.tab, extra: 1 }), + } + + expect(buildBoth(router, cache, opts).location.href).toBe( + '/about?tab=a&extra=1', + ) + await router.navigate({ + to: '/items/$id', + params: { id: '2' }, + search: { tab: 'b' }, + }) + expect(buildBoth(router, cache, opts).location.href).toBe( + '/about?tab=b&extra=1', + ) + }) + + test('retainSearchParams middleware follows the current search', async () => { + const rootRoute = new BaseRootRoute({ + validateSearch: (search: { tab?: string }) => search, + search: { middlewares: [retainSearchParams(['tab'])] }, + }) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const aboutRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/about', + }) + const itemsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/items/$id', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, aboutRoute, itemsRoute]), + history: createMemoryHistory({ initialEntries: ['/items/1?tab=a'] }), + }) + await router.load() + + const cache: BuildLocationCache = {} + const opts = { to: '/about' } + + expect(buildBoth(router, cache, opts).location.href).toBe('/about?tab=a') + await router.navigate({ + to: '/items/$id', + params: { id: '2' }, + search: { tab: 'b' }, + }) + const second = buildBoth(router, cache, opts) + expect(second.hit).toBe(true) + expect(second.location.href).toBe('/about?tab=b') + }) + + test('`hash: true` and hash updaters follow the current hash', async () => { + const router = makeRouter('/items/1#one') + await router.load() + const inherit: BuildLocationCache = {} + const updater: BuildLocationCache = {} + + expect( + buildBoth(router, inherit, { to: '/about', hash: true }).location.href, + ).toBe('/about#one') + expect( + buildBoth(router, updater, { + to: '/about', + hash: (prev: string) => `${prev}-x`, + }).location.href, + ).toBe('/about#one-x') + + await router.navigate({ + to: '/items/$id', + params: { id: '2' }, + hash: 'two', + }) + + expect( + buildBoth(router, inherit, { to: '/about', hash: true }).location.href, + ).toBe('/about#two') + expect( + buildBoth(router, updater, { + to: '/about', + hash: (prev: string) => `${prev}-x`, + }).location.href, + ).toBe('/about#two-x') + }) + + test('`state: true` follows the current state', async () => { + const router = makeRouter('/items/1') + await router.load() + const cache: BuildLocationCache = {} + const opts = { to: '/about', state: true } + + buildBoth(router, cache, opts) + await router.navigate({ + to: '/items/$id', + params: { id: '2' }, + state: { a: 1 } as any, + }) + const second = buildBoth(router, cache, opts) + expect(second.hit).toBe(true) + expect((second.location.state as any).a).toBe(1) + }) + + test('a route with params.stringify keeps following the current params', async () => { + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const itemsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/items/$id', + params: { + // `stringify` reads a param the destination does not supply, so the + // built location depends on the current location's params after all. + stringify: (p: any) => ({ id: `${p.id}${p.suffix ?? ''}` }), + }, + }) + const suffixRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/s/$suffix', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, itemsRoute, suffixRoute]), + history: createMemoryHistory({ initialEntries: ['/s/a'] }), + }) + await router.load() + + const cache: BuildLocationCache = {} + const opts = { to: '/items/$id', params: { id: '9' } } + expect(buildBoth(router, cache, opts).location.href).toBe('/items/9a') + + await router.navigate({ to: '/s/$suffix', params: { suffix: 'b' } }) + const second = buildBoth(router, cache, opts) + expect(second.hit).toBe(false) + expect(second.location.href).toBe('/items/9b') + }) + + test('an explicit mask stays correct (memo disabled)', async () => { + const router = makeRouter('/items/1') + await router.load() + const cache: BuildLocationCache = {} + const opts = { + to: '/items/$id', + params: { id: '9' }, + mask: { to: '/items/$id/detail', params: true }, + } + + const first = buildBoth(router, cache, opts) + expect(first.location.href).toBe('/items/9') + expect(first.location.maskedLocation?.href).toBe('/items/1/detail') + + await router.navigate({ to: '/items/$id', params: { id: '2' } }) + const second = buildBoth(router, cache, opts) + expect(second.hit).toBe(false) + expect(second.location.maskedLocation?.href).toBe('/items/2/detail') + }) + + test('routeMasks disable the memo and keep resolving per navigation', async () => { + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const itemsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/items/$id', + }) + const detailRoute = new BaseRoute({ + getParentRoute: () => itemsRoute, + path: '/detail', + }) + const routeTree = rootRoute.addChildren([ + indexRoute, + itemsRoute.addChildren([detailRoute]), + ]) + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/items/1'] }), + routeMasks: [ + { + routeTree, + from: '/items/$id/detail', + to: '/items/$id', + } as any, + ], + }) + await router.load() + + const cache: BuildLocationCache = {} + const opts = { to: '/items/$id/detail', params: { id: '9' } } + const first = buildBoth(router, cache, opts) + expect(first.hit).toBe(false) + expect(first.location.maskedLocation?.href).toBe('/items/9') + + await router.navigate({ to: '/items/$id', params: { id: '2' } }) + const second = buildBoth(router, cache, opts) + expect(second.hit).toBe(false) + expect(second.location.maskedLocation?.href).toBe('/items/9') + + // Clearing only the option can leave the processed mask tree in place. + router.update({ routeMasks: [] }) + const cleared = buildBoth(router, cache, opts) + expect(cleared.hit).toBe(false) + expect(cleared.location.maskedLocation?.href).toBe('/items/9') + }) + + test('the memo is invalidated when router options change', async () => { + const router = makeRouter('/items/1') + await router.load() + const cache: BuildLocationCache = {} + const opts = { to: '/items/$id', params: { id: '9' } } + + expect(buildBoth(router, cache, opts).location.href).toBe('/items/9') + router.update({ ...router.options, basepath: '/app' }) + const second = buildBoth(router, cache, opts) + expect(second.hit).toBe(false) + expect(second.location.href).toBe('/app/items/9') + }) + + test('the memo is invalidated when the route tree is rebuilt (HMR)', async () => { + const router = makeRouter('/items/1') + await router.load() + const cache: BuildLocationCache = {} + const opts = { to: '/items/$id', params: { id: '9' } } + + expect(buildBoth(router, cache, opts).location.href).toBe('/items/9') + // `handleRouteUpdate` in router-plugin swaps route options in place and + // rebuilds the tree without touching `router.options`. + router.setRoutes(router.buildRouteTree()) + expect(buildBoth(router, cache, opts).hit).toBe(false) + }) + + test('a splat destination that supplies _splat is location-independent', async () => { + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const filesRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/files/$', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, filesRoute]), + history: createMemoryHistory({ initialEntries: ['/files/a/b'] }), + }) + await router.load() + + const supplied: BuildLocationCache = {} + const inherited: BuildLocationCache = {} + expect( + buildBoth(router, supplied, { to: '/files/$', params: { _splat: 'x/y' } }) + .location.href, + ).toBe('/files/x/y') + expect(buildBoth(router, inherited, { to: '/files/$' }).location.href).toBe( + '/files/a/b', + ) + + await router.navigate({ to: '/files/$', params: { _splat: 'c/d' } }) + + const suppliedAfter = buildBoth(router, supplied, { + to: '/files/$', + params: { _splat: 'x/y' }, + }) + expect(suppliedAfter.hit).toBe(true) + expect(suppliedAfter.location.href).toBe('/files/x/y') + + const inheritedAfter = buildBoth(router, inherited, { to: '/files/$' }) + expect(inheritedAfter.hit).toBe(false) + expect(inheritedAfter.location.href).toBe('/files/c/d') + }) +}) From ac868d9cc9c8a033990e3b76c9ea2d22f356a792 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Sat, 5 Sep 2026 14:13:40 +0200 Subject: [PATCH 2/3] test(router): cover pathname cache dependencies and hit rates --- .../tests/link-build-cache.test.tsx | 101 +++++++ .../build-location-cache-regressions.test.ts | 257 ++++++++++++++++-- .../tests/build-location-cache.bench.ts | 96 ++++++- .../tests/build-location-cache.test.ts | 16 +- 4 files changed, 441 insertions(+), 29 deletions(-) diff --git a/packages/react-router/tests/link-build-cache.test.tsx b/packages/react-router/tests/link-build-cache.test.tsx index 9306cc7712..477431e567 100644 --- a/packages/react-router/tests/link-build-cache.test.tsx +++ b/packages/react-router/tests/link-build-cache.test.tsx @@ -256,3 +256,104 @@ test('hash-only navigation updates href and active state on cache hits', async ( expect(href()).toBe('/items/9#two') expect(screen.getByTestId('fixed').className).not.toContain('active') }) + +test.each([ + ['supplied', { id: 'fixed' }, '/optional/fixed'], + ['absent', { id: undefined }, '/optional'], + ['inherited', {}, '/optional/1'], +] as const)( + 'an optional link with %s params hits on search-only changes', + async (_, params, expectedHref) => { + const { router, hits } = setup(() => ( + + optional + + )) + await router.navigate({ to: '/items/$id', params: { id: '1' } }) + await mount(router) + expect(href()).toBe(expectedHref) + const before = hits() + await act(() => + router.navigate({ + to: '/items/$id', + params: { id: '1' }, + search: { page: 2 }, + } as any), + ) + expect(href()).toBe(expectedHref) + expect(hits()).toBeGreaterThan(before) + }, +) + +test('search and hash prop changes preserve the pathname cache', async () => { + function Links() { + const [page, setPage] = React.useState(1) + return ( + <> + + + optional + + + ) + } + const { router, hits } = setup(() => ) + await mount(router) + expect(href()).toBe('/optional/fixed?page=1#section-1') + const before = hits() + fireEvent.click(screen.getByText('change search')) + expect(href()).toBe('/optional/fixed?page=2#section-2') + expect(hits()).toBeGreaterThan(before) +}) + +test('a suspended option transition cannot change the committed link pathname', async () => { + let release!: () => void + const pending = new Promise((resolve) => { + release = resolve + }) + let waiting = true + let suspended = false + function Suspend({ id }: { id: string }) { + if (id === '2' && waiting) { + suspended = true + throw pending + } + return null + } + function Links() { + const [id, setId] = React.useState('1') + return ( + <> + + loading}> + + optional + + + + + ) + } + const { router } = setup(() => ) + await mount(router) + expect(href()).toBe('/optional/1') + fireEvent.click(screen.getByText('transition')) + expect(suspended).toBe(true) + expect(href()).toBe('/optional/1') + await act(() => router.navigate({ to: '/items/$id', params: { id: '3' } })) + expect(href()).toBe('/optional/1') + await act(async () => { + waiting = false + release() + await pending + }) + expect(href()).toBe('/optional/2') +}) diff --git a/packages/router-core/tests/build-location-cache-regressions.test.ts b/packages/router-core/tests/build-location-cache-regressions.test.ts index cfc1fbeef0..c1e24168d9 100644 --- a/packages/router-core/tests/build-location-cache-regressions.test.ts +++ b/packages/router-core/tests/build-location-cache-regressions.test.ts @@ -149,7 +149,12 @@ test('a newly installed params stringifier invalidates a cache hit', async () => expect(router.buildLocation({ ...options, _buildCache: cache }).href).toBe( '/items/x9', ) - expect(cache.value).toBeUndefined() + const nextEntry = cache.value + expect(nextEntry).toBeDefined() + expect(router.buildLocation({ ...options, _buildCache: cache }).href).toBe( + '/items/x9', + ) + expect(cache.value).toBe(nextEntry) }) test('a link cache cannot bypass navigation validation or template matching', async () => { @@ -269,25 +274,241 @@ test('a mutating serializer does not accumulate mutations in a pathname cache', ) }) -test.each(['/items/$*', '/items/$*/$'])( - 'a parameter named star in %s is not mistaken for the splat alias', - async (path) => { - const root = new BaseRootRoute({}) - const route = new BaseRoute({ getParentRoute: () => root, path }) - const router = createTestRouter({ - routeTree: root.addChildren([route]), - history: createMemoryHistory({ initialEntries: ['/items/1/tail'] }), - }) +// Cache eligibility follows the effective values, including absent optionals. +test.each([ + [ + 'explicit optional', + { to: '/optional/{-$id}', params: { id: 'fixed' } }, + '/optional/fixed', + ], + [ + 'explicit undefined optional', + { to: '/optional/{-$id}', params: { id: undefined } }, + '/optional', + ], + [ + 'explicit null optional', + { to: '/optional/{-$id}', params: { id: null } }, + '/optional', + ], + ['inherited optional', { to: '/optional/{-$id}' }, '/optional/1'], + [ + 'partially inherited optional', + { to: '/optional/{-$id}', params: {} }, + '/optional/1', + ], + ['params true', { to: '/optional/{-$id}', params: true }, '/optional/1'], + ['params false', { to: '/optional/{-$id}', params: false }, '/optional'], + [ + 'params updater', + { to: '/optional/{-$id}', params: (p: any) => ({ id: p.id }) }, + '/optional/1', + ], + [ + 'relative with from', + { from: '/items/$id', to: '.', params: { id: 'fixed' } }, + '/items/fixed', + ], + ['relative inherited', { to: '.' }, '/items/1'], + ['concrete pathname', { to: '/items/1' }, '/items/1'], +])( + '%s hits across search/hash-only navigation', + async (_, options, pathname) => { + const { router } = setup() await router.load() - const options = { to: path, params: { _splat: 'tail' } } - const cache = {} - router.buildLocation({ ...options, _buildCache: cache } as any) + await router.navigate({ to: '/items/$id', params: { id: '1' } }) + const cache: import('../src').BuildLocationCache = {} + const build = () => + router.buildLocation({ ...options, _buildCache: cache } as any) + expect(build().pathname).toBe(pathname) + const entry = cache.value + expect(entry).toBeDefined() await router.navigate({ - to: path, - params: { '*': '2', _splat: 'tail' }, + to: '/items/$id', + params: { id: '1' }, + search: { page: 2 }, + hash: 'new', } as any) - expect( - router.buildLocation({ ...options, _buildCache: cache } as any), - ).toEqual(router.buildLocation(options as any)) + expect(build()).toEqual(router.buildLocation(options as any)) + expect(cache.value).toBe(entry) }, ) + +test('an absent inherited optional hits until its dependency appears, then hits again', async () => { + const { router } = setup() + await router.load() + const cache: import('../src').BuildLocationCache = {} + const options = { to: '/optional/{-$id}', params: {}, _buildCache: cache } + expect(router.buildLocation(options).pathname).toBe('/optional') + const absent = cache.value + await router.navigate({ to: '/', search: { page: 2 } } as any) + expect(router.buildLocation(options).pathname).toBe('/optional') + expect(cache.value).toBe(absent) + await router.navigate({ to: '/items/$id', params: { id: '2' } }) + expect(router.buildLocation(options).pathname).toBe('/optional/2') + expect(cache.value).not.toBe(absent) + const present = cache.value + router.buildLocation(options) + expect(cache.value).toBe(present) + await router.navigate({ to: '/' }) + expect(router.buildLocation(options).pathname).toBe('/optional') + expect(cache.value).not.toBe(present) +}) + +test('a stringifier runs on cache hits and invalidates only when its output changes', async () => { + const { router, optional } = setup() + let calls = 0 + let prefix = 'a' + optional.options.params = { + stringify: (params: any) => { + calls++ + return { id: prefix + params.id } + }, + } + await router.load() + const cache: import('../src').BuildLocationCache = {} + const options = { + to: '/optional/{-$id}', + params: { id: '1' }, + _buildCache: cache, + } + expect(router.buildLocation(options).pathname).toBe('/optional/a1') + const first = cache.value + expect(router.buildLocation(options).pathname).toBe('/optional/a1') + expect(cache.value).toBe(first) + expect(calls).toBe(2) + prefix = 'b' + expect(router.buildLocation(options).pathname).toBe('/optional/b1') + expect(cache.value).not.toBe(first) + expect(calls).toBe(3) +}) + +test.each(['/optional/pre{-$id}suf', '/optional/{-$id}/more/{-$other}'])( + 'optional dependency tracking preserves prefixes, suffixes and multiple params in %s', + async (path) => { + const root = new BaseRootRoute({}) + const index = new BaseRoute({ getParentRoute: () => root, path: '/' }) + const route = new BaseRoute({ getParentRoute: () => root, path }) + const router = createTestRouter({ + routeTree: root.addChildren([index, route]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + await router.load() + const cache: import('../src').BuildLocationCache = {} + for (const params of [ + {}, + { id: 'a', other: 'b' }, + { id: undefined, other: 'b' }, + { id: 'a', other: undefined }, + {}, + ]) { + const options = { to: path, params } + expect( + router.buildLocation({ ...options, _buildCache: cache } as any), + ).toEqual(router.buildLocation(options as any)) + const entry = cache.value + expect( + router.buildLocation({ ...options, _buildCache: cache } as any), + ).toEqual(router.buildLocation(options as any)) + expect(cache.value).toBe(entry) + } + }, +) + +test('a frozen non-path getter still runs before URL rewriting on late hits', async () => { + const { router } = setup() + let locale = 'en' + const params = Object.freeze({ + id: '1', + get other() { + locale = locale === 'en' ? 'fr' : 'en' + return 'unused' + }, + }) + router.update({ + rewrite: { + output: ({ url }) => { + url.pathname = `/${locale}${url.pathname}` + return url + }, + }, + }) + await router.load() + const cache: import('../src').BuildLocationCache = {} + const options = { to: '/items/$id', params, _buildCache: cache } + expect(router.buildLocation(options).publicHref).toBe('/fr/items/1') + const entry = cache.value + expect(router.buildLocation(options).publicHref).toBe('/en/items/1') + expect(cache.value).toBe(entry) +}) + +test('equivalent relative parent destinations hit across sibling source routes', async () => { + const root = new BaseRootRoute({}) + const parent = new BaseRoute({ + getParentRoute: () => root, + path: '/items/$id', + }) + const a = new BaseRoute({ getParentRoute: () => parent, path: '/a' }) + const b = new BaseRoute({ getParentRoute: () => parent, path: '/b' }) + const router = createTestRouter({ + routeTree: root.addChildren([parent.addChildren([a, b])]), + history: createMemoryHistory({ initialEntries: ['/items/1/a'] }), + }) + await router.load() + const cache: import('../src').BuildLocationCache = {} + const options = { to: '..', _buildCache: cache } + expect(router.buildLocation(options).pathname).toBe('/items/1') + const entry = cache.value + await router.navigate({ to: '/items/$id/b', params: { id: '1' } }) + expect(router.buildLocation(options).pathname).toBe('/items/1') + expect(cache.value).toBe(entry) +}) + +test('path resolution and interpolation settings are cache dependencies', async () => { + const { router } = setup() + await router.load() + const cache: import('../src').BuildLocationCache = {} + const options = { to: '/items/$id', params: { id: 'a@b' } } + router.buildLocation({ ...options, _buildCache: cache }) + let entry = cache.value + router.update({ defaultPendingMs: 42 }) + expect(router.buildLocation({ ...options, _buildCache: cache })).toEqual( + router.buildLocation(options), + ) + expect(cache.value).toBe(entry) + router.update({ trailingSlash: 'always' } as any) + expect(router.buildLocation({ ...options, _buildCache: cache })).toEqual( + router.buildLocation(options), + ) + expect(cache.value).not.toBe(entry) + entry = cache.value + router.update({ pathParamsAllowedCharacters: ['@'] }) + expect(router.buildLocation({ ...options, _buildCache: cache })).toEqual( + router.buildLocation(options), + ) + expect(cache.value).not.toBe(entry) +}) + +test('braced splats track _splat with prefixes, suffixes and absent values', async () => { + const root = new BaseRootRoute({}) + const index = new BaseRoute({ getParentRoute: () => root, path: '/' }) + const route = new BaseRoute({ + getParentRoute: () => root, + path: '/files/prefix{$}.txt', + }) + const router = createTestRouter({ + routeTree: root.addChildren([index, route]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + await router.load() + const cache: import('../src').BuildLocationCache = {} + for (const _splat of [undefined, 'a/b', 'space here', '', undefined]) { + const options = { to: '/files/prefix{$}.txt', params: { _splat } } + expect(router.buildLocation({ ...options, _buildCache: cache })).toEqual( + router.buildLocation(options), + ) + const entry = cache.value + router.buildLocation({ ...options, _buildCache: cache }) + expect(cache.value).toBe(entry) + } +}) diff --git a/packages/router-core/tests/build-location-cache.bench.ts b/packages/router-core/tests/build-location-cache.bench.ts index 7d57eef412..2b06356d73 100644 --- a/packages/router-core/tests/build-location-cache.bench.ts +++ b/packages/router-core/tests/build-location-cache.bench.ts @@ -47,8 +47,9 @@ for (const [name, router, options, useCache] of [ ['uncached literal', plain, literal, false], ['cached literal', plain, literal, true], ['uncached inherited', plain, inherited, false], - ['cache miss inherited', plain, inherited, true], - ['cache miss optional', plain, optional, true], + ['changing inherited params', plain, inherited, true], + ['uncached optional', plain, optional, false], + ['changing optional params', plain, optional, true], ['uncached middleware', middleware, literal, false], ['cached middleware', middleware, literal, true], ] as const) { @@ -82,7 +83,7 @@ const mixed = [literal, literal, inherited, optional].map((options) => ({ _buildCache: {}, })) for (const [name, cold] of [ - ['mixed warm slots', false], + ['stable mixed slots', false], ['cold literal slots', true], ] as const) { for (const options of mixed) { @@ -109,3 +110,92 @@ for (const [name, cold] of [ ) }) } + +// Isolate hit rates for destinations the first implementation excluded. These +// locations change search/hash while retaining the path parameter dependency. +const stableLocations = [1, 2].map((page) => + plain.buildLocation({ + to: '/items/$id', + params: { id: '1' }, + search: { page }, + hash: String(page), + }), +) +const withStringify = setup() +withStringify.routesByPath['/items/$id']!.options.params = { + stringify: (params: any) => ({ id: String(params.id) }), +} +await withStringify.load() +for (const [name, router, options] of [ + ['optional supplied', plain, { to: '/optional/{-$id}', params: { id: '9' } }], + [ + 'optional absent', + plain, + { to: '/optional/{-$id}', params: { id: undefined } }, + ], + ['optional inherited unchanged', plain, optional], + ['inherited unchanged', plain, inherited], + ['relative unchanged', plain, { to: '.' }], + [ + 'updater unchanged', + plain, + { to: '/items/$id', params: (params: any) => ({ id: params.id }) }, + ], + ['stringifier unchanged', withStringify, literal], + [ + 'explicit mask', + plain, + { ...literal, mask: { to: '/optional/{-$id}', params: true } }, + ], +] as const) { + for (const useCache of [false, true]) { + const cache: { value?: unknown } = {} + const inputs = stableLocations.map((location) => ({ + ...options, + _fromLocation: location, + ...(useCache ? { _buildCache: cache } : {}), + })) + // One Link keeps its slot while the current location changes. + for (const input of inputs) { + const { _buildCache: _, ...fresh } = input as any + expect(router.buildLocation(input as any)).toEqual( + router.buildLocation(fresh), + ) + } + // The parent implementation ignores the slot. On implementations that + // populate it, require real hits across both locations before timing. + if (cache.value) { + const entry = cache.value + for (const input of inputs) { + router.buildLocation(input as any) + expect(cache.value).toBe(entry) + } + } + describe(`${name} ${useCache ? 'cached' : 'uncached'}`, () => { + bench( + '100 alternating builds', + () => { + for (let i = 0; i < batchSize; i++) { + router.buildLocation(inputs[i % 2]! as any) + } + }, + { time: 1_000, warmupTime: 300 }, + ) + }) + } +} + +describe('mixed hits and changing inherited params', () => { + bench( + '100 alternating builds', + () => { + for (let i = 0; i < batchSize; i++) { + plain.buildLocation({ + ...mixed[i % mixed.length]!, + _fromLocation: locations[Math.floor(i / mixed.length) % 2], + } as any) + } + }, + { time: 1_000, warmupTime: 300 }, + ) +}) diff --git a/packages/router-core/tests/build-location-cache.test.ts b/packages/router-core/tests/build-location-cache.test.ts index d34eb92f2b..43b07afc98 100644 --- a/packages/router-core/tests/build-location-cache.test.ts +++ b/packages/router-core/tests/build-location-cache.test.ts @@ -37,7 +37,7 @@ function makeRouter(initialEntry = '/items/1') { /** * Build `opts` with and without a memo slot and assert the memo did not change * the answer. Returns whether the pathname cache reused its previous entry, - * which happens only for location-independent pathnames, so both + * which happens while the template and effective params are unchanged, so both * the fast path and the correctness of the classification are pinned. */ function buildBoth( @@ -399,7 +399,7 @@ describe('buildLocation memo (_buildCache)', () => { expect(second.location.href).toBe('/items/9b') }) - test('an explicit mask stays correct (memo disabled)', async () => { + test('an explicit mask keeps resolving while the main pathname hits', async () => { const router = makeRouter('/items/1') await router.load() const cache: BuildLocationCache = {} @@ -415,11 +415,11 @@ describe('buildLocation memo (_buildCache)', () => { await router.navigate({ to: '/items/$id', params: { id: '2' } }) const second = buildBoth(router, cache, opts) - expect(second.hit).toBe(false) + expect(second.hit).toBe(true) expect(second.location.maskedLocation?.href).toBe('/items/2/detail') }) - test('routeMasks disable the memo and keep resolving per navigation', async () => { + test('routeMasks keep resolving on main pathname cache hits', async () => { const rootRoute = new BaseRootRoute({}) const indexRoute = new BaseRoute({ getParentRoute: () => rootRoute, @@ -458,17 +458,17 @@ describe('buildLocation memo (_buildCache)', () => { await router.navigate({ to: '/items/$id', params: { id: '2' } }) const second = buildBoth(router, cache, opts) - expect(second.hit).toBe(false) + expect(second.hit).toBe(true) expect(second.location.maskedLocation?.href).toBe('/items/9') // Clearing only the option can leave the processed mask tree in place. router.update({ routeMasks: [] }) const cleared = buildBoth(router, cache, opts) - expect(cleared.hit).toBe(false) + expect(cleared.hit).toBe(true) expect(cleared.location.maskedLocation?.href).toBe('/items/9') }) - test('the memo is invalidated when router options change', async () => { + test('unrelated router options preserve the pathname and apply the new basepath', async () => { const router = makeRouter('/items/1') await router.load() const cache: BuildLocationCache = {} @@ -477,7 +477,7 @@ describe('buildLocation memo (_buildCache)', () => { expect(buildBoth(router, cache, opts).location.href).toBe('/items/9') router.update({ ...router.options, basepath: '/app' }) const second = buildBoth(router, cache, opts) - expect(second.hit).toBe(false) + expect(second.hit).toBe(true) expect(second.location.href).toBe('/app/items/9') }) From b62f2aa3cedc551859b05b68f2a9225933b621e1 Mon Sep 17 00:00:00 2001 From: Sheraff Date: Sat, 5 Sep 2026 14:40:03 +0200 Subject: [PATCH 3/3] perf(react-router): cache link pathname dependencies --- .changeset/open-onions-jog.md | 6 + RESULT-optimization-link-pathname-cache.md | 199 +++++++++++ packages/react-router/src/link.tsx | 14 +- packages/router-core/src/RouterProvider.ts | 8 +- packages/router-core/src/index.ts | 1 + packages/router-core/src/path.ts | 9 +- packages/router-core/src/router.ts | 387 +++++++++++++++------ 7 files changed, 511 insertions(+), 113 deletions(-) create mode 100644 .changeset/open-onions-jog.md create mode 100644 RESULT-optimization-link-pathname-cache.md diff --git a/.changeset/open-onions-jog.md b/.changeset/open-onions-jog.md new file mode 100644 index 0000000000..15f98eb90a --- /dev/null +++ b/.changeset/open-onions-jog.md @@ -0,0 +1,6 @@ +--- +'@tanstack/router-core': patch +'@tanstack/react-router': patch +--- + +Reuse mounted React link pathnames while their resolved route template and parameter values are unchanged, including optional, inherited and splat parameters. Preserve parameter callbacks, search middleware, URL rewrites, serializers, hash and state updates. diff --git a/RESULT-optimization-link-pathname-cache.md b/RESULT-optimization-link-pathname-cache.md new file mode 100644 index 0000000000..b95ff38dfd --- /dev/null +++ b/RESULT-optimization-link-pathname-cache.md @@ -0,0 +1,199 @@ +# Link pathname cache: dependency-based revision + +Baseline production implementation: `c18e690814`. Tests and benchmark sources are committed separately in `73ce104784` and `ac868d9cc9`; production changes remain in the working tree. This report supersedes the earlier conservative implementation and its eligibility claims. + +## Contract and behavior + +The cache belongs to one mounted React link and survives search/hash/state/params prop changes. Individual options/params objects follow React's immutable-input convention; each call validates the actual pathname dependencies. + +- Record every parameter read by interpolation, including absent optional parameters. Preserve `_splat` as the dependency and discard its deprecated `*` alias. There is no named-star guard or blanket optional-path exclusion. +- An early hit avoids path resolution, merging and interpolation when the source/destination, route tree, trailing-slash policy, decoder, plain input and effective path values match. +- Otherwise, run ordinary path resolution, parameter updaters, route matching and stringifiers, then compare the resolved template and parameter values. Stable callback output, concrete destinations, and equivalent relative destinations can hit here. +- Accessor-bearing params run through normal merging before comparison, including getters on keys outside the path. Object-valued parameters still interpolate because their string conversion can change. +- Search middleware/validation, search serialization, output rewrites, hash, state and masks continue to run. Mask builds use separate ordinary builds and cannot contaminate the main pathname slot. `leaveParams` bypasses interpolation caching; navigation retains its validation and development diagnostics. +- Unrelated router options do not invalidate the pathname. Route tree and decoder changes do; trailing-slash changes require path resolution before deciding whether interpolation can be reused. + +## BEFORE + +The unoptimized production source is unchanged from the earlier baseline. Its full 18-scenario bundle results and production React navigation measurements are reused. The expanded core benchmark is run with the implementation stashed, using exactly the same source as the candidate. Existing baseline core/React unit and type suites passed in an isolated worktree. + +Navigation baseline: 202 persistent React links, eight navigations per sample; mean **4.8505 ms**, **206.16 Hz**, p99 **6.2805 ms**, p999 **10.5150 ms**, standard deviation **0.3882 ms**, RME **±0.35%**, **2062 samples**. + +| Scenario | Gzip | Initial gzip | Raw | Brotli | +| -------------------------------- | -----: | -----------: | -----: | -----: | +| react-router.minimal | 85772 | 85631 | 268336 | 74649 | +| react-router.full | 89366 | 89225 | 280329 | 77791 | +| solid-router.minimal | 33930 | 33801 | 98429 | 30609 | +| solid-router.full | 38868 | 38745 | 113419 | 34988 | +| vue-router.minimal | 50635 | 50507 | 141472 | 45775 | +| vue-router.full | 56393 | 56265 | 160117 | 50694 | +| react-start.minimal | 98992 | 98855 | 311619 | 85862 | +| react-start.query-integration | 106512 | 106372 | 338754 | 92287 | +| react-start.deferred-hydration | 99733 | 98876 | 313008 | 86520 | +| react-start.full | 102226 | 102089 | 321585 | 88565 | +| react-start.rsbuild.minimal | 102345 | 102170 | 322193 | 88258 | +| react-start.rsbuild.minimal-iife | 102757 | 102588 | 323152 | 88605 | +| react-start.rsbuild.full | 105744 | 105569 | 332524 | 91211 | +| solid-start.minimal | 47080 | 46951 | 140523 | 41897 | +| solid-start.deferred-hydration | 50243 | 47030 | 148163 | 44763 | +| solid-start.full | 52283 | 52155 | 156278 | 46312 | +| vue-start.minimal | 67186 | 67059 | 193548 | 59756 | +| vue-start.full | 71097 | 70969 | 206153 | 63175 | + +Baseline raw reports: `/tmp/link-cache-base-bundle.json`, `/tmp/link-cache-base-perf.json`, `/tmp/link-cache-v6-base-micro.json`. + +Expanded baseline core measurements (ms per 100 builds): + +| Case | Mean ms | RME | Samples | +| ---------------------------------------- | ------: | -----: | ------: | +| uncached literal | 0.23342 | ±0.32% | 4285 | +| cached literal | 0.22957 | ±0.28% | 4357 | +| uncached inherited | 0.19704 | ±0.50% | 5076 | +| changing inherited params | 0.19425 | ±0.38% | 5148 | +| uncached optional | 0.19561 | ±0.25% | 5113 | +| changing optional params | 0.19872 | ±0.59% | 5033 | +| uncached middleware | 0.24427 | ±0.98% | 4094 | +| cached middleware | 0.24281 | ±0.97% | 4119 | +| stable mixed slots | 0.21716 | ±0.39% | 4605 | +| cold literal slots | 0.23085 | ±0.96% | 4332 | +| optional supplied uncached | 0.19846 | ±0.67% | 5039 | +| optional supplied cached | 0.19094 | ±0.32% | 5238 | +| optional absent uncached | 0.14033 | ±0.28% | 7127 | +| optional absent cached | 0.15339 | ±5.38% | 6520 | +| optional inherited unchanged uncached | 0.17370 | ±0.27% | 5758 | +| optional inherited unchanged cached | 0.17599 | ±0.71% | 5683 | +| inherited unchanged uncached | 0.16945 | ±0.88% | 5902 | +| inherited unchanged cached | 0.16949 | ±0.35% | 5900 | +| relative unchanged uncached | 0.15694 | ±7.71% | 6372 | +| relative unchanged cached | 0.14463 | ±0.65% | 6915 | +| updater unchanged uncached | 0.16712 | ±0.68% | 5984 | +| updater unchanged cached | 0.16417 | ±0.30% | 6092 | +| stringifier unchanged uncached | 0.20613 | ±0.73% | 4852 | +| stringifier unchanged cached | 0.19866 | ±0.30% | 5034 | +| explicit mask uncached | 0.35140 | ±0.27% | 2846 | +| explicit mask cached | 0.36551 | ±0.78% | 2736 | +| mixed hits and changing inherited params | 0.19447 | ±0.73% | 5143 | + +## AFTER + +### Navigation benchmark + +A refreshed baseline was measured immediately after the final candidate, on the same machine with the same production React scenario. + +| Metric | Refreshed baseline | Final candidate | +| ------------------ | -----------------: | --------------: | +| Mean | 5.0077 ms | 3.0916 ms | +| Throughput | 199.6926 Hz | 323.4599 Hz | +| p99 | 6.5276 ms | 4.3127 ms | +| p999 | 10.3628 ms | 9.2787 ms | +| Standard deviation | 0.4772 ms | 0.8113 ms | +| RME | 0.4180% | 0.9043% | +| Samples | 1997.0000 | 3235.0000 | + +Mean time decreases **38.3%**, with **1.62× throughput**. Earlier full candidate runs measured about 3.40 ms, and the earlier baseline was 4.85 ms; these are local benchmark measurements with between-run variability, not universal application speedups. The scenario contains many persistent links with reusable destinations. + +### Focused core benchmark + +Milliseconds per 100 builds. All cases check cached/fresh equality before timing; supported warm cases additionally assert actual cache-entry reuse across locations. Baseline uses the same expanded benchmark source and ignores the private cache slot. + +| Case | Baseline ms | Candidate ms | Mean change | Candidate RME | +| ---------------------------------------- | ----------: | -----------: | ----------: | ------------: | +| uncached literal | 0.23342 | 0.23574 | +1.0% | ±0.29% | +| cached literal | 0.22957 | 0.06553 | -71.5% | ±0.22% | +| uncached inherited | 0.19704 | 0.19621 | -0.4% | ±0.29% | +| changing inherited params | 0.19425 | 0.24063 | +23.9% | ±0.80% | +| uncached optional | 0.19561 | 0.19999 | +2.2% | ±0.81% | +| changing optional params | 0.19872 | 0.23823 | +19.9% | ±0.90% | +| uncached middleware | 0.24427 | 0.24465 | +0.2% | ±0.51% | +| cached middleware | 0.24281 | 0.07421 | -69.4% | ±1.43% | +| stable mixed slots | 0.21716 | 0.05937 | -72.7% | ±0.30% | +| cold literal slots | 0.23085 | 0.26474 | +14.7% | ±0.48% | +| optional supplied uncached | 0.19846 | 0.19923 | +0.4% | ±0.49% | +| optional supplied cached | 0.19094 | 0.03378 | -82.3% | ±0.37% | +| optional absent uncached | 0.14033 | 0.14652 | +4.4% | ±0.25% | +| optional absent cached | 0.15339 | 0.03392 | -77.9% | ±0.20% | +| optional inherited unchanged uncached | 0.17370 | 0.17174 | -1.1% | ±0.27% | +| optional inherited unchanged cached | 0.17599 | 0.04298 | -75.6% | ±0.43% | +| inherited unchanged uncached | 0.16945 | 0.16482 | -2.7% | ±0.20% | +| inherited unchanged cached | 0.16949 | 0.04355 | -74.3% | ±1.23% | +| relative unchanged uncached | 0.15694 | 0.14221 | -9.4% | ±0.21% | +| relative unchanged cached | 0.14463 | 0.04264 | -70.5% | ±1.18% | +| updater unchanged uncached | 0.16712 | 0.17017 | +1.8% | ±0.27% | +| updater unchanged cached | 0.16417 | 0.11279 | -31.3% | ±0.46% | +| stringifier unchanged uncached | 0.20613 | 0.20665 | +0.2% | ±0.20% | +| stringifier unchanged cached | 0.19866 | 0.15181 | -23.6% | ±0.90% | +| explicit mask uncached | 0.35140 | 0.37352 | +6.3% | ±0.25% | +| explicit mask cached | 0.36551 | 0.23904 | -34.6% | ±0.98% | +| mixed hits and changing inherited params | 0.19447 | 0.15242 | -21.6% | ±0.40% | + +Using paired uncached/cached cases within the final run: + +| Stable dependency case | Uncached / cached throughput ratio | +| ---------------------------- | ---------------------------------: | +| optional supplied | 5.90× | +| optional absent | 4.32× | +| optional inherited unchanged | 4.00× | +| inherited unchanged | 3.78× | +| relative unchanged | 3.34× | +| updater unchanged | 1.51× | +| stringifier unchanged | 1.36× | +| explicit mask | 1.56× | + +“Stable mixed slots” deliberately keeps each slot's used params stable; the earlier benchmark called this mixed without noticing that its option/location cycles were correlated. “Mixed hits and changing inherited params” uses an independent location cycle so inherited dependencies really change. The latter improves about 22% over baseline. No production-app hit-rate percentage is inferred from these synthetic cases. + +Cold and forced misses remain tradeoffs. Cold literal slots cost about 0.34 microseconds extra per build versus the expanded baseline. Constantly changing inherited/optional destinations cost about 0.40–0.46 microseconds extra per build; they do not benefit from pathname reuse. A subsequent ordinary literal hit saves substantially more than the first-build overhead. Some uncached cases vary by a few percent between runs; the cache is not claimed to accelerate no-slot calls. Stable optional microbenchmarks isolate interpolation work and are not equivalent to a 4–6× application-level improvement. + +### Full bundle comparison + +All 18 scenarios were built. Gzip is primary; initial gzip, raw, Brotli and per-file counts were also inspected. No scenario gained a JavaScript file. Most growth is in the main client chunk; changed import hashes can move a few compressed bytes in tiny lazy chunks. + +| Scenario | Final gzip | Gzip delta | Initial gzip delta | Raw delta | Brotli delta | +| -------------------------------- | ---------: | ---------: | -----------------: | --------: | -----------: | +| react-router.minimal | 86339 | +567 | +569 | +1747 | +570 | +| react-router.full | 89955 | +589 | +592 | +1744 | +584 | +| solid-router.minimal | 34474 | +544 | +546 | +1700 | +457 | +| solid-router.full | 39433 | +565 | +560 | +1700 | +496 | +| vue-router.minimal | 51188 | +553 | +555 | +1703 | +435 | +| vue-router.full | 56946 | +553 | +554 | +1700 | +554 | +| react-start.minimal | 99559 | +567 | +565 | +1735 | +358 | +| react-start.query-integration | 107087 | +575 | +576 | +1730 | +483 | +| react-start.deferred-hydration | 100301 | +568 | +565 | +1735 | +439 | +| react-start.full | 102820 | +594 | +592 | +1726 | +514 | +| react-start.rsbuild.minimal | 102924 | +579 | +579 | +1819 | +489 | +| react-start.rsbuild.minimal-iife | 103334 | +577 | +577 | +1819 | +610 | +| react-start.rsbuild.full | 106311 | +567 | +567 | +1819 | +360 | +| solid-start.minimal | 47653 | +573 | +574 | +1700 | +530 | +| solid-start.deferred-hydration | 50798 | +555 | +555 | +1700 | +450 | +| solid-start.full | 52834 | +551 | +551 | +1700 | +529 | +| vue-start.minimal | 67729 | +543 | +543 | +1706 | +487 | +| vue-start.full | 71647 | +550 | +551 | +1694 | +353 | + +React minimal adds **567 gzip bytes (0.66%)**. Solid/Vue minimal add **544/553 gzip bytes** through shared core, without adapter wiring or a claimed framework-level benefit. This is larger than the previous rejected narrow cache (+257 React gzip bytes): broader dependency tracking and callback-preserving hits require more code. + +### Attribution and limits + +The core cache, optional-dependency tracking and React caller are one dependent production group. The early path improves ordinary immutable inputs; the late path preserves callbacks while recovering interpolation hits. Neither replaces search/rewrites with cached outputs. A mounted-link slot avoids invalidation from unrelated prop changes. It remains internal and is not added to click/preload options. + +The final local candidates were measured separately: the dependency-based cache without the own-parameter constant flag; the constant flag; and setting the optional-tracking property only on cached interpolation options. The constant flag reduced supplied-optional warm builds from 0.04398 to 0.03444 ms/100 and explicitly absent optionals from 0.04216 to 0.03490 ms/100. It does not override inherited or getter dependencies: an independent callback review verified those conditions. The final no-slot options shape measured absent-optional uncached calls at 0.14652 ms/100 versus 0.15146 in the preceding candidate, while other cases varied. The corresponding React-minimal bundle attribution is v6: 86285 gzip / 269928 raw bytes, v7-target: 86330 gzip / 270069 raw bytes, final-v8: 86339 gzip / 270083 raw bytes. The final composed version was measured across all 18 scenarios. + +Remaining deliberate constraints: + +- Params objects are immutable React inputs. Dynamic values should be supplied through new props or callbacks; the cache does not promise to observe in-place mutation of a previously classified data object. +- Getter-bearing params and parameter callbacks execute before a late hit. Object-valued path parameters continue interpolating so string conversion remains observable. +- Concrete destinations still rematch their branch; optional/relative/updater/stringifier/masked destinations are not categorically excluded. +- Mask destinations are rebuilt separately, preserving their own callbacks and dependencies. +- Route collision diagnostics can be emitted on a cold development build and skipped on subsequent early hits; navigation's from-route diagnostics remain on its ordinary path. +- Solid/Vue need their own reactive dependency and performance validation before using this immutable-input cache. This change wires React only. + +### Validation + +Five independent reviews covered optional/splat/relative/mask semantics, callbacks, performance distributions, React concurrency and remaining build modes. Their concrete findings are addressed. The final constant flag received an additional callback/dependency review. + +- Core unit suite: **113 files, 1725 passed, four expected failures**. +- React unit suite: **80 files, 1053 passed, one skipped**. +- Core/React type suites and ESLint passed; existing lint warnings remain. +- Browser tests: **React basic 24/24**, **React i18n Paraglide 13/13**. +- New coverage includes optional present/absent/inherited dependencies, explicit undefined/null, prefixes/suffixes, braced splats, relative sibling destinations, masks, updater/stringifier output changes, accessor effects, route updates, decoder/trailing-slash changes, search/hash prop changes, preload validation and a suspended React transition. +- Prettier and `git diff --check` passed. A changeset is included. No PR was created and the implementation remains uncommitted. + +Final raw reports: `/tmp/link-cache-v8-micro.json`, `/tmp/link-cache-final-v8-nav.json`, `/tmp/link-cache-refreshed-base-nav.json`, `/tmp/link-cache-final-v8-bundle.json`. Verification logs: `/tmp/link-cache-final-v8-checks.log`, `/tmp/link-cache-final-v8-e2e.log`. Intermediate measurement files use `/tmp/link-cache-v6-*` and `/tmp/link-cache-v7-*`. diff --git a/packages/react-router/src/link.tsx b/packages/react-router/src/link.tsx index a0d6968986..ed7746d733 100644 --- a/packages/react-router/src/link.tsx +++ b/packages/react-router/src/link.tsx @@ -20,6 +20,7 @@ import { useHydrated } from './ClientOnly' import type { ActiveOptions, AnyRouter, + BuildLocationCache, Constrain, LinkOptions, ParsedLocation, @@ -496,6 +497,8 @@ export function useLinkProps< // eslint-disable-next-line react-hooks/rules-of-hooks const stableActiveOptions = useValueStable(activeOptions) // eslint-disable-next-line react-hooks/rules-of-hooks + const buildCache = React.useMemo(() => ({}), []) + // eslint-disable-next-line react-hooks/rules-of-hooks const _options = React.useMemo( () => options, // eslint-disable-next-line react-hooks/exhaustive-deps @@ -521,6 +524,7 @@ export function useLinkProps< (location: ParsedLocation): LinkState => { const next = router.buildLocation({ _fromLocation: location, + _buildCache: buildCache, ..._options, } as any) @@ -554,7 +558,15 @@ export function useLinkProps< ), ] }, - [stableActiveOptions, disabled, isHydrated, _options, router, to], + [ + stableActiveOptions, + disabled, + isHydrated, + _options, + router, + to, + buildCache, + ], ) // eslint-disable-next-line react-hooks/rules-of-hooks diff --git a/packages/router-core/src/RouterProvider.ts b/packages/router-core/src/RouterProvider.ts index 52aeaffabb..48d8c079ae 100644 --- a/packages/router-core/src/RouterProvider.ts +++ b/packages/router-core/src/RouterProvider.ts @@ -1,7 +1,11 @@ import type { NavigateOptions, ToOptions } from './link' import type { ParsedLocation } from './location' import type { RoutePaths } from './routeInfo' -import type { RegisteredRouter, ViewTransitionOptions } from './router' +import type { + BuildLocationCache, + RegisteredRouter, + ViewTransitionOptions, +} from './router' export interface MatchLocation { to?: string | number | null @@ -43,5 +47,7 @@ export type BuildLocationFn = < leaveParams?: boolean _includeValidateSearch?: boolean _isNavigate?: boolean + /** @internal */ + _buildCache?: BuildLocationCache }, ) => ParsedLocation diff --git a/packages/router-core/src/index.ts b/packages/router-core/src/index.ts index a296629ffa..003587d1e2 100644 --- a/packages/router-core/src/index.ts +++ b/packages/router-core/src/index.ts @@ -255,6 +255,7 @@ export type { RegisteredRouter, RouterState, BuildNextOptions, + BuildLocationCache, RouterListener, RouterEvent, ListenerFn, diff --git a/packages/router-core/src/path.ts b/packages/router-core/src/path.ts index d302ee13ab..81be6f3fec 100644 --- a/packages/router-core/src/path.ts +++ b/packages/router-core/src/path.ts @@ -222,6 +222,8 @@ interface InterpolatePathOptions { * For testing only, in development mode we use the router.isServer value */ server?: boolean + /** @internal Include absent optional parameters when tracking dependencies. */ + trackOptionalParams?: boolean } type InterPolatePathResult = { @@ -400,7 +402,12 @@ export function interpolatePath({ const valueRaw = params[key] // Check if optional parameter is missing or undefined - if (valueRaw == null) continue + if (valueRaw == null) { + if (rest.trackOptionalParams) { + usedParams[key] = valueRaw + } + continue + } usedParams[key] = valueRaw diff --git a/packages/router-core/src/router.ts b/packages/router-core/src/router.ts index fa4168b9ce..0631dd84fb 100644 --- a/packages/router-core/src/router.ts +++ b/packages/router-core/src/router.ts @@ -576,6 +576,33 @@ export interface BuildNextOptions { _fromLocation?: ParsedLocation unsafeRelative?: 'path' _isNavigate?: boolean + /** @internal */ + _buildCache?: BuildLocationCache +} + +/** + * Caller-owned pathname cache for immutable link options. All parameters, + * including absent optional ones, are dependencies. Callbacks still run. + * @internal + */ +export interface BuildLocationCache { + value?: { + decoder: unknown + trailingSlash: unknown + tree: unknown + to: unknown + from: string | undefined + template: string + route: AnyRoute | undefined + routes: ReadonlyArray + params: Record + pathname: string + input: unknown + // The immutable input has no enumerable accessors, including non-path keys. + plain: boolean + // Every interpolation dependency is an own primitive input value. + constant: boolean + } } type NavigationEventInfo = { @@ -1840,6 +1867,7 @@ export class RouterCore< dest: BuildNextOptions & { unmaskOnReload?: boolean } = {}, + cache?: BuildLocationCache, ): ParsedLocation => { if (dest.href) { const parsed = parseHref(dest.href, {} as ParsedHistoryState) @@ -1858,128 +1886,216 @@ export class RouterCore< const currentLocation = dest._fromLocation || this._pendingLocation || this.latestLocation - // Use lightweight matching - only computes what buildLocation needs - // (fullPath, search, params) without creating full match objects + // Current-location matching and callbacks retain their normal semantics. const lightweightResult = this.matchRoutesLightweight(currentLocation) - - // check that from path exists in the current route tree - // do this check only on navigations during test or development - if ( - process.env.NODE_ENV !== 'production' && - dest.from && - dest._isNavigate - ) { - const [allFromMatches] = this.getMatchedRoutes(dest.from) - - const matchedFrom = findLast( - lightweightResult[0 /* matchedRoutes */], - (d) => { - return comparePaths(d.fullPath, dest.from!) - }, - ) - - const matchedCurrent = findLast(allFromMatches, (d) => { - return comparePaths(d.fullPath, lightweightResult[1 /* fullPath */]) - }) - - // for from to be invalid it shouldn't just be unmatched to currentLocation - // but the currentLocation should also be unmatched to from - if (!matchedFrom && !matchedCurrent) { - console.warn(`Could not find match for from: ${dest.from}`) - } - } - + const fromSearch = lightweightResult[2 /* search */] + const fromParams = lightweightResult[3 /* params */] const defaultedFromPath = dest.unsafeRelative === 'path' ? currentLocation.pathname : (dest.from ?? lightweightResult[1 /* fullPath */]) - - // From search should always use the current location - const fromSearch = lightweightResult[2 /* search */] - // Same with params. It can't hurt to provide as many as possible - const fromParams = lightweightResult[3 /* params */] - - const nextTo = this.resolvePathWithBase( - defaultedFromPath, - dest.to ? `${dest.to}` : '.', - ) - - // Resolve the next params - let nextParams = resolveNextParams(dest.params, fromParams) - - const destRoute = this.routesByPath[ - trimPathRight(nextTo) as keyof typeof this.routesByPath - ] as AnyRoute | undefined - - let destRoutes: ReadonlyArray - if (destRoute) { - destRoutes = this.getRouteBranch(destRoute) - } else if (nextTo.includes('$')) { - // Route templates must match routesByPath exactly. A miss here is a - // typed destination mismatch, not a concrete URL to route-match. - destRoutes = [] - } else { - const [matchedRoutes, rawParams, foundRoute] = - this.getMatchedRoutes(nextTo) - destRoutes = matchedRoutes - - if ( - this.options.notFoundRoute && - (!foundRoute || (foundRoute.path !== '/' && rawParams['**'])) - ) { - destRoutes = [...destRoutes, this.options.notFoundRoute] - } + const from = + cache && !(typeof dest.to === 'string' && dest.to.startsWith('/')) + ? defaultedFromPath + : undefined + let entry = cache?.value + if ( + entry && + (entry.decoder !== this.pathParamsDecoder || + entry.tree !== this.processedTree) + ) { + entry = undefined } + let nextPathname: string + let destRoutes: ReadonlyArray + // Plain params can be compared before merging. Callbacks still take the + // ordinary path below, where their resolved output may also hit the cache. + if ( + entry?.route && + entry.to === dest.to && + entry.from === from && + entry.trailingSlash === this.options.trailingSlash && + entry.input === dest.params && + entry.plain && + !dest.href && + !opts.leaveParams && + !opts._isNavigate && + typeof dest.params !== 'function' && + !entry.routes.some(routeHasParamsStringify) && + (entry.constant || + equalPathParams( + entry.params, + dest.params, + dest.params === false || dest.params === null + ? undefined + : fromParams, + )) + ) { + nextPathname = entry.pathname + destRoutes = entry.routes + } else { + // check that from path exists in the current route tree + // do this check only on navigations during test or development + if ( + process.env.NODE_ENV !== 'production' && + dest.from && + dest._isNavigate + ) { + const [allFromMatches] = this.getMatchedRoutes(dest.from) - // If there are any params, we need to stringify them - if (destRoutes.length && hasKeys(nextParams)) { - for (const route of destRoutes) { - const fn = - route.options.params?.stringify ?? route.options.stringifyParams - if (fn) { - if (nextParams === fromParams) { - nextParams = Object.assign(Object.create(null), nextParams) - } - try { - Object.assign(nextParams, fn(nextParams)) - } catch { - // Ignore errors here. When a paired parseParams is defined, - // extractStrictParams will re-throw during route matching, - // storing the error on the match and allowing the route's - // errorComponent to render. If no parseParams is defined, - // the stringify error is silently dropped. + const matchedFrom = findLast( + lightweightResult[0 /* matchedRoutes */], + (d) => { + return comparePaths(d.fullPath, dest.from!) + }, + ) + + const matchedCurrent = findLast(allFromMatches, (d) => { + return comparePaths(d.fullPath, lightweightResult[1 /* fullPath */]) + }) + + // for from to be invalid it shouldn't just be unmatched to currentLocation + // but the currentLocation should also be unmatched to from + if (!matchedFrom && !matchedCurrent) { + console.warn(`Could not find match for from: ${dest.from}`) + } + } + + const nextTo = this.resolvePathWithBase( + defaultedFromPath, + dest.to ? `${dest.to}` : '.', + ) + + // Resolve the next params + let nextParams = resolveNextParams(dest.params, fromParams) + + const destRoute = this.routesByPath[ + trimPathRight(nextTo) as keyof typeof this.routesByPath + ] as AnyRoute | undefined + + if (destRoute) { + destRoutes = this.getRouteBranch(destRoute) + } else if (nextTo.includes('$')) { + // Route templates must match routesByPath exactly. A miss here is a + // typed destination mismatch, not a concrete URL to route-match. + destRoutes = [] + } else { + const [matchedRoutes, rawParams, foundRoute] = + this.getMatchedRoutes(nextTo) + destRoutes = matchedRoutes + + if ( + this.options.notFoundRoute && + (!foundRoute || (foundRoute.path !== '/' && rawParams['**'])) + ) { + destRoutes = [...destRoutes, this.options.notFoundRoute] + } + } + + // If there are any params, we need to stringify them + if (destRoutes.length && hasKeys(nextParams)) { + for (const route of destRoutes) { + const fn = + route.options.params?.stringify ?? route.options.stringifyParams + if (fn) { + if (nextParams === fromParams) { + nextParams = Object.assign(Object.create(null), nextParams) + } + try { + Object.assign(nextParams, fn(nextParams)) + } catch { + // Ignore errors here. When a paired parseParams is defined, + // extractStrictParams will re-throw during route matching, + // storing the error on the match and allowing the route's + // errorComponent to render. If no parseParams is defined, + // the stringify error is silently dropped. + } } } } - } - const nextPathname = opts.leaveParams - ? // Keep path params uninterpolated for matchRoute/template matching. - nextTo - : decodePath( - interpolatePath({ - path: nextTo, - params: nextParams, - decoder: this.pathParamsDecoder, - server: this.isServer, - }).interpolatedPath, - ).path - - if ( - process.env.NODE_ENV !== 'production' && - destRoute && - !opts.leaveParams - ) { - try { - const foundRoute = this.getMatchedRoutes(nextPathname)[2] - if (foundRoute?.id !== destRoute.id) { - console.warn( - `Generated path "${nextPathname}" for route "${destRoute.id}" matched route "${foundRoute?.id}" instead. This can happen when multiple route templates resolve to the same URL. Use the route template that matches the intended route, or adjust params.stringify if it changed the target path.`, + const hit = + !opts.leaveParams && + entry && + entry.decoder === this.pathParamsDecoder && + entry.template === nextTo && + equalPathParams(entry.params, nextParams) + if (hit) { + nextPathname = entry!.pathname + entry!.to = dest.to + entry!.from = from + entry!.trailingSlash = this.options.trailingSlash + entry!.route = destRoute + entry!.routes = destRoutes + if (entry!.input !== dest.params) { + entry!.input = dest.params + entry!.plain = hasDataParams(dest.params) + entry!.constant = equalPathParams( + entry!.params, + dest.params, + undefined, + true, ) } - } catch { - // Ignore roundtrip validation errors. The generated location will be - // handled by the normal navigation flow. + } else if (opts.leaveParams) { + nextPathname = nextTo + } else { + const interpolationOptions: Parameters[0] = { + path: nextTo, + params: nextParams, + decoder: this.pathParamsDecoder, + server: this.isServer, + } + if (cache) { + interpolationOptions.trackOptionalParams = true + } + const interpolated = interpolatePath(interpolationOptions) + nextPathname = decodePath(interpolated.interpolatedPath).path + if (cache) { + // "*" is the deprecated alias for _splat, not a separate dependency. + delete interpolated.usedParams['*'] + cache.value = { + decoder: this.pathParamsDecoder, + trailingSlash: this.options.trailingSlash, + tree: this.processedTree, + to: dest.to, + from, + template: nextTo, + route: destRoute, + routes: destRoutes, + params: interpolated.usedParams, + pathname: nextPathname, + input: dest.params, + plain: + entry && entry.input === dest.params + ? entry.plain + : hasDataParams(dest.params), + constant: equalPathParams( + interpolated.usedParams, + dest.params, + undefined, + true, + ), + } + } + } + + if ( + process.env.NODE_ENV !== 'production' && + destRoute && + !opts.leaveParams + ) { + try { + const foundRoute = this.getMatchedRoutes(nextPathname)[2] + if (foundRoute?.id !== destRoute.id) { + console.warn( + `Generated path "${nextPathname}" for route "${destRoute.id}" matched route "${foundRoute?.id}" instead. This can happen when multiple route templates resolve to the same URL. Use the route template that matches the intended route, or adjust params.stringify if it changed the target path.`, + ) + } + } catch { + // Ignore roundtrip validation errors. The generated location will be + // handled by the normal navigation flow. + } } } @@ -2086,7 +2202,7 @@ export class RouterCore< } } - const next = build(opts) + const next = build(opts, opts._buildCache) if (opts.mask) { next.maskedLocation = build({ @@ -2835,6 +2951,57 @@ function applySearchMiddleware( return applyNext(0, search) } +function routeHasParamsStringify(route: AnyRoute) { + return !!(route.options.params?.stringify || route.options.stringifyParams) +} + +// Inspect once per immutable params object, including keys outside the path: +// their getters can have effects needed by later search/URL callbacks. +function hasDataParams(params: unknown) { + if (params && typeof params === 'object') { + for (const key of Reflect.ownKeys(params)) { + const descriptor = Object.getOwnPropertyDescriptor(params, key)! + if (descriptor.enumerable && !('value' in descriptor)) { + return false + } + } + } + return true +} + +/** Compare exactly the values interpolation reads, without allocating a merge. */ +function equalPathParams( + previous: Record, + params: unknown, + inherited?: Record, + requireOwn = false, +) { + for (const key in previous) { + const descriptor = params + ? Object.getOwnPropertyDescriptor(params, key) + : undefined + if (requireOwn && !descriptor?.enumerable) { + return false + } + let value = inherited?.[key] + if (descriptor?.enumerable) { + // Accessors must run through resolveNextParams before checking a hit. + if (!('value' in descriptor)) { + return false + } + value = descriptor.value + } + if ( + value !== previous[key] || + (value !== null && typeof value === 'object') || + typeof value === 'function' + ) { + return false + } + } + return true +} + function findGlobalNotFoundRouteId( notFoundMode: 'root' | 'fuzzy' | undefined, routes: ReadonlyArray,