From 62c2244229425cf04cfd650cfd75799cf97be204 Mon Sep 17 00:00:00 2001 From: Yunfei He Date: Fri, 4 Dec 2026 16:55:05 +0800 Subject: [PATCH 1/5] feat(pages): support typed page action results --- docs/guide/pages-routing/actions-and-forms.md | 31 ++- packages/edge/src/headers.ts | 2 + packages/edge/src/index.ts | 4 + packages/edge/src/pages-protocol.ts | 19 ++ packages/react/src/runtime/pages-client.ts | 2 +- .../test/unit/page-action-result.test.ts | 74 +++++ packages/void/src/codegen/route-types.ts | 22 ++ packages/void/src/index.ts | 1 + packages/void/src/pages/action-result.ts | 4 +- packages/void/src/pages/client.ts | 19 +- packages/void/src/pages/navigation-engine.ts | 47 +++- packages/void/src/pages/protocol.ts | 40 ++- packages/void/src/pages/redirect.ts | 2 + packages/void/src/routes-stub.ts | 18 ++ packages/void/src/runtime/handler/index.ts | 20 +- packages/void/src/runtime/routing/index.ts | 2 + .../page-action-types-typecheck.test.ts | 101 +++++-- packages/void/test/unit/pages-client.test.ts | 88 ++++++ .../void/test/unit/pages-protocol.test.ts | 255 +++++++++++++++++- 19 files changed, 713 insertions(+), 38 deletions(-) create mode 100644 packages/react/test/unit/page-action-result.test.ts diff --git a/docs/guide/pages-routing/actions-and-forms.md b/docs/guide/pages-routing/actions-and-forms.md index 53b9cc6a85..2515cc9b41 100644 --- a/docs/guide/pages-routing/actions-and-forms.md +++ b/docs/guide/pages-routing/actions-and-forms.md @@ -288,7 +288,7 @@ Each named action has its own validator schema, which supplies types for its URL ## `action()` Helper -Use `action()` for a button or other mutation that does not need form state. It updates the page after a successful request: +Use `action()` for a button or other mutation that does not need form state. By default, it refreshes the page after a successful request: ```ts import { action } from '@void/react'; // or "@void/vue", "@void/svelte", "@void/solid" @@ -308,6 +308,33 @@ A successful call returns `{ ok: true, pageData }`. Expected errors, such as val For `4xx` errors, `error.message` uses the [`HTTPException`](../../integrations/hono.md#utilities) message or the body of a plain-text response. Other response formats use a status summary, such as `Action failed with 404 Not Found`. +### Returning a result without refreshing + +Wrap the entire action with `definePageAction(handler, { reload: false })` to return a value to `action()` and skip the loader. Put authorization in the action or in middleware. + +```ts +// pages/imports.server.ts +import { defineHandler, definePageAction } from 'void'; + +export const actions = { + preview: definePageAction( + defineHandler(() => ({ validRows: 3 })), + { reload: false }, + ), +}; +``` + +```ts +import { action } from '@void/react'; // or "@void/vue", "@void/svelte", "@void/solid" + +const reply = await action('/imports?preview'); +if (reply.ok) console.log(reply.result?.validRows); +``` + +The result can be a serializable value such as a `Date`, or `undefined` for an acknowledgement. A result-only response leaves `pageData` undefined and preserves the current page, URL, history and scroll. React may show its configured navigation fallback while the request is pending. + +This option applies to `action()` in the full Pages router. Forms and actions on older servers continue to refresh the page. To refresh after receiving a result, call `router.refresh()` once navigation has settled. Refreshing cancels a pending visit and can still serve a cached page from public ISR. + ## Validation Errors `withValidator()` and `ValidationError` populate `form.errors` automatically. @@ -511,5 +538,5 @@ Pick the storage key on the server and allow only the file types you expect. See | Primitive | Page update | Form state | Framework-specific | | ---------------- | ----------- | -------------------------- | ------------------ | | `useForm` | Yes | Yes (errors, dirty, reset) | Yes | -| `action()` | Yes | No | Yes | +| `action()` | By default | No | Yes | | Native `fetch()` | No | No | No | diff --git a/packages/edge/src/headers.ts b/packages/edge/src/headers.ts index d2deef1935..a3f6be7fca 100644 --- a/packages/edge/src/headers.ts +++ b/packages/edge/src/headers.ts @@ -1,4 +1,5 @@ import type { HeaderRule } from '@void/deploy-core'; +import { protectPageActionResultCache } from './pages-protocol.ts'; import { matchLiteralPattern } from './pattern.ts'; export type { HeaderRule } from '@void/deploy-core'; @@ -179,5 +180,6 @@ export function applyHeaderRules( newResponse.headers.set(name, value); } + protectPageActionResultCache(newResponse.headers, response.headers); return newResponse; } diff --git a/packages/edge/src/index.ts b/packages/edge/src/index.ts index 34a27048f0..820273138b 100644 --- a/packages/edge/src/index.ts +++ b/packages/edge/src/index.ts @@ -1,11 +1,15 @@ export type { ProjectZeroTrustRouting } from './access.ts'; export { buildHeaders, + isPageActionResult, isStaleBuild, isStaleBuildReload, + PAGE_ACTION_RESULT_HEADER, + PAGE_ACTION_RESULT_TYPE, pagesPayloadFitsBuild, PAGES_BUILD_HEADER, PAGES_PROTOCOL_VERSION, + protectPageActionResultCache, } from './pages-protocol.ts'; export { redirectToHttps } from './https.ts'; export { diff --git a/packages/edge/src/pages-protocol.ts b/packages/edge/src/pages-protocol.ts index a4ea6d02b3..993209c71e 100644 --- a/packages/edge/src/pages-protocol.ts +++ b/packages/edge/src/pages-protocol.ts @@ -8,6 +8,25 @@ export const PAGES_PROTOCOL_VERSION = '2'; */ export const PAGES_BUILD_HEADER = 'X-VoidPages-Build'; +export const PAGE_ACTION_RESULT_HEADER = 'X-VoidPages-Action-Result'; +export const PAGE_ACTION_RESULT_TYPE = 'application/vnd.void.action-result+json'; + +export function isPageActionResult(headers: Headers): boolean { + const type = headers.get('Content-Type')?.split(';', 1)[0]?.trim().toLowerCase(); + return type === PAGE_ACTION_RESULT_TYPE; +} + +/** Header rules can replace the media type while the body still carries the result. */ +export function protectPageActionResultCache(headers: Headers, original: Headers = headers): void { + if (!original.has(PAGE_ACTION_RESULT_HEADER) && !isPageActionResult(original)) { + return; + } + headers.set('Cache-Control', 'no-store'); + headers.delete('CDN-Cache-Control'); + headers.delete('Cloudflare-CDN-Cache-Control'); + headers.delete('Surrogate-Control'); +} + /** * 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 diff --git a/packages/react/src/runtime/pages-client.ts b/packages/react/src/runtime/pages-client.ts index 97f6418c42..67ca59fd84 100644 --- a/packages/react/src/runtime/pages-client.ts +++ b/packages/react/src/runtime/pages-client.ts @@ -664,7 +664,7 @@ function App({ if (activePendingNavigationId === prepared.id) { activePendingNavigationId = null; } - // The browser is leaving or downloading a file: keep the current page. + // The response has no destination page. Keep the current page. dispatch({ type: 'abandon', resource: prepared, location: currentUrl() }); resolveVisit(undefined); } else if (resolveOnData) { diff --git a/packages/react/test/unit/page-action-result.test.ts b/packages/react/test/unit/page-action-result.test.ts new file mode 100644 index 0000000000..ef4d130d7f --- /dev/null +++ b/packages/react/test/unit/page-action-result.test.ts @@ -0,0 +1,74 @@ +// @vitest-environment happy-dom + +import { act, createElement, useState } from 'react'; +import { afterEach, expect, it, vi } from 'vite-plus/test'; +import { action } from '../../src/runtime/action.ts'; +import { startReactPages } from '../../src/runtime/pages-client.ts'; + +declare module 'void/routes' { + interface PageActionMap { + '/react-preview': { body: Record; result: string }; + } +} + +afterEach(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + document.body.replaceChildren(); +}); + +it('settles a result-only action at the React shell without committing another page', async () => { + vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true); + document.body.innerHTML = '
'; + const data = document.createElement('script'); + data.id = '__VOID_PAGE_DATA__'; + data.textContent = JSON.stringify({ component: 'home', props: {}, url: '/' }); + document.body.append(data); + const fetch = vi.fn( + async () => + new Response('[{"result":1},"saved"]', { + headers: { + 'Content-Type': 'application/vnd.void.action-result+json', + 'X-VoidPages-Action-Result': '/react-preview', + }, + }), + ); + vi.stubGlobal('fetch', fetch); + function Home() { + const [draft, setDraft] = useState('initial'); + return createElement('button', { onClick: () => setDraft('local draft') }, draft); + } + await act(async () => { + await startReactPages({ + components: { home: async () => ({ default: Home }) }, + layoutTree: {}, + routeMeta: {}, + matchRoute: () => 'home', + prefetchHoverDelay: 0, + prefetchDefaultCacheFor: { stale: 0, expires: 0 }, + viewTransitions: false, + staticPageData: false, + staticPageDataFastPath: false, + }); + }); + const button = document.querySelector('button'); + act(() => button?.click()); + const push = vi.spyOn(history, 'pushState'); + const replace = vi.spyOn(history, 'replaceState'); + const scroll = vi.spyOn(window, 'scrollTo'); + const url = location.href; + await act(async () => { + expect(await action('/react-preview')).toEqual({ + ok: true, + pageData: undefined, + result: 'saved', + }); + }); + expect(document.querySelector('button')).toBe(button); + expect(button?.textContent).toBe('local draft'); + expect(location.href).toBe(url); + expect(push).not.toHaveBeenCalled(); + expect(replace).not.toHaveBeenCalled(); + expect(scroll).not.toHaveBeenCalled(); + expect(fetch).toHaveBeenCalledOnce(); +}); diff --git a/packages/void/src/codegen/route-types.ts b/packages/void/src/codegen/route-types.ts index b0f5042684..0e6a8710d9 100644 --- a/packages/void/src/codegen/route-types.ts +++ b/packages/void/src/codegen/route-types.ts @@ -196,6 +196,8 @@ export function generateRouteTypes( ' V[K] extends StandardSchemaV1 ? StandardSchemaV1.InferInput : never;', '};', '', + 'type PageActionValueOf = H extends { __pageActionResult: true; __output: infer R } ? R : undefined;', + '', 'type ExtractOutput =', ' S extends StandardSchemaV1 ? StandardSchemaV1.InferOutput : never;', '', @@ -453,6 +455,24 @@ export function generateRouteTypes( ' : PageNamedActionBody["base"]], ParseActionUrl["action"]>', ' : Record;', '', + ' type PageActionValue = A extends { result: infer R } ? R : undefined;', + '', + ' type PageActionValueFor = [K] extends [never]', + ' ? P extends { body: unknown }', + ' ? PageActionValue

