diff --git a/docs/guide/pages-routing/actions-and-forms.md b/docs/guide/pages-routing/actions-and-forms.md index 53b9cc6a8..2515cc9b4 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 d2deef193..190327efa 100644 --- a/packages/edge/src/headers.ts +++ b/packages/edge/src/headers.ts @@ -1,4 +1,8 @@ import type { HeaderRule } from '@void/deploy-core'; +import { + hasProtectedPageActionContentType, + protectPageActionResultCache, +} from './pages-protocol.ts'; import { matchLiteralPattern } from './pattern.ts'; export type { HeaderRule } from '@void/deploy-core'; @@ -162,6 +166,9 @@ export function applyHeaderRules( rawOriginClearSiteData === null ? null : sanitizeClearSiteData(rawOriginClearSiteData); for (const [name, value] of matched) { const lowerName = name.toLowerCase(); + if (lowerName === 'content-type' && hasProtectedPageActionContentType(response)) { + continue; + } if (isolateSharedDomainCookies && BLOCKED_HEADERS.has(lowerName)) { continue; } @@ -179,5 +186,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 34a27048f..09e074a5c 100644 --- a/packages/edge/src/index.ts +++ b/packages/edge/src/index.ts @@ -1,11 +1,17 @@ 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, + 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 a4ea6d02b..dcbd37373 100644 --- a/packages/edge/src/pages-protocol.ts +++ b/packages/edge/src/pages-protocol.ts @@ -8,6 +8,36 @@ 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 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)) { + 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 97f6418c4..b2ea79d59 100644 --- a/packages/react/src/runtime/pages-client.ts +++ b/packages/react/src/runtime/pages-client.ts @@ -664,7 +664,10 @@ 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. + 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 new file mode 100644 index 000000000..e99aed4d6 --- /dev/null +++ b/packages/react/test/unit/page-action-result.test.ts @@ -0,0 +1,111 @@ +// @vitest-environment happy-dom + +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'; + +declare module 'void/routes' { + interface PageActionMap { + '/react-preview': { body: Record; result: string }; + } +} + +afterEach(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + document.body.replaceChildren(); +}); + +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: '/draft?view=edit' }); + document.body.append(data); + const fetch = vi.fn( + async (target: string) => + new Response('[{"result":1},"saved"]', { + headers: { + 'Content-Type': 'application/vnd.void.action-result+json', + 'X-VoidPages-Action-Result': pageActionTargetId(new URL(target, location.origin)), + }, + }), + ); + vi.stubGlobal('fetch', fetch); + function Home() { + const [draft, setDraft] = useState('initial'); + 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', + 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'); + 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(); + + // 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/codegen/route-types.ts b/packages/void/src/codegen/route-types.ts index b0f504268..1c3042275 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,21 @@ export function generateRouteTypes( ' : PageNamedActionBody["base"]], ParseActionUrl["action"]>', ' : Record;', '', + ' type PageActionValue = A extends { result: infer R } ? R : undefined;', + '', + // 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 }', + ' ? PageActionValue]>', + ' : 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 +601,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 f82a925e0..fdff50544 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-key.ts b/packages/void/src/pages/action-key.ts index d05b307dc..f156090d9 100644 --- a/packages/void/src/pages/action-key.ts +++ b/packages/void/src/pages/action-key.ts @@ -43,6 +43,21 @@ export function searchWithoutActionKey(search: string): string { */ export const PRESERVED_QUERY_HEADER = 'X-VoidPages-Preserved-Query'; +/** A fixed-size FNV-1a identity check for the concrete action target, not a security boundary. */ +export function pageActionTargetId(url: URL): string { + 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 { return new URLSearchParams(segment).keys().next().value; } diff --git a/packages/void/src/pages/action-result.ts b/packages/void/src/pages/action-result.ts index b0e315a17..2d3b2ab58 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 62d0a5f0e..7b8dacf1b 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 f2194b85a..b55b030aa 100644 --- a/packages/void/src/pages/navigation-engine.ts +++ b/packages/void/src/pages/navigation-engine.ts @@ -1,11 +1,24 @@ /// -import { buildHeaders, isStaleBuild, PAGES_BUILD_HEADER, PAGES_PROTOCOL_VERSION } from '@void/edge'; -import { PRESERVED_QUERY_HEADER, searchWithoutActionKey } from './action-key.ts'; +import { + buildHeaders, + isPageActionResult, + isStaleBuild, + PAGE_ACTION_RESULT_HEADER, + PAGES_BUILD_HEADER, + PAGES_PROTOCOL_VERSION, +} from '@void/edge'; +import { parse } from 'devalue'; +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'; 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 +84,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 +835,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 +849,11 @@ export async function createPageNavigationEngine( if (options._preservedQuery && method !== 'GET') { headers[PRESERVED_QUERY_HEADER] = options._preservedQuery; } + const actionTargetId = + options._onActionResult && method !== 'GET' ? pageActionTargetId(target) : undefined; + if (actionTargetId) { + headers[PAGE_ACTION_RESULT_HEADER] = actionTargetId; + } const fetchOptions: PageFetchOptions = { method, headers, signal }; if (options.data && method !== 'GET') { @@ -968,6 +993,31 @@ export async function createPageNavigationEngine( throw await createActionErrorFromResponse(response, fetchUrl); } + if ( + response?.ok && + options._onActionResult && + actionTargetId && + isPageActionResult(response.headers) + ) { + signal.throwIfAborted(); + if ( + response.headers.get(PAGE_ACTION_RESULT_HEADER) === actionTargetId && + (!fetched?.redirectedTo || fetchUrl === target.pathname + target.search) + ) { + 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); + if (_pendingResource?.id === id) { + _pendingResource = null; + } + 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 c4df8cbaf..877beffdc 100644 --- a/packages/void/src/pages/protocol.ts +++ b/packages/void/src/pages/protocol.ts @@ -1,4 +1,14 @@ -import { buildHeaders, isStaleBuild, PAGES_BUILD_HEADER, PAGES_PROTOCOL_VERSION } from '@void/edge'; +import { + buildHeaders, + isStaleBuild, + PAGE_ACTION_RESULT_HEADER, + PAGE_ACTION_RESULT_TYPE, + PAGE_ACTION_VALIDATION_HEADER, + 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'; @@ -6,7 +16,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'; @@ -1189,6 +1199,21 @@ async function runPageMutation( return new Response('Cross-origin page actions are not allowed.', { status: 403 }); } const renderMode = options?.renderMode ?? 'server'; + // 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) && + requestedTargetId === pageActionTargetId(new URL(c.req.url)) + ) { + resultTargetId = requestedTargetId; + } function buildMutationPageObj( props: Record, @@ -1260,6 +1285,11 @@ async function runPageMutation( } function respondWithErrors(errors: Record): Promise { + if (resultTargetId !== undefined) { + 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 })); } @@ -1300,9 +1330,17 @@ async function runPageMutation( if (status !== 204) { return result; } + } else if (resultTargetId !== undefined) { + const headers = pageResponseHeaders(c, { + 'Content-Type': PAGE_ACTION_RESULT_TYPE, + [PAGE_ACTION_RESULT_HEADER]: resultTargetId, + }); + 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 af1ab55ed..9e5a6858f 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 7968e3493..3066b4b62 100644 --- a/packages/void/src/routes-stub.ts +++ b/packages/void/src/routes-stub.ts @@ -110,6 +110,21 @@ export type ResolveActionBody = : PageNamedActionBody['base']], ParseActionUrl['action']> : Record; +type PageActionValue = A extends { result: infer R } ? R : undefined; + +// 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 } + ? PageActionValue]> + : 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 70e9eeb7b..1dcd584d6 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 f1a01123d..6a16bccca 100644 --- a/packages/void/src/runtime/routing/index.ts +++ b/packages/void/src/runtime/routing/index.ts @@ -1,9 +1,11 @@ import { AsyncLocalStorage } from 'node:async_hooks'; import { compilePattern, + hasProtectedPageActionContentType, matchPattern, matchPatternCaptures, mergeQueryIntoLocation, + protectPageActionResultCache, substituteParams, } from '@void/edge'; import type { Context, Hono, MiddlewareHandler, NotFoundHandler } from 'hono'; @@ -351,6 +353,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; } @@ -454,6 +457,9 @@ export function createRoutingRuntime( } const asset = isUnchangedStaticAsset(c); for (const [key, [name, value]] of last) { + if (key === 'content-type' && hasProtectedPageActionContentType(c.res)) { + continue; + } if ( protectCache && (key === 'cache-control' || key === 'pragma' || SHARED_CACHE_HEADERS.includes(key)) 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 de9c594bd..c531ec693 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,15 @@ 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')], + 'routes-stub': [join(voidDist, 'routes-stub.d.mts')], }, }, files: ['.void/routes.d.ts', 'check.ts'], }), - '.void/routes.d.ts': dts, + 'package.json': '{"type":"module"}', 'routes-base.d.ts': 'export {};', ...files, }; @@ -92,6 +86,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 +117,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 +149,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 +168,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 +188,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 +207,64 @@ 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';", + "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) { type Result = Assert>; }', + '// @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) { type Result = Assert>; }', + "const empty = await action('/items/[id]?empty', { params });", + `if (empty.ok) { type Result = Assert>; }`, + "const unwrapped = await action('/items/[id]?unwrapped', { params });", + `if (unwrapped.ok) { type Result = Assert>; }`, + '// @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/action-result.test.ts b/packages/void/test/unit/action-result.test.ts index 2ac4008bb..47c083556 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 9de9529a9..58661934e 100644 --- a/packages/void/test/unit/pages-client.test.ts +++ b/packages/void/test/unit/pages-client.test.ts @@ -1,9 +1,14 @@ +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 { pageActionTargetId } from '../../src/pages/action-key.ts'; import { + createActionClient, createRouterFacade, createSsrRouter, createVoidRouter, @@ -11,6 +16,7 @@ import { mergeDataIntoHref, readPageQuery, ssrProxy, + submitIslandAction, submitAction, } from '../../src/pages/client.ts'; import type { VoidRouterConfig } from '../../src/pages/client.ts'; @@ -20,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, @@ -34,6 +41,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 +3365,235 @@ 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('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'; + 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 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(); + 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(targetId); + 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); + + const otherTargetId = pageActionTargetId(new URL('/other?save', window.location.origin)); + fetch.mockResolvedValueOnce(payload('[{"result":1},42]', otherTargetId)); + 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 50fcb43a1..10b968ba0 100644 --- a/packages/void/test/unit/pages-protocol.test.ts +++ b/packages/void/test/unit/pages-protocol.test.ts @@ -1,8 +1,14 @@ +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 { PAGES_PROTOCOL_VERSION } from '../../../edge/src/pages-protocol.ts'; -import { markActionKey } from '../../src/pages/action-key.ts'; +import { applyHeaderRules } from '../../../edge/src/headers.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, @@ -10,18 +16,27 @@ 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'; +function actionTargetId(target: string): string { + return pageActionTargetId(new URL(target, 'http://localhost')); +} + type RenderPage = { component: string }; type PageResponse = { component: string; @@ -2137,3 +2152,316 @@ 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]: actionTargetId(capability) }), + ...extra, + }, + }); + + const reply = await post(target); + expect(reply.headers.get('Content-Type')).toBe(resultType); + 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'); + 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]: actionTargetId(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.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 })); + 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': actionTargetId('/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); +}); diff --git a/packages/void/test/unit/route-types.test.ts b/packages/void/test/unit/route-types.test.ts index 7c27f18ff..a42ad1275 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]"];');