diff --git a/docs/guide/pages-routing/overview.md b/docs/guide/pages-routing/overview.md index 5667d48c1..8dfeeb3dd 100644 --- a/docs/guide/pages-routing/overview.md +++ b/docs/guide/pages-routing/overview.md @@ -128,6 +128,20 @@ Production deploys exclude resources used only by `.dev` pages and their compani The first request receives rendered HTML. Later navigations run the loader and update the page without reloading the document. Form submissions run an action, then refresh page props or redirect. +### After a deploy + +An open tab keeps the code it loaded. Deploy while it stays open, and its next navigation asks for chunks that no longer exist. + +Void recovers that navigation. The tab sends the build it is running with each page request, and an answer from a different build makes it load the requested page as a document instead of rendering it. The destination keeps its query string and fragment, and the current page stays visible until the load starts. + +These never reload the tab: + +- A prefetch drops the response and lets the next navigation decide. +- A form submission renders its response, so the action never runs twice. The next navigation reloads if it has to. +- A failed request is not treated as a deploy. + +Recovery is on by default. Set `deployRecovery: false` in your framework plugin's options to keep your own [error boundaries](./errors.md) in charge instead. + To opt a specific route out of server-rendered component HTML, export `ssr = false` from its companion `.server.ts` file: ```ts diff --git a/docs/reference/api/pages.md b/docs/reference/api/pages.md index 390670498..1ddece7ec 100644 --- a/docs/reference/api/pages.md +++ b/docs/reference/api/pages.md @@ -91,6 +91,7 @@ interface VoidVueOptions { hoverDelay?: number; // default: 75 (ms) cacheFor?: number | string | [string, string]; // default: '30s' }; + deployRecovery?: boolean; // reload a tab whose build is gone. default: true } ``` @@ -147,6 +148,7 @@ interface VoidReactOptions { hoverDelay?: number; // default: 75 (ms) cacheFor?: number | string | [string, string]; // default: '30s' }; + deployRecovery?: boolean; // reload a tab whose build is gone. default: true } ``` @@ -232,6 +234,7 @@ interface VoidSvelteOptions { hoverDelay?: number; // default: 75 (ms) cacheFor?: number | string | [string, string]; // default: '30s' }; + deployRecovery?: boolean; // reload a tab whose build is gone. default: true } ``` @@ -286,6 +289,7 @@ interface VoidSolidOptions { hoverDelay?: number; // default: 75 (ms) cacheFor?: number | string | [string, string]; // default: '30s' }; + deployRecovery?: boolean; // reload a tab whose build is gone. default: true } ``` diff --git a/packages/edge/src/index.ts b/packages/edge/src/index.ts index 54610bc0b..d7166a9f6 100644 --- a/packages/edge/src/index.ts +++ b/packages/edge/src/index.ts @@ -1,5 +1,10 @@ export type { ProjectZeroTrustRouting } from './access.ts'; -export { PAGES_PROTOCOL_VERSION } from './pages-protocol.ts'; +export { + buildHeaders, + isStaleBuild, + PAGES_BUILD_HEADER, + PAGES_PROTOCOL_VERSION, +} from './pages-protocol.ts'; export { redirectToHttps } from './https.ts'; export { applyHeaderRules, diff --git a/packages/edge/src/pages-protocol.ts b/packages/edge/src/pages-protocol.ts index c36071404..43c072bf8 100644 --- a/packages/edge/src/pages-protocol.ts +++ b/packages/edge/src/pages-protocol.ts @@ -1,2 +1,23 @@ /** Current Pages wire version; a missing header identifies legacy clients. */ export const PAGES_PROTOCOL_VERSION = '2'; + +/** + * The build a request or response belongs to. Unlike the protocol version it + * changes with every deploy, so a tab that outlives a deployment can tell that + * the chunks it still holds are gone. + */ +export const PAGES_BUILD_HEADER = 'X-VoidPages-Build'; + +/** + * Whether a build id seen on the wire belongs to another deployment. A peer + * that sends no id (an older Void, or a parse of a partial response) is not + * evidence of a new build, so it never counts as a mismatch. + */ +export function isStaleBuild(buildId: string, seen: string | null | undefined): boolean { + return buildId !== '' && seen != null && seen !== buildId; +} + +/** Request and response headers that carry a build, empty when none is known. */ +export function buildHeaders(buildId: string): Record { + return buildId === '' ? {} : { [PAGES_BUILD_HEADER]: buildId }; +} diff --git a/packages/isr/src/runtime.ts b/packages/isr/src/runtime.ts index d553320dc..9ea5ee142 100644 --- a/packages/isr/src/runtime.ts +++ b/packages/isr/src/runtime.ts @@ -1,4 +1,9 @@ -import { matchSegmentPattern, PAGES_PROTOCOL_VERSION } from '@void/edge'; +import { + isStaleBuild, + matchSegmentPattern, + PAGES_BUILD_HEADER, + PAGES_PROTOCOL_VERSION, +} from '@void/edge'; import { buildVariantOriginalUrl, decodeIsrCacheEntry, @@ -326,7 +331,12 @@ function sharedHtmlCacheHeaders(response: Response, ttl: number, state: 'HIT' | return headers; } -function jsonCacheResponse(pageData: string, ttl: number, state: 'HIT' | 'MISS'): Response { +function jsonCacheResponse( + pageData: string, + ttl: number, + state: 'HIT' | 'MISS', + build: string | null, +): Response { const response = new Response(pageData, { headers: { 'content-type': 'application/json', @@ -334,6 +344,9 @@ function jsonCacheResponse(pageData: string, ttl: number, state: 'HIT' | 'MISS') // `X-VoidPages` is present, and otherwise reloads the whole page. 'X-VoidPages': 'true', 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION, + // Kept with the payload: a hit for a client from another build must not + // pass off this render's props as its own. + ...(build ? { [PAGES_BUILD_HEADER]: build } : {}), Vary: 'X-VoidPages, X-VoidPages-Version', 'Cache-Control': `public, s-maxage=${ttl}, max-age=0, must-revalidate`, 'x-isr-cache': state, @@ -359,6 +372,7 @@ export async function populateJsonEdgeCache( return; } try { + const build = response.headers.get(PAGES_BUILD_HEADER); const fromHeader = response.headers.get('x-void-page-data'); const pageData = fromHeader ? normalizePageDataForJsonCache(fromHeader) @@ -366,7 +380,7 @@ export async function populateJsonEdgeCache( if (!pageData) { return; } - await cache.put(cacheKey, jsonCacheResponse(pageData, ttl, state)); + await cache.put(cacheKey, jsonCacheResponse(pageData, ttl, state, build)); } catch { // Fail open. } @@ -582,6 +596,12 @@ async function handleIsrInternal( return null; // fail open → caller renders live } if (jsonCached && hasCurrentSharedCachePolicy(jsonCached)) { + // A cached payload from another build would hand this client page props it + // has no components for. Let the app answer, which reloads a stale tab. + const cachedBuild = jsonCached.headers.get(PAGES_BUILD_HEADER) ?? ''; + if (isStaleBuild(cachedBuild, request.headers.get(PAGES_BUILD_HEADER))) { + return render(request); + } return clientRevalidateResponse(jsonCached); } if (jsonCached) { diff --git a/packages/react/src/plugin-pages.ts b/packages/react/src/plugin-pages.ts index 261a30419..8caad9991 100644 --- a/packages/react/src/plugin-pages.ts +++ b/packages/react/src/plugin-pages.ts @@ -43,6 +43,7 @@ export function pagesPlugin(pagesDir: string, options?: PagesPluginOptions): Plu return createPagesPlugin(pagesDir, { name: 'void-react:pages', root, + deployRecovery: options?.deployRecovery, generateRenderer(scan, isDev) { return generateRendererModule(scan, pagesDir, isDev); }, diff --git a/packages/react/src/plugin.ts b/packages/react/src/plugin.ts index cd3fb0477..ddba0f6ef 100644 --- a/packages/react/src/plugin.ts +++ b/packages/react/src/plugin.ts @@ -8,6 +8,7 @@ export type VoidReactOptions = Readonly<{ react?: Parameters[0]; viewTransitions?: boolean; prefetch?: PrefetchConfig; + deployRecovery?: boolean; }>; export function voidReact(options?: VoidReactOptions): Array { @@ -15,11 +16,8 @@ export function voidReact(options?: VoidReactOptions): Array { const pagesDir = resolvePagesDir(root); return [ ...react(options?.react), - pagesPlugin(pagesDir, { - root, - viewTransitions: options?.viewTransitions, - prefetch: options?.prefetch, - }), + // Spread so adapter options the pages plugin owns reach it without per-option glue. + pagesPlugin(pagesDir, { ...options, root }), ...islandsPlugin(pagesDir, { root }), ]; } diff --git a/packages/solid/src/plugin-pages.ts b/packages/solid/src/plugin-pages.ts index 83d7b99ca..d55379696 100644 --- a/packages/solid/src/plugin-pages.ts +++ b/packages/solid/src/plugin-pages.ts @@ -15,6 +15,7 @@ export function pagesPlugin(pagesDir: string, options?: PagesPluginOptions): Plu return createPagesPlugin(pagesDir, { name: 'void-solid:pages', root: options?.root, + deployRecovery: options?.deployRecovery, generateRenderer(scan) { return generateRendererModule(scan, pagesDir); }, diff --git a/packages/solid/src/plugin.ts b/packages/solid/src/plugin.ts index ae01b000e..5f6c83b4c 100644 --- a/packages/solid/src/plugin.ts +++ b/packages/solid/src/plugin.ts @@ -10,6 +10,7 @@ export type VoidSolidOptions = Readonly<{ solid?: Parameters[0]; viewTransitions?: boolean; prefetch?: PrefetchConfig; + deployRecovery?: boolean; }>; // The runtime entry exports raw `.tsx` source. Without these hints, Vite's SSR @@ -46,11 +47,8 @@ export function voidSolid(options?: VoidSolidOptions): Array { return [ configPlugin(), solid({ ssr: true, ...options?.solid }), - pagesPlugin(pagesDir, { - root, - viewTransitions: options?.viewTransitions, - prefetch: options?.prefetch, - }), + // Spread so adapter options the pages plugin owns reach it without per-option glue. + pagesPlugin(pagesDir, { ...options, root }), ...islandsPlugin(pagesDir, { root }), ]; } diff --git a/packages/svelte/src/plugin-pages.ts b/packages/svelte/src/plugin-pages.ts index 80c4b784e..c57e3ffd4 100644 --- a/packages/svelte/src/plugin-pages.ts +++ b/packages/svelte/src/plugin-pages.ts @@ -47,6 +47,7 @@ export function pagesPlugin(pagesDir: string, options?: PagesPluginOptions): Plu return createPagesPlugin(pagesDir, { name: 'void-svelte:pages', root: options?.root, + deployRecovery: options?.deployRecovery, generateRenderer(scan) { return generateRendererModule(scan, pagesDir); }, diff --git a/packages/svelte/src/plugin.ts b/packages/svelte/src/plugin.ts index 24e802d0f..b0b56c8d4 100644 --- a/packages/svelte/src/plugin.ts +++ b/packages/svelte/src/plugin.ts @@ -8,6 +8,7 @@ export type VoidSvelteOptions = Readonly<{ svelte?: Parameters[0]; viewTransitions?: boolean; prefetch?: PrefetchConfig; + deployRecovery?: boolean; }>; export function voidSvelte(options?: VoidSvelteOptions): Array { @@ -15,11 +16,8 @@ export function voidSvelte(options?: VoidSvelteOptions): Array { const pagesDir = resolvePagesDir(root); return [ ...(svelte(options?.svelte) as ReadonlyArray), - pagesPlugin(pagesDir, { - root, - viewTransitions: options?.viewTransitions, - prefetch: options?.prefetch, - }), + // Spread so adapter options the pages plugin owns reach it without per-option glue. + pagesPlugin(pagesDir, { ...options, root }), ...islandsPlugin(pagesDir, { root }), ]; } diff --git a/packages/void/env.d.ts b/packages/void/env.d.ts new file mode 100644 index 000000000..3ab5ed917 --- /dev/null +++ b/packages/void/env.d.ts @@ -0,0 +1,7 @@ +/** + * Constants the build folds into both the client and server bundles, such as + * the Pages build id. Vite replaces each key at build time. + */ +interface ImportMeta { + readonly env: Record; +} diff --git a/packages/void/src/pages/build-id-source.ts b/packages/void/src/pages/build-id-source.ts new file mode 100644 index 000000000..b84b545b6 --- /dev/null +++ b/packages/void/src/pages/build-id-source.ts @@ -0,0 +1,117 @@ +import { createHash } from 'node:crypto'; +import { mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs'; +import { isAbsolute, join } from 'pathslash'; + +/** Directories never part of the app source, whatever their position. */ +const alwaysSkipped = new Set(['node_modules']); + +/** Beside the generated types, which the scaffold already ignores. */ +const CACHE_FILE = '.void/pages-build-id.json'; + +const ID_PATTERN = /^[0-9a-f]{12}$/; + +type CacheEntry = { + fingerprint: string; + id: string; +}; + +/** + * A stable id for one build of an app: a hash of its source files. Every + * environment of a Vite build derives the same id from the same tree, which a + * per-process random value cannot guarantee, since Vite may resolve the config + * once per environment. + * + * The id changes with any source change, including server-only ones, which + * reloads a stale tab that did not need it. That is the safe direction: missing + * the id means importing chunks that no longer exist. + * + * Resolving the config per environment means hashing the tree twice. The cache + * turns the second pass into one stat walk, keyed by file size and modification + * time. A write always moves the modification time, so a fingerprint that still + * matches describes the same content. + */ +export function computePagesBuildId(root: string, excludeDirs: Array): string { + const excluded = new Set(excludeDirs.map((dir) => (isAbsolute(dir) ? dir : join(root, dir)))); + const files = sourceFiles(root, excluded); + const fingerprint = fingerprintOf(root, files); + const cached = readCachedId(root, fingerprint); + if (cached) { + return cached; + } + const id = contentIdOf(root, files); + writeCachedId(root, fingerprint, id); + return id; +} + +/** Relative paths of the files under `root` that describe the app, sorted. */ +function sourceFiles(root: string, excluded: Set): Array { + const files: Array = []; + const walk = (directory: string): void => { + for (const entry of readdirSync(join(root, directory), { withFileTypes: true })) { + // Dot directories hold tool state (.git, .void, .wrangler), and dot files + // hold local settings such as .env that a deploy must not depend on. + if (entry.name.startsWith('.') || alwaysSkipped.has(entry.name)) { + continue; + } + const path = directory ? `${directory}/${entry.name}` : entry.name; + if (excluded.has(join(root, path))) { + continue; + } + // Symlinked directories are not followed: they can leave the tree. + if (entry.isDirectory()) { + walk(path); + } else if (entry.isFile()) { + files.push(path); + } + } + }; + walk(''); + return files.sort(); +} + +function fingerprintOf(root: string, files: Array): string { + const hash = createHash('sha256'); + for (const file of files) { + const stats = statSync(join(root, file)); + hash.update(`${file}\0${stats.size}\0${stats.mtimeMs}\0`); + } + return hash.digest('hex'); +} + +function contentIdOf(root: string, files: Array): string { + const hash = createHash('sha256'); + for (const file of files) { + hash.update(file); + hash.update('\0'); + hash.update(readFileSync(join(root, file))); + hash.update('\0'); + } + return hash.digest('hex').slice(0, 12); +} + +/** The last id, when the tree still looks the way it did when the id was made. */ +function readCachedId(root: string, fingerprint: string): string | null { + try { + const entry = JSON.parse(readFileSync(join(root, CACHE_FILE), 'utf8')) as Partial; + if ( + entry.fingerprint === fingerprint && + typeof entry.id === 'string' && + ID_PATTERN.test(entry.id) + ) { + return entry.id; + } + } catch { + // No cache, unreadable cache, or a cache from another tool: hash the tree. + } + return null; +} + +function writeCachedId(root: string, fingerprint: string, id: string): void { + try { + const path = join(root, CACHE_FILE); + mkdirSync(join(root, '.void'), { recursive: true }); + writeFileSync(path, JSON.stringify({ fingerprint, id } satisfies CacheEntry)); + } catch { + // A read-only tree still builds; it just pays for the second pass. + } +} diff --git a/packages/void/src/pages/build-id.ts b/packages/void/src/pages/build-id.ts new file mode 100644 index 000000000..aa786acde --- /dev/null +++ b/packages/void/src/pages/build-id.ts @@ -0,0 +1,13 @@ +/** The define the pages plugin fills in once per build. */ +export const PAGES_BUILD_ID_DEFINE = 'import.meta.env.__VOID_PAGES_BUILD_ID'; + +/** + * The id of the build this code was bundled into. The pages plugin defines it + * per build; it is empty in the dev server and in tests, which turns every + * build check into a no-op. + */ +export function pagesBuildId(): string { + // Spelled out so the build replaces this expression with the id literal. + const value: unknown = import.meta.env.__VOID_PAGES_BUILD_ID; + return typeof value === 'string' ? value : ''; +} diff --git a/packages/void/src/pages/navigation-engine.ts b/packages/void/src/pages/navigation-engine.ts index 3351e2d94..2a49a4105 100644 --- a/packages/void/src/pages/navigation-engine.ts +++ b/packages/void/src/pages/navigation-engine.ts @@ -1,10 +1,11 @@ /// -import { PAGES_PROTOCOL_VERSION } from '@void/edge'; +import { buildHeaders, isStaleBuild, PAGES_BUILD_HEADER, PAGES_PROTOCOL_VERSION } from '@void/edge'; import { PRESERVED_QUERY_HEADER, searchWithoutActionKey } from './action-key.ts'; import { createActionErrorFromResponse, isAbortError } from './action-result.ts'; import { pageBoundarySlots, clientPageError, showTerminalPageError } from './boundary-client.ts'; import type { BoundaryManifest } from './boundary-plans.ts'; +import { pagesBuildId } from './build-id.ts'; import { initClientHead, applyClientHead } from './head-client.ts'; import type { HeadDescriptor } from './head.ts'; import { PrefetchCache, parseCacheFor } from './prefetch.ts'; @@ -233,6 +234,38 @@ function abortError(): DOMException { return new DOMException('Navigation aborted', 'AbortError'); } +const DEPLOY_RELOAD_KEY = '__void_pages_deploy_reload'; +/** A reload that lands on the same stale build must not reload again. */ +const DEPLOY_RELOAD_WINDOW_MS = 10_000; + +/** + * Claims the one reload this tab may spend to recover `url` from `build`. Returns + * false when that reload already happened: a cache can keep serving the document + * from the old build, and reloading it again would loop. + */ +function claimDeployReload(build: string, url: string): boolean { + try { + const now = Date.now(); + const previous = JSON.parse(sessionStorage.getItem(DEPLOY_RELOAD_KEY) ?? 'null') as { + build?: unknown; + url?: unknown; + at?: unknown; + } | null; + if ( + previous?.build === build && + previous.url === url && + typeof previous.at === 'number' && + now - previous.at < DEPLOY_RELOAD_WINDOW_MS + ) { + return false; + } + sessionStorage.setItem(DEPLOY_RELOAD_KEY, JSON.stringify({ build, url, at: now })); + } catch { + // Storage may be blocked or full. A reload is still better than a dead page. + } + return true; +} + function abortSignalPromise(signal: AbortSignal): Promise { if (signal.aborted) { return Promise.reject(abortError()); @@ -603,6 +636,7 @@ export async function createPageNavigationEngine( const headers = { 'X-VoidPages': 'true', 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION, + ...buildHeaders(pagesBuildId()), Accept: 'application/json', Purpose: 'prefetch', }; @@ -619,6 +653,11 @@ export async function createPageNavigationEngine( if (!r || result?.redirectedTo) { return null; } + // Another deployment answered: cache nothing, so the visit that follows a + // hover reloads instead of rendering props this build's chunks cannot show. + if (isStaleBuild(pagesBuildId(), r.headers.get(PAGES_BUILD_HEADER))) { + return null; + } if (!r.headers.get('X-VoidPages')) { return ( (await loadStaticPageData(url, r, undefined, !STATIC_PAGE_DATA_FAST_PATH))?.pageData ?? @@ -717,6 +756,7 @@ export async function createPageNavigationEngine( const headers: Record = { 'X-VoidPages': 'true', 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION, + ...buildHeaders(pagesBuildId()), Accept: 'application/json', }; if (options._preservedQuery && method !== 'GET') { @@ -792,7 +832,25 @@ export async function createPageNavigationEngine( ? await fetchPageResponse(url, fetchOptions) : await fetchPages(url, fetchOptions) : null; - const response = fetched?.response ?? null; + let response = fetched?.response ?? null; + + // The destination was rendered by another deployment, so this tab's chunks + // are gone. Treat the payload as absent: the document load below lands on the + // requested destination with its query and hash. A mutation has already run, + // so only a GET is allowed to get here. One reload per destination: when the + // document comes back from the old build anyway, rendering the payload lets + // the error boundaries take over instead of reloading in a loop. A response + // that names no build, from an older Void, is not evidence of a new one. + const servedBy = response?.headers.get(PAGES_BUILD_HEADER) ?? null; + if ( + method === 'GET' && + servedBy !== null && + isStaleBuild(pagesBuildId(), servedBy) && + claimDeployReload(servedBy, url) + ) { + response = null; + pageData = undefined; + } if (pageData === undefined && !response) { window.location.href = url; diff --git a/packages/void/src/pages/plugin.ts b/packages/void/src/pages/plugin.ts index 705c45318..810f03870 100644 --- a/packages/void/src/pages/plugin.ts +++ b/packages/void/src/pages/plugin.ts @@ -1,6 +1,8 @@ import { existsSync } from 'node:fs'; -import { dirname } from 'pathslash'; +import { dirname, isAbsolute, join } from 'pathslash'; import { normalizePath, type Plugin, type ResolvedConfig, type UserConfig } from 'vite'; +import { computePagesBuildId } from './build-id-source.ts'; +import { PAGES_BUILD_ID_DEFINE } from './build-id.ts'; import { assertLinkPrefetchValue, type CacheForInput, type LinkPrefetchValue } from './prefetch.ts'; import { scanPages } from './scan.ts'; import { @@ -30,6 +32,11 @@ export type PagesPluginOptions = { root?: string; viewTransitions?: boolean; prefetch?: PrefetchConfig; + /** + * Reload the destination when a tab navigates against a newer deployment. + * Defaults to `true`. Turn it off to keep error boundaries in charge. + */ + deployRecovery?: boolean; }; /** @@ -51,11 +58,31 @@ export function resolvePrefetchConfig( type CreatePagesPluginOptions = { name: string; root?: string; + deployRecovery?: boolean; generateRenderer: (scan: PageScanResult, isDev: boolean) => string; generateClient: (scan: PageScanResult, staticPageData: StaticPageDataBuildOptions) => string; config: (context: PagesPluginContext) => UserConfig | void | Promise; }; +/** + * The files that are not app source: the build output of every environment, and + * assets that never take part in a chunk hash. + */ +function buildIdExcludes(root: string, userConfig: UserConfig): Array { + const dirs = new Set(['dist']); + const add = (dir: unknown) => { + if (typeof dir === 'string') { + dirs.add(dir); + } + }; + add(userConfig.build?.outDir); + for (const environment of Object.values(userConfig.environments ?? {})) { + add(environment?.build?.outDir); + } + add(userConfig.publicDir === undefined ? 'public' : userConfig.publicDir); + return [...dirs].map((dir) => (isAbsolute(dir) ? dir : join(root, dir))); +} + /** Shared Vite lifecycle; adapters own their generated code and environment configuration. */ export function createPagesPlugin(pagesDir: string, options: CreatePagesPluginOptions): Plugin { let pageScan: PageScanResult | null = null; @@ -63,6 +90,10 @@ export function createPagesPlugin(pagesDir: string, options: CreatePagesPluginOp let viteConfig: ResolvedConfig | undefined; const root = options.root ?? dirname(pagesDir); const normalizedPagesDir = normalizePath(pagesDir); + // One id for the whole app: both bundles get it from the same define, and Vite + // may resolve this config once per environment, so it is derived from the source + // rather than minted here. + let buildId: string | undefined; let pendingRescan: Promise | null = null; async function rescanPages(): Promise { pageScan = existsSync(pagesDir) @@ -164,19 +195,42 @@ export function createPagesPlugin(pagesDir: string, options: CreatePagesPluginOp viteConfig = config; }, - config(_, env) { + config(userConfig, env) { // Set before the early return: pages/ may be created after the server starts. - isDev = env.command === 'serve'; + const dev = env.command === 'serve'; + isDev = dev; if (!existsSync(pagesDir)) { return; } - return options.config({ + const pagesConfig = options.config({ isDev, async scan() { await runRescan(); return pageScan; }, }); + const withBuildId = (resolved: UserConfig | void): UserConfig | void => { + // The dev server serves a single build, so a tab never outlives the chunks + // it imported, and an app without a client entry has no tab to recover. + // Leaving the id undefined keeps every build check a no-op there. + if (dev || resolved == null || options.deployRecovery === false) { + return resolved; + } + buildId ??= computePagesBuildId(root, buildIdExcludes(root, userConfig)); + return { + ...resolved, + define: { + ...resolved.define, + [PAGES_BUILD_ID_DEFINE]: JSON.stringify(buildId), + // An explicit app define wins: it pins the id for a fixture or forces + // one that outlives this process, such as a commit sha. + ...userConfig.define, + }, + }; + }; + return pagesConfig instanceof Promise + ? pagesConfig.then(withBuildId) + : withBuildId(pagesConfig); }, }; } diff --git a/packages/void/src/pages/protocol.ts b/packages/void/src/pages/protocol.ts index eccd6fb45..feb8d4e24 100644 --- a/packages/void/src/pages/protocol.ts +++ b/packages/void/src/pages/protocol.ts @@ -1,10 +1,11 @@ -import { PAGES_PROTOCOL_VERSION } from '@void/edge'; +import { buildHeaders, isStaleBuild, PAGES_BUILD_HEADER, PAGES_PROTOCOL_VERSION } from '@void/edge'; import type { Context } from 'hono'; import type { HTTPException } from 'hono/http-exception'; import { executeComposedHandler, getHandlerComposition } from '../runtime/handler/composition.ts'; import type { CloudBindings, CloudContext } from '../runtime/handler/index.ts'; import { isConvertedResponse } from '../runtime/handler/response.ts'; import { hasActionKey, searchWithoutActionKey } from './action-key.ts'; +import { pagesBuildId } from './build-id.ts'; import { DEFERRED, separateDeferred, type ResolvedDeferredGroup } from './defer.ts'; import { absolutizeHead, @@ -97,7 +98,17 @@ function isPagesRequest(c: CloudContext): boolean { } function needsPageReload(c: CloudContext): boolean { - return isPagesRequest(c) && c.req.header('X-VoidPages-Version') !== PAGES_PROTOCOL_VERSION; + if (!isPagesRequest(c)) { + return false; + } + // A tab that outlived its deployment holds chunks that are gone. Its next GET + // navigation reloads the destination instead of importing a stale component. + // Mutations keep their response: the action already ran, and a page load would + // throw away its result. + return ( + c.req.header('X-VoidPages-Version') !== PAGES_PROTOCOL_VERSION || + (c.req.method === 'GET' && isStaleBuild(pagesBuildId(), c.req.header(PAGES_BUILD_HEADER))) + ); } /** Old clients reload a successful non-Pages response; form errors stay readable. */ @@ -110,6 +121,8 @@ function legacyPageResponse( 'Content-Type': errors ? 'application/json' : 'text/plain; charset=utf-8', 'Cache-Control': 'no-store', Vary: 'X-VoidPages, X-VoidPages-Version', + // Tells the client why it is reloading, and from which build to reload. + ...buildHeaders(pagesBuildId()), }); headers.delete('X-VoidPages'); return new Response(errors ? JSON.stringify({ errors }) : null, { @@ -301,7 +314,11 @@ function pageJsonResponse(c: CloudContext, pageObj: PageObject): Response { headers: pageResponseHeaders(c, { 'X-VoidPages': 'true', 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION, + ...buildHeaders(pagesBuildId()), 'Content-Type': 'application/json', + // Not in Vary: the body does not depend on the build, and a per-build key + // would split every shared cache entry. Only the reload response differs, + // and it is no-store. Vary: 'X-VoidPages, X-VoidPages-Version', ...POWERED_BY, }), @@ -876,6 +893,10 @@ async function runPageGet( // Stream NDJSON: first line is PageObject, subsequent lines are deferred groups c.header('X-VoidPages', 'true'); c.header('X-VoidPages-Version', PAGES_PROTOCOL_VERSION); + const build = pagesBuildId(); + if (build !== '') { + c.header(PAGES_BUILD_HEADER, build); + } return streamDeferredResponse( serializePageData(pageObj) + '\n', deferredMap, diff --git a/packages/void/test/unit/isr-cache.test.ts b/packages/void/test/unit/isr-cache.test.ts index f5fa0e691..d5fd8796c 100644 --- a/packages/void/test/unit/isr-cache.test.ts +++ b/packages/void/test/unit/isr-cache.test.ts @@ -927,6 +927,83 @@ describe('handleIsr', () => { expect(await res!.text()).toBe('{"component":"Blog","props":{}}'); }); + it('bypasses a cached JSON variant that belongs to another build', async () => { + const { kv } = createKvMock(); + const env = makeEnv(kv); + const { render } = createRender( + () => + new Response('live', { + headers: { + 'content-type': 'text/html', + 'x-void-page-data': '{"component":"Blog","props":{}}', + 'X-VoidPages-Build': 'build-1', + }, + }), + ); + const { ctx, flush } = createCtx(); + await handleIsr(htmlRequest(), env, ctx, OPTS, render); + await flush(); + expect(edge.store.has(jsonEdgeKey(HOST, '/blog/post', DPL))).toBe(true); + + const pagesHeaders = (build: string) => ({ + 'X-VoidPages': 'true', + 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION, + 'X-VoidPages-Build': build, + }); + + // Same build: the cached payload answers and names the build it came from. + const { render: hitRender, spy: hitSpy } = createRender( + () => new Response('SHOULD-NOT-RENDER'), + ); + const hit = await handleIsr( + htmlRequest('/blog/post', pagesHeaders('build-1')), + env, + createCtx().ctx, + OPTS, + hitRender, + ); + expect(hitSpy).not.toHaveBeenCalled(); + expect(hit!.headers.get('X-VoidPages-Build')).toBe('build-1'); + + // A client that sends no build id cannot be shown a reload; the payload stays. + const { render: legacyRender, spy: legacySpy } = createRender( + () => new Response('SHOULD-NOT-RENDER'), + ); + const legacy = await handleIsr( + htmlRequest('/blog/post', { + 'X-VoidPages': 'true', + 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION, + }), + env, + createCtx().ctx, + OPTS, + legacyRender, + ); + expect(legacySpy).not.toHaveBeenCalled(); + expect(legacy!.headers.get('X-VoidPages-Build')).toBe('build-1'); + + // Another build: the app answers instead, which reloads the stale tab. + const { render: liveRender, spy: liveSpy } = createRender( + () => + new Response('{"component":"Blog","props":{"fresh":true}}', { + headers: { + 'content-type': 'application/json', + 'X-VoidPages': 'true', + 'X-VoidPages-Build': 'build-2', + }, + }), + ); + const live = await handleIsr( + htmlRequest('/blog/post', pagesHeaders('build-2')), + env, + createCtx().ctx, + OPTS, + liveRender, + ); + expect(liveSpy).toHaveBeenCalledTimes(1); + expect(live!.headers.get('X-VoidPages-Build')).toBe('build-2'); + }); + it.each([ ['getWithMetadata throws', true], ['the KV entry is from an older cache policy', false], diff --git a/packages/void/test/unit/pages-build-id.test.ts b/packages/void/test/unit/pages-build-id.test.ts new file mode 100644 index 000000000..bc2faca9d --- /dev/null +++ b/packages/void/test/unit/pages-build-id.test.ts @@ -0,0 +1,174 @@ +import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, describe, expect, it, vi } from 'vite-plus/test'; +import { buildHeaders, isStaleBuild } from '../../../edge/src/pages-protocol.ts'; +import { computePagesBuildId } from '../../src/pages/build-id-source.ts'; +import { pagesBuildId } from '../../src/pages/build-id.ts'; +import { createPagesPlugin } from '../../src/pages/plugin.ts'; +import { getHookHandler } from '../helpers/vite-hooks.ts'; + +afterEach(() => { + vi.unstubAllEnvs(); +}); + +describe('pagesBuildId', () => { + it('reads the id the build defines', () => { + vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); + expect(pagesBuildId()).toBe('build-2'); + }); + + it('is empty where no build defined one, which disables every check', () => { + expect(pagesBuildId()).toBe(''); + }); +}); + +describe('isStaleBuild', () => { + it.each([ + ['another build', 'build-2', 'build-1', true], + ['the same build', 'build-2', 'build-2', false], + ['no id on the wire', 'build-2', null, false], + ['the header missing', 'build-2', undefined, false], + ['no id in this bundle', '', 'build-1', false], + ])('%s', (_, buildId, seen, expected) => { + expect(isStaleBuild(buildId, seen)).toBe(expected); + }); +}); + +describe('buildHeaders', () => { + it('carries the build only when one is known', () => { + expect(buildHeaders('')).toEqual({}); + expect(buildHeaders('build-2')).toEqual({ 'X-VoidPages-Build': 'build-2' }); + }); +}); + +describe('computePagesBuildId', () => { + function createSourceFixture(content: string): string { + const root = mkdtempSync(join(tmpdir(), 'void-build-id-')); + mkdirSync(join(root, 'pages'), { recursive: true }); + writeFileSync(join(root, 'pages/index.tsx'), content); + return root; + } + + it('hashes the source, so identical trees keep the id', () => { + const content = 'export default function Page() {}\n'; + expect(computePagesBuildId(createSourceFixture(content), [])).toBe( + computePagesBuildId(createSourceFixture(content), []), + ); + }); + + it('recomputes when a file changes', () => { + const root = createSourceFixture('export default function Page() {}\n'); + const first = computePagesBuildId(root, []); + + writeFileSync(join(root, 'pages/index.tsx'), 'export default function Page() { return 1 }\n'); + + expect(computePagesBuildId(root, [])).not.toBe(first); + }); + + it('reuses the id while size and modification time still match', () => { + const root = createSourceFixture('export default function Page() {}\n'); + const path = join(root, 'pages/index.tsx'); + // A whole second, so the restored timestamp is byte for byte the old one. + const stamp = 1_700_000_000; + utimesSync(path, stamp, stamp); + const first = computePagesBuildId(root, []); + + // Same size, and the mtime put back: nothing a build can observe changed. + writeFileSync(path, 'export default function Home() {}\n'); + utimesSync(path, stamp, stamp); + expect(computePagesBuildId(root, [])).toBe(first); + + // The content really did change, so a fresh pass must notice. + rmSync(join(root, '.void'), { recursive: true, force: true }); + expect(computePagesBuildId(root, [])).not.toBe(first); + }); + + it('ignores build output, dot directories and installed packages', () => { + const root = createSourceFixture('export default function Page() {}\n'); + const first = computePagesBuildId(root, [join(root, 'dist')]); + + for (const dir of ['dist', 'node_modules/pkg', '.void', '.wrangler']) { + mkdirSync(join(root, dir), { recursive: true }); + writeFileSync(join(root, dir, 'generated.js'), 'changed\n'); + } + + expect(computePagesBuildId(root, [join(root, 'dist')])).toBe(first); + }); +}); + +describe('createPagesPlugin build id', () => { + type PagesConfigHook = ( + userConfig: Record, + env: { command: 'build' | 'serve' }, + ) => Promise<{ define?: Record } | undefined>; + + function createConfigHook( + root?: string, + pluginOptions: { deployRecovery?: boolean } = {}, + ): PagesConfigHook { + const appRoot = root ?? createFixture(); + const plugin = createPagesPlugin(join(appRoot, 'pages'), { + name: 'test:pages', + generateRenderer: () => '', + generateClient: () => '', + config: () => ({}), + ...pluginOptions, + }); + return getHookHandler(plugin.config) as unknown as PagesConfigHook; + } + + function createFixture(): string { + const root = mkdtempSync(join(tmpdir(), 'void-pages-build-')); + const pagesDir = join(root, 'pages'); + mkdirSync(pagesDir, { recursive: true }); + writeFileSync(join(pagesDir, 'index.tsx'), 'export default function Page() {}\n'); + return root; + } + + const DEFINE = 'import.meta.env.__VOID_PAGES_BUILD_ID'; + + it('defines one id for a build, shared by every environment', async () => { + const config = createConfigHook(); + + const client = await config({}, { command: 'build' }); + const server = await config({}, { command: 'build' }); + + const id = client!.define![DEFINE]!; + expect(JSON.parse(id)).toMatch(/^[0-9a-f]{12}$/); + // Both bundles must carry the same id, or every navigation would reload. + expect(server!.define![DEFINE]).toBe(id); + }); + + it('derives the id from the app source, so identical sources keep it', async () => { + const root = createFixture(); + const idOf = async () => + (await createConfigHook(root)({}, { command: 'build' }))!.define![DEFINE]; + + const first = await idOf(); + expect(await idOf()).toBe(first); + + writeFileSync(join(root, 'pages', 'index.tsx'), 'export default function Other() {}\n'); + expect(await idOf()).not.toBe(first); + }); + + it('defines nothing when deploy recovery is off', async () => { + const config = createConfigHook(undefined, { deployRecovery: false }); + + expect(await config({}, { command: 'build' })).toEqual({}); + }); + + it('defines nothing in the dev server, which serves one build', async () => { + const config = createConfigHook(); + + expect(await config({}, { command: 'serve' })).toEqual({}); + }); + + it('lets an explicit define pin the id', async () => { + const config = createConfigHook(); + + const pinned = await config({ define: { [DEFINE]: '"commit-abc"' } }, { command: 'build' }); + + expect(pinned!.define![DEFINE]).toBe('"commit-abc"'); + }); +}); diff --git a/packages/void/test/unit/pages-client.test.ts b/packages/void/test/unit/pages-client.test.ts index 8a91fdb15..db7aa539b 100644 --- a/packages/void/test/unit/pages-client.test.ts +++ b/packages/void/test/unit/pages-client.test.ts @@ -133,6 +133,120 @@ function createTestRouter({ adapter, ...config }: TestRouterConfig = {}) { afterEach(() => { vi.unstubAllGlobals(); + vi.unstubAllEnvs(); +}); + +describe('Pages build recovery', () => { + function staleJson(body: unknown): Response { + return Response.json(body, { + headers: { 'X-VoidPages': 'true', 'X-VoidPages-Build': 'build-1' }, + }); + } + + const stalePage = { + component: 'home', + props: { title: 'post' }, + url: '/next?tab=1', + errors: null, + }; + + it('reloads the destination when another build answered the navigation', async () => { + stubClientGlobals(); + vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); + const fetch = vi.fn(async () => staleJson(stalePage)); + vi.stubGlobal('fetch', fetch); + const applyUpdate = vi.fn(); + const { router } = await createTestRouter({ adapter: { applyUpdate } }); + + await router.visit('/next?tab=1#details'); + + // This tab names its own build, so the server can answer for it. + expect(fetch).toHaveBeenCalledWith( + '/next?tab=1', + expect.objectContaining({ + headers: expect.objectContaining({ 'X-VoidPages-Build': 'build-2' }), + }), + ); + // A document load keeps the query and the fragment, and never renders stale props. + expect(window.location.href).toBe('/next?tab=1#details'); + expect(applyUpdate).not.toHaveBeenCalled(); + }); + + it('drops a prefetch from another build and reloads on the visit instead', async () => { + stubClientGlobals(); + vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); + vi.stubGlobal( + 'fetch', + vi.fn(async () => staleJson(stalePage)), + ); + const { router } = await createTestRouter(); + + await router.prefetch('/next'); + expect(window.location.href).toBeUndefined(); + + await router.visit('/next'); + expect(window.location.href).toBe('/next'); + }); + + it('treats a response from a server with no build id as unchanged', async () => { + stubClientGlobals(); + vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); + // An older Void names no build. It is not evidence of a new one. + vi.stubGlobal( + 'fetch', + vi.fn(async () => Response.json(stalePage, { headers: { 'X-VoidPages': 'true' } })), + ); + const applyUpdate = vi.fn(); + const { router } = await createTestRouter({ adapter: { applyUpdate } }); + + await router.visit('/next'); + + expect(window.location.href).toBeUndefined(); + expect(applyUpdate).toHaveBeenCalled(); + }); + + it('reloads a destination once, then lets the page render and fail on its own', async () => { + stubClientGlobals(); + vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); + const stored = new Map(); + vi.stubGlobal('sessionStorage', { + getItem: (key: string) => stored.get(key) ?? null, + setItem: (key: string, value: string) => void stored.set(key, value), + removeItem: (key: string) => void stored.delete(key), + }); + vi.stubGlobal( + 'fetch', + vi.fn(async () => staleJson(stalePage)), + ); + const applyUpdate = vi.fn(); + const { router } = await createTestRouter({ adapter: { applyUpdate } }); + + await router.visit('/next'); + expect(window.location.href).toBe('/next'); + + // The document came back from the old build anyway: rendering must not loop. + (window.location as unknown as { href?: string }).href = undefined; + await router.visit('/next'); + expect(window.location.href).toBeUndefined(); + expect(applyUpdate).toHaveBeenCalled(); + }); + + it('applies a mutation answered by another build and never reloads', async () => { + stubClientGlobals(); + vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); + vi.stubGlobal( + 'fetch', + vi.fn(async () => staleJson(stalePage)), + ); + const applyUpdate = vi.fn(); + const { router } = await createTestRouter({ adapter: { applyUpdate } }); + + await router.visit('/next', { method: 'POST' }); + + // The action already ran: a page load would replay nothing and lose its result. + expect(window.location.href).toBeUndefined(); + expect(applyUpdate).toHaveBeenCalled(); + }); }); describe('Pages serialization compatibility', () => { diff --git a/packages/void/test/unit/pages-plugin-adapters.test.ts b/packages/void/test/unit/pages-plugin-adapters.test.ts index 825a74e94..ea09f0db6 100644 --- a/packages/void/test/unit/pages-plugin-adapters.test.ts +++ b/packages/void/test/unit/pages-plugin-adapters.test.ts @@ -39,13 +39,14 @@ describe.each(adapters)('$name Pages plugin contract', (adapter) => { root = undefined; }); - function setup() { + function setup(options: Record = {}) { root = mkdtempSync(join(tmpdir(), `void-${adapter.name}-pages-plugin-`)); const pagesDir = join(root, '_source', '_views'); const plugins = adapter.create(pagesDir, { root, viewTransitions: true, prefetch: { defaultStrategy: ['hover', 'click'], hoverDelay: 123, cacheFor: '45s' }, + ...options, }); const plugin = (Array.isArray(plugins) ? plugins : [plugins]).find( (candidate: Plugin) => candidate.name === `void-${adapter.name}:pages`, @@ -87,7 +88,14 @@ describe.each(adapters)('$name Pages plugin contract', (adapter) => { rollupOptions: { input: { 'pages-client': 'virtual:void-pages-client' } }, }, }; - expect(config).toEqual( + const { define, ...rest } = config as Record & { + define?: Record; + }; + // Every Pages client carries the build it was compiled into. + expect(define).toEqual({ + 'import.meta.env.__VOID_PAGES_BUILD_ID': expect.stringMatching(/^"[0-9a-f]{12}"$/), + }); + expect(rest).toEqual( adapter.name === 'vue' ? { environments: { client: clientConfig } } : adapter.name === 'react' @@ -99,6 +107,17 @@ describe.each(adapters)('$name Pages plugin contract', (adapter) => { } }); + it('omits the build id when deploy recovery is off', async () => { + const { plugin, write } = setup({ deployRecovery: false }); + write(`about.${adapter.extension}`); + + const config = (await handler(plugin.config)({}, { command: 'build' })) as + | { define?: Record } + | undefined; + + expect(config?.define).toBeUndefined(); + }); + it('resolves only the Pages virtual module IDs', async () => { const { plugin } = setup(); const hook = plugin.resolveId as { filter: { id: RegExp } }; diff --git a/packages/void/test/unit/pages-protocol.test.ts b/packages/void/test/unit/pages-protocol.test.ts index 38eac035b..65f9f0d15 100644 --- a/packages/void/test/unit/pages-protocol.test.ts +++ b/packages/void/test/unit/pages-protocol.test.ts @@ -1,6 +1,6 @@ import { Hono } from 'hono'; import { HTTPException } from 'hono/http-exception'; -import { describe, expect, it, vi } from 'vite-plus/test'; +import { describe, expect, it, vi, afterEach } from 'vite-plus/test'; import { PAGES_PROTOCOL_VERSION } from '../../../edge/src/pages-protocol.ts'; import { defer } from '../../src/pages/defer.ts'; import { @@ -1607,6 +1607,80 @@ describe('handlePageGet with deferred props', () => { }); }); +describe('Pages build recovery', () => { + afterEach(() => { + vi.unstubAllEnvs(); + }); + + function pagesContext(method: 'GET' | 'POST', build: string | null) { + return createTestContext(method, '/blog/post', { + headers: { + 'x-voidpages': 'true', + 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION, + ...(build === null ? {} : { 'X-VoidPages-Build': build }), + }, + }); + } + + it('answers a tab from another build with a reload instead of page props', async () => { + vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); + const handler = vi.fn(() => ({ title: 'post' })); + const render = vi.fn(async () => 'rendered'); + + const response = await handlePageGet( + handler, + undefined, + await pagesContext('GET', 'build-1'), + 'blog/post', + render, + mockGetAssetTags, + ); + + // Nothing from this build may reach a client that cannot import it. + expect(handler).not.toHaveBeenCalled(); + expect(render).not.toHaveBeenCalled(); + expect(response.headers.get('X-VoidPages')).toBeNull(); + expect(response.headers.get('Cache-Control')).toBe('no-store'); + // The client reloads because this build differs from its own. + expect(response.headers.get('X-VoidPages-Build')).toBe('build-2'); + }); + + it('serves the payload to the build that rendered it', async () => { + vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); + + const response = await handlePageGet( + () => ({ title: 'post' }), + undefined, + await pagesContext('GET', 'build-2'), + 'blog/post', + mockRenderFn, + mockGetAssetTags, + ); + + expect(response.headers.get('X-VoidPages')).toBe('true'); + expect(response.headers.get('X-VoidPages-Build')).toBe('build-2'); + }); + + it('keeps its response for a stale mutation, so the action never replays', async () => { + vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); + const action = vi.fn(); + + const response = await handlePageMutation( + action, + () => ({ title: 'post' }), + undefined, + await pagesContext('POST', 'build-1'), + 'blog/post', + mockRenderFn, + mockGetAssetTags, + ); + + expect(action).toHaveBeenCalledOnce(); + expect(response.headers.get('X-VoidPages')).toBe('true'); + expect(response.headers.get('X-VoidPages-Build')).toBe('build-2'); + }); +}); + describe('flattenValidationErrors', () => { it('flattens nested issues format into flat map', () => { const body = { diff --git a/packages/vue/src/plugin-pages.ts b/packages/vue/src/plugin-pages.ts index 916064d25..e01cb6c97 100644 --- a/packages/vue/src/plugin-pages.ts +++ b/packages/vue/src/plugin-pages.ts @@ -235,6 +235,7 @@ export function pagesPlugin( createPagesPlugin(pagesDir, { name: 'void-vue:pages', root: options?.root, + deployRecovery: options?.deployRecovery, generateRenderer(scan) { return generateRendererModule(scan, pagesDir); }, diff --git a/packages/vue/src/plugin.ts b/packages/vue/src/plugin.ts index 98920e1be..3cfb710ab 100644 --- a/packages/vue/src/plugin.ts +++ b/packages/vue/src/plugin.ts @@ -8,6 +8,7 @@ export type VoidVueOptions = Readonly<{ vue?: Parameters[0]; viewTransitions?: boolean; prefetch?: PrefetchConfig; + deployRecovery?: boolean; }>; export function voidVue(options?: VoidVueOptions): Array { @@ -17,7 +18,8 @@ export function voidVue(options?: VoidVueOptions): Array { vue(options?.vue) as Plugin, ...pagesPlugin( pagesDir, - { root, viewTransitions: options?.viewTransitions, prefetch: options?.prefetch }, + // Spread so adapter options the pages plugin owns reach it without per-option glue. + { ...options, root }, options?.vue?.script?.babelParserPlugins, ), ...islandsPlugin(pagesDir, { root }),