', + ' : never', + ' : P extends { actions: infer A }', + ' ? K extends keyof A', + ' ? PageActionValue', + ' : never', + ' : never;', + '', + ' export type ResolveActionResult = U extends unknown', + " ? ParseActionUrl['base'] extends keyof PageActionMap", + " ? PageActionValueFor['base']], ParseActionUrl['action']>", + ' : undefined', + ' : never;', + '', ' export type ResolveActionParams =', ' ParseActionUrl["base"] extends keyof PageActionMap', ' ? PageActionMap[ParseActionUrl["base"]] extends { params: infer P }', @@ -584,12 +604,14 @@ export function generateRouteTypes( body.push( ` actions: { [K in keyof ${actionsImport}]: {`, ` body: ExtractInput<${actionsImport}[K]["__validators"]> extends { body: infer B } ? B : Record;`, + ` result: PageActionValueOf<${actionsImport}[K]>;`, ' } };', ); } else { const importExpr = `(typeof import(${JSON.stringify(importPath)}))["action"]`; body.push( ` body: ExtractInput<${importExpr}["__validators"]> extends { body: infer B } ? B : Record;`, + ` result: PageActionValueOf<${importExpr}>;`, ); } diff --git a/packages/void/src/index.ts b/packages/void/src/index.ts index f82a925e06..fdff505443 100644 --- a/packages/void/src/index.ts +++ b/packages/void/src/index.ts @@ -1252,6 +1252,7 @@ export function voidPlugin(options?: { // Re-export runtime types and functions export { defineHandler, + definePageAction, defineMiddleware, basicAuth, defineScheduled, diff --git a/packages/void/src/pages/action-result.ts b/packages/void/src/pages/action-result.ts index b0e315a179..2d3b2ab584 100644 --- a/packages/void/src/pages/action-result.ts +++ b/packages/void/src/pages/action-result.ts @@ -4,8 +4,8 @@ import type { PageObject } from './protocol.ts'; export type ActionErrorHandlingScope = 'callSite' | 'boundary'; -export type ActionResult = - | { ok: true; pageData: T } +export type ActionResult = + | { ok: true; pageData: T; result?: TResult } | { ok: false; error: VoidActionError }; export class VoidActionError extends Error { diff --git a/packages/void/src/pages/client.ts b/packages/void/src/pages/client.ts index 62d0a5f0e5..7b8dacf1b6 100644 --- a/packages/void/src/pages/client.ts +++ b/packages/void/src/pages/client.ts @@ -1,6 +1,12 @@ /// -import type { ActionUrl, ResolveActionBody, ResolveActionParams, RouteUrlInput } from 'void/routes'; +import type { + ActionUrl, + ResolveActionBody, + ResolveActionParams, + ResolveActionResult, + RouteUrlInput, +} from 'void/routes'; import { toUrlString } from '../runtime/routing/route-url.ts'; import { interpolateRouteParams } from '../runtime/routing/route-url.ts'; import { withPageQuery } from './action-key.ts'; @@ -392,7 +398,7 @@ export type ActionClient = { this: void, url: U, ...args: HasParams extends true ? [options: ActionOptions] : [options?: ActionOptions] - ): Promise; + ): Promise>>; }; /** Creates an action client with its own router for each framework adapter. */ @@ -410,7 +416,7 @@ export function createActionClient( async function action( url: U, ...args: HasParams extends true ? [options: ActionOptions] : [options?: ActionOptions] - ): Promise { + ): Promise>> { if (!_router) { throw new Error('action(): called before router initialization.'); } @@ -423,12 +429,17 @@ export function createActionClient( url, options?.params as Record | undefined, ); - return submitAction(_router, resolvedUrl, { + let published: { result: ResolveActionResult } | undefined; + const reply = await submitAction(_router, resolvedUrl, { method, data, preserveScroll: options?.preserveScroll, ...defaults, + _onActionResult: (result) => { + published = { result: result as ResolveActionResult }; + }, }); + return reply.ok && published ? { ...reply, ...published } : reply; } return { action, setActionRouter }; diff --git a/packages/void/src/pages/navigation-engine.ts b/packages/void/src/pages/navigation-engine.ts index f2194b85a4..636bf39aec 100644 --- a/packages/void/src/pages/navigation-engine.ts +++ b/packages/void/src/pages/navigation-engine.ts @@ -1,11 +1,20 @@ /// -import { buildHeaders, isStaleBuild, PAGES_BUILD_HEADER, PAGES_PROTOCOL_VERSION } from '@void/edge'; +import { + buildHeaders, + isPageActionResult, + isStaleBuild, + PAGE_ACTION_RESULT_HEADER, + PAGES_BUILD_HEADER, + PAGES_PROTOCOL_VERSION, +} from '@void/edge'; +import { parse } from 'devalue'; 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 { isPlainObject } from './form-value-equality.ts'; import { initClientHead, applyClientHead } from './head-client.ts'; import { PrefetchCache, parseCacheFor } from './prefetch.ts'; import type { CacheForInput, CacheForResult, LinkPrefetchValue } from './prefetch.ts'; @@ -71,6 +80,8 @@ export type VisitOptions = { _refresh?: boolean; /** @internal Used by actions: the page query they added to the URL, which redirects leave out */ _preservedQuery?: string; + /** @internal Receives an action result without changing the visit return value. */ + _onActionResult?: (result: unknown) => void; }; export type PrefetchOptions = { @@ -820,7 +831,12 @@ export async function createPageNavigationEngine( preloadComponentPromise?.catch(() => {}); const headers: Record<'X-VoidPages' | 'X-VoidPages-Version' | 'Accept', string> & - Partial> = { + Partial< + Record< + typeof PRESERVED_QUERY_HEADER | typeof PAGE_ACTION_RESULT_HEADER | 'Content-Type', + string + > + > = { 'X-VoidPages': 'true', 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION, ...buildHeaders(pagesBuildId()), @@ -829,6 +845,11 @@ export async function createPageNavigationEngine( if (options._preservedQuery && method !== 'GET') { headers[PRESERVED_QUERY_HEADER] = options._preservedQuery; } + const actionTarget = + options._onActionResult && method !== 'GET' ? target.pathname + target.search : undefined; + if (actionTarget) { + headers[PAGE_ACTION_RESULT_HEADER] = actionTarget; + } const fetchOptions: PageFetchOptions = { method, headers, signal }; if (options.data && method !== 'GET') { @@ -968,6 +989,28 @@ export async function createPageNavigationEngine( throw await createActionErrorFromResponse(response, fetchUrl); } + if ( + response?.ok && + options._onActionResult && + actionTarget && + isPageActionResult(response.headers) + ) { + signal.throwIfAborted(); + if ( + response.headers.get(PAGE_ACTION_RESULT_HEADER) === actionTarget && + (!fetched?.redirectedTo || fetchUrl === actionTarget) + ) { + const text = await response.text(); + signal.throwIfAborted(); + const payload: unknown = parse(text); + if (!isPlainObject(payload) || !Object.hasOwn(payload, 'result')) { + throw new Error('pages: Invalid action result payload.'); + } + options._onActionResult(payload.result); + return undefined; + } + } + if (response && !response.headers.get('X-VoidPages')) { if (method === 'GET') { const staticPageData = await loadStaticPageData( diff --git a/packages/void/src/pages/protocol.ts b/packages/void/src/pages/protocol.ts index c4df8cbaf2..b752d356d7 100644 --- a/packages/void/src/pages/protocol.ts +++ b/packages/void/src/pages/protocol.ts @@ -1,4 +1,13 @@ -import { buildHeaders, isStaleBuild, PAGES_BUILD_HEADER, PAGES_PROTOCOL_VERSION } from '@void/edge'; +import { + buildHeaders, + isStaleBuild, + PAGE_ACTION_RESULT_HEADER, + PAGE_ACTION_RESULT_TYPE, + PAGES_BUILD_HEADER, + PAGES_PROTOCOL_VERSION, + protectPageActionResultCache, +} from '@void/edge'; +import { stringify } from 'devalue'; import type { Context } from 'hono'; import type { HTTPException } from 'hono/http-exception'; import { executeComposedHandler, getHandlerComposition } from '../runtime/handler/composition.ts'; @@ -1189,6 +1198,22 @@ async function runPageMutation( return new Response('Cross-origin page actions are not allowed.', { status: 403 }); } const renderMode = options?.renderMode ?? 'server'; + let resultTarget: string | undefined; + if ( + renderMode !== 'island' && + mutationHandler && + '__pageActionResult' in mutationHandler && + mutationHandler.__pageActionResult === true && + isPagesRequest(c) && + !needsPageReload(c) + ) { + // Rewrites and HTTP redirects can forward the original capability header. + const resolved = new URL(c.req.url); + const target = resolved.pathname + resolved.search; + if (c.req.header(PAGE_ACTION_RESULT_HEADER) === target) { + resultTarget = target; + } + } function buildMutationPageObj( props: Record, @@ -1260,6 +1285,9 @@ async function runPageMutation( } function respondWithErrors(errors: Record): Promise { + if (resultTarget !== undefined) { + return Promise.resolve(legacyPageResponse(c, errors)); + } if (renderMode === 'island') { return Promise.resolve(Response.json({ errors }, { status: 422 })); } @@ -1300,9 +1328,17 @@ async function runPageMutation( if (status !== 204) { return result; } + } else if (resultTarget !== undefined) { + const headers = pageResponseHeaders(c, { + 'Content-Type': PAGE_ACTION_RESULT_TYPE, + [PAGE_ACTION_RESULT_HEADER]: resultTarget, + }); + headers.delete('X-VoidPages'); + protectPageActionResultCache(headers); + return new Response(stringify({ result }), { headers }); } - // void — re-run GET with fresh props + // Re-run GET with fresh props for legacy clients and explicit 204s. if (renderMode === 'island') { return Response.json({ success: true }); } diff --git a/packages/void/src/pages/redirect.ts b/packages/void/src/pages/redirect.ts index af1ab55eda..9e5a6858fa 100644 --- a/packages/void/src/pages/redirect.ts +++ b/packages/void/src/pages/redirect.ts @@ -1,3 +1,4 @@ +import { PAGE_ACTION_RESULT_HEADER } from '@void/edge'; import { isSameOrigin } from './url.ts'; const REDIRECT_HEADER = 'X-VoidPages-Redirect'; @@ -92,6 +93,7 @@ export async function fetchPages( init.method = 'GET'; init.body = undefined; } + delete headers[PAGE_ACTION_RESULT_HEADER]; url = destination.href; } throw new TypeError('Too many Pages redirects.'); diff --git a/packages/void/src/routes-stub.ts b/packages/void/src/routes-stub.ts index 7968e34936..84d14d3b80 100644 --- a/packages/void/src/routes-stub.ts +++ b/packages/void/src/routes-stub.ts @@ -110,6 +110,24 @@ export type ResolveActionBody = : PageNamedActionBody['base']], ParseActionUrl['action']> : Record; +type PageActionValue = A extends { result: infer R } ? R : undefined; + +type PageActionValueFor = [K] extends [never] + ? P extends { body: unknown } + ? PageActionValue

