diff --git a/docs/reference/api/pages.md b/docs/reference/api/pages.md index 1ddece7ec..d22e4431d 100644 --- a/docs/reference/api/pages.md +++ b/docs/reference/api/pages.md @@ -95,6 +95,31 @@ interface VoidVueOptions { } ``` +### Vue app setup {#vue-app-setup} + +In `pages/_app.ts` or `pages/_app.js`, directly default-export a function declaration, function expression, or arrow function to install Vue plugins. The setup function must be synchronous. Void passes each Vue Pages app to setup before server rendering or browser mount. The server imports `_app` even for client-only pages, so keep browser-only code out of module scope and guard it in setup with `if (!import.meta.env.SSR)`. Create request-local state inside the function. + +```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; + }, + }; +} +``` + +To transfer state, return both hooks as synchronous functions. Void sends the serializable result of `dehydrate()` after server rendering and passes it to `hydrate(state)` before the browser app mounts. A page app keeps its state during client-side navigation. + +All islands on a page render in one app on the server. Each interactive island starts with its own copy of the rendered app state and runs in its own browser app. + ### 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..08db9f95b 100644 --- a/packages/void/src/pages/islands-plugin.ts +++ b/packages/void/src/pages/islands-plugin.ts @@ -349,23 +349,24 @@ type IslandBuildContext = { const islandStylesByPagesDir = new Map>(); /** - * Call from `buildEnd`. Island pages render only on the server, so the server - * build has resolved their imports (aliases, packages, Vue and Svelte style - * blocks) and the client build has not. Records the stylesheets of island pages - * and their layouts for the islands client entry, which builds after it. + * Records the stylesheets of island pages, their layouts and error components, + * and the optional setup module. Call from `buildEnd` so the server has + * resolved its imports before the islands client build. */ 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/plugin-routing.ts b/packages/void/src/plugin-routing.ts index 026883deb..1c67e1997 100644 --- a/packages/void/src/plugin-routing.ts +++ b/packages/void/src/plugin-routing.ts @@ -977,6 +977,20 @@ export function routingPlugin( // Watch the source convention directories for file changes const watcher = devServer.watcher; + const usesVuePages = resolvedConfig?.plugins?.some( + (plugin) => plugin.name === 'void-vue:pages', + ); + + function invalidatePageEntries(): void { + for (const env of Object.values(devServer.environments)) { + for (const id of PAGE_VIRTUAL_MODULE_IDS) { + const mod = env.moduleGraph.getModuleById(id); + if (mod) { + env.moduleGraph.invalidateModule(mod); + } + } + } + } const handleFileChange = async (path: string, event: 'add' | 'change' | 'unlink') => { const normalizedPath = normalizePath(path); @@ -1003,6 +1017,15 @@ export function routingPlugin( return; } + const isVueSetupFile = + usesVuePages && + (normalizedPath === `${normalizedPagesDir}/_app.ts` || + normalizedPath === `${normalizedPagesDir}/_app.js`); + if (isVueSetupFile) { + // Setup imports can change while the entries still use the last good route scan. + invalidatePageEntries(); + } + const shouldRestart = await regenerateInOrder(async () => { invalidateSourceAnalysis(normalizedPath); // Re-scan and invalidate the virtual module in ALL environments. @@ -1086,15 +1109,10 @@ export function routingPlugin( const pageManifestChanged = isInDirectory(normalizedPath, normalizedPagesDir) && (structural || normalizedPath.endsWith('.md')); + if (pageManifestChanged && !isVueSetupFile) { + invalidatePageEntries(); + } for (const env of Object.values(devServer.environments)) { - if (pageManifestChanged) { - for (const id of PAGE_VIRTUAL_MODULE_IDS) { - const pageMod = env.moduleGraph.getModuleById(id); - if (pageMod) { - env.moduleGraph.invalidateModule(pageMod); - } - } - } const mod = env.moduleGraph.getModuleById(VIRTUAL_ROUTES_ID); if (mod && routeInputsChanged) { env.moduleGraph.invalidateModule(mod); diff --git a/packages/void/test/unit/island-css-rewrite.test.ts b/packages/void/test/unit/island-css-rewrite.test.ts index e1de4757b..d5757070f 100644 --- a/packages/void/test/unit/island-css-rewrite.test.ts +++ b/packages/void/test/unit/island-css-rewrite.test.ts @@ -8,6 +8,8 @@ import { createIslandManifest, generateIslandClientEntry, islandStyleRoots, + recordIslandStyles, + recordedIslandStyles, rewriteCssImportForVirtualModule, } from '../../src/pages/islands-plugin.ts'; import type { PageDefinition } from '../../src/pages/types.ts'; @@ -124,6 +126,40 @@ describe('collectIslandStyles', () => { }); }); +describe('recordIslandStyles', () => { + it('records setup and page styles from the Pages server build and keeps them across auxiliary Worker builds', () => { + const pagesDir = p('/app-with-auxiliary-worker/pages'); + const setup = p('/app-with-auxiliary-worker/shared/setup.ts'); + const page = `${pagesDir}/index.island.vue`; + const styles = [`${pagesDir}/setup.css`, `${pagesDir}/page.css`]; + const graph = new Map([ + [setup, { importedIds: [styles[0]] }], + [page, { importedIds: [styles[1]] }], + ]); + const context = { + environment: { config: { consumer: 'server' } }, + getModuleInfo: (id: string) => graph.get(id) ?? null, + }; + const scan = { + pages: [ + { componentId: 'index', componentPath: 'index.island.vue', island: true } as PageDefinition, + ], + layouts: [], + namedLayouts: [], + }; + + recordIslandStyles(context, scan, pagesDir); + expect(recordedIslandStyles(pagesDir)).toEqual([styles[1]]); + + recordIslandStyles(context, scan, pagesDir, setup); + expect(recordedIslandStyles(pagesDir)).toEqual(styles); + + graph.delete(page); + recordIslandStyles(context, scan, pagesDir); + expect(recordedIslandStyles(pagesDir)).toEqual(styles); + }); +}); + describe('islandStyleRoots', () => { const page = (componentPath: string, island: boolean) => ({ diff --git a/packages/void/test/unit/plugin-routing.test.ts b/packages/void/test/unit/plugin-routing.test.ts index 265ed6cd1..ba7ee7ee8 100644 --- a/packages/void/test/unit/plugin-routing.test.ts +++ b/packages/void/test/unit/plugin-routing.test.ts @@ -492,6 +492,26 @@ describe('routingPlugin', () => { expect(readFileSync(typesPath, 'utf8')).toBe(before); }); + it('refreshes Vue setup entries when a route conflict keeps the last good scan', async () => { + const root = createTempRoot(); + const pages = join(root, 'pages'); + mkdirSync(join(pages, 'index'), { recursive: true }); + writeFileSync(join(pages, 'index.vue'), ''); + const setup = join(pages, '_app.ts'); + writeFileSync(setup, 'export default function setup() {}'); + + const plugin = createRoutingPlugin(root, { isAuthEnabled: () => false }); + resolveConfig(plugin, 'serve', [{ name: 'void-vue:pages' }]); + const { emit, invalidated } = await startDevServer(plugin, PAGE_MODULE_IDS); + const duplicate = join(pages, 'index', 'index.vue'); + writeFileSync(duplicate, ''); + await emit('add', duplicate); + + writeFileSync(setup, 'export const helper = true;'); + await emit('change', setup); + expect(invalidated).toEqual(PAGE_MODULE_IDS.slice(0, -1)); + }); + it('keeps page and route modules for saves that change no scanned facts', async () => { const root = createTempRoot(); mkdirSync(join(root, 'pages'), { recursive: true }); diff --git a/packages/vue/src/app-setup.ts b/packages/vue/src/app-setup.ts new file mode 100644 index 000000000..ebc315b67 --- /dev/null +++ b/packages/vue/src/app-setup.ts @@ -0,0 +1,94 @@ +import { readFileSync, statSync } from 'node:fs'; +import { join } from 'pathslash'; +import { parseSync } from 'vite'; + +const SYNCHRONOUS_SETUP_ERROR = 'pages/_app setup must be synchronous.'; + +function appSetupKind(file: string, source: string): 'sync' | 'async' | undefined { + const { program } = parseSync(file, source, { preserveParens: false }); + for (const node of program.body) { + if (node.type !== 'ExportDefaultDeclaration') { + continue; + } + const { declaration } = node; + if ( + declaration.type === 'FunctionDeclaration' || + declaration.type === 'FunctionExpression' || + declaration.type === 'ArrowFunctionExpression' + ) { + return declaration.async ? 'async' : 'sync'; + } + } +} + +export function createAppSetupResolver(pagesDir: string): () => string | undefined { + const cache = new Map }>(); + return () => { + for (const name of ['_app.ts', '_app.js']) { + const file = join(pagesDir, name); + if (!statSync(file, { throwIfNoEntry: false })?.isFile()) { + continue; + } + let source: string; + try { + source = readFileSync(file, 'utf8'); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') { + continue; + } + throw error; + } + let entry = cache.get(file); + if (entry?.source !== source) { + entry = { source, kind: appSetupKind(file, source) }; + cache.set(file, entry); + } + if (entry.kind === 'async') { + throw new Error(SYNCHRONOUS_SETUP_ERROR); + } + if (entry.kind === 'sync') { + return file; + } + } + }; +} + +export const APP_SETUP_CALL: string = ` + const appHooks = setupApp(app); + if (typeof appHooks?.then === "function") { + void Promise.resolve(appHooks).catch(() => {}); + throw new Error(${JSON.stringify(SYNCHRONOUS_SETUP_ERROR)}); + }`; + +export function generateAppErrorHandler(appSetup: string | undefined, handler: string): string { + if (!appSetup) { + return `app.config.errorHandler = ${handler};`; + } + return `{ + const handleAppError = app.config.errorHandler; + const handleVoidError = ${handler}; + app.config.errorHandler = (error, instance, info) => { + handleVoidError(error); + handleAppError?.(error, instance, info); + }; + }`; +} + +// Report the error and let Vue decide whether the server render should throw. +export const CAPTURE_SSR_ERROR: string = ` + if (reportError) onErrorCaptured((...args) => { reportError(...args); });`; + +export function generateSsrRender(appSetup: string | undefined): string { + const handler = generateAppErrorHandler(appSetup, 'error => { renderFailure ??= { error }; }'); + return `let renderFailure;${appSetup ? '\n let reportError;' : ''} + if (Object.keys(boundaryManifest.plans).length) ${handler}${ + appSetup + ? ` else { + reportError = app.config.errorHandler; + if (reportError) app.config.errorHandler = undefined; + }` + : '' + } + const html = await renderToString(app); + if (renderFailure) throw renderFailure.error;`; +} diff --git a/packages/vue/src/plugin-islands.ts b/packages/vue/src/plugin-islands.ts index 7a54d402d..cb890e076 100644 --- a/packages/vue/src/plugin-islands.ts +++ b/packages/vue/src/plugin-islands.ts @@ -20,18 +20,41 @@ import { editIslandSource, } from 'void/pages-islands-plugin'; import type { IslandSourceEdit } from 'void/pages-islands-plugin'; +import { + APP_SETUP_CALL, + CAPTURE_SSR_ERROR, + createAppSetupResolver, + generateSsrRender, +} from './app-setup.ts'; const COMPONENT_EXTENSIONS = ['.vue', '.tsx', '.jsx', '.ts', '.js']; +const ISLAND_PAGE_DATA_ID = '__VOID_ISLAND_PAGE_DATA__'; -const HYDRATE_ISLAND = ` +function generateHydrateIsland(appSetup: string | undefined, isDev: boolean): string { + const specifier = appSetup && JSON.stringify(appSetup); + // The dev CSS collector follows static imports from the client entry. + const setupImports = specifier + ? `import { deserializePageData } from "void/pages-server"; +${isDev ? `import setupApp from ${specifier};\n` : ''}const pageData = document.getElementById("${ISLAND_PAGE_DATA_ID}")?.textContent; +` + : ''; + 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);${ + specifier + ? `${isDev ? '' : `\n const { default: setupApp } = await import(${specifier});`}${APP_SETUP_CALL} + if (pageData && typeof appHooks?.hydrate === "function") { + appHooks.hydrate(deserializePageData(pageData).appState); + }` + : '' + } app.mount(el); el.setAttribute("data-hydrated", "true"); }`; +} /** Imports for the ``, @@ -29,6 +49,7 @@ import Badge from '../src/Badge.vue' with { island: 'load' }; `, }, expectedCss: [ + '.setup-probe{color:#032d43}', '.shell{outline-offset:7px}', 'main{outline-width:9px}', '{text-indent:9px}', @@ -41,4 +62,7 @@ import Badge from '../src/Badge.vue' with { island: 'load' }; const scope = html.slice(start, html.indexOf('>', start)).split(' ')[0]; expect(css, file).toContain(`.note[${scope}]{outline-width:11px}`); }, + checkBuild({ page }) { + expect(page('404.html').html).toContain('

Setup ran

'); + }, }); diff --git a/packages/vue/test/unit/plugin-pages.test.ts b/packages/vue/test/unit/plugin-pages.test.ts index ef597e502..a40fbfb3c 100644 --- a/packages/vue/test/unit/plugin-pages.test.ts +++ b/packages/vue/test/unit/plugin-pages.test.ts @@ -468,3 +468,42 @@ describe('pagesPlugin environment suffixes', () => { expect(renderer).toContain('debug.dev.vue'); }); }); + +describe('pagesPlugin app setup', () => { + afterEach(() => { + rmSync(TMP, { recursive: true, force: true }); + }); + + it.each([ + ['js', 'export default (app) => app.provide("setup", true)'], + ['ts', 'export default function setup(app: import("vue").App) { app.provide("setup", true); }'], + ])( + 'imports the _app.%s setup function in the Pages server and browser entries', + async (extension, source) => { + writePage('index.vue', ''); + const setup = `_app.${extension}`; + writePage(setup, source); + const plugin = pagesPlugin(PAGES_DIR).find( + (p) => p.name === 'void-vue:pages', + ) as PagesPluginHooks; + await getHookHandler(plugin.buildStart).call({}); + const load = getHookHandler(plugin.load); + for (const id of ['\0virtual:void-pages-renderer', '\0virtual:void-pages-client']) { + expect(await load(id)).toContain(`/pages/${setup}";`); + } + }, + ); + + it('rejects a declared async setup function during entry generation', async () => { + writePage('index.vue', ''); + writePage('_app.ts', 'export default async function setup() {}'); + const plugin = pagesPlugin(PAGES_DIR).find( + (p) => p.name === 'void-vue:pages', + ) as PagesPluginHooks; + await getHookHandler(plugin.buildStart).call({}); + const load = getHookHandler(plugin.load); + await expect(load('\0virtual:void-pages-renderer')).rejects.toThrow( + 'pages/_app setup must be synchronous.', + ); + }); +});