diff --git a/docs/reference/api/pages.md b/docs/reference/api/pages.md index 1ddece7ec..5cdc10deb 100644 --- a/docs/reference/api/pages.md +++ b/docs/reference/api/pages.md @@ -85,6 +85,7 @@ function voidVue(options?: VoidVueOptions): Plugin[]; ```ts interface VoidVueOptions { vue?: VuePluginOptions; // passed through to @vitejs/plugin-vue + appSetup?: string; // path from the project root to the Vue app setup module viewTransitions?: boolean; // enable View Transitions API for navigations prefetch?: { defaultStrategy?: boolean | LinkPrefetchStrategy | LinkPrefetchStrategy[]; // default: false @@ -95,6 +96,34 @@ interface VoidVueOptions { } ``` +### Vue app setup {#vue-app-setup} + +Set `voidVue({ appSetup: './src/vue-app.ts' })` in your Vite config to install Vue plugins, provide values, or configure the app before it renders. Default-export a synchronous setup function from that file. Void calls it on the server for each request that renders a Vue app, and in the browser before mounting the page app and each island app. + +Guard browser APIs in the setup module with `if (!import.meta.env.SSR)`. + +Return optional synchronous `dehydrate()` and `hydrate(state)` functions to transfer state for server-rendered pages with hydration enabled. Void calls `dehydrate()` as soon as the page finishes rendering, before running deferred callbacks. When `dehydrate()` returns a value, Void includes it in the initial HTML and passes it to `hydrate(state)` before mounting the page app. + +Each island in the browser starts with the state its own `setup(app)` creates. Pass server data to islands as props, including any values that the page or its loaders changed on the server. + +```ts +// src/vue-app.ts +import { createPinia } from 'pinia'; +import type { App } from 'vue'; + +export default function setup(app: App) { + const pinia = createPinia(); + app.use(pinia); + + return { + dehydrate: () => pinia.state.value, + hydrate(state: typeof pinia.state.value) { + pinia.state.value = state; + }, + }; +} +``` + ### Vue Runtime {#vue-runtime} Imported from `"@void/vue"`. diff --git a/packages/void/src/pages/islands-plugin.ts b/packages/void/src/pages/islands-plugin.ts index 226a0034e..72ddb1a35 100644 --- a/packages/void/src/pages/islands-plugin.ts +++ b/packages/void/src/pages/islands-plugin.ts @@ -358,14 +358,16 @@ export function recordIslandStyles( context: IslandBuildContext, pageScan: PageScanResult | null, pagesDir: string, + setupModule?: string, ): void { if (!pageScan || context.environment?.config.consumer !== 'server') { return; } - const styles = collectIslandStyles( - (id) => context.getModuleInfo(id), - islandStyleRoots(pageScan, pagesDir), - ); + const roots = islandStyleRoots(pageScan, pagesDir); + if (setupModule) { + roots.unshift(setupModule); + } + const styles = collectIslandStyles((id) => context.getModuleInfo(id), roots); // Another server environment (an auxiliary Worker) does not have the pages. if (styles) { islandStylesByPagesDir.set(normalizePath(pagesDir), styles); diff --git a/packages/void/src/pages/protocol.ts b/packages/void/src/pages/protocol.ts index 745f58d7c..10288cdee 100644 --- a/packages/void/src/pages/protocol.ts +++ b/packages/void/src/pages/protocol.ts @@ -87,6 +87,7 @@ type RenderPage = ( pageObj: PageObject, assetTags: AssetTags, requestUrl: string, + request: CloudContext['req'], ) => Promise; type RenderPageWithMetadata = RenderPage & { preambleScript?: string; @@ -256,10 +257,10 @@ async function renderWithAssetTags( renderFn: RenderPage, pageObj: PageObject, assetTags: AssetTags, - requestUrl: string, + request: CloudContext, ): Promise { try { - return await renderFn(pageObj, assetTags, requestUrl); + return await renderFn(pageObj, assetTags, request.req.url, request.req); } catch (error) { attachRenderErrorAssetTags(error, assetTags); } @@ -300,7 +301,7 @@ async function renderPageHtml( const html = renderMode === 'client' ? renderClientOnlyPage(pageObj, assetTags, renderFn) - : await renderWithAssetTags(renderFn, pageObj, assetTags, c.req.url); + : await renderWithAssetTags(renderFn, pageObj, assetTags, c); return { html, assetTags }; } @@ -437,6 +438,15 @@ function isRecoverableHttpException(error: unknown): error is HTTPException { ); } +export function isPageResponseError(error: unknown): error is Pick { + return ( + !!error && + typeof error === 'object' && + 'getResponse' in error && + typeof error.getResponse === 'function' + ); +} + /** Recover HTTP failures outside the loader leaf without executing application code again. */ export async function recoverPageHttpException( error: unknown, @@ -466,12 +476,8 @@ async function renderPageFailure( configHead: HeadConfig | undefined, options: PageRenderOptions | undefined, ): Promise { - const httpError = - error && - typeof error === 'object' && - 'getResponse' in error && - typeof error.getResponse === 'function'; - const explicit = httpError ? (error as { getResponse(): Response }).getResponse() : original; + const httpError = isPageResponseError(error); + const explicit = httpError ? error.getResponse() : original; const recoverHttpError = isRecoverableHttpException(error); if ( explicit && diff --git a/packages/void/src/pages/serialize.ts b/packages/void/src/pages/serialize.ts index d3a6cbc15..ef321e0ad 100644 --- a/packages/void/src/pages/serialize.ts +++ b/packages/void/src/pages/serialize.ts @@ -1,6 +1,20 @@ -import { stringify, unflatten } from 'devalue'; +import { parse, stringify, unflatten } from 'devalue'; +import type { Context } from 'hono'; import { escapeScriptJson } from './script-json.ts'; +type AppRequest = Context['req']; +let appSetups: WeakMap> | undefined; + +export function requestAppSetup(setup: () => T, request: AppRequest): Promise { + const cache = (appSetups ??= new WeakMap()); + let pending = cache.get(request); + if (!pending) { + pending = Promise.resolve().then(setup); + cache.set(request, pending); + } + return pending as Promise; +} + /** * Serialize Pages data without losing supported JavaScript values. The envelope * keeps deferred metadata visible to existing ISR caches, which must not cache @@ -35,6 +49,24 @@ export function deserializePageData(text: string): T { return decodePageData(JSON.parse(text)); } +const APP_STATE_ID = '__VOID_APP_STATE__'; + +export function appStateScript(hooks?: { dehydrate?: () => unknown }): string { + const state = hooks?.dehydrate ? hooks.dehydrate() : undefined; + return state === undefined + ? '' + : `\n `; +} + +export function hydrateAppState(hooks?: { hydrate?: (state: unknown) => void }): void { + if (typeof hooks?.hydrate === 'function') { + const state = document.getElementById(APP_STATE_ID)?.textContent; + if (state) { + hooks.hydrate(parse(state)); + } + } +} + /** Element id of the Markdown page frontmatter that islands read when they hydrate. */ export const ISLAND_FRONTMATTER_ID = '__void_frontmatter'; diff --git a/packages/void/src/runtime/routing/pages.ts b/packages/void/src/runtime/routing/pages.ts index 22e3cd39b..98a3bae65 100644 --- a/packages/void/src/runtime/routing/pages.ts +++ b/packages/void/src/runtime/routing/pages.ts @@ -201,8 +201,13 @@ export function createStaticNotFound( const handle = createPageGetHandler({ ...options, renderOptions: { ...options.renderOptions, renderMode: 'server' }, - render: (page, assets, url) => - options.render({ ...page, documentOnly: true }, { ...assets, body: '', preloads: '' }, url), + render: (page, assets, url, request) => + options.render( + { ...page, documentOnly: true }, + { ...assets, body: '', preloads: '' }, + url, + request, + ), }); return (request, env) => handle(new Context(new Request(new URL('/404', request.url)), { env })); } diff --git a/packages/void/test/unit/pages-protocol.test.ts b/packages/void/test/unit/pages-protocol.test.ts index 37e328491..957037b0f 100644 --- a/packages/void/test/unit/pages-protocol.test.ts +++ b/packages/void/test/unit/pages-protocol.test.ts @@ -12,11 +12,13 @@ import { import { deserializePageData, decodePageData, + requestAppSetup, serializePageData, } from '../../src/pages/serialize.ts'; import { defineHandler } 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'; type RenderPage = { component: string }; type PageResponse = { @@ -73,6 +75,31 @@ function createTestContext( const mockRenderFn = vi.fn(async (pageObj: RenderPage) => `${pageObj.component}`); const mockGetAssetTags = vi.fn(async () => ({ css: '', preloads: '', body: '' })); +it('keeps the same setup request when the static 404 tries an error boundary', async () => { + const setup = vi.fn(() => ({ touched: false })); + const render = createStaticNotFound({ + componentId: 'missing', + headConfig: null, + renderOptions: { + boundaries: { notFound: 'missing', notFoundErrors: ['error'], errors: ['error'] }, + }, + load: async () => ({ loader: () => new Response(null, { status: 404 }) }), + assets: mockGetAssetTags, + render: async (page, _assets, _url, request) => { + const state = await requestAppSetup(setup, request); + if (page.component === 'missing') { + state.touched = true; + throw new Error('404 component threw'); + } + expect(page.documentOnly).toBe(true); + return `