+ : never + : P extends { actions: infer A } + ? K extends keyof A + ? PageActionValue + : never + : never; + +export type ResolveActionResult = U extends unknown + ? ParseActionUrl['base'] extends keyof PageActionMap + ? PageActionValueFor['base']], ParseActionUrl['action']> + : undefined + : never; + export type ResolveActionParams = ParseActionUrl['base'] extends keyof PageActionMap ? PageActionMap[ParseActionUrl['base']] extends { params: infer P } diff --git a/packages/void/src/runtime/handler/index.ts b/packages/void/src/runtime/handler/index.ts index 70e9eeb7bf..1dcd584d60 100644 --- a/packages/void/src/runtime/handler/index.ts +++ b/packages/void/src/runtime/handler/index.ts @@ -7,7 +7,11 @@ import type { AuthSession, AuthUser } from '../auth/index.ts'; import type { CloudBindings } from '../env/bindings.ts'; import { isVoidInternalPath } from '../routing/internal-path.ts'; import type { TypedRoutes } from '../routing/route-url.ts'; -import { executeComposedHandler, setHandlerComposition } from './composition.ts'; +import { + executeComposedHandler, + getHandlerComposition, + setHandlerComposition, +} from './composition.ts'; import type { HandlerLeaf } from './composition.ts'; import { convertReturnValue } from './response.ts'; import { runValidation } from './validator.ts'; @@ -311,6 +315,20 @@ export function defineHandler(...args: Array): TypedHa return composed as TypedHandler; } +/** Publish a composed page action's return value to action() without reloading page data. */ +export function definePageAction( + handler: TypedHandler, + _options: { reload: false }, +): TypedHandler & { readonly __pageActionResult: true } { + const wrapped = Object.assign((c: CloudContext) => handler(c), { + __pageActionResult: true as const, + }); + if (getHandlerComposition(handler)) { + setHandlerComposition(wrapped, [], handler); + } + return wrapped as TypedHandler & { readonly __pageActionResult: true }; +} + /** * Create a handler with input validation using Standard Schema validators. * diff --git a/packages/void/src/runtime/routing/index.ts b/packages/void/src/runtime/routing/index.ts index f1a01123da..d80e3a1d2c 100644 --- a/packages/void/src/runtime/routing/index.ts +++ b/packages/void/src/runtime/routing/index.ts @@ -4,6 +4,7 @@ import { matchPattern, matchPatternCaptures, mergeQueryIntoLocation, + protectPageActionResultCache, substituteParams, } from '@void/edge'; import type { Context, Hono, MiddlewareHandler, NotFoundHandler } from 'hono'; @@ -351,6 +352,7 @@ export function createRoutingRuntime( c.isRewritten = () => originalUrls.has(c.req.raw); await next(); c.res = pagesRedirectResponse(c.req.raw, c.res); + protectPageActionResultCache(c.res.headers); if (!trackAssetMisses) { return; } diff --git a/packages/void/test/integration/page-action-types-typecheck.test.ts b/packages/void/test/integration/page-action-types-typecheck.test.ts index de9c594bd4..1aa382a12d 100644 --- a/packages/void/test/integration/page-action-types-typecheck.test.ts +++ b/packages/void/test/integration/page-action-types-typecheck.test.ts @@ -5,6 +5,7 @@ import { tmpdir } from 'node:os'; import { dirname, join } from 'node:path'; import { afterEach, describe, expect, it } from 'vite-plus/test'; import { generateRouteTypes } from '../../src/codegen/route-types.ts'; +import { scanPages } from '../../src/pages/scan.ts'; import type { PageDefinition } from '../../src/pages/types.ts'; import type { ScanResult } from '../../src/router/scan.ts'; @@ -49,21 +50,12 @@ const schema = (body: string) => `declare const body: Schema<${body}>;`, ].join('\n'); -function typecheck(pages: Array, files: Record) { +async function typecheck( + pages: Array | 'dev' | 'prod' | undefined, + files: Record, +) { const root = mkdtempSync(join(tmpdir(), 'void-page-action-types-')); roots.push(root); - const { dts } = generateRouteTypes( - { - routes: [], - middleware: [], - jobs: [], - queues: [], - pages: { pages, layouts: [], namedLayouts: [] }, - } satisfies ScanResult, - join(root, 'routes'), - join(root, '.void'), - join(root, 'pages'), - ); const all: Record = { 'tsconfig.json': JSON.stringify({ compilerOptions: { @@ -78,13 +70,14 @@ function typecheck(pages: Array, files: Record) allowImportingTsExtensions: true, paths: { void: [join(voidDist, 'index.d.mts')], + '@void/react': [join(voidDist, '../../react/dist/index.d.mts')], // Shipped helper aliases must not hide defects in the generated helpers. 'void/routes': [join(root, 'routes-base.d.ts')], }, }, files: ['.void/routes.d.ts', 'check.ts'], }), - '.void/routes.d.ts': dts, + 'package.json': '{"type":"module"}', 'routes-base.d.ts': 'export {};', ...files, }; @@ -92,6 +85,22 @@ function typecheck(pages: Array, files: Record) mkdirSync(dirname(join(root, path)), { recursive: true }); writeFileSync(join(root, path), content); } + const { dts } = generateRouteTypes( + { + routes: [], + middleware: [], + jobs: [], + queues: [], + pages: Array.isArray(pages) + ? { pages, layouts: [], namedLayouts: [] } + : await scanPages(root, { environment: pages }), + } satisfies ScanResult, + join(root, 'routes'), + join(root, '.void'), + join(root, 'pages'), + ); + mkdirSync(join(root, '.void'), { recursive: true }); + writeFileSync(join(root, '.void/routes.d.ts'), dts); const tsrs = join( dirname(createRequire(import.meta.url).resolve('tsrs/package.json')), 'bin/tsrs', @@ -107,8 +116,8 @@ const useForm = [ 'declare function useForm(url: U, body: ResolveActionBody, options?: ActionFormOptions): void;', ]; -it('accepts query parameters on generated named action URLs without losing body or route params', () => { - const result = typecheck( +it('accepts query parameters on generated named action URLs without losing body or route params', async () => { + const result = await typecheck( [{ ...page('dev', ['actions']), pattern: '/contact/:id', params: ['id'] }], { 'pages/contact.dev.server.ts': `${schema('{ title: string }')} @@ -139,11 +148,11 @@ export const actions = { save: defineHandler.withValidator({ body })(() => ({ ok }); describe('page action types for a .dev + .prod page pair', () => { - it('accepts the body of each page when the two bodies differ', () => { + it('accepts the body of each page when the two bodies differ', async () => { const companion = (age: string) => `${schema(`{ email: string; age: ${age} }`)} export const action = defineHandler.withValidator({ body })(() => ({ ok: true }));`; - const result = typecheck([page('dev', ['action']), page('prod', ['action'])], { + const result = await typecheck([page('dev', ['action']), page('prod', ['action'])], { 'pages/contact.dev.server.ts': companion('string'), 'pages/contact.prod.server.ts': companion('number'), 'check.ts': [ @@ -158,8 +167,8 @@ export const action = defineHandler.withValidator({ body })(() => ({ ok: true }) expect(result.status).toBe(0); }); - it('accepts both URLs when only one page of the pair has named actions', () => { - const result = typecheck([page('dev', ['action']), page('prod', ['actions'])], { + it('accepts both URLs when only one page of the pair has named actions', async () => { + const result = await typecheck([page('dev', ['action']), page('prod', ['actions'])], { 'pages/contact.dev.server.ts': `${schema('{ email: string }')} export const action = defineHandler.withValidator({ body })(() => ({ ok: true }));`, 'pages/contact.prod.server.ts': `${schema('{ title: string }')} @@ -178,11 +187,11 @@ export const actions = { save: defineHandler.withValidator({ body })(() => ({ ok expect(result.status).toBe(0); }); - it('accepts the named actions of each page when the two sets differ', () => { + it('accepts the named actions of each page when the two sets differ', async () => { const companion = (name: string) => `${schema('{ title: string }')} export const actions = { ${name}: defineHandler.withValidator({ body })(() => ({ ok: true })) };`; - const result = typecheck([page('dev', ['actions']), page('prod', ['actions'])], { + const result = await typecheck([page('dev', ['actions']), page('prod', ['actions'])], { 'pages/contact.dev.server.ts': companion('save'), 'pages/contact.prod.server.ts': companion('publish'), 'check.ts': [ @@ -197,3 +206,51 @@ export const actions = { ${name}: defineHandler.withValidator({ body })(() => ({ expect(result.status).toBe(0); }); }); + +it.each(['dev', 'prod', undefined] as const)( + 'infers action results in the real React adapter for a %s scan', + async (environment) => { + const result = await typecheck(environment, { + 'pages/items/[id].dev.vue': '', + 'pages/items/[id].prod.vue': '', + 'pages/items/[id].dev.server.ts': `${schema('{ title: string }')} +import { definePageAction, defineMiddleware } from 'void'; +export const action = definePageAction(defineHandler(defineMiddleware((_c, next) => next()), + defineHandler.withValidator({ body })(() => ({ total: 1n }))), { reload: false });`, + 'pages/items/[id].prod.server.ts': `${schema('{ title: string }')} +import { definePageAction } from 'void'; +export const actions = { + default: definePageAction(defineHandler.withValidator({ body })(() => new Date()), { reload: false }), + empty: definePageAction(defineHandler(() => {}), { reload: false }), + unwrapped: defineHandler(() => ({ hidden: true })), +};`, + 'check.ts': [ + "import { action } from '@void/react';", + 'const params = { id: "1" };', + 'const data = { title: "draft" };', + ...(environment !== 'prod' + ? [ + "const single = await action('/items/[id]', { params, data });", + 'if (single.ok) { const value: { total: bigint } | undefined = single.result; single.result?.total; }', + '// @ts-expect-error validator body is still checked', + "await action('/items/[id]', { params, data: { title: 42 } });", + ] + : []), + ...(environment !== 'dev' + ? [ + "const named = await action('/items/[id]?default&tab=profile', { params, data });", + 'if (named.ok) { const value: Date | undefined = named.result; named.result?.getTime(); }', + "const empty = await action('/items/[id]?empty', { params });", + 'if (empty.ok) { const value: void = empty.result; }', + "const unwrapped = await action('/items/[id]?unwrapped', { params });", + 'if (unwrapped.ok) { const value: undefined = unwrapped.result; }', + '// @ts-expect-error the route requires params', + "await action('/items/[id]?default', { data });", + ] + : []), + ].join('\n'), + }); + expect(result.stdout + result.stderr).toBe(''); + expect(result.status).toBe(0); + }, +); diff --git a/packages/void/test/unit/pages-client.test.ts b/packages/void/test/unit/pages-client.test.ts index 9de9529a98..cf06e9fee7 100644 --- a/packages/void/test/unit/pages-client.test.ts +++ b/packages/void/test/unit/pages-client.test.ts @@ -4,6 +4,7 @@ import { afterEach, describe, expect, it, vi } from 'vite-plus/test'; import type { RouteDestination } from 'void/routes'; import { PAGES_PROTOCOL_VERSION } from '../../../edge/src/pages-protocol.ts'; import { + createActionClient, createRouterFacade, createSsrRouter, createVoidRouter, @@ -11,6 +12,7 @@ import { mergeDataIntoHref, readPageQuery, ssrProxy, + submitIslandAction, submitAction, } from '../../src/pages/client.ts'; import type { VoidRouterConfig } from '../../src/pages/client.ts'; @@ -34,6 +36,12 @@ type DeferredTestWindow = Window & { }; declare module 'void/routes' { + interface PageActionMap { + '/preview/[id]': { + params: { id: string }; + actions: { save: { body: Record; result: number } }; + }; + } interface RoutePathMap { '/typed-router/:id': 'id'; } @@ -3352,3 +3360,83 @@ describe('superseded navigation commits (#507)', () => { }); }); }); + +it('settles result-only actions without a page commit and preserves newer visits', async () => { + stubClientGlobals(); + const resultHeader = 'X-VoidPages-Action-Result'; + const resultType = 'application/vnd.void.action-result+json'; + window.location.pathname = '/preview/2'; + window.location.search = '?tab=profile'; + const target = '/preview/2?save&tab=profile'; + const payload = (text: string, echo = target) => + new Response(text, { headers: { 'Content-Type': resultType, [resultHeader]: echo } }); + const applyUpdate = vi.fn(); + const { router } = await createTestRouter({ adapter: { applyUpdate } }); + const { action, setActionRouter } = createActionClient(); + setActionRouter(router); + const preview = () => action('/preview/[id]?save', { params: { id: '2' } }); + const page = { component: 'home', props: { fresh: true }, errors: null, url: '/next' }; + const fetch = vi.fn<(url: string, init: RequestInit) => Promise>(); + vi.stubGlobal('fetch', fetch); + + fetch.mockResolvedValueOnce(payload('[{"result":1},42]')); + expect(await preview()).toEqual({ ok: true, result: 42, pageData: undefined }); + expect(new Headers(fetch.mock.calls[0][1].headers).get(resultHeader)).toBe(target); + expect(router.url.pathname + router.url.search).toBe('/preview/2?tab=profile'); + expect(window.location.href).toBeUndefined(); + expect(history.pushState).not.toHaveBeenCalled(); + expect(history.replaceState).not.toHaveBeenCalled(); + expect(window.scrollTo).not.toHaveBeenCalled(); + expect(applyUpdate).not.toHaveBeenCalled(); + + fetch.mockResolvedValueOnce(payload('{"result":42}')); + await expect(preview()).rejects.toThrow(); + expect(window.location.href).toBeUndefined(); + expect(fetch).toHaveBeenCalledTimes(2); + + const pending = controlledPromise(); + fetch.mockReturnValueOnce(pending.promise).mockResolvedValueOnce(pageJson(page)); + const canceled = preview(); + const rejected = expect(canceled).rejects.toMatchObject({ name: 'AbortError' }); + await router.visit('/next'); + pending.resolve(payload('[{"result":1},42]')); + await rejected; + expect(applyUpdate).toHaveBeenCalledTimes(1); + expect(fetch.mock.calls.map(([url, init]) => [url, init.method])).toEqual([ + [target, 'POST'], + [target, 'POST'], + [target, 'POST'], + ['/next', 'GET'], + ]); + + fetch.mockResolvedValueOnce(pageJson(page)); + const legacy = await preview(); + expect(legacy).toMatchObject({ ok: true, pageData: page }); + if (legacy.ok) { + expect(legacy.result).toBeUndefined(); + } + fetch.mockResolvedValueOnce(pageJson(page)); + await submitAction(router, '/next', { method: 'POST' }); + expect(new Headers(fetch.mock.lastCall?.[1].headers).has(resultHeader)).toBe(false); + + fetch.mockResolvedValueOnce(Response.json({ success: true })); + await submitIslandAction('/preview/2?save', 'POST', {}); + expect(new Headers(fetch.mock.lastCall?.[1].headers).has(resultHeader)).toBe(false); + + fetch.mockResolvedValueOnce(payload('[{"result":1},42]', '/other?save')); + expect(await preview()).toEqual({ + ok: true, + pageData: undefined, + }); + expect(window.location.href).toBe(target); + const redirected = payload('[{"result":1},42]'); + Object.defineProperties(redirected, { + redirected: { value: true }, + url: { value: 'http://localhost/preview/3?save' }, + }); + fetch.mockClear(); + fetch.mockResolvedValueOnce(redirected); + expect(await preview()).toEqual({ ok: true, pageData: undefined }); + expect(window.location.href).toBe('/preview/3?save'); + expect(fetch).toHaveBeenCalledOnce(); +}); diff --git a/packages/void/test/unit/pages-protocol.test.ts b/packages/void/test/unit/pages-protocol.test.ts index 50fcb43a11..1395ae84ac 100644 --- a/packages/void/test/unit/pages-protocol.test.ts +++ b/packages/void/test/unit/pages-protocol.test.ts @@ -1,6 +1,8 @@ +import { parse } from 'devalue'; import { Hono } from 'hono'; import { HTTPException } from 'hono/http-exception'; import { describe, expect, it, vi, afterEach } from 'vite-plus/test'; +import { applyHeaderRules } from '../../../edge/src/headers.ts'; import { PAGES_PROTOCOL_VERSION } from '../../../edge/src/pages-protocol.ts'; import { markActionKey } from '../../src/pages/action-key.ts'; import { defer } from '../../src/pages/defer.ts'; @@ -10,16 +12,21 @@ import { flattenValidationErrors, ValidationError, } from '../../src/pages/protocol.ts'; +import { fetchPages } from '../../src/pages/redirect.ts'; import { deserializePageData, decodePageData, requestAppSetup, serializePageData, } from '../../src/pages/serialize.ts'; -import { defineHandler } from '../../src/runtime/handler/index.ts'; +import { defineHandler, definePageAction } from '../../src/runtime/handler/index.ts'; import type { CloudContext, CloudEnv } from '../../src/runtime/handler/index.ts'; import { createRoutingRuntime } from '../../src/runtime/routing/index.ts'; -import { createStaticNotFound } from '../../src/runtime/routing/pages.ts'; +import { + createPageGetHandler, + createPageMutationHandler, + createStaticNotFound, +} from '../../src/runtime/routing/pages.ts'; import type { StandardSchemaV1 } from '../../src/standard-schema.ts'; type RenderPage = { component: string }; @@ -2137,3 +2144,247 @@ describe('flattenValidationErrors', () => { expect(flattenValidationErrors(undefined)).toEqual({}); }); }); + +it('negotiates result-only page actions on the resolved target', async () => { + const app = new Hono(); + const runtime = createRoutingRuntime(app as unknown as Hono, { nodeTarget: true }); + const resultHeader = 'X-VoidPages-Action-Result'; + const resultType = 'application/vnd.void.action-result+json'; + const headers = { 'X-VoidPages': 'true', 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION }; + const result = { date: new Date('2026-11-08'), count: 42n, map: new Map([['x', 1]]) }; + const mutate = vi.fn((c: CloudContext) => { + c.header('Set-Cookie', 'action=ran; Path=/'); + return result; + }); + const loader = vi.fn(() => ({ fresh: true })); + const target = '/items/2?save&tab=profile'; + const cacheRules: Array<[string, string]> = [ + ['Cache-Control', 'public, max-age=600'], + ['CDN-Cache-Control', 'public'], + ['Cloudflare-CDN-Cache-Control', 'public'], + ['Surrogate-Control', 'max-age=600'], + ]; + app.onError((_error, c) => c.text('Unhandled', 500)); + app.use(runtime.contextMiddleware); + app.use(runtime.headerMiddleware([{ pattern: '/items/**', headers: cacheRules }])); + app.use('/items/:id', async (c, next) => { + if (c.req.header('app-error')) { + throw new ValidationError({ name: 'app' }); + } + await next(); + if (c.req.header('replace') === 'app') { + c.res = c.json({ replaced: 'app' }); + } + }); + app.post('/rewrite', (c) => (c as CloudContext).rewrite(target)); + for (const status of [303, 307, 308] as const) { + app.post('/redirect/' + status, (c) => c.redirect(target, status)); + } + const wrap = (handler: ReturnType) => + definePageAction(handler, { reload: false }); + const save = wrap( + defineHandler(async (c, next) => { + if (!c.req.header('Authorization')) { + return c.text('Sign in', 401); + } + if (c.req.header('route-error')) { + throw new ValidationError({ name: 'route' }); + } + await next(); + if (c.req.header('replace') === 'route') { + return c.json({ replaced: 'route' }); + } + }, mutate), + ); + const actions = { + save, + legacy: defineHandler(mutate), + empty: wrap(defineHandler(() => undefined)), + explicit: wrap(defineHandler(() => new Response(null, { status: 204 }))), + json: wrap(defineHandler((c) => c.json({ explicit: true }))), + invalid: wrap( + defineHandler.withValidator({ + body: { + '~standard': { + version: 1, + vendor: 'test', + validate: () => ({ issues: [{ message: 'Required', path: ['name'] }] }), + }, + }, + })(mutate), + ), + throws: wrap( + defineHandler(() => { + throw new ValidationError({ name: 'action' }); + }), + ), + unserializable: wrap(defineHandler(() => () => {})), + }; + const route = { + componentId: 'items', + load: async () => ({ actions, loader }), + namedActions: true, + render: mockRenderFn, + assets: mockGetAssetTags, + headConfig: null, + renderOptions: {}, + }; + app.get('/items/:id', createPageGetHandler(route)); + app.post('/items/:id', createPageMutationHandler(route)); + app.post( + '/island', + createPageMutationHandler({ ...route, renderOptions: { renderMode: 'island' } }), + ); + const post = (url: string, capability: string | null = url, extra: Record = {}) => + app.request(url, { + method: 'POST', + body: '{}', + headers: { + 'Content-Type': 'application/json', + ...headers, + Authorization: 'test', + ...(capability && { [resultHeader]: capability }), + ...extra, + }, + }); + + const reply = await post(target); + expect(reply.headers.get('Content-Type')).toBe(resultType); + expect(reply.headers.get(resultHeader)).toBe(target); + expect(reply.headers.get('X-VoidPages')).toBeNull(); + expect(reply.headers.getSetCookie()).toEqual(['action=ran; Path=/']); + expect(reply.headers.get('Cache-Control')).toBe('no-store'); + for (const [name] of cacheRules.slice(1)) { + expect(reply.headers.get(name)).toBeNull(); + } + const hosted = applyHeaderRules(reply, '/items/2', [ + { pattern: '/items/*', headers: [...cacheRules, ['X-Hosted-Rule', 'applied']] }, + ]); + expect(hosted.headers.get('X-Hosted-Rule')).toBe('applied'); + expect(hosted.headers.get('Cache-Control')).toBe('no-store'); + for (const [name] of cacheRules.slice(1)) { + expect(hosted.headers.get(name)).toBeNull(); + } + expect(parse(await hosted.text())).toEqual({ result }); + expect(mutate).toHaveBeenCalledTimes(1); + expect(loader).not.toHaveBeenCalled(); + + for (const [url, capability] of [ + [target, null], + [target, '/items/1?save&tab=profile'], + [target, '/items/2?empty'], + ['/rewrite', '/rewrite'], + ['/items/2?explicit', '/items/2?explicit'], + ] as const) { + expect(await json(await post(url, capability))).toMatchObject({ props: { fresh: true } }); + } + expect(loader).toHaveBeenCalledTimes(5); + expect(mutate).toHaveBeenCalledTimes(5); + const legacy = await post('/items/2?legacy', null); + const advertised = await post('/items/2?legacy'); + expect([...advertised.headers]).toEqual([...legacy.headers]); + expect(advertised.headers.get('Cache-Control')).toBe('public, max-age=600'); + expect(await advertised.text()).toBe(await legacy.text()); + expect(mutate).toHaveBeenCalledTimes(7); + expect(loader).toHaveBeenCalledTimes(7); + + expect(await (await post('/island?empty')).json()).toEqual({ success: true }); + expect(parse(await (await post('/items/2?empty')).text())).toStrictEqual({ result: undefined }); + for (const source of ['app', 'route']) { + const replaced = await post(target, target, { replace: source }); + expect(replaced.headers.get('X-VoidPages')).toBeNull(); + expect(await replaced.json()).toEqual({ replaced: source }); + } + expect(await (await post('/items/2?json')).json()).toEqual({ explicit: true }); + expect((await post('/items/2?unserializable')).status).toBe(500); + expect((await post(target, target, { Authorization: '' })).status).toBe(401); + expect((await post(target, target, { Origin: 'https://elsewhere.test' })).status).toBe(403); + expect((await post(target, target, { 'app-error': '1' })).status).toBe(500); + const skew = { 'X-VoidPages-Version': 'unsupported' }; + for (const [url, expected, extra] of [ + ['/items/2?throws', 'action', {}], + ['/items/2?invalid', 'Required', {}], + [target, 'route', { 'route-error': '1' }], + ['/items/2?invalid', 'Required', skew], + ] as const) { + const response = await post(url, url, extra); + expect(response.status).toBe(422); + expect(await response.json()).toEqual({ errors: { name: expected } }); + } + const unsupported = await post(target, target, skew); + expect(await unsupported.text()).toBe(''); + expect(unsupported.headers.get('X-VoidPages')).toBeNull(); + expect(mutate).toHaveBeenCalledTimes(10); + expect(loader).toHaveBeenCalledTimes(7); + expect(await json(await app.request(target, { headers }))).toMatchObject({ + props: { fresh: true }, + }); + + try { + vi.stubGlobal('window', { location: new URL('http://localhost/') }); + const fetch = vi.fn((url: string, init: RequestInit) => app.request(url, init)); + vi.stubGlobal('fetch', fetch); + for (const status of [303, 307, 308] as const) { + fetch.mockClear(); + const url = '/redirect/' + status; + const { response, method } = await fetchPages(url, { + method: 'POST', + headers: { ...headers, Authorization: 'test', [resultHeader]: url }, + }); + expect(method).toBe(status === 303 ? 'GET' : 'POST'); + expect(new Headers(fetch.mock.calls[1][1].headers).has(resultHeader)).toBe(false); + expect(await json(response)).toMatchObject({ props: { fresh: true } }); + } + expect(mutate).toHaveBeenCalledTimes(12); + expect(loader).toHaveBeenCalledTimes(11); + } finally { + vi.unstubAllGlobals(); + } +}); + +it('keeps the unwrapped action wire bytes with the new capability header', async () => { + const loader = vi.fn(() => ({ fresh: true })); + const action = vi.fn(() => ({ discarded: true })); + const request = async (capability: Record) => { + const c = await createTestContext('POST', '/legacy', { + headers: { + 'X-VoidPages': 'true', + 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION, + ...capability, + }, + }); + const response = await handlePageMutation( + action, + loader, + undefined, + c, + 'legacy', + mockRenderFn, + mockGetAssetTags, + ); + return { status: response.status, headers: [...response.headers], body: await response.text() }; + }; + const legacy = await request({}); + const advertised = await request({ 'X-VoidPages-Action-Result': '/legacy' }); + expect(advertised).toEqual(legacy); + expect(advertised.status).toBe(200); + expect(advertised.headers).toEqual([ + ['content-type', 'application/json'], + ['vary', 'X-VoidPages, X-VoidPages-Version'], + ['x-powered-by', 'Void'], + ['x-voidpages', 'true'], + ['x-voidpages-version', PAGES_PROTOCOL_VERSION], + ]); + expect(advertised.body).toBe( + serializePageData({ + component: 'legacy', + props: { fresh: true }, + params: {}, + shared: {}, + url: '/legacy', + errors: null, + }), + ); + expect(action).toHaveBeenCalledTimes(2); + expect(loader).toHaveBeenCalledTimes(2); +}); From b7554ab9e690ad9ee25fdd7a12059284a4e5241c Mon Sep 17 00:00:00 2001 From: Yunfei He Date: Fri, 4 Dec 2026 17:09:58 +0800 Subject: [PATCH 2/5] feat(pages): bound action result negotiation and preserve its media type --- packages/edge/src/headers.ts | 5 +- .../test/unit/page-action-result.test.ts | 3 +- packages/void/package.json | 1 + packages/void/src/pages/action-key.ts | 8 ++ packages/void/src/pages/navigation-engine.ts | 20 +-- packages/void/src/pages/protocol.ts | 23 ++-- packages/void/src/runtime/routing/index.ts | 4 + packages/void/test/unit/pages-client.test.ts | 120 +++++++++++++++++- .../void/test/unit/pages-protocol.test.ts | 13 +- pnpm-lock.yaml | 3 + 10 files changed, 171 insertions(+), 29 deletions(-) diff --git a/packages/edge/src/headers.ts b/packages/edge/src/headers.ts index a3f6be7fca..e9b01e6fef 100644 --- a/packages/edge/src/headers.ts +++ b/packages/edge/src/headers.ts @@ -1,5 +1,5 @@ import type { HeaderRule } from '@void/deploy-core'; -import { protectPageActionResultCache } from './pages-protocol.ts'; +import { isPageActionResult, protectPageActionResultCache } from './pages-protocol.ts'; import { matchLiteralPattern } from './pattern.ts'; export type { HeaderRule } from '@void/deploy-core'; @@ -163,6 +163,9 @@ export function applyHeaderRules( rawOriginClearSiteData === null ? null : sanitizeClearSiteData(rawOriginClearSiteData); for (const [name, value] of matched) { const lowerName = name.toLowerCase(); + if (lowerName === 'content-type' && isPageActionResult(response.headers)) { + continue; + } if (isolateSharedDomainCookies && BLOCKED_HEADERS.has(lowerName)) { continue; } diff --git a/packages/react/test/unit/page-action-result.test.ts b/packages/react/test/unit/page-action-result.test.ts index ef4d130d7f..19b04d88d3 100644 --- a/packages/react/test/unit/page-action-result.test.ts +++ b/packages/react/test/unit/page-action-result.test.ts @@ -1,5 +1,6 @@ // @vitest-environment happy-dom +import { createHash } from 'node:crypto'; import { act, createElement, useState } from 'react'; import { afterEach, expect, it, vi } from 'vite-plus/test'; import { action } from '../../src/runtime/action.ts'; @@ -29,7 +30,7 @@ it('settles a result-only action at the React shell without committing another p new Response('[{"result":1},"saved"]', { headers: { 'Content-Type': 'application/vnd.void.action-result+json', - 'X-VoidPages-Action-Result': '/react-preview', + 'X-VoidPages-Action-Result': createHash('sha256').update('/react-preview').digest('hex'), }, }), ); diff --git a/packages/void/package.json b/packages/void/package.json index a4733bf90d..0a9c52a9bb 100644 --- a/packages/void/package.json +++ b/packages/void/package.json @@ -393,6 +393,7 @@ "@cloudflare/workers-types": "catalog:", "@cloudflare/workers-utils": "catalog:", "@napi-rs/keyring": "catalog:", + "@noble/hashes": "^2.4.0", "@void/deploy-cloudflare": "workspace:*", "@void/deploy-core": "workspace:*", "@void/edge": "workspace:*", diff --git a/packages/void/src/pages/action-key.ts b/packages/void/src/pages/action-key.ts index d05b307dc6..58f1132957 100644 --- a/packages/void/src/pages/action-key.ts +++ b/packages/void/src/pages/action-key.ts @@ -1,3 +1,6 @@ +import { sha256 } from '@noble/hashes/sha2.js'; +import { bytesToHex } from '@noble/hashes/utils.js'; + // On a page with named actions, the first query key selects the action // (`/books?delete&page=2`). It addresses the action, not the page, so the page // URL, history and c.redirect() leave it out. @@ -43,6 +46,11 @@ export function searchWithoutActionKey(search: string): string { */ export const PRESERVED_QUERY_HEADER = 'X-VoidPages-Preserved-Query'; +/** Identifies the concrete action target with a fixed-size header value. */ +export function pageActionTargetId(url: URL): string { + return bytesToHex(sha256(new TextEncoder().encode(url.pathname + url.search))); +} + export function queryKey(segment: string): string | undefined { return new URLSearchParams(segment).keys().next().value; } diff --git a/packages/void/src/pages/navigation-engine.ts b/packages/void/src/pages/navigation-engine.ts index 636bf39aec..39d480ddb4 100644 --- a/packages/void/src/pages/navigation-engine.ts +++ b/packages/void/src/pages/navigation-engine.ts @@ -9,7 +9,11 @@ import { PAGES_PROTOCOL_VERSION, } from '@void/edge'; import { parse } from 'devalue'; -import { PRESERVED_QUERY_HEADER, searchWithoutActionKey } from './action-key.ts'; +import { + pageActionTargetId, + 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'; @@ -845,10 +849,10 @@ export async function createPageNavigationEngine( if (options._preservedQuery && method !== 'GET') { headers[PRESERVED_QUERY_HEADER] = options._preservedQuery; } - const actionTarget = - options._onActionResult && method !== 'GET' ? target.pathname + target.search : undefined; - if (actionTarget) { - headers[PAGE_ACTION_RESULT_HEADER] = actionTarget; + const actionTargetId = + options._onActionResult && method !== 'GET' ? pageActionTargetId(target) : undefined; + if (actionTargetId) { + headers[PAGE_ACTION_RESULT_HEADER] = actionTargetId; } const fetchOptions: PageFetchOptions = { method, headers, signal }; @@ -992,13 +996,13 @@ export async function createPageNavigationEngine( if ( response?.ok && options._onActionResult && - actionTarget && + actionTargetId && isPageActionResult(response.headers) ) { signal.throwIfAborted(); if ( - response.headers.get(PAGE_ACTION_RESULT_HEADER) === actionTarget && - (!fetched?.redirectedTo || fetchUrl === actionTarget) + response.headers.get(PAGE_ACTION_RESULT_HEADER) === actionTargetId && + (!fetched?.redirectedTo || fetchUrl === target.pathname + target.search) ) { const text = await response.text(); signal.throwIfAborted(); diff --git a/packages/void/src/pages/protocol.ts b/packages/void/src/pages/protocol.ts index b752d356d7..b0efd325d8 100644 --- a/packages/void/src/pages/protocol.ts +++ b/packages/void/src/pages/protocol.ts @@ -15,7 +15,7 @@ import type { HandlerLeaf, LoaderValidationOptions } from '../runtime/handler/co import type { CloudBindings, CloudContext } from '../runtime/handler/index.ts'; import { isConvertedResponse } from '../runtime/handler/response.ts'; import type { StandardSchemaV1 } from '../standard-schema.ts'; -import { hasActionKey, searchWithoutActionKey } from './action-key.ts'; +import { hasActionKey, pageActionTargetId, searchWithoutActionKey } from './action-key.ts'; import { pagesBuildId } from './build-id.ts'; import { DEFERRED, separateDeferred } from './defer.ts'; import type { ResolvedDeferredGroup } from './defer.ts'; @@ -1198,21 +1198,20 @@ async function runPageMutation( return new Response('Cross-origin page actions are not allowed.', { status: 403 }); } const renderMode = options?.renderMode ?? 'server'; - let resultTarget: string | undefined; + // Rewrites and HTTP redirects can forward the original capability header. + const requestedTargetId = c.req.header(PAGE_ACTION_RESULT_HEADER); + let resultTargetId: string | undefined; if ( + requestedTargetId && renderMode !== 'island' && mutationHandler && '__pageActionResult' in mutationHandler && mutationHandler.__pageActionResult === true && isPagesRequest(c) && - !needsPageReload(c) + !needsPageReload(c) && + requestedTargetId === pageActionTargetId(new URL(c.req.url)) ) { - // Rewrites and HTTP redirects can forward the original capability header. - const resolved = new URL(c.req.url); - const target = resolved.pathname + resolved.search; - if (c.req.header(PAGE_ACTION_RESULT_HEADER) === target) { - resultTarget = target; - } + resultTargetId = requestedTargetId; } function buildMutationPageObj( @@ -1285,7 +1284,7 @@ async function runPageMutation( } function respondWithErrors(errors: Record): Promise { - if (resultTarget !== undefined) { + if (resultTargetId !== undefined) { return Promise.resolve(legacyPageResponse(c, errors)); } if (renderMode === 'island') { @@ -1328,10 +1327,10 @@ async function runPageMutation( if (status !== 204) { return result; } - } else if (resultTarget !== undefined) { + } else if (resultTargetId !== undefined) { const headers = pageResponseHeaders(c, { 'Content-Type': PAGE_ACTION_RESULT_TYPE, - [PAGE_ACTION_RESULT_HEADER]: resultTarget, + [PAGE_ACTION_RESULT_HEADER]: resultTargetId, }); headers.delete('X-VoidPages'); protectPageActionResultCache(headers); diff --git a/packages/void/src/runtime/routing/index.ts b/packages/void/src/runtime/routing/index.ts index d80e3a1d2c..5911d3e270 100644 --- a/packages/void/src/runtime/routing/index.ts +++ b/packages/void/src/runtime/routing/index.ts @@ -1,6 +1,7 @@ import { AsyncLocalStorage } from 'node:async_hooks'; import { compilePattern, + isPageActionResult, matchPattern, matchPatternCaptures, mergeQueryIntoLocation, @@ -456,6 +457,9 @@ export function createRoutingRuntime( } const asset = isUnchangedStaticAsset(c); for (const [key, [name, value]] of last) { + if (key === 'content-type' && isPageActionResult(c.res.headers)) { + continue; + } if ( protectCache && (key === 'cache-control' || key === 'pragma' || SHARED_CACHE_HEADERS.includes(key)) diff --git a/packages/void/test/unit/pages-client.test.ts b/packages/void/test/unit/pages-client.test.ts index cf06e9fee7..359e3a757c 100644 --- a/packages/void/test/unit/pages-client.test.ts +++ b/packages/void/test/unit/pages-client.test.ts @@ -1,7 +1,11 @@ +import { createHash } from 'node:crypto'; +import { once } from 'node:events'; +import { createServer } from 'node:http'; import { Hono } from 'hono'; import { matchedRoutes } from 'hono/route'; import { afterEach, describe, expect, it, vi } from 'vite-plus/test'; import type { RouteDestination } from 'void/routes'; +import { applyHeaderRules } from '../../../edge/src/headers.ts'; import { PAGES_PROTOCOL_VERSION } from '../../../edge/src/pages-protocol.ts'; import { createActionClient, @@ -22,6 +26,7 @@ import { parseCacheFor } from '../../src/pages/prefetch.ts'; import { ValidationError } from '../../src/pages/protocol.ts'; import { decodePageData, serializePageData } from '../../src/pages/serialize.ts'; import type { PageDefinition } from '../../src/pages/types.ts'; +import { defineHandler, definePageAction } from '../../src/runtime/handler/index.ts'; import type { CloudContext } from '../../src/runtime/handler/index.ts'; import { createPageGetHandler, @@ -3361,6 +3366,113 @@ describe('superseded navigation commits (#507)', () => { }); }); +it('sends long preserved action queries within the Node HTTP header limit', async () => { + stubClientGlobals(); + const path = '/preview/2'; + const query = `search=${'a'.repeat(6000)}&tag=a%20b&tag=c+d`; + const pageUrl = `${path}?${query}`; + window.location.pathname = path; + window.location.search = `?${query}`; + const page = { component: 'home', props: { fresh: true }, errors: null, url: pageUrl }; + const requests: Array<{ + url: string | undefined; + preserved: string | Array | undefined; + }> = []; + const server = createServer((request, response) => { + requests.push({ url: request.url, preserved: request.headers['x-voidpages-preserved-query'] }); + response.writeHead(200, { 'X-VoidPages': 'true', 'Content-Type': 'application/json' }); + response.end(JSON.stringify(page)); + }); + server.listen(0, '127.0.0.1'); + try { + await once(server, 'listening'); + const address = server.address(); + if (!address || typeof address === 'string') { + throw new Error('Expected a TCP server address'); + } + const fetch = globalThis.fetch; + vi.stubGlobal('fetch', async (url: string, init: RequestInit) => { + const response = await fetch(`http://127.0.0.1:${address.port}${url}`, init); + expect(response.status).toBe(200); + return response; + }); + const { router } = await createTestRouter(); + const { action, setActionRouter } = createActionClient(); + setActionRouter(router); + expect(await action('/preview/[id]?save', { params: { id: '2' } })).toMatchObject({ + ok: true, + pageData: page, + }); + expect(requests).toEqual([{ url: `${path}?save&${query}`, preserved: query }]); + expect(router.url.pathname + router.url.search).toBe(pageUrl); + } finally { + await new Promise((resolve, reject) => { + server.close((error) => (error ? reject(error) : resolve())); + }); + } +}); + +it.each(['native', 'hosted'] as const)( + 'preserves the action result content type through %s header rules', + async (runtimeKind) => { + stubClientGlobals(); + const path = '/preview/2'; + const ruleHeaders: Array<[string, string]> = [ + ['content-type', 'application/json'], + ['X-Rule', 'applied'], + ]; + const rules = [{ pattern: path, headers: ruleHeaders }]; + const loader = vi.fn(() => ({ fresh: true })); + const app = new Hono(); + const runtime = createRoutingRuntime(app, { nodeTarget: true }); + app.use(runtime.contextMiddleware); + if (runtimeKind === 'native') { + app.use(runtime.headerMiddleware(rules)); + } + app.post( + path, + createPageMutationHandler({ + componentId: 'home', + namedActions: true, + load: async () => ({ + actions: { + save: definePageAction( + defineHandler(() => 42), + { reload: false }, + ), + }, + loader, + }), + render: async () => '', + assets: async () => ({ css: '', body: '', preloads: '' }), + headConfig: undefined, + renderOptions: {}, + }), + ); + vi.stubGlobal('fetch', async (url: string, init: RequestInit) => { + const originResponse = await app.fetch( + new Request(new URL(url, window.location.origin), init), + ); + const response = + runtimeKind === 'hosted' ? applyHeaderRules(originResponse, path, rules) : originResponse; + expect(response.headers.get('X-Rule')).toBe('applied'); + return response; + }); + const applyUpdate = vi.fn(); + const { router } = await createTestRouter({ adapter: { applyUpdate } }); + const { action, setActionRouter } = createActionClient(); + setActionRouter(router); + expect(await action('/preview/[id]?save', { params: { id: '2' } })).toEqual({ + ok: true, + result: 42, + pageData: undefined, + }); + expect(loader).not.toHaveBeenCalled(); + expect(applyUpdate).not.toHaveBeenCalled(); + expect(window.location.href).toBeUndefined(); + }, +); + it('settles result-only actions without a page commit and preserves newer visits', async () => { stubClientGlobals(); const resultHeader = 'X-VoidPages-Action-Result'; @@ -3368,7 +3480,8 @@ it('settles result-only actions without a page commit and preserves newer visits window.location.pathname = '/preview/2'; window.location.search = '?tab=profile'; const target = '/preview/2?save&tab=profile'; - const payload = (text: string, echo = target) => + const targetId = createHash('sha256').update(target).digest('hex'); + const payload = (text: string, echo = targetId) => new Response(text, { headers: { 'Content-Type': resultType, [resultHeader]: echo } }); const applyUpdate = vi.fn(); const { router } = await createTestRouter({ adapter: { applyUpdate } }); @@ -3381,7 +3494,7 @@ it('settles result-only actions without a page commit and preserves newer visits fetch.mockResolvedValueOnce(payload('[{"result":1},42]')); expect(await preview()).toEqual({ ok: true, result: 42, pageData: undefined }); - expect(new Headers(fetch.mock.calls[0][1].headers).get(resultHeader)).toBe(target); + expect(new Headers(fetch.mock.calls[0][1].headers).get(resultHeader)).toBe(targetId); expect(router.url.pathname + router.url.search).toBe('/preview/2?tab=profile'); expect(window.location.href).toBeUndefined(); expect(history.pushState).not.toHaveBeenCalled(); @@ -3423,7 +3536,8 @@ it('settles result-only actions without a page commit and preserves newer visits await submitIslandAction('/preview/2?save', 'POST', {}); expect(new Headers(fetch.mock.lastCall?.[1].headers).has(resultHeader)).toBe(false); - fetch.mockResolvedValueOnce(payload('[{"result":1},42]', '/other?save')); + const otherTargetId = createHash('sha256').update('/other?save').digest('hex'); + fetch.mockResolvedValueOnce(payload('[{"result":1},42]', otherTargetId)); expect(await preview()).toEqual({ ok: true, pageData: undefined, diff --git a/packages/void/test/unit/pages-protocol.test.ts b/packages/void/test/unit/pages-protocol.test.ts index 1395ae84ac..3eb419f64a 100644 --- a/packages/void/test/unit/pages-protocol.test.ts +++ b/packages/void/test/unit/pages-protocol.test.ts @@ -1,3 +1,4 @@ +import { createHash } from 'node:crypto'; import { parse } from 'devalue'; import { Hono } from 'hono'; import { HTTPException } from 'hono/http-exception'; @@ -29,6 +30,10 @@ import { } from '../../src/runtime/routing/pages.ts'; import type { StandardSchemaV1 } from '../../src/standard-schema.ts'; +function actionTargetId(target: string): string { + return createHash('sha256').update(target).digest('hex'); +} + type RenderPage = { component: string }; type PageResponse = { component: string; @@ -2243,14 +2248,14 @@ it('negotiates result-only page actions on the resolved target', async () => { 'Content-Type': 'application/json', ...headers, Authorization: 'test', - ...(capability && { [resultHeader]: capability }), + ...(capability && { [resultHeader]: actionTargetId(capability) }), ...extra, }, }); const reply = await post(target); expect(reply.headers.get('Content-Type')).toBe(resultType); - expect(reply.headers.get(resultHeader)).toBe(target); + expect(reply.headers.get(resultHeader)).toBe(actionTargetId(target)); expect(reply.headers.get('X-VoidPages')).toBeNull(); expect(reply.headers.getSetCookie()).toEqual(['action=ran; Path=/']); expect(reply.headers.get('Cache-Control')).toBe('no-store'); @@ -2329,7 +2334,7 @@ it('negotiates result-only page actions on the resolved target', async () => { const url = '/redirect/' + status; const { response, method } = await fetchPages(url, { method: 'POST', - headers: { ...headers, Authorization: 'test', [resultHeader]: url }, + headers: { ...headers, Authorization: 'test', [resultHeader]: actionTargetId(url) }, }); expect(method).toBe(status === 303 ? 'GET' : 'POST'); expect(new Headers(fetch.mock.calls[1][1].headers).has(resultHeader)).toBe(false); @@ -2365,7 +2370,7 @@ it('keeps the unwrapped action wire bytes with the new capability header', async return { status: response.status, headers: [...response.headers], body: await response.text() }; }; const legacy = await request({}); - const advertised = await request({ 'X-VoidPages-Action-Result': '/legacy' }); + const advertised = await request({ 'X-VoidPages-Action-Result': actionTargetId('/legacy') }); expect(advertised).toEqual(legacy); expect(advertised.status).toBe(200); expect(advertised.headers).toEqual([ diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e9680f5555..9c3540e8f8 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -843,6 +843,9 @@ importers: '@napi-rs/keyring': specifier: 'catalog:' version: 2.1.2 + '@noble/hashes': + specifier: ^2.4.0 + version: 2.4.0 '@void/deploy-cloudflare': specifier: workspace:* version: link:../deploy-cloudflare From ba2ead262aef7bd8aa6f27b56b96d5e940071ba6 Mon Sep 17 00:00:00 2001 From: Yunfei He Date: Fri, 4 Dec 2026 17:20:09 +0800 Subject: [PATCH 3/5] feat(pages): use FNV-1a for action target IDs --- .../react/test/unit/page-action-result.test.ts | 6 ++++-- packages/void/package.json | 1 - packages/void/src/pages/action-key.ts | 17 ++++++++++++----- packages/void/test/unit/pages-client.test.ts | 7 ++++--- packages/void/test/unit/pages-protocol.test.ts | 5 ++--- pnpm-lock.yaml | 3 --- 6 files changed, 22 insertions(+), 17 deletions(-) diff --git a/packages/react/test/unit/page-action-result.test.ts b/packages/react/test/unit/page-action-result.test.ts index 19b04d88d3..340fac4570 100644 --- a/packages/react/test/unit/page-action-result.test.ts +++ b/packages/react/test/unit/page-action-result.test.ts @@ -1,8 +1,8 @@ // @vitest-environment happy-dom -import { createHash } from 'node:crypto'; import { act, createElement, useState } from 'react'; import { afterEach, expect, it, vi } from 'vite-plus/test'; +import { pageActionTargetId } from '../../../void/src/pages/action-key.ts'; import { action } from '../../src/runtime/action.ts'; import { startReactPages } from '../../src/runtime/pages-client.ts'; @@ -30,7 +30,9 @@ it('settles a result-only action at the React shell without committing another p new Response('[{"result":1},"saved"]', { headers: { 'Content-Type': 'application/vnd.void.action-result+json', - 'X-VoidPages-Action-Result': createHash('sha256').update('/react-preview').digest('hex'), + 'X-VoidPages-Action-Result': pageActionTargetId( + new URL('/react-preview', location.origin), + ), }, }), ); diff --git a/packages/void/package.json b/packages/void/package.json index 0a9c52a9bb..a4733bf90d 100644 --- a/packages/void/package.json +++ b/packages/void/package.json @@ -393,7 +393,6 @@ "@cloudflare/workers-types": "catalog:", "@cloudflare/workers-utils": "catalog:", "@napi-rs/keyring": "catalog:", - "@noble/hashes": "^2.4.0", "@void/deploy-cloudflare": "workspace:*", "@void/deploy-core": "workspace:*", "@void/edge": "workspace:*", diff --git a/packages/void/src/pages/action-key.ts b/packages/void/src/pages/action-key.ts index 58f1132957..f156090d99 100644 --- a/packages/void/src/pages/action-key.ts +++ b/packages/void/src/pages/action-key.ts @@ -1,6 +1,3 @@ -import { sha256 } from '@noble/hashes/sha2.js'; -import { bytesToHex } from '@noble/hashes/utils.js'; - // On a page with named actions, the first query key selects the action // (`/books?delete&page=2`). It addresses the action, not the page, so the page // URL, history and c.redirect() leave it out. @@ -46,9 +43,19 @@ export function searchWithoutActionKey(search: string): string { */ export const PRESERVED_QUERY_HEADER = 'X-VoidPages-Preserved-Query'; -/** Identifies the concrete action target with a fixed-size header value. */ +/** A fixed-size FNV-1a identity check for the concrete action target, not a security boundary. */ export function pageActionTargetId(url: URL): string { - return bytesToHex(sha256(new TextEncoder().encode(url.pathname + url.search))); + const target = url.pathname + url.search; + let high = 0xcb_f2_9c_e4; + let low = 0x84_22_23_25; + for (let index = 0; index < target.length; index++) { + low = (low ^ target.charCodeAt(index)) >>> 0; + // Multiply by the FNV prime (2^40 + 435), carrying from the low word. + const lowProduct = low * 435; + high = (Math.imul(high, 435) + (low << 8) + Math.floor(lowProduct / 2 ** 32)) >>> 0; + low = lowProduct >>> 0; + } + return high.toString(16).padStart(8, '0') + low.toString(16).padStart(8, '0'); } export function queryKey(segment: string): string | undefined { diff --git a/packages/void/test/unit/pages-client.test.ts b/packages/void/test/unit/pages-client.test.ts index 359e3a757c..c7e6e49913 100644 --- a/packages/void/test/unit/pages-client.test.ts +++ b/packages/void/test/unit/pages-client.test.ts @@ -1,4 +1,3 @@ -import { createHash } from 'node:crypto'; import { once } from 'node:events'; import { createServer } from 'node:http'; import { Hono } from 'hono'; @@ -7,6 +6,7 @@ import { afterEach, describe, expect, it, vi } from 'vite-plus/test'; import type { RouteDestination } from 'void/routes'; import { applyHeaderRules } from '../../../edge/src/headers.ts'; import { PAGES_PROTOCOL_VERSION } from '../../../edge/src/pages-protocol.ts'; +import { pageActionTargetId } from '../../src/pages/action-key.ts'; import { createActionClient, createRouterFacade, @@ -3480,7 +3480,8 @@ it('settles result-only actions without a page commit and preserves newer visits window.location.pathname = '/preview/2'; window.location.search = '?tab=profile'; const target = '/preview/2?save&tab=profile'; - const targetId = createHash('sha256').update(target).digest('hex'); + const targetId = pageActionTargetId(new URL(target, window.location.origin)); + expect(targetId).toMatch(/^[0-9a-f]{16}$/); const payload = (text: string, echo = targetId) => new Response(text, { headers: { 'Content-Type': resultType, [resultHeader]: echo } }); const applyUpdate = vi.fn(); @@ -3536,7 +3537,7 @@ it('settles result-only actions without a page commit and preserves newer visits await submitIslandAction('/preview/2?save', 'POST', {}); expect(new Headers(fetch.mock.lastCall?.[1].headers).has(resultHeader)).toBe(false); - const otherTargetId = createHash('sha256').update('/other?save').digest('hex'); + const otherTargetId = pageActionTargetId(new URL('/other?save', window.location.origin)); fetch.mockResolvedValueOnce(payload('[{"result":1},42]', otherTargetId)); expect(await preview()).toEqual({ ok: true, diff --git a/packages/void/test/unit/pages-protocol.test.ts b/packages/void/test/unit/pages-protocol.test.ts index 3eb419f64a..0cba626a33 100644 --- a/packages/void/test/unit/pages-protocol.test.ts +++ b/packages/void/test/unit/pages-protocol.test.ts @@ -1,11 +1,10 @@ -import { createHash } from 'node:crypto'; import { parse } from 'devalue'; import { Hono } from 'hono'; import { HTTPException } from 'hono/http-exception'; import { describe, expect, it, vi, afterEach } from 'vite-plus/test'; import { applyHeaderRules } from '../../../edge/src/headers.ts'; import { PAGES_PROTOCOL_VERSION } from '../../../edge/src/pages-protocol.ts'; -import { markActionKey } from '../../src/pages/action-key.ts'; +import { markActionKey, pageActionTargetId } from '../../src/pages/action-key.ts'; import { defer } from '../../src/pages/defer.ts'; import { handlePageGet, @@ -31,7 +30,7 @@ import { import type { StandardSchemaV1 } from '../../src/standard-schema.ts'; function actionTargetId(target: string): string { - return createHash('sha256').update(target).digest('hex'); + return pageActionTargetId(new URL(target, 'http://localhost')); } type RenderPage = { component: string }; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9c3540e8f8..e9680f5555 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -843,9 +843,6 @@ importers: '@napi-rs/keyring': specifier: 'catalog:' version: 2.1.2 - '@noble/hashes': - specifier: ^2.4.0 - version: 2.4.0 '@void/deploy-cloudflare': specifier: workspace:* version: link:../deploy-cloudflare From 449c574ab4ee4efcc8c1c30e3567b8226385a1b1 Mon Sep 17 00:00:00 2001 From: Yunfei He Date: Fri, 4 Dec 2026 17:38:28 +0800 Subject: [PATCH 4/5] feat(pages): align action result types and preserve validation JSON --- packages/edge/src/headers.ts | 7 +- packages/edge/src/index.ts | 2 + packages/edge/src/pages-protocol.ts | 11 +++ packages/void/src/codegen/route-types.ts | 11 +-- packages/void/src/pages/protocol.ts | 5 +- packages/void/src/routes-stub.ts | 11 +-- packages/void/src/runtime/routing/index.ts | 4 +- .../page-action-types-typecheck.test.ts | 22 +++++- .../void/test/unit/pages-protocol.test.ts | 75 ++++++++++++++++++- 9 files changed, 124 insertions(+), 24 deletions(-) diff --git a/packages/edge/src/headers.ts b/packages/edge/src/headers.ts index e9b01e6fef..190327efac 100644 --- a/packages/edge/src/headers.ts +++ b/packages/edge/src/headers.ts @@ -1,5 +1,8 @@ import type { HeaderRule } from '@void/deploy-core'; -import { isPageActionResult, protectPageActionResultCache } from './pages-protocol.ts'; +import { + hasProtectedPageActionContentType, + protectPageActionResultCache, +} from './pages-protocol.ts'; import { matchLiteralPattern } from './pattern.ts'; export type { HeaderRule } from '@void/deploy-core'; @@ -163,7 +166,7 @@ export function applyHeaderRules( rawOriginClearSiteData === null ? null : sanitizeClearSiteData(rawOriginClearSiteData); for (const [name, value] of matched) { const lowerName = name.toLowerCase(); - if (lowerName === 'content-type' && isPageActionResult(response.headers)) { + if (lowerName === 'content-type' && hasProtectedPageActionContentType(response)) { continue; } if (isolateSharedDomainCookies && BLOCKED_HEADERS.has(lowerName)) { diff --git a/packages/edge/src/index.ts b/packages/edge/src/index.ts index 820273138b..09e074a5cb 100644 --- a/packages/edge/src/index.ts +++ b/packages/edge/src/index.ts @@ -1,11 +1,13 @@ export type { ProjectZeroTrustRouting } from './access.ts'; export { buildHeaders, + hasProtectedPageActionContentType, isPageActionResult, isStaleBuild, isStaleBuildReload, PAGE_ACTION_RESULT_HEADER, PAGE_ACTION_RESULT_TYPE, + PAGE_ACTION_VALIDATION_HEADER, pagesPayloadFitsBuild, PAGES_BUILD_HEADER, PAGES_PROTOCOL_VERSION, diff --git a/packages/edge/src/pages-protocol.ts b/packages/edge/src/pages-protocol.ts index 993209c71e..dcbd373736 100644 --- a/packages/edge/src/pages-protocol.ts +++ b/packages/edge/src/pages-protocol.ts @@ -10,12 +10,23 @@ export const PAGES_BUILD_HEADER = 'X-VoidPages-Build'; export const PAGE_ACTION_RESULT_HEADER = 'X-VoidPages-Action-Result'; export const PAGE_ACTION_RESULT_TYPE = 'application/vnd.void.action-result+json'; +export const PAGE_ACTION_VALIDATION_HEADER = 'X-VoidPages-Action-Validation'; export function isPageActionResult(headers: Headers): boolean { const type = headers.get('Content-Type')?.split(';', 1)[0]?.trim().toLowerCase(); return type === PAGE_ACTION_RESULT_TYPE; } +export function hasProtectedPageActionContentType(response: Response): boolean { + const { headers, status } = response; + return ( + isPageActionResult(headers) || + (status === 422 && + headers.get(PAGE_ACTION_VALIDATION_HEADER) === 'true' && + headers.get('Content-Type') === 'application/json') + ); +} + /** Header rules can replace the media type while the body still carries the result. */ export function protectPageActionResultCache(headers: Headers, original: Headers = headers): void { if (!original.has(PAGE_ACTION_RESULT_HEADER) && !isPageActionResult(original)) { diff --git a/packages/void/src/codegen/route-types.ts b/packages/void/src/codegen/route-types.ts index 0e6a8710d9..1c3042275d 100644 --- a/packages/void/src/codegen/route-types.ts +++ b/packages/void/src/codegen/route-types.ts @@ -457,14 +457,11 @@ export function generateRouteTypes( '', ' type PageActionValue = A extends { result: infer R } ? R : undefined;', '', - ' type PageActionValueFor = [K] extends [never]', - ' ? P extends { body: unknown }', - ' ? PageActionValue

', - ' : never', + // Single actions ignore the selector. Named actions use "default" when it is absent. + ' type PageActionValueFor = P extends { body: unknown }', + ' ? PageActionValue

', ' : P extends { actions: infer A }', - ' ? K extends keyof A', - ' ? PageActionValue', - ' : never', + ' ? PageActionValue]>', ' : never;', '', ' export type ResolveActionResult = U extends unknown', diff --git a/packages/void/src/pages/protocol.ts b/packages/void/src/pages/protocol.ts index b0efd325d8..877beffdcd 100644 --- a/packages/void/src/pages/protocol.ts +++ b/packages/void/src/pages/protocol.ts @@ -3,6 +3,7 @@ import { isStaleBuild, PAGE_ACTION_RESULT_HEADER, PAGE_ACTION_RESULT_TYPE, + PAGE_ACTION_VALIDATION_HEADER, PAGES_BUILD_HEADER, PAGES_PROTOCOL_VERSION, protectPageActionResultCache, @@ -1285,7 +1286,9 @@ async function runPageMutation( function respondWithErrors(errors: Record): Promise { if (resultTargetId !== undefined) { - return Promise.resolve(legacyPageResponse(c, errors)); + const response = legacyPageResponse(c, errors); + response.headers.set(PAGE_ACTION_VALIDATION_HEADER, 'true'); + return Promise.resolve(response); } if (renderMode === 'island') { return Promise.resolve(Response.json({ errors }, { status: 422 })); diff --git a/packages/void/src/routes-stub.ts b/packages/void/src/routes-stub.ts index 84d14d3b80..3066b4b62d 100644 --- a/packages/void/src/routes-stub.ts +++ b/packages/void/src/routes-stub.ts @@ -112,14 +112,11 @@ export type ResolveActionBody = type PageActionValue = A extends { result: infer R } ? R : undefined; -type PageActionValueFor = [K] extends [never] - ? P extends { body: unknown } - ? PageActionValue

