diff --git a/docs/guide/pages-routing/overview.md b/docs/guide/pages-routing/overview.md index 5667d48c1..132a26086 100644 --- a/docs/guide/pages-routing/overview.md +++ b/docs/guide/pages-routing/overview.md @@ -128,6 +128,24 @@ 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 keeps its response, so the action never runs twice. If the action redirects, the destination loads as a document. +- A failed request is not treated as a deploy. + +If that document load still returns the old build, for example from a CDN that caches HTML across deploys, the tab shows an error page instead of reloading again. Keep HTML out of shared caches, or purge it on deploy. + +Prerendered pages of an [`output: "static"`](../ssg.md) app are served as files and are not covered: a stale tab still reaches its error boundary there. + +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..34a27048f 100644 --- a/packages/edge/src/index.ts +++ b/packages/edge/src/index.ts @@ -1,5 +1,12 @@ export type { ProjectZeroTrustRouting } from './access.ts'; -export { PAGES_PROTOCOL_VERSION } from './pages-protocol.ts'; +export { + buildHeaders, + isStaleBuild, + isStaleBuildReload, + pagesPayloadFitsBuild, + 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..a4ea6d02b 100644 --- a/packages/edge/src/pages-protocol.ts +++ b/packages/edge/src/pages-protocol.ts @@ -1,2 +1,57 @@ /** 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 !== '' && typeof seen === 'string' && 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 }; +} + +/** + * Whether a cached Pages payload may answer a request. A client that names no + * build cannot tell builds apart, so it keeps the cached payload. A client that + * names one accepts only a payload from that same build, and an entry without an + * id predates ids, so it is not trusted either. + */ +export function pagesPayloadFitsBuild( + cachedBuild: string | null, + requestBuild: string | null, +): boolean { + return requestBuild === null || cachedBuild === requestBuild; +} + +/** + * Whether `response` is the app's reload answer to a Pages client from another + * build: an empty plain-text answer without page data, naming a build other than + * the one the client sent. A rendered page, such as an island route's HTML, is + * not one even when it names another build. The reload answer says nothing about + * cached copies of the page, which other tabs still use. + */ +export function isStaleBuildReload(request: Request, response: Response): boolean { + const sent = request.headers.get(PAGES_BUILD_HEADER); + const answered = response.headers.get(PAGES_BUILD_HEADER); + const type = (response.headers.get('Content-Type') ?? '').split(';', 1)[0]?.trim(); + return ( + request.headers.has('X-VoidPages') && + !response.headers.has('X-VoidPages') && + type === 'text/plain' && + sent !== null && + answered !== null && + sent !== answered + ); +} diff --git a/packages/isr/src/runtime.ts b/packages/isr/src/runtime.ts index 79593863d..c5c306117 100644 --- a/packages/isr/src/runtime.ts +++ b/packages/isr/src/runtime.ts @@ -1,4 +1,10 @@ -import { matchSegmentPattern, PAGES_PROTOCOL_VERSION } from '@void/edge'; +import { + isStaleBuildReload, + matchSegmentPattern, + pagesPayloadFitsBuild, + PAGES_BUILD_HEADER, + PAGES_PROTOCOL_VERSION, +} from '@void/edge'; import { buildVariantOriginalUrl, decodeIsrCacheEntry, @@ -324,7 +330,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', @@ -332,6 +343,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, @@ -357,6 +371,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) @@ -364,7 +379,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. } @@ -580,12 +595,26 @@ async function handleIsrInternal( return null; // fail open → caller renders live } if (jsonCached && hasCurrentSharedCachePolicy(jsonCached)) { - return clientRevalidateResponse(jsonCached); - } - if (jsonCached) { + // A cached payload from another build would hand this client page props it + // has no components for. Let the app answer below, which reloads a stale + // tab, and keep the entry: it is still right for clients of its own build. + if ( + pagesPayloadFitsBuild( + jsonCached.headers.get(PAGES_BUILD_HEADER), + request.headers.get(PAGES_BUILD_HEADER), + ) + ) { + return clientRevalidateResponse(jsonCached); + } + } else if (jsonCached) { await safeCacheDelete(cache, jsonKey); } const response = await render(request); + // The app answered a stale client with its reload response. That says nothing + // about this path's cached HTML, which other tabs can still use. + if (isStaleBuildReload(request, response)) { + return response; + } const ttl = resolveRevalidateTtl(response, isrTtl); if (isUncacheableRender(response, ttl, false)) { ctx.waitUntil( diff --git a/packages/react/src/plugin-pages.ts b/packages/react/src/plugin-pages.ts index 46ce1ebac..3e359a41b 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 1076362a0..d72ecc085 100644 --- a/packages/react/src/plugin.ts +++ b/packages/react/src/plugin.ts @@ -9,6 +9,7 @@ export type VoidReactOptions = Readonly<{ react?: Parameters[0]; viewTransitions?: boolean; prefetch?: PrefetchConfig; + deployRecovery?: boolean; }>; export function voidReact(options?: VoidReactOptions): Array { @@ -16,11 +17,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 bd00b7855..af66623ed 100644 --- a/packages/solid/src/plugin.ts +++ b/packages/solid/src/plugin.ts @@ -11,6 +11,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 @@ -47,11 +48,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 3d46326b6..d72d1a4e0 100644 --- a/packages/svelte/src/plugin.ts +++ b/packages/svelte/src/plugin.ts @@ -9,6 +9,7 @@ export type VoidSvelteOptions = Readonly<{ svelte?: Parameters[0]; viewTransitions?: boolean; prefetch?: PrefetchConfig; + deployRecovery?: boolean; }>; export function voidSvelte(options?: VoidSvelteOptions): Array { @@ -16,11 +17,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/installed-packages.ts b/packages/void/src/installed-packages.ts index d2b7e03dc..51ff801a2 100644 --- a/packages/void/src/installed-packages.ts +++ b/packages/void/src/installed-packages.ts @@ -26,7 +26,7 @@ function readManifest(dir: string): PackageManifest | undefined { type PnpApi = { resolveToUnqualified(request: string, issuer: string): string | null }; /** The directory Node loads `name` from for code in `fromDir`. Ignores `exports`. */ -function findInstalledPackage(name: string, fromDir: string): string | undefined { +export function findInstalledPackage(name: string, fromDir: string): string | undefined { // A Yarn Plug'n'Play install has no node_modules. Under `yarn`, its runtime adds // `findPnpApi` to `node:module` and serves the packages' files from its archives. const pnp = (module as { findPnpApi?: (path: string) => PnpApi | null }).findPnpApi?.(fromDir); diff --git a/packages/void/src/pages/boundary-client.ts b/packages/void/src/pages/boundary-client.ts index 11cce7d96..b93efcedd 100644 --- a/packages/void/src/pages/boundary-client.ts +++ b/packages/void/src/pages/boundary-client.ts @@ -1,6 +1,7 @@ import { isVoidActionError } from './action-result.ts'; import type { BoundaryManifest } from './boundary-plans.ts'; import type { PageError } from './types.ts'; +import { isSameOrigin } from './url.ts'; export type ClientPageBoundary = { id: string; @@ -49,7 +50,7 @@ export function clientPageError(error: unknown, dev = false): PageError { /** Terminal recovery cannot depend on the failed adapter, imports, or component tree. */ export function showTerminalPageError(url: string = window.location.href): void { const target = new URL(url, window.location.href); - if (target.origin !== window.location.origin) { + if (!isSameOrigin(target, window.location.origin)) { throw new Error('Invalid error page destination'); } try { 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..503f672c0 --- /dev/null +++ b/packages/void/src/pages/build-id-source.ts @@ -0,0 +1,315 @@ +import { createHash } from 'node:crypto'; +import { + existsSync, + mkdirSync, + readFileSync, + readdirSync, + realpathSync, + statSync, + writeFileSync, +} from 'node:fs'; +import { isAbsolute, join, relative } from 'pathslash'; +import { searchForWorkspaceRoot } from 'vite'; +import { findInstalledPackage } from '../installed-packages.ts'; + +/** 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'; + +/** Workspace files that pin what the installed packages contain. */ +const WORKSPACE_FILES = [ + 'package.json', + 'pnpm-workspace.yaml', + 'pnpm-lock.yaml', + 'package-lock.json', + 'npm-shrinkwrap.json', + 'yarn.lock', + 'bun.lock', + 'bun.lockb', +]; + +const DEPENDENCY_FIELDS = [ + 'dependencies', + 'devDependencies', + 'optionalDependencies', + 'peerDependencies', +] as const; + +const HEX_DIGITS = '0123456789abcdef'; + +/** Twelve lowercase hex digits, the shape `contentIdOf` makes. */ +function isBuildId(value: unknown): value is string { + if (typeof value !== 'string' || value.length !== 12) { + return false; + } + for (let index = 0; index < value.length; index++) { + if (!HEX_DIGITS.includes(value.charAt(index))) { + return false; + } + } + return true; +} + +type CacheEntry = { + fingerprint: string; + id: string; +}; + +export type PagesBuildInputs = { + /** Env values the client inlines. They belong to the build, like a source file. */ + env?: string; + /** The app's `define` entries, which the client inlines too. */ + define?: string; +}; + +/** + * The id each app root got in the current build. Vite resolves the config again + * for every environment, with new plugin instances, and the values it sees can + * differ between those passes: a define such as `Date.now()`, or a file another + * task writes meanwhile. The first pass decides, so both bundles get one id. + */ +const currentBuildIds = new Map(); + +/** + * A stable id for one build of an app: a hash of what its bundles are made of. + * Every environment of a Vite build derives the same id from the same tree, + * which a per-process random value cannot guarantee. + * + * The hash covers the app folder, the workspace packages it depends on (found + * through its installed links, transitively), and the workspace manifest and + * lockfile, since a dependency upgrade renames chunks without touching the app. + * Modules imported by a relative path from outside all of these are not seen. + * + * The id changes with any change there, including server-only ones, which + * reloads a stale tab that did not need it. That is the safe direction: missing + * a change means importing chunks that no longer exist. + * + * Hashing contents is cached across processes, 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, + inputs: PagesBuildInputs = {}, +): string { + const current = currentBuildIds.get(root); + if (current !== undefined) { + return current; + } + const workspace = searchForWorkspaceRoot(root); + const excluded = new Set(excludeDirs.map((dir) => (isAbsolute(dir) ? dir : join(root, dir)))); + const files = buildSourceFiles(root, workspace, excluded); + const buildInputs = `${inputs.env ?? ''}\0${inputs.define ?? ''}`; + const fingerprint = fingerprintOf(workspace, files, buildInputs); + let id = readCachedId(root, fingerprint); + if (id === null) { + id = contentIdOf(workspace, files, buildInputs); + writeCachedId(root, fingerprint, id); + } + currentBuildIds.set(root, id); + return id; +} + +/** Ends the current build of `root`, or of every app, so the next build hashes again. */ +export function endPagesBuild(root?: string): void { + if (root === undefined) { + currentBuildIds.clear(); + } else { + currentBuildIds.delete(root); + } +} + +/** Paths, relative to the workspace, of every file the id covers, sorted. */ +function buildSourceFiles(root: string, workspace: string, excluded: Set): Array { + const files = new Set(); + const add = (directory: string) => { + for (const file of sourceFiles(directory, excluded)) { + files.add(relative(workspace, file)); + } + }; + add(root); + for (const directory of workspaceDependencies(root, workspace)) { + add(directory); + } + if (workspace !== root) { + for (const name of WORKSPACE_FILES) { + if (existsSync(join(workspace, name))) { + files.add(name); + } + } + } + return [...files].sort(); +} + +/** Real path, or null when it cannot be resolved. */ +function realPath(path: string): string | null { + try { + return realpathSync(path); + } catch { + return null; + } +} + +function dependencyNames(directory: string): Array { + try { + const manifest = JSON.parse(readFileSync(join(directory, 'package.json'), 'utf8')) as Record< + string, + unknown + >; + const names: Array = []; + for (const field of DEPENDENCY_FIELDS) { + const deps = manifest[field]; + if (deps !== null && typeof deps === 'object') { + names.push(...Object.keys(deps)); + } + } + return names; + } catch { + return []; + } +} + +/** + * Folders of the workspace packages `root` depends on, directly or through other + * workspace packages. Package managers link them into node_modules, or Yarn + * Plug'n'Play maps them, and they lie in the workspace outside any node_modules. + */ +function workspaceDependencies(root: string, workspace: string): Array { + const realWorkspace = realPath(workspace); + const realRoot = realPath(root); + if (realWorkspace === null || realRoot === null) { + return []; + } + const seen = new Set([realRoot]); + const found: Array = []; + const queue = [realRoot]; + for (let directory = queue.shift(); directory !== undefined; directory = queue.shift()) { + for (const name of dependencyNames(directory)) { + // Follows node_modules links, or asks Yarn Plug'n'Play where there are none. + const installed = findInstalledPackage(name, directory); + const target = installed === undefined ? null : (realPath(installed) ?? installed); + if (target === null || seen.has(target)) { + continue; + } + const inWorkspace = relative(realWorkspace, target); + if ( + inWorkspace.startsWith('..') || + isAbsolute(inWorkspace) || + inWorkspace.split('/').includes('node_modules') + ) { + continue; + } + seen.add(target); + found.push(join(workspace, inWorkspace)); + queue.push(target); + } + } + return found; +} + +/** + * Dot directories hold tool state (.git, .void, .wrangler), and .env files hold + * local settings, whose client values reach the id through `inputs.env`. Other + * dot files can configure the build (.postcssrc, .browserslistrc), so they count. + */ +function isSkipped(name: string, isDirectory: boolean): boolean { + if (alwaysSkipped.has(name)) { + return true; + } + if (!name.startsWith('.')) { + return false; + } + return isDirectory || name.startsWith('.env') || name === '.DS_Store'; +} + +/** Absolute paths of the files under `directory` that describe it. */ +function sourceFiles(directory: string, excluded: Set): Array { + const files: Array = []; + const walk = (current: string): void => { + let entries; + try { + entries = readdirSync(current, { withFileTypes: true }); + } catch { + // A folder the build cannot read (a database volume, a root-owned cache) + // cannot feed the bundle either. + return; + } + for (const entry of entries) { + if (isSkipped(entry.name, entry.isDirectory())) { + continue; + } + const path = join(current, entry.name); + if (excluded.has(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(directory); + return files; +} + +function fingerprintOf(workspace: string, files: Array, inputs: string): string { + const hash = createHash('sha256'); + hash.update(inputs); + hash.update('\0'); + for (const file of files) { + try { + const stats = statSync(join(workspace, file)); + hash.update(`${file}\0${stats.size}\0${stats.mtimeMs}\0`); + } catch { + // Removed since the walk. + hash.update(`${file}\0-\0`); + } + } + return hash.digest('hex'); +} + +function contentIdOf(workspace: string, files: Array, inputs: string): string { + const hash = createHash('sha256'); + hash.update(inputs); + hash.update('\0'); + for (const file of files) { + hash.update(file); + hash.update('\0'); + try { + hash.update(readFileSync(join(workspace, file))); + } catch { + // Removed or unreadable since the walk: the bundle cannot read it either. + hash.update('-'); + } + 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 && isBuildId(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 b54ba6842..53bc93eea 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 { PrefetchCache, parseCacheFor } from './prefetch.ts'; import type { CacheForInput, CacheForResult, LinkPrefetchValue } from './prefetch.ts'; @@ -237,6 +238,58 @@ 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; +} + +/** + * Loads `url` as a new document. Setting `location.href` to the current URL with + * a fragment only scrolls, and that is the URL a refresh or a back/forward visit + * asks for, so that case reloads the page instead. + */ +function loadDocument(url: string): void { + const { origin, pathname, search, hash } = window.location; + const target = new URL(url, `${origin}${pathname}${search}`); + const sameDocument = + isSameOrigin(target, origin) && target.pathname === pathname && target.search === search; + if (!sameDocument || target.hash === '') { + window.location.href = url; + return; + } + if (target.hash !== hash) { + history.replaceState(history.state, '', url); + } + window.location.reload(); +} + function abortSignalPromise(signal: AbortSignal): Promise { if (signal.aborted) { return Promise.reject(abortError()); @@ -303,6 +356,9 @@ export async function createPageNavigationEngine( const hasBoundaries = Object.keys(config.boundaryManifest?.plans ?? {}).length > 0; const _prefetchCache = new PrefetchCache(); const uncachedPayloads = new WeakSet(); + // Prefetched URLs that another deployment answered, with that build. The visit + // that consumes one spends the same single reload as an ordinary navigation. + const stalePrefetches = new Map(); let _nextNavigationId = 0; // The newest visit whose URL is in the address bar: the last commit, or a back/forward // visit, which the browser has already moved to. An older visit must not commit over it. @@ -630,6 +686,7 @@ export async function createPageNavigationEngine( const headers = { 'X-VoidPages': 'true', 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION, + ...buildHeaders(pagesBuildId()), Accept: 'application/json', Purpose: 'prefetch', }; @@ -646,6 +703,13 @@ 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. + const servedBy = r.headers.get(PAGES_BUILD_HEADER); + if (servedBy !== null && isStaleBuild(pagesBuildId(), servedBy)) { + stalePrefetches.set(url, servedBy); + return null; + } if (!r.headers.get('X-VoidPages')) { return ( (await loadStaticPageData(url, r, undefined, !STATIC_PAGE_DATA_FAST_PATH))?.pageData ?? @@ -730,6 +794,7 @@ export async function createPageNavigationEngine( Partial> = { 'X-VoidPages': 'true', 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION, + ...buildHeaders(pagesBuildId()), Accept: 'application/json', }; if (options._preservedQuery && method !== 'GET') { @@ -758,7 +823,17 @@ export async function createPageNavigationEngine( const cachedPageData = await cacheEntry.response; _prefetchCache.consume(fetchUrl, method); if (cachedPageData === null) { - window.location.href = url; + if (signal.aborted) { + throw abortError(); + } + const staleBuild = stalePrefetches.get(fetchUrl); + stalePrefetches.delete(fetchUrl); + if (staleBuild !== undefined && !claimDeployReload(staleBuild, url)) { + // The last reload landed on the same old document; see the visit path below. + showTerminalPageError(url); + return undefined; + } + loadDocument(url); return undefined; } // Deferred initialization and adapters mutate props; retain the cached wire payload. @@ -805,10 +880,12 @@ export async function createPageNavigationEngine( ? await fetchPageResponse(url, fetchOptions) : await fetchPages(url, fetchOptions) : null; - const response = fetched?.response ?? null; + let response = fetched?.response ?? null; + // A 307 or 308 answers a mutation with a mutation, whatever URL it lands on. + const answeredMethod = fetched?.method ?? method; if (pageData === undefined && !response) { - window.location.href = url; + loadDocument(url); return undefined; } @@ -828,6 +905,36 @@ export async function createPageNavigationEngine( commitTarget.method = method; } + // 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 answer is allowed here, which includes the page a mutation was + // redirected to with a 303. 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 (answeredMethod === 'GET' && servedBy !== null && isStaleBuild(pagesBuildId(), servedBy)) { + // A newer visit owns the page now. Leaving it is not this visit's call, and + // neither is the reload this tab may spend. + if (signal.aborted) { + throw abortError(); + } + if (claimDeployReload(servedBy, url)) { + response = null; + pageData = undefined; + } else { + // The last reload landed on the same old document, so this payload would + // replace the page with components that cannot load here, and reloading + // again would loop. Stop, and leave the tab a way out. + showTerminalPageError(url); + return undefined; + } + } + + if (pageData === undefined && !response) { + loadDocument(url); + return undefined; + } + if (response && method !== 'GET' && !response.ok) { throw await createActionErrorFromResponse(response, fetchUrl); } @@ -844,7 +951,7 @@ export async function createPageNavigationEngine( pageData = staticPageData.pageData; deferredRegistry.setup(pageData, staticPageData.resolvedDeferred); } else { - window.location.href = url; + loadDocument(url); return undefined; } } else { @@ -858,7 +965,7 @@ export async function createPageNavigationEngine( if (pageData !== undefined) { // Static page-data fallback already loaded the page object. } else if (!response) { - window.location.href = url; + loadDocument(url); return undefined; } else if (contentType.includes('application/x-ndjson')) { if (!response.body) { @@ -955,7 +1062,7 @@ export async function createPageNavigationEngine( // Reuse the preload only if the response selects the matched page; redirects // or rewrites may select another. Cancellation stops waiting for the imports. if (!components[pageData.component]) { - window.location.href = url; + loadDocument(url); return undefined; } let component: Component; diff --git a/packages/void/src/pages/plugin.ts b/packages/void/src/pages/plugin.ts index ee9bfd497..9bc59bb46 100644 --- a/packages/void/src/pages/plugin.ts +++ b/packages/void/src/pages/plugin.ts @@ -1,7 +1,10 @@ import { existsSync } from 'node:fs'; -import { dirname } from 'pathslash'; -import { normalizePath } from 'vite'; +import { dirname, isAbsolute, join } from 'pathslash'; +import { loadEnv, normalizePath } from 'vite'; import type { Plugin, ResolvedConfig, UserConfig } from 'vite'; +import { computePagesBuildId, endPagesBuild } from './build-id-source.ts'; +import type { PagesBuildInputs } from './build-id-source.ts'; +import { PAGES_BUILD_ID_DEFINE } from './build-id.ts'; import { assertLinkPrefetchValue } from './prefetch.ts'; import type { CacheForInput, LinkPrefetchValue } from './prefetch.ts'; import { scanPages } from './scan.ts'; @@ -30,6 +33,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 +59,70 @@ 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))); +} + +/** Entries sorted by key, so the order they were written in does not change the id. */ +function sortedEntries(record: Record): Array<[string, unknown]> { + return Object.entries(record).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)); +} + +/** + * Values the client bundle inlines without appearing in a source file: the + * env vars Vite exposes, and the app's `define` entries. Two builds that differ + * only here still emit different chunks, so the id has to cover them. + */ +function clientBuildInputs(root: string, userConfig: UserConfig, mode: string): PagesBuildInputs { + const { envDir } = userConfig; + // `false` skips the .env files, but shell values still reach the client. + const env = loadEnv( + mode, + typeof envDir === 'string' + ? isAbsolute(envDir) + ? envDir + : join(root, envDir) + : (envDir ?? root), + // Fixed-prefix VITE_ keys an env.ts declares reach the client whatever the prefix. + [...new Set(['VITE_', ...[userConfig.envPrefix ?? []].flat()])], + ); + return { + // Vite also inlines MODE, BASE_URL, and DEV/PROD from NODE_ENV. + env: JSON.stringify([ + sortedEntries(env), + mode, + userConfig.base ?? null, + process.env.NODE_ENV ?? null, + ]), + // The client environment can add or override defines of its own. + define: JSON.stringify([ + sortedEntries(userConfig.define ?? {}), + sortedEntries(userConfig.environments?.client?.define ?? {}), + ]), + }; +} + /** Shared Vite lifecycle; adapters own their generated code and environment configuration. */ export function createPagesPlugin(pagesDir: string, options: CreatePagesPluginOptions): Plugin { let pageScan: PageScanResult | null = null; @@ -164,19 +231,64 @@ export function createPagesPlugin(pagesDir: string, options: CreatePagesPluginOp viteConfig = config; }, - config(_, env) { + // Every environment has resolved its config, and so read the id, by now. The + // next build in this process hashes again. + buildApp: { + order: 'post', + async handler() { + endPagesBuild(root); + }, + }, + + 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 || + resolved === undefined || + options.deployRecovery === false + ) { + return resolved; + } + // An explicit app define pins the id, for a fixture or for one that + // outlives this process such as a commit sha. Vite applies it as written. + if (userConfig.define?.[PAGES_BUILD_ID_DEFINE] !== undefined) { + return resolved; + } + // One id per build for every environment: computePagesBuildId keeps the + // first one until buildApp ends, whichever plugin instance asks. + const buildId = computePagesBuildId( + root, + buildIdExcludes(root, userConfig), + clientBuildInputs(root, userConfig, env.mode), + ); + return { + ...resolved, + define: { + ...resolved.define, + [PAGES_BUILD_ID_DEFINE]: JSON.stringify(buildId), + }, + }; + }; + 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 c9542f900..745f58d7c 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 } from './defer.ts'; import type { ResolvedDeferredGroup } from './defer.ts'; import { @@ -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, }), @@ -670,6 +687,9 @@ function renderedResponse( headers: adjustDevCssCsp( pageResponseHeaders(c, { 'content-type': contentType, + // ISR copies the page data out of this document into its JSON cache, and + // keeps the build with it. + ...buildHeaders(pagesBuildId()), ...POWERED_BY, }), assetTags?.devCssNonce, @@ -880,6 +900,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/src/pages/redirect.ts b/packages/void/src/pages/redirect.ts index 2886fddcf..af1ab55ed 100644 --- a/packages/void/src/pages/redirect.ts +++ b/packages/void/src/pages/redirect.ts @@ -22,7 +22,16 @@ export function pagesRedirectResponse(request: Request, response: Response): Res return new Response(response.body, { status: 200, headers }); } -export type PagesFetchResult = { response: Response; redirectedTo?: string }; +export type PagesFetchResult = { + response: Response; + redirectedTo?: string; + /** + * The method of the request that got `response`: a 303 turns a POST into a GET, + * a 307 or 308 keeps it. A redirect the browser followed itself is not seen, so + * it keeps the method that was sent. + */ + method: string; +}; export type PagesFetchOptions = Omit & { headers: Record }; /** Follow negotiated redirects with HTTP method rules and origin checks. */ @@ -34,6 +43,7 @@ export async function fetchPages( const headers: PagesFetchOptions['headers'] = { ...options.headers, [REDIRECT_HEADER]: 'manual' }; const init = { ...options, headers }; let redirectedTo: string | undefined; + const finalMethod = () => (init.method ?? 'GET').toUpperCase(); for (let redirects = 0; redirects <= 20; redirects++) { const response = await fetch(url.split('#')[0], init); const status = Number(response.headers.get(REDIRECT_HEADER)); @@ -48,7 +58,7 @@ export async function fetchPages( } redirectedTo = destination.href; } - return { response, redirectedTo }; + return { response, redirectedTo, method: finalMethod() }; } await response.body?.cancel(); const base = new URL( @@ -71,7 +81,7 @@ export async function fetchPages( !isSameOrigin(destination, window.location.origin) || (!followGetRedirects && (get || method === 'GET' || method === 'HEAD')) ) { - return { response, redirectedTo }; + return { response, redirectedTo, method: finalMethod() }; } if (get) { for (const name of Object.keys(headers)) { diff --git a/packages/void/test/unit/isr-cache.test.ts b/packages/void/test/unit/isr-cache.test.ts index 6af520c3a..b6b78eb9f 100644 --- a/packages/void/test/unit/isr-cache.test.ts +++ b/packages/void/test/unit/isr-cache.test.ts @@ -13,6 +13,7 @@ import { markSharedCachePolicy, normalizeIsrPath, packIsrValue, + populateJsonEdgeCache, readIsrCache, SHARED_CACHE_POLICY_VERSION, writeIsrCache, @@ -925,6 +926,224 @@ 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('still evicts shared copies when the app answers a bypassed entry with no-store', async () => { + const { kv } = createKvMock(); + const env = makeEnv(kv); + const htmlKey = htmlEdgeKey(HOST, '/blog/post', DPL); + const jsonKey = jsonEdgeKey(HOST, '/blog/post', DPL); + edge.store.set(htmlKey, currentSharedCacheResponse(new Response('cached'))); + edge.store.set( + jsonKey, + currentSharedCacheResponse( + new Response('{"component":"Blog","props":{}}', { + headers: { 'content-type': 'application/json', 'X-VoidPages-Build': 'build-1' }, + }), + ), + ); + // The app now answers this page privately, with page data for this client. + const { render } = createRender( + () => + new Response('{"component":"Blog","props":{"me":true}}', { + headers: { + 'content-type': 'application/json', + 'X-VoidPages': 'true', + 'Cache-Control': 'private, no-store', + }, + }), + ); + const { ctx, flush } = createCtx(); + + await handleIsr( + htmlRequest('/blog/post', { + 'X-VoidPages': 'true', + 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION, + 'X-VoidPages-Build': 'build-2', + }), + env, + ctx, + OPTS, + render, + ); + await flush(); + + expect(edge.store.has(htmlKey)).toBe(false); + }); + + it('leaves an entry with no build id to the app when the client names one', async () => { + // An entry from before ids existed cannot answer a client that has one. + await populateJsonEdgeCache( + edge.cache, + jsonEdgeKey(HOST, '/blog/post', DPL), + new Response('', { + headers: { 'x-void-page-data': '{"component":"Blog","props":{}}' }, + }), + 60, + 'HIT', + ); + const env = makeEnv(createKvMock().kv); + const { render, spy } = createRender( + () => + new Response('{"component":"Blog","props":{"fresh":true}}', { + headers: { + 'content-type': 'application/json', + 'X-VoidPages': 'true', + 'X-VoidPages-Build': 'build-2', + }, + }), + ); + + const res = await handleIsr( + htmlRequest('/blog/post', { + 'X-VoidPages': 'true', + 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION, + 'X-VoidPages-Build': 'build-2', + }), + env, + createCtx().ctx, + OPTS, + render, + ); + + expect(spy).toHaveBeenCalledTimes(1); + expect(res!.headers.get('X-VoidPages-Build')).toBe('build-2'); + }); + + it.each([ + [ + 'keeps', + 'the reload response for a client from another build', + 'build-2', + 'text/plain; charset=utf-8', + true, + ], + [ + 'evicts', + 'an ordinary answer that opts out of sharing', + null, + 'text/plain; charset=utf-8', + false, + ], + [ + 'evicts', + 'a rendered page from another build that opts out of sharing', + 'build-2', + 'text/html', + false, + ], + ])('%s cached HTML on %s', async (_, __, answeredBuild, contentType, kept) => { + const { store, kv } = createKvMock(); + store.set(isrKey(DPL, HOST, '/blog/post'), corruptCases[0].seed()); + const env = makeEnv(kv); + const htmlKey = htmlEdgeKey(HOST, '/blog/post', DPL); + edge.store.set(htmlKey, currentSharedCacheResponse(new Response('cached'))); + const { render } = createRender( + () => + new Response(null, { + headers: { + 'Cache-Control': 'no-store', + 'Content-Type': contentType, + ...(answeredBuild === null ? {} : { 'X-VoidPages-Build': answeredBuild }), + }, + }), + ); + const { ctx, flush } = createCtx(); + + const res = await handleIsr( + htmlRequest('/blog/post', { + 'X-VoidPages': 'true', + 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION, + 'X-VoidPages-Build': 'build-1', + }), + env, + ctx, + OPTS, + render, + ); + await flush(); + + // A reload answer belongs to one stale tab; other tabs still hold this HTML. + expect(res!.headers.get('Cache-Control')).toBe('no-store'); + expect(edge.store.has(htmlKey)).toBe(kept); + expect(store.has(isrKey(DPL, HOST, '/blog/post'))).toBe(kept); + }); + 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..1eb1e2198 --- /dev/null +++ b/packages/void/test/unit/pages-build-id.test.ts @@ -0,0 +1,469 @@ +import { + chmodSync, + existsSync, + mkdirSync, + mkdtempSync, + rmSync, + symlinkSync, + utimesSync, + writeFileSync, +} from 'node:fs'; +import module from 'node:module'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { afterEach, describe, expect, it, vi } from 'vite-plus/test'; +import { + buildHeaders, + isStaleBuild, + isStaleBuildReload, +} from '../../../edge/src/pages-protocol.ts'; +import { computePagesBuildId, endPagesBuild } 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'; + +const roots: Array = []; + +/** A fresh folder, removed after the test. */ +function tempRoot(prefix: string): string { + const root = mkdtempSync(join(tmpdir(), prefix)); + roots.push(root); + return root; +} + +afterEach(() => { + vi.unstubAllEnvs(); + // Each test stands for its own build process. + endPagesBuild(); + for (const root of roots.splice(0)) { + chmodSync(root, 0o700); + rmSync(root, { recursive: true, force: true }); + } +}); + +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('isStaleBuildReload', () => { + const request = new Request('https://app.test/next', { + headers: { 'X-VoidPages': 'true', 'X-VoidPages-Build': 'build-1' }, + }); + const answer = (headers: Record) => new Response(null, { headers }); + + it.each([ + [ + 'the reload answer', + { 'Content-Type': 'text/plain; charset=utf-8', 'X-VoidPages-Build': 'build-2' }, + true, + ], + [ + 'page data', + { 'Content-Type': 'application/json', 'X-VoidPages': 'true', 'X-VoidPages-Build': 'build-2' }, + false, + ], + [ + 'rendered HTML from another build', + { 'Content-Type': 'text/html', 'X-VoidPages-Build': 'build-2' }, + false, + ], + [ + 'an answer from the same build', + { 'Content-Type': 'text/plain', 'X-VoidPages-Build': 'build-1' }, + false, + ], + ['an answer that names no build', { 'Content-Type': 'text/plain' }, false], + ])('%s', (_, headers, expected) => { + expect(isStaleBuildReload(request, answer(headers))).toBe(expected); + }); +}); + +describe('computePagesBuildId', () => { + function createSourceFixture(content: string): string { + const root = tempRoot('void-build-id-'); + mkdirSync(join(root, 'pages'), { recursive: true }); + writeFileSync(join(root, 'pages/index.tsx'), content); + return root; + } + + /** The id a new build of `root` gets. */ + function buildIdOf(root: string, excludeDirs: Array = []): string { + endPagesBuild(root); + return computePagesBuildId(root, excludeDirs); + } + + it('hashes the source, so identical trees keep the id', () => { + const content = 'export default function Page() {}\n'; + expect(buildIdOf(createSourceFixture(content))).toBe(buildIdOf(createSourceFixture(content))); + }); + + it('recomputes when a file changes', () => { + const root = createSourceFixture('export default function Page() {}\n'); + const first = buildIdOf(root); + + writeFileSync(join(root, 'pages/index.tsx'), 'export default function Page() { return 1 }\n'); + + expect(buildIdOf(root)).not.toBe(first); + }); + + it('keeps the first id until the build ends, whatever changes meanwhile', () => { + const root = createSourceFixture('export default function Page() {}\n'); + const first = computePagesBuildId(root, []); + + // Another task writes while Vite resolves the next environment. + writeFileSync(join(root, 'pages/index.tsx'), 'export default function Page() { return 1 }\n'); + expect(computePagesBuildId(root, [])).toBe(first); + + endPagesBuild(root); + 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 = buildIdOf(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(buildIdOf(root)).toBe(first); + + // The content really did change, so a fresh pass must notice. + rmSync(join(root, '.void'), { recursive: true, force: true }); + expect(buildIdOf(root)).not.toBe(first); + }); + + it('ignores build output, dot directories, .env files and installed packages', () => { + const root = createSourceFixture('export default function Page() {}\n'); + const first = buildIdOf(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'); + } + writeFileSync(join(root, '.env.local'), 'SECRET=1\n'); + + expect(buildIdOf(root, [join(root, 'dist')])).toBe(first); + }); + + it('counts dot files that configure the build', () => { + const root = createSourceFixture('export default function Page() {}\n'); + const first = buildIdOf(root); + + writeFileSync(join(root, '.browserslistrc'), 'last 1 chrome version\n'); + + expect(buildIdOf(root)).not.toBe(first); + }); + + describe('in a workspace', () => { + /** A pnpm-style workspace: the app links the ui package into its node_modules. */ + function createWorkspace(appDir = 'apps/web') { + const workspace = tempRoot('void-build-id-workspace-'); + const write = (path: string, content: string) => { + mkdirSync(dirname(join(workspace, path)), { recursive: true }); + writeFileSync(join(workspace, path), content); + }; + write('pnpm-workspace.yaml', 'packages:\n - apps/*\n - packages/*\n'); + write('packages/ui/package.json', '{"name":"ui"}'); + write('packages/ui/index.ts', 'export const label = 1;\n'); + write('apps/docs/package.json', '{"name":"docs"}'); + write(`${appDir}/package.json`, '{"name":"web","dependencies":{"ui":"workspace:*"}}'); + write(`${appDir}/pages/index.tsx`, "import { label } from 'ui';\n"); + mkdirSync(join(workspace, appDir, 'node_modules'), { recursive: true }); + symlinkSync( + join(workspace, 'packages/ui'), + join(workspace, appDir, 'node_modules/ui'), + 'dir', + ); + return { app: join(workspace, appDir), write }; + } + + it('covers the workspace packages the app depends on, and the lockfile', () => { + const { app, write } = createWorkspace(); + const first = buildIdOf(app); + + write('packages/ui/index.ts', 'export const label = 22;\n'); + const second = buildIdOf(app); + expect(second).not.toBe(first); + + write('pnpm-lock.yaml', 'lockfileVersion: 9.0\n'); + expect(buildIdOf(app)).not.toBe(second); + }); + + it('ignores workspace packages the app does not use', () => { + const { app, write } = createWorkspace(); + const first = buildIdOf(app); + + // A sibling app building at the same time. + write('apps/docs/dist/index.js', 'built\n'); + + expect(buildIdOf(app)).toBe(first); + }); + + it("asks Yarn Plug'n'Play for workspace packages when there is no node_modules", () => { + const { app, write } = createWorkspace(); + rmSync(join(app, 'node_modules'), { recursive: true, force: true }); + const ui = join(dirname(dirname(app)), 'packages/ui'); + const runtime = module as { + findPnpApi?: (path: string) => { resolveToUnqualified(request: string): string } | null; + }; + runtime.findPnpApi = () => ({ + resolveToUnqualified: (request) => { + if (request !== 'ui/package.json') { + throw new Error(`${request} is not a dependency`); + } + return join(ui, 'package.json'); + }, + }); + try { + const first = buildIdOf(app); + write('packages/ui/index.ts', 'export const label = 22;\n'); + expect(buildIdOf(app)).not.toBe(first); + } finally { + delete runtime.findPnpApi; + } + }); + + it('covers an app that sits under a dot folder', () => { + const { app, write } = createWorkspace('.examples/web'); + const first = buildIdOf(app); + + write('.examples/web/pages/index.tsx', 'export default 2;\n'); + + expect(buildIdOf(app)).not.toBe(first); + }); + }); + + it.skipIf(process.platform === 'win32' || process.getuid?.() === 0)( + 'skips a folder the build cannot read', + () => { + const root = createSourceFixture('export default function Page() {}\n'); + mkdirSync(join(root, 'pgdata/base'), { recursive: true }); + chmodSync(join(root, 'pgdata'), 0o000); + try { + expect(buildIdOf(root)).toHaveLength(12); + } finally { + chmodSync(join(root, 'pgdata'), 0o700); + } + }, + ); +}); + +describe('createPagesPlugin build id', () => { + type BuildConfig = { define?: Record } | undefined; + type PagesConfigHook = ( + userConfig: Record, + env: { command: 'build' | 'serve' }, + ) => Promise; + + 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, + }); + const hook = getHookHandler(plugin.config) as unknown as ( + userConfig: Record, + env: { command: 'build' | 'serve'; mode: string }, + ) => Promise; + // Vite always passes a mode; the tests only vary the command. + return (userConfig, env) => hook(userConfig, { mode: 'production', ...env }); + } + + function createFixture(): string { + const root = tempRoot('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'; + + function idIn(config: BuildConfig): string | undefined { + return config?.define?.[DEFINE]; + } + + it('defines one id for a build, shared by every environment', async () => { + const config = createConfigHook(); + + const id = idIn(await config({}, { command: 'build' })); + expect(JSON.parse(id ?? '""')).toMatch(/^[0-9a-f]{12}$/); + // Both bundles must carry the same id, or every navigation would reload. + expect(idIn(await config({}, { command: 'build' }))).toBe(id); + }); + + it('keeps one id when each environment evaluates the config to another define', async () => { + const root = createFixture(); + // Vite evaluates vite.config.ts again per environment, with a new plugin each + // time, so a define such as Date.now() differs between the two bundles. + const client = await createConfigHook(root)( + { define: { __BUILT_AT__: '"1"' } }, + { command: 'build' }, + ); + const server = await createConfigHook(root)( + { define: { __BUILT_AT__: '"2"' } }, + { command: 'build' }, + ); + + expect(idIn(server)).toBe(idIn(client)); + }); + + it('hashes again once the build ends, for the next build in this process', async () => { + const root = createFixture(); + const plugin = createPagesPlugin(join(root, 'pages'), { + name: 'test:pages', + generateRenderer: () => '', + generateClient: () => '', + config: () => ({}), + }); + // The same plugin instance builds twice, as through Vite's JavaScript API. + const config = getHookHandler(plugin.config) as unknown as ( + userConfig: Record, + env: { command: 'build'; mode: string }, + ) => Promise; + const build = () => config({}, { command: 'build', mode: 'production' }); + const first = idIn(await build()); + + writeFileSync(join(root, 'pages', 'index.tsx'), 'export default function Other() {}\n'); + const endBuild = getHookHandler(plugin.buildApp) as unknown as () => Promise; + await endBuild(); + + expect(idIn(await build())).not.toBe(first); + }); + + it('derives the id from the app source, so identical sources keep it', async () => { + const root = createFixture(); + const idOf = async () => { + endPagesBuild(root); + return idIn(await createConfigHook(root)({}, { command: 'build' })); + }; + + 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.each([ + ['from the default env folder', {}], + ['from the shell when env files are off', { envDir: false }], + ['with the fixed VITE_ prefix under a custom envPrefix', { envPrefix: 'PUBLIC_' }], + ])('changes the id for env values the client inlines, %s', async (_, userConfig) => { + const root = createFixture(); + const idFor = async (value: string) => { + vi.stubEnv('VITE_PROBE', value); + endPagesBuild(root); + return idIn(await createConfigHook(root)(userConfig, { command: 'build' })); + }; + + // Two builds that differ only here still emit different chunks. + expect(await idFor('one')).not.toBe(await idFor('two')); + }); + + it('changes the id for the mode and base Vite inlines', async () => { + const root = createFixture(); + // A new plugin per build, as Vite makes one. + const idFor = async (userConfig: Record, mode: string) => { + endPagesBuild(root); + const plugin = createPagesPlugin(join(root, 'pages'), { + name: 'test:pages', + generateRenderer: () => '', + generateClient: () => '', + config: () => ({}), + }); + const hook = getHookHandler(plugin.config) as unknown as ( + userConfig: Record, + env: { command: 'build'; mode: string }, + ) => Promise; + return idIn(await hook(userConfig, { command: 'build', mode })); + }; + + const production = await idFor({}, 'production'); + expect(await idFor({}, 'staging')).not.toBe(production); + expect(await idFor({ base: '/app/' }, 'production')).not.toBe(production); + }); + + it('changes the id for an app define the client inlines', async () => { + // Two apps with the same source, built apart, that differ only in a define. + const idFor = async (value: string) => + idIn( + await createConfigHook(createFixture())( + { define: { __PROBE__: JSON.stringify(value) } }, + { command: 'build' }, + ), + ); + + expect(await idFor('one')).not.toBe(await idFor('two')); + }); + + it('changes the id for a define of the client environment', async () => { + const idFor = async (value: string) => + idIn( + await createConfigHook(createFixture())( + { environments: { client: { define: { __API__: JSON.stringify(value) } } } }, + { command: 'build' }, + ), + ); + + expect(await idFor('one')).not.toBe(await idFor('two')); + }); + + 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('leaves an id the app defines to Vite, without hashing the tree', async () => { + const root = createFixture(); + const config = createConfigHook(root); + + const pinned = await config({ define: { [DEFINE]: '"commit-abc"' } }, { command: 'build' }); + + expect(idIn(pinned)).toBeUndefined(); + expect(existsSync(join(root, '.void'))).toBe(false); + }); +}); diff --git a/packages/void/test/unit/pages-client.test.ts b/packages/void/test/unit/pages-client.test.ts index 33eb2a373..691a17119 100644 --- a/packages/void/test/unit/pages-client.test.ts +++ b/packages/void/test/unit/pages-client.test.ts @@ -43,7 +43,7 @@ type TestRouterConfig = Partial> & { function stubClientGlobals(origin = 'http://localhost') { const documentStub = { - createElement: vi.fn(() => ({})), + createElement: vi.fn(() => ({ appendChild: vi.fn(), style: {} })), getElementById: vi.fn((id: string) => { if (id === '__VOID_PAGE_DATA__') { return { @@ -65,6 +65,7 @@ function stubClientGlobals(origin = 'http://localhost') { querySelector: vi.fn(() => null), querySelectorAll: vi.fn(() => []), }, + body: { replaceChildren: vi.fn() }, querySelector: vi.fn(() => null), }; @@ -133,6 +134,344 @@ 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(); + }); + + function stubReloadGuard(): void { + 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), + }); + } + + // The shape the server actually sends: a reload response, not page props. + const staleReloadResponse = () => + new Response(null, { + headers: { 'X-VoidPages-Build': 'build-1', 'Cache-Control': 'no-store' }, + }); + + it.each([ + ['page props from another build', () => staleJson(stalePage)], + ['a reload response for another build', staleReloadResponse], + ])('reloads a destination once, then stops on %s', async (_, response) => { + stubClientGlobals(); + vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); + stubReloadGuard(); + vi.stubGlobal( + 'fetch', + vi.fn(async () => response()), + ); + 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. Reloading again would + // loop, so the tab stops on the recovery page instead. + const documentUrl = 'http://localhost/'; + (window.location as unknown as { href?: string }).href = documentUrl; + await router.visit('/next'); + expect(window.location.href).toBe(documentUrl); + expect(applyUpdate).not.toHaveBeenCalled(); + expect(document.body.replaceChildren).toHaveBeenCalled(); + }); + + it.each([ + ['the first reload', false], + ['the recovery page', true], + ])('skips %s when a newer visit took over', async (_, reloadSpent) => { + stubClientGlobals(); + vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); + stubReloadGuard(); + if (reloadSpent) { + sessionStorage.setItem( + '__void_pages_deploy_reload', + JSON.stringify({ build: 'build-1', url: '/old', at: Date.now() }), + ); + } + // The old visit's response arrives after the newer visit aborted it, as a + // fetch that already resolved does. + const stale = controlledPromise(); + vi.stubGlobal( + 'fetch', + vi.fn(async (url: string) => + url === '/old' + ? stale.promise + : Response.json( + { ...stalePage, url: '/new' }, + { headers: { 'X-VoidPages': 'true', 'X-VoidPages-Build': 'build-2' } }, + ), + ), + ); + const applyUpdate = vi.fn(); + const { router } = await createTestRouter({ adapter: { applyUpdate } }); + + const oldVisit = router.visit('/old'); + await Promise.resolve(); + const newVisit = router.visit('/new'); + stale.resolve(staleReloadResponse()); + + // A superseded GET visit settles quietly. + await expect(oldVisit).resolves.toBeUndefined(); + await newVisit; + expect(window.location.href).toBeUndefined(); + expect(document.body.replaceChildren).not.toHaveBeenCalled(); + expect(applyUpdate).toHaveBeenCalled(); + }); + + it('reloads when a refresh of a URL with a fragment is answered by another build', async () => { + stubClientGlobals(); + vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); + stubReloadGuard(); + const reload = vi.fn(); + Object.assign(window.location, { pathname: '/docs', hash: '#install', reload }); + vi.stubGlobal( + 'fetch', + vi.fn(async () => staleReloadResponse()), + ); + const { router } = await createTestRouter(); + + await router.refresh(); + + // Assigning the same URL with a fragment only scrolls, so the tab would keep + // its stale page without loading anything. + expect(reload).toHaveBeenCalledOnce(); + expect(window.location.href).toBeUndefined(); + }); + + it('reloads a refresh with a fragment inside a Capacitor app', async () => { + stubClientGlobals('capacitor://localhost'); + vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); + stubReloadGuard(); + const reload = vi.fn(); + Object.assign(window.location, { pathname: '/docs', hash: '#install', reload }); + vi.stubGlobal( + 'fetch', + vi.fn(async () => staleReloadResponse()), + ); + const { router } = await createTestRouter(); + + await router.refresh(); + + // A custom scheme has an opaque URL origin, so the current page must still match. + expect(reload).toHaveBeenCalledOnce(); + expect(window.location.href).toBeUndefined(); + }); + + it('shows the recovery page inside a Capacitor app when the retry is stale too', async () => { + stubClientGlobals('capacitor://localhost'); + vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); + stubReloadGuard(); + vi.stubGlobal( + 'fetch', + vi.fn(async () => staleReloadResponse()), + ); + const { router } = await createTestRouter(); + + await router.visit('/next'); + (window.location as unknown as { href?: string }).href = 'capacitor://localhost/'; + await router.visit('/next'); + + expect(document.body.replaceChildren).toHaveBeenCalled(); + }); + + it('reloads a back/forward visit to an entry with a fragment answered by another build', async () => { + stubClientGlobals(); + vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); + stubReloadGuard(); + const reload = vi.fn(); + vi.stubGlobal( + 'fetch', + vi.fn(async () => staleReloadResponse()), + ); + const { router } = await createTestRouter(); + // The browser has already moved the address to the entry it went back to. + Object.assign(window.location, { pathname: '/b', hash: '#h', reload }); + + await router.visit('/b#h', { preserveState: true, _popstate: true }); + + expect(reload).toHaveBeenCalledOnce(); + expect(history.replaceState).not.toHaveBeenCalled(); + }); + + it('reloads a back/forward visit whose prefetch was answered by another build', async () => { + stubClientGlobals(); + vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); + const reload = vi.fn(); + vi.stubGlobal( + 'fetch', + vi.fn(async () => staleJson(stalePage)), + ); + const { router } = await createTestRouter(); + await router.prefetch('/b'); + Object.assign(window.location, { pathname: '/b', hash: '#h', reload }); + + await router.visit('/b#h', { preserveState: true, _popstate: true }); + + expect(reload).toHaveBeenCalledOnce(); + }); + + it('spends one reload on a stale prefetch, then stops when the retry is stale too', async () => { + stubClientGlobals(); + vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); + stubReloadGuard(); + vi.stubGlobal( + 'fetch', + vi.fn(async () => staleJson(stalePage)), + ); + const applyUpdate = vi.fn(); + const { router } = await createTestRouter({ adapter: { applyUpdate } }); + + await router.prefetch('/next'); + await router.visit('/next'); + expect(window.location.href).toBe('/next'); + + // The reload came back from the old build: a new document of the same build, + // where the user hovers and clicks again. + const documentUrl = 'http://localhost/'; + (window.location as unknown as { href?: string }).href = documentUrl; + const { router: reloaded } = await createTestRouter({ adapter: { applyUpdate } }); + await reloaded.prefetch('/next'); + await reloaded.visit('/next'); + + expect(window.location.href).toBe(documentUrl); + expect(applyUpdate).not.toHaveBeenCalled(); + expect(document.body.replaceChildren).toHaveBeenCalled(); + }); + + /** The transport's redirect handshake, then the destination's answer. */ + function redirectThen(status: 303 | 307, answer: Response) { + return vi + .fn() + .mockResolvedValueOnce( + new Response(null, { + headers: { 'X-VoidPages-Redirect': String(status), Location: '/items/1' }, + }), + ) + .mockResolvedValueOnce(answer); + } + + it('reloads the page a mutation redirected to when another build rendered it', async () => { + stubClientGlobals(); + vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); + stubReloadGuard(); + const fetch = redirectThen(303, staleJson({ ...stalePage, url: '/items/1' })); + vi.stubGlobal('fetch', fetch); + const applyUpdate = vi.fn(); + const { router } = await createTestRouter({ adapter: { applyUpdate } }); + + await router.visit('/items', { method: 'POST' }); + + // The action ran once; only the page it redirected to is loaded again. + expect(fetch).toHaveBeenCalledTimes(2); + expect(fetch.mock.calls[1]?.[1]).toMatchObject({ method: 'GET' }); + expect(window.location.href).toBe('/items/1'); + expect(applyUpdate).not.toHaveBeenCalled(); + }); + + it('keeps a mutation response that a 307 redirect answered, from any build', async () => { + stubClientGlobals(); + vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); + stubReloadGuard(); + vi.stubGlobal('fetch', redirectThen(307, staleJson({ ...stalePage, url: '/items/1' }))); + const applyUpdate = vi.fn(); + const { router } = await createTestRouter({ adapter: { applyUpdate } }); + + await router.visit('/items', { method: 'POST' }); + + // The POST ran at the new URL, so reloading would lose its result. + 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 5dccfde91..e3fcc5b82 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 c710c8056..37e328491 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 { @@ -1604,6 +1604,96 @@ 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('names its build on the HTML document, which ISR copies into its JSON cache', async () => { + vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); + + const response = await handlePageGet( + () => ({ title: 'post' }), + undefined, + await createTestContext('GET', '/blog/post'), + 'blog/post', + mockRenderFn, + mockGetAssetTags, + ); + + expect(response.headers.get('content-type')).toContain('text/html'); + 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/void/test/unit/pages-redirect.test.ts b/packages/void/test/unit/pages-redirect.test.ts index 8f194d3ad..315895ea4 100644 --- a/packages/void/test/unit/pages-redirect.test.ts +++ b/packages/void/test/unit/pages-redirect.test.ts @@ -39,6 +39,7 @@ it.each([301, 302, 303, 307, 308] as const)( }); const get = status === 303 || ((status === 301 || status === 302) && method === 'POST'); expect(result.redirectedTo).toBe('https://app.test/to#details'); + expect(result.method).toBe(get ? 'GET' : method); expect(await result.response.json()).toEqual({ method: get ? 'GET' : method, body: get ? '' : '{"id":42}', diff --git a/packages/vue/src/plugin-pages.ts b/packages/vue/src/plugin-pages.ts index 03fd617be..3f8bc978a 100644 --- a/packages/vue/src/plugin-pages.ts +++ b/packages/vue/src/plugin-pages.ts @@ -241,6 +241,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 9ea809190..f00c55121 100644 --- a/packages/vue/src/plugin.ts +++ b/packages/vue/src/plugin.ts @@ -9,6 +9,7 @@ export type VoidVueOptions = Readonly<{ vue?: Parameters[0]; viewTransitions?: boolean; prefetch?: PrefetchConfig; + deployRecovery?: boolean; }>; export function voidVue(options?: VoidVueOptions): Array { @@ -18,7 +19,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 }), diff --git a/platform/packages/dispatch/src/index.ts b/platform/packages/dispatch/src/index.ts index 125c9d396..64392edea 100644 --- a/platform/packages/dispatch/src/index.ts +++ b/platform/packages/dispatch/src/index.ts @@ -1,4 +1,11 @@ -import { matchLiteralPattern, PAGES_PROTOCOL_VERSION, redirectToHttps } from '@void/edge'; +import { + isStaleBuildReload, + matchLiteralPattern, + pagesPayloadFitsBuild, + PAGES_BUILD_HEADER, + PAGES_PROTOCOL_VERSION, + redirectToHttps, +} from '@void/edge'; import { clientRevalidateResponse, isEventStreamResponse } from '@void/isr/runtime'; import { PLATFORM_HEALTH_HOSTNAME_LABEL, @@ -160,12 +167,19 @@ export function isHtmlResponse(response: Response): boolean { ); } -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', 'X-VoidPages': 'true', 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION, + // Kept with the payload, so a client from another build skips this entry. + ...(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, @@ -189,7 +203,10 @@ async function populateJsonEdgeCache( if (!pageData) { return; } - await cache.put(cacheKey, jsonCacheResponse(pageData, ttl, state)); + await cache.put( + cacheKey, + jsonCacheResponse(pageData, ttl, state, response.headers.get(PAGES_BUILD_HEADER)), + ); } type SharedIsrEntry = Readonly<{ @@ -1208,10 +1225,19 @@ const dispatcher = { if (isPagesRequest) { const jsonCached = await cache.match(jsonCacheKey); if (jsonCached && hasCurrentSharedCachePolicy(jsonCached)) { - requestType = 'isr'; - return meter(clientRevalidateResponse(jsonCached)); - } - if (jsonCached) { + // A payload rendered by another build carries props this client cannot + // render. Fall through so the app answers and reloads the tab, and keep + // the entry: it is still right for clients of its own build. + if ( + pagesPayloadFitsBuild( + jsonCached.headers.get(PAGES_BUILD_HEADER), + request.headers.get(PAGES_BUILD_HEADER), + ) + ) { + requestType = 'isr'; + return meter(clientRevalidateResponse(jsonCached)); + } + } else if (jsonCached) { await cache.delete(jsonCacheKey); } // Miss — fall through to general dispatch (worker returns JSON for X-VoidPages) @@ -1800,6 +1826,8 @@ const dispatcher = { if ( sharedIsrEntry && + // The app's answer to a stale Pages client says nothing about cached HTML. + !isStaleBuildReload(request, response) && response.status === 200 && !writebackFallbackApplied && (resolveRevalidateTtl( diff --git a/platform/packages/dispatch/test/unit/index.test.ts b/platform/packages/dispatch/test/unit/index.test.ts index 04118b63f..92534e418 100644 --- a/platform/packages/dispatch/test/unit/index.test.ts +++ b/platform/packages/dispatch/test/unit/index.test.ts @@ -3405,6 +3405,170 @@ describe('ISR JSON edge cache (pages protocol)', () => { expect(await response.json()).toEqual(JSON.parse(pageData)); }); + it('pages request ignores a JSON edge entry rendered by another build', async () => { + edgeCacheStore.set( + 'https://my-app.void.app/dashboard?__void=json&__void_isr=legacy', + currentSharedCacheResponse( + new Response(pageData, { + headers: { + 'content-type': 'application/json', + 'x-isr-cache': 'HIT', + 'X-VoidPages-Build': 'build-1', + }, + }), + ), + ); + + const { env, workerFetch } = createEnv({ + routing: isrRouting, + workerResponse: new Response(pageData, { + headers: { 'content-type': 'application/json', 'X-VoidPages-Build': 'build-2' }, + }), + }); + + const response = await app.fetch( + new Request('https://my-app.void.app/dashboard', { + headers: { + 'X-VoidPages': 'true', + 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION, + 'X-VoidPages-Build': 'build-2', + }, + }), + env, + createCtx(), + ); + + // The entry holds props this client cannot render, so the app answers. + expect(workerFetch).toHaveBeenCalledOnce(); + expect(response.headers.get('X-VoidPages-Build')).toBe('build-2'); + // Clients of the build that rendered it can still use it. + expect( + edgeCacheStore.has('https://my-app.void.app/dashboard?__void=json&__void_isr=legacy'), + ).toBe(true); + }); + + it('stores the build of an HTML render with its JSON entry, so that build hits it', async () => { + const { env, workerFetch } = createEnv({ + routing: isrRouting, + workerResponse: new Response(pageHtml(), { + headers: { 'Content-Type': 'text/html', 'X-VoidPages-Build': 'build-2' }, + }), + }); + const documentCtx = createCtx(); + await app.fetch(new Request('https://my-app.void.app/dashboard'), env, documentCtx); + await waitForBackgroundTasks(documentCtx); + + const response = await app.fetch( + new Request('https://my-app.void.app/dashboard', { + headers: { + 'X-VoidPages': 'true', + 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION, + 'X-VoidPages-Build': 'build-2', + }, + }), + env, + createCtx(), + ); + + expect(workerFetch).toHaveBeenCalledOnce(); + expect(response.headers.get('X-VoidPages-Build')).toBe('build-2'); + expect(await response.json()).toEqual(JSON.parse(pageData)); + }); + + it('evicts cached HTML when a Pages answer opts out of sharing', async () => { + const htmlKey = 'https://my-app.void.app/dashboard?__void_isr=legacy'; + edgeCacheStore.set( + htmlKey, + currentSharedCacheResponse( + new Response(pageHtml(), { headers: { 'Content-Type': 'text/html' } }), + ), + ); + const { env } = createEnv({ + routing: isrRouting, + workerResponse: new Response(pageData, { + headers: { + 'content-type': 'application/json', + 'X-VoidPages': 'true', + 'Cache-Control': 'no-store', + }, + }), + }); + const ctx = createCtx(); + + await app.fetch( + new Request('https://my-app.void.app/dashboard', { + headers: { 'X-VoidPages': 'true', 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION }, + }), + env, + ctx, + ); + await waitForBackgroundTasks(ctx); + + expect(edgeCacheStore.has(htmlKey)).toBe(false); + }); + + it.each([ + [ + 'keeps', + 'the reload response for a client from another build', + 'build-2', + 'text/plain; charset=utf-8', + true, + ], + [ + 'evicts', + 'an ordinary answer that opts out of sharing', + null, + 'text/plain; charset=utf-8', + false, + ], + [ + 'evicts', + 'a rendered page from another build that opts out of sharing', + 'build-2', + 'text/html', + false, + ], + ])('%s cached HTML on %s', async (_, __, answeredBuild, contentType, kept) => { + const htmlKey = 'https://my-app.void.app/dashboard?__void_isr=legacy'; + edgeCacheStore.set( + htmlKey, + currentSharedCacheResponse( + new Response(pageHtml(), { headers: { 'Content-Type': 'text/html' } }), + ), + ); + + const { env, workerFetch } = createEnv({ + routing: isrRouting, + workerResponse: new Response(null, { + headers: { + 'Cache-Control': 'no-store', + 'Content-Type': contentType, + ...(answeredBuild === null ? {} : { 'X-VoidPages-Build': answeredBuild }), + }, + }), + }); + const ctx = createCtx(); + + const response = await app.fetch( + new Request('https://my-app.void.app/dashboard', { + headers: { + 'X-VoidPages': 'true', + 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION, + 'X-VoidPages-Build': 'build-1', + }, + }), + env, + ctx, + ); + await waitForBackgroundTasks(ctx); + + // A reload answer belongs to one stale tab; other tabs still hold this HTML. + expect(workerFetch).toHaveBeenCalledOnce(); + expect(response.headers.get('Cache-Control')).toBe('no-store'); + expect(edgeCacheStore.has(htmlKey)).toBe(kept); + }); + it('pages request falls through to worker on JSON cache miss', async () => { const { env, workerFetch } = createEnv({ routing: isrRouting,