touched ${state.touched}

`; + }, + }); + const response = await render(new Request('http://localhost/'), {}); + expect(await response.text()).toContain('touched true'); + expect(setup).toHaveBeenCalledTimes(1); +}); + describe('handlePageGet', () => { it.each(['plain', 'validated', 'middleware'] as const)( 'preserves rich loader and shared data for %s handlers and action reloads', @@ -314,6 +341,7 @@ describe('handlePageGet', () => { }), expect.anything(), 'http://localhost/posts/abc-123', + c.req, ); }); diff --git a/packages/vue/src/app-render.ts b/packages/vue/src/app-render.ts new file mode 100644 index 000000000..ac84d842c --- /dev/null +++ b/packages/vue/src/app-render.ts @@ -0,0 +1,49 @@ +export type AppSetupModule = { id: string; file: string }; + +export function generateSetupCall({ file }: AppSetupModule): string { + const option = `voidVue appSetup (${file})`; + return ` + if (typeof setupApp !== "function") { + throw new TypeError(${JSON.stringify(`${option} must default-export a function.`)}); + } + const appHooks = setupApp(app); + if (typeof appHooks?.then === "function") { + void Promise.resolve(appHooks).catch(() => {}); + throw new TypeError(${JSON.stringify(`${option} must be synchronous.`)}); + }`; +} + +export function generateSsrAppSetup(appSetup: AppSetupModule): string { + return ` +import setupApp from ${JSON.stringify(appSetup.id)}; +import { isPageResponseError } from "void/pages-protocol"; +async function requestApp(root, request) { + const entry = await requestAppSetup(() => { + const app = createSSRApp({ setup: () => entry.root.setup() });${generateSetupCall(appSetup)} + return { app, root, appHooks }; + }, request); + return Object.assign(entry, { root }); +}`; +} + +export function generateSsrRender(appSetup: AppSetupModule | undefined): string { + const handler = appSetup + ? `const setupErrorHandler = app.config.errorHandler; + const boundary = boundaryManifest.pages[pageObj.component]; + if (Object.keys(boundaryManifest.plans).length) app.config.errorHandler = (error, ...args) => { + if (!setupErrorHandler || isPageResponseError(error) || boundary?.errors.length || + boundaryManifest.plans[pageObj.component]) { + renderFailure ??= { error }; + } + try { + setupErrorHandler?.(error, ...args); + } catch (error) { + renderFailure ??= { error }; + } + };` + : 'if (Object.keys(boundaryManifest.plans).length) app.config.errorHandler = error => { renderFailure ??= { error }; };'; + return `let renderFailure; + ${handler} + const html = await renderToString(app)${appSetup ? '.finally(() => { app.config.errorHandler = setupErrorHandler; })' : ''}; + if (renderFailure) throw renderFailure.error;`; +} diff --git a/packages/vue/src/plugin-islands.ts b/packages/vue/src/plugin-islands.ts index 7a54d402d..98cc9eb6a 100644 --- a/packages/vue/src/plugin-islands.ts +++ b/packages/vue/src/plugin-islands.ts @@ -20,18 +20,23 @@ import { editIslandSource, } from 'void/pages-islands-plugin'; import type { IslandSourceEdit } from 'void/pages-islands-plugin'; +import { generateSetupCall, generateSsrAppSetup, generateSsrRender } from './app-render.ts'; +import type { AppSetupModule } from './app-render.ts'; const COMPONENT_EXTENSIONS = ['.vue', '.tsx', '.jsx', '.ts', '.js']; -const HYDRATE_ISLAND = ` +function generateHydrateIsland(appSetup: AppSetupModule | undefined): string { + const setupImports = appSetup ? `import setupApp from ${JSON.stringify(appSetup.id)};\n` : ''; + return `${setupImports} async function hydrateIsland(el, mod, props, frontmatter) { const { createSSRApp, h } = await import("vue"); const Component = mod.default || mod; const app = createSSRApp({ render: () => h(Component, props) }); - app.provide("__void_frontmatter", frontmatter); + app.provide("__void_frontmatter", frontmatter);${appSetup ? generateSetupCall(appSetup) : ''} app.mount(el); el.setAttribute("data-hydrated", "true"); }`; +} /** Imports for the ``, @@ -22,6 +53,7 @@ import Shell from '../src/Shell.vue'; `, 'pages/index.island.vue': '', + 'pages/state.vue': '', // The layout renders Badge without hydrating it; this page hydrates it. 'pages/badge.island.vue': `