Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions docs/reference/api/pages.md
Original file line number Diff line number Diff line change
Expand Up @@ -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"`.
Expand Down
17 changes: 9 additions & 8 deletions packages/void/src/pages/islands-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -349,23 +349,24 @@ type IslandBuildContext = {
const islandStylesByPagesDir = new Map<string, Array<string>>();

/**
* 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);
Expand Down
34 changes: 26 additions & 8 deletions packages/void/src/plugin-routing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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.
Expand Down Expand Up @@ -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);
Expand Down
36 changes: 36 additions & 0 deletions packages/void/test/unit/island-css-rewrite.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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) =>
({
Expand Down
20 changes: 20 additions & 0 deletions packages/void/test/unit/plugin-routing.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'), '<template>Home</template>');
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, '<template>Duplicate</template>');
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 });
Expand Down
94 changes: 94 additions & 0 deletions packages/vue/src/app-setup.ts
Original file line number Diff line number Diff line change
@@ -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<string, { source: string; kind: ReturnType<typeof appSetupKind> }>();
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;`;
}
Loading