- : never +// Single actions ignore the selector. Named actions use "default" when it is absent. +type PageActionValueFor = P extends { body: unknown } + ? PageActionValue

: P extends { actions: infer A } - ? K extends keyof A - ? PageActionValue - : never + ? PageActionValue]> : never; export type ResolveActionResult = U extends unknown diff --git a/packages/void/src/runtime/routing/index.ts b/packages/void/src/runtime/routing/index.ts index 5911d3e270..6a16bcccaf 100644 --- a/packages/void/src/runtime/routing/index.ts +++ b/packages/void/src/runtime/routing/index.ts @@ -1,7 +1,7 @@ import { AsyncLocalStorage } from 'node:async_hooks'; import { compilePattern, - isPageActionResult, + hasProtectedPageActionContentType, matchPattern, matchPatternCaptures, mergeQueryIntoLocation, @@ -457,7 +457,7 @@ export function createRoutingRuntime( } const asset = isUnchangedStaticAsset(c); for (const [key, [name, value]] of last) { - if (key === 'content-type' && isPageActionResult(c.res.headers)) { + if (key === 'content-type' && hasProtectedPageActionContentType(c.res)) { continue; } if ( diff --git a/packages/void/test/integration/page-action-types-typecheck.test.ts b/packages/void/test/integration/page-action-types-typecheck.test.ts index 1aa382a12d..c531ec6932 100644 --- a/packages/void/test/integration/page-action-types-typecheck.test.ts +++ b/packages/void/test/integration/page-action-types-typecheck.test.ts @@ -73,6 +73,7 @@ async function typecheck( '@void/react': [join(voidDist, '../../react/dist/index.d.mts')], // Shipped helper aliases must not hide defects in the generated helpers. 'void/routes': [join(root, 'routes-base.d.ts')], + 'routes-stub': [join(voidDist, 'routes-stub.d.mts')], }, }, files: ['.void/routes.d.ts', 'check.ts'], @@ -226,12 +227,25 @@ export const actions = { };`, 'check.ts': [ "import { action } from '@void/react';", + "import type { PageActionMap as GeneratedActions, ResolveActionResult } from 'void/routes';", + "import type { ResolveActionResult as StubResult } from 'routes-stub';", + "declare module 'routes-stub' { interface PageActionMap extends GeneratedActions {} }", + 'type Equal = (() => T extends A ? 1 : 2) extends (() => T extends B ? 1 : 2) ? true : false;', + 'type Assert = T;', + 'type Single = { total: bigint };', + `type Default = ${environment === 'dev' ? 'Single' : environment === 'prod' ? 'Date' : 'Single | Date'};`, + "type GeneratedBare = Assert, Default>>;", + "type GeneratedEmptyQuery = Assert, Default>>;", + "type StubBare = Assert, Default>>;", + "type StubEmptyQuery = Assert, Default>>;", + "type StubNamed = Assert, Default>>;", + `type Unlisted = Assert, ${environment === 'prod' ? 'never' : 'Single'}>>;`, 'const params = { id: "1" };', 'const data = { title: "draft" };', ...(environment !== 'prod' ? [ "const single = await action('/items/[id]', { params, data });", - 'if (single.ok) { const value: { total: bigint } | undefined = single.result; single.result?.total; }', + 'if (single.ok) { type Result = Assert>; }', '// @ts-expect-error validator body is still checked', "await action('/items/[id]', { params, data: { title: 42 } });", ] @@ -239,11 +253,11 @@ export const actions = { ...(environment !== 'dev' ? [ "const named = await action('/items/[id]?default&tab=profile', { params, data });", - 'if (named.ok) { const value: Date | undefined = named.result; named.result?.getTime(); }', + 'if (named.ok) { type Result = Assert>; }', "const empty = await action('/items/[id]?empty', { params });", - 'if (empty.ok) { const value: void = empty.result; }', + `if (empty.ok) { type Result = Assert>; }`, "const unwrapped = await action('/items/[id]?unwrapped', { params });", - 'if (unwrapped.ok) { const value: undefined = unwrapped.result; }', + `if (unwrapped.ok) { type Result = Assert>; }`, '// @ts-expect-error the route requires params', "await action('/items/[id]?default', { data });", ] diff --git a/packages/void/test/unit/pages-protocol.test.ts b/packages/void/test/unit/pages-protocol.test.ts index 0cba626a33..10b968ba09 100644 --- a/packages/void/test/unit/pages-protocol.test.ts +++ b/packages/void/test/unit/pages-protocol.test.ts @@ -3,8 +3,12 @@ import { Hono } from 'hono'; import { HTTPException } from 'hono/http-exception'; import { describe, expect, it, vi, afterEach } from 'vite-plus/test'; import { applyHeaderRules } from '../../../edge/src/headers.ts'; -import { PAGES_PROTOCOL_VERSION } from '../../../edge/src/pages-protocol.ts'; +import { + PAGE_ACTION_RESULT_HEADER, + PAGES_PROTOCOL_VERSION, +} from '../../../edge/src/pages-protocol.ts'; import { markActionKey, pageActionTargetId } from '../../src/pages/action-key.ts'; +import { createActionErrorFromResponse } from '../../src/pages/action-result.ts'; import { defer } from '../../src/pages/defer.ts'; import { handlePageGet, @@ -2346,6 +2350,75 @@ it('negotiates result-only page actions on the resolved target', async () => { } }); +it.each(['native', 'hosted'])( + 'keeps result-mode validation errors JSON through %s rules', + async (mode) => { + const app = new Hono(); + const runtime = createRoutingRuntime(app, { nodeTarget: true }); + const path = '/items/1'; + const rules = [ + { + pattern: '/items/*', + headers: [ + ['Content-Type', 'text/html; charset=utf-8'], + ['X-Test-Rule', 'applied'], + ] as Array<[string, string]>, + }, + ]; + const loader = vi.fn(); + const action = definePageAction( + defineHandler((c) => { + if (c.req.header('X-Test-Explicit')) { + return c.json({ explicit: true }, 422); + } + throw new ValidationError({ name: 'Required' }); + }), + { reload: false }, + ); + app.use(runtime.contextMiddleware); + if (mode === 'native') { + app.use(runtime.headerMiddleware(rules)); + } + app.post( + '/items/:id', + createPageMutationHandler({ + load: async () => ({ action, loader }), + componentId: 'items', + render: mockRenderFn, + assets: mockGetAssetTags, + headConfig: null, + renderOptions: {}, + }), + ); + + const post = async (extra?: Record) => { + const response = await app.request(path, { + method: 'POST', + headers: { + 'X-VoidPages': 'true', + 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION, + [PAGE_ACTION_RESULT_HEADER]: actionTargetId(path), + ...extra, + }, + }); + return mode === 'hosted' ? applyHeaderRules(response, path, rules) : response; + }; + + const response = await post(); + expect(response.status).toBe(422); + expect(response.headers.get('X-Test-Rule')).toBe('applied'); + expect(response.headers.get('Content-Type')).toBe('application/json'); + expect((await createActionErrorFromResponse(response, path)).body).toEqual({ + errors: { name: 'Required' }, + }); + expect(loader).not.toHaveBeenCalled(); + + const explicit = await post({ 'X-Test-Explicit': '1' }); + expect(explicit.status).toBe(422); + expect(explicit.headers.get('Content-Type')).toBe('text/html; charset=utf-8'); + }, +); + it('keeps the unwrapped action wire bytes with the new capability header', async () => { const loader = vi.fn(() => ({ fresh: true })); const action = vi.fn(() => ({ discarded: true })); From 1445cd2c95bc20262b646d91e6511b1d7a2b91c8 Mon Sep 17 00:00:00 2001 From: Yunfei He Date: Sat, 5 Dec 2026 16:10:26 +0800 Subject: [PATCH 5/5] fix(pages): release result-only navigation state MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Keep React error recovery on the current page and release the shared router’s pending resource when a result-only action settles. Update the action client and route declaration tests to cover the result callback and generated result type. --- packages/react/src/runtime/pages-client.ts | 3 ++ .../test/unit/page-action-result.test.ts | 50 ++++++++++++++++--- packages/void/src/pages/navigation-engine.ts | 3 ++ packages/void/test/unit/action-result.test.ts | 3 ++ packages/void/test/unit/pages-client.test.ts | 42 ++++++++++++++++ packages/void/test/unit/route-types.test.ts | 3 ++ 6 files changed, 96 insertions(+), 8 deletions(-) diff --git a/packages/react/src/runtime/pages-client.ts b/packages/react/src/runtime/pages-client.ts index 67ca59fd84..b2ea79d59d 100644 --- a/packages/react/src/runtime/pages-client.ts +++ b/packages/react/src/runtime/pages-client.ts @@ -665,6 +665,9 @@ function App({ activePendingNavigationId = null; } // The response has no destination page. Keep the current page. + if (terminalResource === next) { + terminalResource = null; + } dispatch({ type: 'abandon', resource: prepared, location: currentUrl() }); resolveVisit(undefined); } else if (resolveOnData) { diff --git a/packages/react/test/unit/page-action-result.test.ts b/packages/react/test/unit/page-action-result.test.ts index 340fac4570..e99aed4d64 100644 --- a/packages/react/test/unit/page-action-result.test.ts +++ b/packages/react/test/unit/page-action-result.test.ts @@ -18,32 +18,56 @@ afterEach(() => { document.body.replaceChildren(); }); -it('settles a result-only action at the React shell without committing another page', async () => { +it('keeps React state and error recovery on the current page after a result-only action', async () => { vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true); + history.replaceState(null, '', '/draft?view=edit#note'); + const url = location.href; document.body.innerHTML = '

'; const data = document.createElement('script'); data.id = '__VOID_PAGE_DATA__'; - data.textContent = JSON.stringify({ component: 'home', props: {}, url: '/' }); + data.textContent = JSON.stringify({ component: 'home', props: {}, url: '/draft?view=edit' }); document.body.append(data); const fetch = vi.fn( - async () => + async (target: string) => new Response('[{"result":1},"saved"]', { headers: { 'Content-Type': 'application/vnd.void.action-result+json', - 'X-VoidPages-Action-Result': pageActionTargetId( - new URL('/react-preview', location.origin), - ), + 'X-VoidPages-Action-Result': pageActionTargetId(new URL(target, location.origin)), }, }), ); vi.stubGlobal('fetch', fetch); function Home() { const [draft, setDraft] = useState('initial'); - return createElement('button', { onClick: () => setDraft('local draft') }, draft); + const [broken, setBroken] = useState(false); + if (broken) { + throw new Error('Page render failed'); + } + return createElement( + 'main', + null, + createElement('button', { onClick: () => setDraft('local draft') }, draft), + createElement('button', { id: 'break-page', onClick: () => setBroken(true) }, 'Break page'), + ); } await act(async () => { await startReactPages({ components: { home: async () => ({ default: Home }) }, + boundaryManifest: { + plans: { + 'root-not-found': { + id: 'root-not-found', + componentId: '_not-found', + filePath: '_not-found.tsx', + directory: '', + kind: 'not-found', + source: 'root-not-found', + layouts: [], + }, + }, + pages: {}, + root: 'root-not-found', + }, layoutTree: {}, routeMeta: {}, matchRoute: () => 'home', @@ -59,7 +83,6 @@ it('settles a result-only action at the React shell without committing another p const push = vi.spyOn(history, 'pushState'); const replace = vi.spyOn(history, 'replaceState'); const scroll = vi.spyOn(window, 'scrollTo'); - const url = location.href; await act(async () => { expect(await action('/react-preview')).toEqual({ ok: true, @@ -74,4 +97,15 @@ it('settles a result-only action at the React shell without committing another p expect(replace).not.toHaveBeenCalled(); expect(scroll).not.toHaveBeenCalled(); expect(fetch).toHaveBeenCalledOnce(); + + // React's act() rethrows render failures instead of calling the root's error handler. + vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', false); + document.querySelector('#break-page')?.click(); + await vi.waitFor(() => { + expect(document.querySelector('main a')?.textContent).toBe('Try again'); + }); + expect({ + address: location.href, + retry: document.querySelector('main a')?.getAttribute('href'), + }).toEqual({ address: url, retry: url }); }); diff --git a/packages/void/src/pages/navigation-engine.ts b/packages/void/src/pages/navigation-engine.ts index 39d480ddb4..b55b030aab 100644 --- a/packages/void/src/pages/navigation-engine.ts +++ b/packages/void/src/pages/navigation-engine.ts @@ -1011,6 +1011,9 @@ export async function createPageNavigationEngine( throw new Error('pages: Invalid action result payload.'); } options._onActionResult(payload.result); + if (_pendingResource?.id === id) { + _pendingResource = null; + } return undefined; } } diff --git a/packages/void/test/unit/action-result.test.ts b/packages/void/test/unit/action-result.test.ts index 2ac4008bb0..47c0835561 100644 --- a/packages/void/test/unit/action-result.test.ts +++ b/packages/void/test/unit/action-result.test.ts @@ -259,6 +259,7 @@ describe('action clients', () => { data: undefined, _resolveOnShell: true, preserveScroll: undefined, + _onActionResult: expect.any(Function), }); }); @@ -291,6 +292,7 @@ describe('action clients', () => { method: 'POST', data: undefined, preserveScroll: undefined, + _onActionResult: expect.any(Function), }); }); @@ -311,6 +313,7 @@ describe('action clients', () => { method: 'PATCH', data: { name: 'Alice' }, preserveScroll: undefined, + _onActionResult: expect.any(Function), }); }, ); diff --git a/packages/void/test/unit/pages-client.test.ts b/packages/void/test/unit/pages-client.test.ts index c7e6e49913..58661934eb 100644 --- a/packages/void/test/unit/pages-client.test.ts +++ b/packages/void/test/unit/pages-client.test.ts @@ -3473,6 +3473,48 @@ it.each(['native', 'hosted'] as const)( }, ); +it('releases a result-only navigation resource when its shell settles', async () => { + stubClientGlobals(); + const target = '/preview/2?save'; + const result = new Response('[{"result":1},42]', { + headers: { + 'Content-Type': 'application/vnd.void.action-result+json', + 'X-VoidPages-Action-Result': pageActionTargetId(new URL(target, window.location.origin)), + }, + }); + const page = { component: 'home', props: {}, errors: null, url: '/next' }; + const fetch = vi.fn().mockResolvedValueOnce(result).mockResolvedValueOnce(pageJson(page)); + vi.stubGlobal('fetch', fetch); + const engine = await createPageNavigationEngine({ + adapter: { + createDeferred: () => ({}), + resolveDeferred: (_ref, value) => value, + rejectDeferred: (_ref, error) => error, + isLoading: () => false, + }, + components: { home: loadComponent }, + layoutTree: {}, + routeMeta: {}, + matchRoute: () => 'home', + viewTransitions: false, + prefetchHoverDelay: 75, + prefetchDefaultCacheFor: parseCacheFor('30s'), + }); + const onResult = vi.fn(); + const resource = engine.prepareVisit(target, { + method: 'POST', + data: { draft: 'preview' }, + _onActionResult: onResult, + }); + const abort = vi.spyOn(resource, 'abort'); + await expect(resource.shell).resolves.toBeUndefined(); + expect(onResult).toHaveBeenCalledWith(42); + + const next = engine.prepareVisit('/next'); + await expect(next.shell).resolves.toMatchObject({ pageData: page }); + expect(abort).not.toHaveBeenCalled(); +}); + it('settles result-only actions without a page commit and preserves newer visits', async () => { stubClientGlobals(); const resultHeader = 'X-VoidPages-Action-Result'; diff --git a/packages/void/test/unit/route-types.test.ts b/packages/void/test/unit/route-types.test.ts index 7c27f18ff3..a42ad1275e 100644 --- a/packages/void/test/unit/route-types.test.ts +++ b/packages/void/test/unit/route-types.test.ts @@ -415,9 +415,12 @@ describe('generateRouteTypes', () => { [ ' "/users/[id]": {', ` body: ExtractInput<${dev}["__validators"]> extends { body: infer B } ? B : Record;`, + ` result: PageActionValueOf<${dev}>;`, ' params: { id: string };', ' } | {', ` actions: { [K in keyof ${prod}]: {`, + ` body: ExtractInput<${prod}[K]["__validators"]> extends { body: infer B } ? B : Record;`, + ` result: PageActionValueOf<${prod}[K]>;`, ].join('\n'), ); expect(actionMap).toContain(' "/users/:id": PageActionMap["/users/[id]"];');