From 8bc4e19d1744138d0d2142e4f439869b841c474c Mon Sep 17 00:00:00 2001
From: Christoph Nakazawa
Date: Tue, 17 Nov 2026 19:27:21 +0900
Subject: [PATCH 01/27] test: add opt-in performance and contract reports
---
TESTING.md | 11 ++++++
package.json | 1 +
test/performance-reporter.ts | 73 ++++++++++++++++++++++++++++++++++++
3 files changed, 85 insertions(+)
create mode 100644 test/performance-reporter.ts
diff --git a/TESTING.md b/TESTING.md
index c92f9fbda..74a22f9a4 100644
--- a/TESTING.md
+++ b/TESTING.md
@@ -136,6 +136,17 @@ the cache for V8 coverage, and `NODE_V8_COVERAGE` disables it too, to preserve p
## Profiling slow tests
+Capture machine information, per-file phases, and individual test durations with:
+
+```sh
+vp run test:benchmark --outputFile=/tmp/void-test-baseline.json
+vp run test:benchmark packages/react/test/integration --outputFile=/tmp/void-react-tests.json
+```
+
+The reporter is opt-in and never skips tests. Keep the same selection, toolchain, cache state,
+and machine load when comparing reports. Per-file and per-case durations overlap when tests
+run concurrently; their sums are work estimates, not elapsed time or additive savings.
+
Vitest 5's import diagnostics are opt-in so ordinary runs stay quiet:
```sh
diff --git a/package.json b/package.json
index d4466e92d..cbf6b865f 100644
--- a/package.json
+++ b/package.json
@@ -17,6 +17,7 @@
"lint": "vp lint",
"prepare": "vp config && vp run build:core",
"test": "node test/affected.mjs",
+ "test:benchmark": "vp test run --reporter=default --reporter=./test/performance-reporter.ts",
"test:full": "vp test run",
"test:integration": "vp test run --project parallel-integration",
"test:metaframeworks": "vp test run --project parallel-integration analog.test.ts astro.test.ts nitro-worker.test.ts nuxt.test.ts react-router.test.ts sveltekit.test.ts tanstack-start.test.ts vinext-app.test.ts vinext-pages.test.ts",
diff --git a/test/performance-reporter.ts b/test/performance-reporter.ts
new file mode 100644
index 000000000..8218061d4
--- /dev/null
+++ b/test/performance-reporter.ts
@@ -0,0 +1,73 @@
+import { mkdirSync, writeFileSync } from 'node:fs';
+import { availableParallelism, cpus, platform, release, totalmem } from 'node:os';
+import { dirname, relative, resolve } from 'node:path';
+import type { Reporter, TestModule, Vitest } from 'vite-plus/test/node';
+
+/** Opt-in measurements; this reporter never participates in test selection or result reuse. */
+export default class PerformanceReporter implements Reporter {
+ private root = process.cwd();
+ private output = '';
+ private started = 0;
+
+ onInit(vitest: Vitest): void {
+ this.root = vitest.config.root;
+ const configured = vitest.config.outputFile;
+ this.output = resolve(
+ this.root,
+ (typeof configured === 'string' ? configured : configured?.performance) ??
+ 'node_modules/.cache/void-tests/performance.json',
+ );
+ this.started = performance.now();
+ }
+
+ onTestRunEnd(
+ modules: ReadonlyArray,
+ errors: ReadonlyArray,
+ reason: string,
+ ): void {
+ const files = modules.map((module) => {
+ const diagnostic = module.diagnostic();
+ return {
+ project: module.project.name,
+ file: relative(this.root, module.moduleId).replaceAll('\\', '/'),
+ durationMs: diagnostic.duration,
+ collectMs: diagnostic.collectDuration,
+ setupMs: diagnostic.setupDuration,
+ prepareMs: diagnostic.prepareDuration,
+ environmentMs: diagnostic.environmentSetupDuration,
+ worker: diagnostic.concurrencyId,
+ tests: [...module.children.allTests()].map((test) => ({
+ name: test.fullName,
+ state: test.result().state,
+ durationMs: test.diagnostic()?.duration ?? 0,
+ })),
+ };
+ });
+ mkdirSync(dirname(this.output), { recursive: true });
+ writeFileSync(
+ this.output,
+ `${JSON.stringify(
+ {
+ version: 1,
+ recordedAt: new Date().toISOString(),
+ durationMs: performance.now() - this.started,
+ reason,
+ unhandledErrors: errors.length,
+ machine: {
+ node: process.version,
+ platform: platform(),
+ release: release(),
+ arch: process.arch,
+ cpu: cpus()[0]?.model,
+ parallelism: availableParallelism(),
+ memoryBytes: totalmem(),
+ },
+ files,
+ },
+ null,
+ 2,
+ )}\n`,
+ );
+ console.log(`Test performance report: ${this.output}`);
+ }
+}
From 982a6ca335dc1acd353d960cc4c7d33ef8474231 Mon Sep 17 00:00:00 2001
From: Christoph Nakazawa
Date: Tue, 17 Nov 2026 19:29:10 +0900
Subject: [PATCH 02/27] test: schedule Pages error contracts independently by
framework
---
.../test/integration/page-errors.test.ts | 3 +
.../test/integration/page-errors.test.ts | 3 +
.../test/integration/page-errors.test.ts | 3 +
.../test/integration/page-errors.cases.ts | 717 ++++++++++++++++++
.../void/test/integration/page-errors.test.ts | 711 -----------------
.../vue/test/integration/page-errors.test.ts | 3 +
test/integration-timings.ts | 4 +
7 files changed, 733 insertions(+), 711 deletions(-)
create mode 100644 packages/react/test/integration/page-errors.test.ts
create mode 100644 packages/solid/test/integration/page-errors.test.ts
create mode 100644 packages/svelte/test/integration/page-errors.test.ts
create mode 100644 packages/void/test/integration/page-errors.cases.ts
delete mode 100644 packages/void/test/integration/page-errors.test.ts
create mode 100644 packages/vue/test/integration/page-errors.test.ts
diff --git a/packages/react/test/integration/page-errors.test.ts b/packages/react/test/integration/page-errors.test.ts
new file mode 100644
index 000000000..02b5fb2ad
--- /dev/null
+++ b/packages/react/test/integration/page-errors.test.ts
@@ -0,0 +1,3 @@
+import { definePageErrorsTests } from '../../../void/test/integration/page-errors.cases.ts';
+
+definePageErrorsTests('react');
diff --git a/packages/solid/test/integration/page-errors.test.ts b/packages/solid/test/integration/page-errors.test.ts
new file mode 100644
index 000000000..26f692d95
--- /dev/null
+++ b/packages/solid/test/integration/page-errors.test.ts
@@ -0,0 +1,3 @@
+import { definePageErrorsTests } from '../../../void/test/integration/page-errors.cases.ts';
+
+definePageErrorsTests('solid');
diff --git a/packages/svelte/test/integration/page-errors.test.ts b/packages/svelte/test/integration/page-errors.test.ts
new file mode 100644
index 000000000..e421f7ad6
--- /dev/null
+++ b/packages/svelte/test/integration/page-errors.test.ts
@@ -0,0 +1,3 @@
+import { definePageErrorsTests } from '../../../void/test/integration/page-errors.cases.ts';
+
+definePageErrorsTests('svelte');
diff --git a/packages/void/test/integration/page-errors.cases.ts b/packages/void/test/integration/page-errors.cases.ts
new file mode 100644
index 000000000..2b1b9a6e0
--- /dev/null
+++ b/packages/void/test/integration/page-errors.cases.ts
@@ -0,0 +1,717 @@
+import { execFileSync } from 'node:child_process';
+import {
+ mkdirSync,
+ rmSync,
+ writeFileSync,
+ symlinkSync,
+ realpathSync,
+ existsSync,
+ readFileSync,
+} from 'node:fs';
+import { join } from 'node:path';
+import spawn from 'cross-spawn';
+import type { Browser } from 'playwright';
+import { afterAll, beforeAll, describe, expect, it } from 'vite-plus/test';
+import {
+ createIsolatedPlayground,
+ killChild,
+ startServer,
+ type IsolatedPlayground,
+} from '../../../../test/integration-helpers.ts';
+import { launchPagesBrowser } from '../../../../test/pages-browser.ts';
+import { PAGES_PROTOCOL_VERSION } from '../../../edge/src/pages-protocol.ts';
+import { deserializePageData } from '../../src/pages/serialize.ts';
+
+const repository = join(import.meta.dirname, '../../../..');
+
+export function definePageErrorsTests(framework: 'react' | 'vue' | 'svelte' | 'solid'): void {
+ describe(`Pages errors with ${framework}`, () => {
+ let fixture: IsolatedPlayground;
+ let child: ReturnType;
+ let browser: Browser;
+ let base: string;
+ const extension = framework === 'vue' ? 'vue' : framework === 'svelte' ? 'svelte' : 'tsx';
+ function write(path: string, source: string) {
+ const file = join(fixture.root, path);
+ mkdirSync(join(file, '..'), { recursive: true });
+ writeFileSync(file, source);
+ }
+ function component(content: string, script = '', layout = false) {
+ if (framework === 'vue') {
+ return `${content}${layout ? '' : ''}`;
+ }
+ if (framework === 'svelte') {
+ return `${content}${layout ? '{@render children?.()}' : ''}`;
+ }
+ return `import { Link, useShared, useParams, useRouter } from '@void/${framework}'; export default function Component(props) { const shared = useShared(); const params = useParams(); const error = props.error; ${script} return <>${content}${layout ? '{props.children}' : ''}>; }`;
+ }
+ beforeAll(async () => {
+ fixture = createIsolatedPlayground(
+ repository,
+ framework === 'react' ? 'playground/node-app' : `playground/${framework}-pages`,
+ );
+ const nodeServer = join(fixture.root, 'node_modules/@hono/node-server');
+ if (!existsSync(nodeServer)) {
+ mkdirSync(join(nodeServer, '..'), { recursive: true });
+ symlinkSync(
+ realpathSync(join(repository, 'playground/node-app/node_modules/@hono/node-server')),
+ nodeServer,
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+ }
+ for (const dir of ['pages', 'routes', 'middleware', 'db']) {
+ rmSync(join(fixture.root, dir), { recursive: true, force: true });
+ }
+ write(
+ 'tsconfig.json',
+ JSON.stringify({
+ compilerOptions: {
+ target: 'ESNext',
+ module: 'ESNext',
+ moduleResolution: 'bundler',
+ jsx: 'preserve',
+ },
+ }),
+ );
+ write(
+ 'void.config.ts',
+ `import { defineConfig } from 'void/config'; export default defineConfig({target:'node',head:{titleTemplate:'%s | Error tests'}});`,
+ );
+ write(
+ 'middleware/shared.ts',
+ `import { defineMiddleware } from 'void/handler'; export default defineMiddleware(async (c,next)=>{c.set('shared',{viewer:'alice',...(c.req.header('X-Test-No-Root') ? { noRoot: true } : {})}); c.header('X-Security','retained'); const guard=c.req.header('X-Test-Guard'); if(guard==='not-found') return c.notFound(); if(guard==='explicit') return c.text('Hidden by guard',404); await next(); if(guard==='after-not-found') c.res=await c.notFound();});`,
+ );
+ write('pages/style.css', 'nav { color: rgb(20, 80, 100); }');
+ write(
+ 'middleware/status.ts',
+ `import { defineMiddleware } from 'void/handler';
+import { HTTPException } from 'hono/http-exception';
+export default defineMiddleware(async (c, next) => {
+ const status = c.req.header('X-Test-Error-Status');
+ if (status === '403' || status === '503') {
+ c.header('Retry-After', '120');
+ throw new HTTPException(status === '403' ? 403 : 503, {
+ message: status === '403' ? 'Your account is banned' : 'Down for maintenance',
+ });
+ }
+ await next();
+});`,
+ );
+ const nav =
+ '';
+ let rootLayout = component(nav, '', true);
+ if (framework === 'vue' || framework === 'svelte') {
+ rootLayout = rootLayout
+
+ .replace('import { Link,', "import './style.css'; import { Link,");
+ } else {
+ rootLayout = `import './style.css'; ${rootLayout}`;
+ }
+ write(`pages/layout.${extension}`, rootLayout);
+ write(
+ `pages/index.${extension}`,
+ component(
+ 'Home page
',
+ "const router = useRouter(); if(typeof window!=='undefined') window.testRouter=router;",
+ ),
+ );
+ write(
+ `pages/_not-found.${extension}`,
+ component(
+ 'Missing page
{error.message}
',
+ "if(shared.noRoot) throw new Error('UNUSED_ROOT_BOUNDARY');",
+ ),
+ );
+ write(`pages/_error.${extension}`, component('Error page
{error.message}
'));
+ if (framework === 'vue') {
+ write(
+ `pages/_not-found.${extension}`,
+ component(
+ 'Missing page
{{error.message}}
',
+ "if(shared.noRoot) throw new Error('UNUSED_ROOT_BOUNDARY');",
+ ),
+ );
+ write(
+ `pages/_error.${extension}`,
+ component('Error page
{{error.message}}
'),
+ );
+ }
+ write(`pages/items/[id].${extension}`, component('Item
'));
+ write(`pages/status/[code].${extension}`, component('Status page
'));
+ write(
+ 'pages/status/[code].server.ts',
+ `import { defineHandler } from 'void/handler';
+export const loader = defineHandler(c => {
+ c.status(c.req.param('code') === '403' ? 403 : 503);
+ c.header('Retry-After', '120');
+ return {};
+});`,
+ );
+ for (const name of ['falsy', 'island-falsy.island']) {
+ write(`pages/${name}.${extension}`, component('Broken view
', 'throw undefined;'));
+ }
+ write(
+ 'pages/items/[id].server.ts',
+ `import { defineHandler } from 'void/handler'; import { HTTPException } from 'hono/http-exception'; export const loader = defineHandler(c=>{const id=c.req.param('id'); if(id==='returned') return c.notFound(); if(id==='thrown') throw new HTTPException(404,{message:'Deleted item'}); if(id==='unexpected') throw Object.assign(new Error('SECRET_SERVER_MARKER'),{secret:'SECRET_CUSTOM_MARKER'}); return {};});`,
+ );
+ write(
+ `pages/crash.${extension}`,
+ component(
+ 'Crash route
',
+ `if(typeof window!=='undefined') throw new Error('SECRET_CLIENT_MARKER');`,
+ ),
+ );
+ write(
+ `pages/nested/layout.${extension}`,
+ component(
+ '',
+ "if(params.kind==='layout') throw new Error('SECRET_LAYOUT_MARKER');",
+ true,
+ ),
+ );
+ write(`pages/nested/_error.${extension}`, component('Nested error
'));
+ write(
+ `pages/nested/deep/_error.${extension}`,
+ component('Broken fallback
', "throw new Error('SECRET_FALLBACK_MARKER');"),
+ );
+ for (const prefix of ['nested', 'nested/deep']) {
+ write(
+ `pages/${prefix}/[kind].${extension}`,
+ component(
+ 'Nested route
',
+ "if(params.kind==='server'||(params.kind!=='healthy'&&typeof window!=='undefined')) throw new Error('SECRET_RENDER_MARKER');",
+ ),
+ );
+ }
+ write(
+ `pages/client-only.${extension}`,
+ component(
+ 'Client only
',
+ "if(typeof window==='undefined') throw new Error('SECRET_SSR_DISABLED');",
+ ),
+ );
+ write(
+ 'pages/client-only.server.ts',
+ 'export const ssr = false; export const loader = () => new Response(null,{status:404});',
+ );
+ write(
+ `pages/retry.${extension}`,
+ component(
+ 'Recovered page
',
+ "if(typeof window!=='undefined'&&!window.recovered) throw new Error('SECRET_RETRY');",
+ ),
+ );
+ write(
+ `pages/fatal/[kind].${extension}`,
+ component(
+ 'Fatal route
',
+ "if(typeof window!=='undefined') throw new Error('SECRET_FATAL');",
+ ),
+ );
+ write(
+ 'routes/old-terminal.ts',
+ "export default (c) => c.redirect('/fatal/terminal?from=old');",
+ );
+ write(
+ `pages/_error.${extension}`,
+ component(
+ framework === 'vue'
+ ? 'Error page
{{error.message}}
'
+ : 'Error page
{error.message}
',
+ "if(params.kind==='terminal') throw new Error('SECRET_TERMINAL');",
+ ),
+ );
+ write(`pages/nested/other.${extension}`, component('Other nested page
'));
+ write(`pages/islands/index.island.${extension}`, component('Island document
'));
+ write('pages/islands/index.server.ts', 'export const loader = c => c.notFound();');
+ write(`pages/islands/_not-found.${extension}`, component('Missing island page
'));
+ const counter =
+ framework === 'react'
+ ? "import {useState} from 'react'; export default function Counter(){const [n,setN]=useState(0);return }"
+ : framework === 'solid'
+ ? "import {createSignal} from 'solid-js'; export default function Counter(){const [n,setN]=createSignal(0);return }"
+ : framework === 'vue'
+ ? ''
+ : '';
+ write(`pages/islands/_Counter.${extension}`, counter);
+ let islandLayout = component('', '', true);
+ const counterImport = `import Counter from './_Counter.${extension}' with {island:'load'};`;
+ islandLayout =
+ framework === 'vue' || framework === 'svelte'
+ ? islandLayout.replace('import { Link,', counterImport + '\n import { Link,')
+ : counterImport + islandLayout;
+ write(`pages/islands/layout.island.${extension}`, islandLayout);
+ for (const section of ['alpha', 'beta']) {
+ write(
+ `pages/${section}/index.${extension}`,
+ component(
+ 'Section page
',
+ "if(typeof window!=='undefined') throw new Error('SECRET_SECTION');",
+ ),
+ );
+ write(`pages/${section}/_error.${extension}`, component(`${section} error
`));
+ }
+ write(`pages/hmr/index.${extension}`, component('HMR route
'));
+ write(
+ 'pages/hmr/index.server.ts',
+ 'export const loader = () => new Response(null,{status:404});',
+ );
+ write('routes/api/missing.ts', `export const GET = c => c.text('API missing',404);`);
+ execFileSync('vp', ['build'], {
+ cwd: fixture.root,
+ stdio: 'pipe',
+ timeout: 60_000,
+ env: { ...process.env, NODE_ENV: 'production' },
+ });
+ const server = await startServer(
+ (port) =>
+ (child = spawn(process.execPath, ['dist/ssr/index.js'], {
+ cwd: fixture.root,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ env: { ...process.env, PORT: String(port) },
+ })),
+ 30_000,
+ );
+ base = server.base;
+ browser = await launchPagesBrowser();
+ }, 90_000);
+ afterAll(async () => {
+ await browser?.close();
+ if (child) {
+ await killChild(child);
+ }
+ fixture?.cleanup();
+ });
+ it.each(['not-found', 'after-not-found'])(
+ 'uses the root not-found for middleware guards (%s) and preserves explicit responses',
+ async (guard) => {
+ for (const pages of [false, true]) {
+ const headers = {
+ 'X-Test-Guard': guard,
+ ...(pages && { 'X-VoidPages': 'true', 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION }),
+ };
+ const response = await fetch(base + '/islands', { headers });
+ expect(response.status).toBe(404);
+ expect(response.headers.get('X-Security')).toBe('retained');
+ const body = await response.text();
+ if (pages) {
+ expect(response.headers.get('X-VoidPages')).toBe('true');
+ const data = deserializePageData<{ component: string }>(body);
+ expect(data.component).toContain('_void:boundary:root-not-found:');
+ expect(data).toMatchObject({
+ props: { error: { status: 404, message: 'Not Found' } },
+ shared: { viewer: 'alice' },
+ });
+ } else {
+ expect(body).toContain('Missing page');
+ expect(body).toContain('data-layout="root"');
+ expect(body).not.toContain('Missing island page');
+ }
+ const explicit = await fetch(base + '/islands', {
+ headers: { ...headers, 'X-Test-Guard': 'explicit' },
+ });
+ expect(explicit.status).toBe(404);
+ expect(explicit.headers.has('X-VoidPages')).toBe(false);
+ expect(await explicit.text()).toBe('Hidden by guard');
+ }
+ },
+ );
+
+ it('renders a loader not-found without attempting an unused root boundary', async () => {
+ const response = await fetch(base + '/islands', { headers: { 'X-Test-No-Root': 'true' } });
+ expect(response.status).toBe(404);
+ expect(await response.text()).toContain('Missing island page');
+ });
+
+ it.each(
+ ([403, 503] as const).flatMap((status) =>
+ (['HTML', 'Pages JSON'] as const).map((format) => ({ status, format })),
+ ),
+ )(
+ 'renders middleware errors through the root page boundary with HTTP $status ($format)',
+ async ({ status, format }) => {
+ const message = status === 403 ? 'Your account is banned' : 'Down for maintenance';
+ // This route throws a different error if its loader is reached.
+ const response = await fetch(base + '/items/unexpected', {
+ headers: {
+ 'X-Test-Error-Status': String(status),
+ ...(format === 'Pages JSON'
+ ? { 'X-VoidPages': 'true', 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION }
+ : { Accept: 'text/html' }),
+ },
+ });
+ const body = await response.text();
+ expect(response.status).toBe(status);
+ expect(body).not.toContain('SECRET_');
+ if (format === 'Pages JSON') {
+ expect(response.headers.get('X-VoidPages')).toBe('true');
+ expect(deserializePageData(body)).toMatchObject({
+ props: { error: { status, message } },
+ shared: { viewer: 'alice' },
+ url: '/items/unexpected',
+ });
+ } else {
+ expect(response.headers.get('Content-Type')).toContain('text/html');
+ expect(body).toContain('Error page');
+ expect(body).toContain(message);
+ expect(body).toContain('data-layout="root"');
+ expect(body).toContain('stylesheet');
+ }
+ expect(response.headers.get('Retry-After')).toBe('120');
+ expect(response.headers.get('X-Security')).toBe('retained');
+ expect(response.headers.get('Cache-Control')).toBe('no-store');
+ },
+ );
+
+ it('returns status-correct documents and marked error payloads without exposing secrets', async () => {
+ for (const [path, status] of [
+ ['/unknown', 404],
+ ['/items/returned', 404],
+ ['/items/thrown', 404],
+ ['/items/unexpected', 500],
+ ] as const) {
+ for (const pages of [false, true]) {
+ const response = await fetch(base + path, {
+ headers: pages
+ ? { 'X-VoidPages': 'true', 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION }
+ : { Accept: 'text/html' },
+ });
+ expect(response.status, path).toBe(status);
+ expect(response.headers.get('Cache-Control')).toBe('no-store');
+ expect(response.headers.get('X-Security')).toBe('retained');
+ const text = await response.text();
+ expect(text).not.toContain('SECRET_');
+ const title = `${status === 404 ? 'Not Found' : 'Internal Server Error'} | Error tests`;
+ if (pages) {
+ expect(response.headers.get('X-VoidPages')).toBe('true');
+ expect(deserializePageData(text)).toMatchObject({
+ url: path,
+ shared: { viewer: 'alice' },
+ props: { error: { status } },
+ head: { title },
+ });
+ } else {
+ expect(text).toContain('data-layout="root"');
+ expect(text).toContain(`${title}`);
+ }
+ }
+ }
+ for (const path of [
+ '/nested/server',
+ '/nested/deep/server',
+ '/nested/layout',
+ '/falsy',
+ '/island-falsy',
+ ]) {
+ const document = await fetch(base + path);
+ expect(document.status, path).toBe(500);
+ const html = await document.text();
+ expect(html).toContain(
+ path.endsWith('/layout') || path.includes('falsy') ? 'Error page' : 'Nested error',
+ );
+ expect(html).not.toContain('SECRET_');
+ }
+ const response = await fetch(base + '/api/missing');
+ expect(response.status).toBe(404);
+ expect(await response.text()).toBe('API missing');
+ });
+ it('renders application-defined error statuses on document loads and client visits', async () => {
+ const page = await browser.newPage();
+ page.setDefaultTimeout(8_000);
+ try {
+ for (const status of [403, 503]) {
+ const path = `/status/${status}`;
+ const documentResponse = await fetch(base + path);
+ expect(documentResponse.status).toBe(status);
+ expect(documentResponse.headers.get('Retry-After')).toBe('120');
+ expect(await documentResponse.text()).toContain('Status page');
+
+ await page.goto(base);
+ await page.waitForSelector('#app[data-hydrated="true"]');
+ await page.evaluate(() =>
+ document.querySelector('nav')!.setAttribute('data-retained', 'yes'),
+ );
+ const navigation = page.waitForResponse(
+ (response) =>
+ response.url() === base + path &&
+ response.request().headers()['x-voidpages'] === 'true',
+ );
+ await page.evaluate(`window.testRouter.visit(${JSON.stringify(path)})`);
+ const response = await navigation;
+ expect(response.status()).toBe(status);
+ expect(response.headers()['x-voidpages']).toBe('true');
+ await expect.poll(() => page.locator('h1').textContent()).toBe('Status page');
+ expect(await page.locator('nav').getAttribute('data-retained')).toBe('yes');
+ }
+ } finally {
+ await page.close();
+ }
+ });
+
+ it('keeps the app and outer layout mounted across 404s and client errors', async () => {
+ const page = await browser.newPage();
+ const errors: Array = [];
+ page.on('pageerror', (e) => errors.push(e.stack ?? e.message));
+ page.on('console', (m) => {
+ if (m.type() === 'error') {
+ errors.push(m.text());
+ }
+ });
+ page.setDefaultTimeout(8_000);
+ try {
+ await page.goto(base);
+ await page.waitForSelector('#app[data-hydrated="true"]');
+ await page.evaluate(() => {
+ (window as unknown as { marker: boolean }).marker = true;
+ document.querySelector('nav')!.setAttribute('data-retained', 'yes');
+ });
+ for (const name of ['Returned', 'Thrown', 'Unexpected', 'Crash']) {
+ await page.getByRole('link', { name, exact: true }).click();
+ await expect
+ .poll(() => page.locator('h1').textContent())
+ .toBe(name === 'Returned' || name === 'Thrown' ? 'Missing page' : 'Error page');
+ if (name !== 'Crash') {
+ await expect
+ .poll(() => page.title())
+ .toBe(
+ `${name === 'Unexpected' ? 'Internal Server Error' : 'Not Found'} | Error tests`,
+ );
+ }
+ expect(await page.evaluate(() => (window as unknown as { marker: boolean }).marker)).toBe(
+ true,
+ );
+ expect(await page.locator('nav').getAttribute('data-retained')).toBe('yes');
+ expect(await page.locator('body').textContent()).not.toContain('SECRET_');
+ }
+ } catch (error) {
+ console.error(framework, page.url(), errors);
+ throw error;
+ } finally {
+ await page.close();
+ }
+ });
+ it('escalates failed fallbacks and layouts while retaining healthy ancestors', async () => {
+ const page = await browser.newPage();
+ const errors: Array = [];
+ page.on('pageerror', (e) => errors.push(e.stack ?? e.message));
+ page.on('console', (m) => {
+ if (m.type() === 'error') {
+ errors.push(m.text());
+ }
+ });
+ page.setDefaultTimeout(8_000);
+ try {
+ await page.goto(base);
+ await page.waitForSelector('#app[data-hydrated="true"]');
+ await page.evaluate(() =>
+ document.querySelector('nav')!.setAttribute('data-retained', 'yes'),
+ );
+ for (const [link, expected] of [
+ ['Nested', 'Nested error'],
+ ['Deep', 'Nested error'],
+ ['Layout', 'Error page'],
+ ['Client only', 'Missing page'],
+ ]) {
+ await page.getByRole('link', { name: link, exact: true }).click();
+ await expect.poll(() => page.locator('h1').textContent()).toBe(expected);
+ expect(await page.locator('nav').getAttribute('data-retained')).toBe('yes');
+ expect(await page.locator('body').textContent()).not.toContain('SECRET_');
+ await page.getByRole('link', { name: 'Home', exact: true }).click();
+ await expect.poll(() => page.locator('h1').textContent()).toBe('Home page');
+ }
+ await page.goto(base + '/nested/deep/server');
+ await page.waitForSelector('#app[data-hydrated="true"]');
+ expect(await page.locator('h1').textContent()).toBe('Nested error');
+ expect(await page.locator('body').textContent()).not.toContain('SECRET_');
+ } catch (error) {
+ console.error(framework, page.url(), errors);
+ throw error;
+ } finally {
+ await page.close();
+ }
+ });
+
+ it('refreshes a failed client page, preserves a common nested layout, and settles terminal navigation', async () => {
+ const page = await browser.newPage();
+ page.setDefaultTimeout(8_000);
+ try {
+ await page.goto(base);
+ await page.waitForSelector('#app[data-hydrated="true"]');
+ const visit = (url: string) =>
+ page.evaluate(
+ `window.testRouter.visit(${JSON.stringify(url)}).then(() => 'resolved', () => 'rejected')`,
+ );
+ await visit('/retry');
+ await expect.poll(() => page.locator('h1').textContent()).toBe('Error page');
+ await page.evaluate('window.recovered=true; window.testRouter.refresh()');
+ await expect.poll(() => page.locator('h1').textContent()).toBe('Recovered page');
+ for (const section of ['alpha', 'beta']) {
+ await visit('/' + section);
+ await expect.poll(() => page.locator('h1').textContent()).toBe(section + ' error');
+ }
+ await visit('/nested/healthy');
+ await page
+ .locator('section[data-layout="nested"]')
+ .evaluate((el) => el.setAttribute('data-retained', 'yes'));
+ await visit('/nested/other');
+ expect(
+ await page.locator('section[data-layout="nested"]').getAttribute('data-retained'),
+ ).toBe('yes');
+ await visit('/old-terminal');
+ await expect.poll(() => page.locator('h1').textContent()).toBe('Something went wrong');
+ expect(new URL(page.url()).pathname).toBe('/fatal/terminal');
+ expect(new URL(page.url()).search).toBe('?from=old');
+ expect(
+ await page.getByRole('link', { name: 'Try again', exact: true }).getAttribute('href'),
+ ).toBe(base + '/fatal/terminal?from=old');
+ } finally {
+ await page.close();
+ }
+ });
+ it('hydrates retained layout islands in a server-only boundary document', async () => {
+ const response = await fetch(base + '/islands');
+ expect(response.status).toBe(404);
+ const html = await response.text();
+ expect(html).toContain('Missing island page');
+ expect(html).not.toContain('__VOID_PAGE_DATA__');
+ const page = await browser.newPage();
+ try {
+ await page.goto(base + '/islands');
+ await page.waitForSelector('[data-island][data-hydrated="true"]');
+ await page.getByRole('button', { name: 'Count: 0', exact: true }).click();
+ await expect.poll(() => page.getByRole('button').textContent()).toBe('Count: 1');
+ } finally {
+ await page.close();
+ }
+ });
+
+ it('refreshes boundary metadata when files are added and removed during development', async () => {
+ await killChild(child);
+ write('public/download', 'Download bytes');
+ const dev = await startServer(
+ (port) =>
+ (child = spawn(
+ 'vp',
+ ['dev', '--host', '127.0.0.1', '--port', String(port), '--strictPort'],
+ {
+ cwd: fixture.root,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ env: { ...process.env, NODE_ENV: 'development' },
+ },
+ )),
+ 30_000,
+ );
+ try {
+ const download = await fetch(dev.base + '/download');
+ expect(download.status).toBe(200);
+ expect(await download.text()).toBe('Download bytes');
+ const missing = await fetch(dev.base + '/hmr');
+ expect(missing.status).toBe(404);
+ expect(await missing.text()).toContain('Missing page');
+ const file = `pages/hmr/_not-found.${extension}`;
+ write(file, component('HMR missing page
'));
+ await expect
+ .poll(async () => (await fetch(dev.base + '/hmr')).text(), { timeout: 10_000 })
+ .toContain('HMR missing page');
+ rmSync(join(fixture.root, file));
+ await expect
+ .poll(async () => (await fetch(dev.base + '/hmr')).text(), { timeout: 10_000 })
+ .not.toContain('HMR missing page');
+ const updated = await fetch(dev.base + '/hmr');
+ expect(updated.status).toBe(404);
+ expect(await updated.text()).toContain('Missing page');
+ } finally {
+ await killChild(child);
+ rmSync(join(fixture.root, 'public/download'));
+ }
+
+ write('public/404.html', 'Static fallback
');
+ write(
+ 'void.config.ts',
+ "import { defineConfig } from 'void/config'; export default defineConfig({target:'node',routing:{trailingSlash:true}});",
+ );
+ const trailing = await startServer(
+ (port) =>
+ (child = spawn(
+ 'vp',
+ ['dev', '--host', '127.0.0.1', '--port', String(port), '--strictPort'],
+ {
+ cwd: fixture.root,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ env: { ...process.env, NODE_ENV: 'development' },
+ },
+ )),
+ 30_000,
+ );
+ const page = await browser.newPage();
+ try {
+ const module = await fetch(trailing.base + '/pages/index.' + extension);
+ expect(module.status).toBe(200);
+ expect(await module.text()).not.toContain('Static fallback');
+ await page.goto(trailing.base);
+ await page.waitForSelector('#app[data-hydrated="true"]');
+ await page.getByRole('link', { name: 'Returned', exact: true }).click();
+ await expect.poll(() => page.locator('h1').textContent()).toBe('Missing page');
+ } finally {
+ await page.close();
+ await killChild(child);
+ rmSync(join(fixture.root, 'public/404.html'));
+ }
+ });
+ it('generates a server-only static 404 without request middleware or hydration data', async () => {
+ await killChild(child);
+ for (const path of [
+ 'pages/hmr',
+ 'pages/alpha',
+ 'pages/beta',
+ 'pages/fatal',
+ 'pages/retry.' + extension,
+ 'pages/islands',
+ 'pages/nested',
+ 'pages/crash.' + extension,
+ 'pages/client-only.' + extension,
+ 'pages/client-only.server.ts',
+ 'pages/items',
+ 'pages/falsy.' + extension,
+ 'pages/island-falsy.island.' + extension,
+ ]) {
+ rmSync(join(fixture.root, path), { recursive: true, force: true });
+ }
+ write(
+ 'void.config.ts',
+ "import { defineConfig } from 'void/config'; export default defineConfig({target:'node',output:'static'});",
+ );
+ execFileSync('vp', ['build'], {
+ cwd: fixture.root,
+ stdio: 'pipe',
+ timeout: 60_000,
+ env: { ...process.env, NODE_ENV: 'production' },
+ });
+ const html = readFileSync(join(fixture.root, 'dist/client/404.html'), 'utf8');
+ expect(html).toContain('Missing page');
+ expect(html).toContain('data-layout="root"');
+ expect(html).toContain('stylesheet');
+ expect(html).not.toContain('__VOID_PAGE_DATA__');
+ expect(html).not.toContain('type="module"');
+ expect(html).not.toContain('alice');
+ expect(existsSync(join(fixture.root, 'dist/client/_void/pages/404.json'))).toBe(false);
+ if (framework === 'react') {
+ rmSync(join(fixture.root, 'pages/index.tsx'));
+ write(
+ 'void.config.ts',
+ "import { defineConfig } from 'void/config'; export default defineConfig({target:'cloudflare',output:'static'});",
+ );
+ execFileSync('vp', ['build'], {
+ cwd: fixture.root,
+ stdio: 'pipe',
+ timeout: 60_000,
+ env: { ...process.env, NODE_ENV: 'production' },
+ });
+ const native404 = readFileSync(join(fixture.root, 'dist/client/404.html'), 'utf8');
+ expect(native404).toContain('Missing page');
+ expect(native404).not.toContain('__VOID_PAGE_DATA__');
+ expect(native404).not.toContain('type="module"');
+ }
+ });
+ });
+}
diff --git a/packages/void/test/integration/page-errors.test.ts b/packages/void/test/integration/page-errors.test.ts
deleted file mode 100644
index 5c284eef7..000000000
--- a/packages/void/test/integration/page-errors.test.ts
+++ /dev/null
@@ -1,711 +0,0 @@
-import { execFileSync } from 'node:child_process';
-import {
- mkdirSync,
- rmSync,
- writeFileSync,
- symlinkSync,
- realpathSync,
- existsSync,
- readFileSync,
-} from 'node:fs';
-import { join } from 'node:path';
-import spawn from 'cross-spawn';
-import type { Browser } from 'playwright';
-import { afterAll, beforeAll, describe, expect, it } from 'vite-plus/test';
-import {
- createIsolatedPlayground,
- killChild,
- startServer,
- type IsolatedPlayground,
-} from '../../../../test/integration-helpers.ts';
-import { launchPagesBrowser } from '../../../../test/pages-browser.ts';
-import { PAGES_PROTOCOL_VERSION } from '../../../edge/src/pages-protocol.ts';
-import { deserializePageData } from '../../src/pages/serialize.ts';
-
-const repository = join(import.meta.dirname, '../../../..');
-const frameworks = ['react', 'vue', 'svelte', 'solid'] as const;
-
-describe.each(frameworks)('Pages errors with %s', (framework) => {
- let fixture: IsolatedPlayground;
- let child: ReturnType;
- let browser: Browser;
- let base: string;
- const extension = framework === 'vue' ? 'vue' : framework === 'svelte' ? 'svelte' : 'tsx';
- function write(path: string, source: string) {
- const file = join(fixture.root, path);
- mkdirSync(join(file, '..'), { recursive: true });
- writeFileSync(file, source);
- }
- function component(content: string, script = '', layout = false) {
- if (framework === 'vue') {
- return `${content}${layout ? '' : ''}`;
- }
- if (framework === 'svelte') {
- return `${content}${layout ? '{@render children?.()}' : ''}`;
- }
- return `import { Link, useShared, useParams, useRouter } from '@void/${framework}'; export default function Component(props) { const shared = useShared(); const params = useParams(); const error = props.error; ${script} return <>${content}${layout ? '{props.children}' : ''}>; }`;
- }
- beforeAll(async () => {
- fixture = createIsolatedPlayground(
- repository,
- framework === 'react' ? 'playground/node-app' : `playground/${framework}-pages`,
- );
- const nodeServer = join(fixture.root, 'node_modules/@hono/node-server');
- if (!existsSync(nodeServer)) {
- mkdirSync(join(nodeServer, '..'), { recursive: true });
- symlinkSync(
- realpathSync(join(repository, 'playground/node-app/node_modules/@hono/node-server')),
- nodeServer,
- process.platform === 'win32' ? 'junction' : 'dir',
- );
- }
- for (const dir of ['pages', 'routes', 'middleware', 'db']) {
- rmSync(join(fixture.root, dir), { recursive: true, force: true });
- }
- write(
- 'tsconfig.json',
- JSON.stringify({
- compilerOptions: {
- target: 'ESNext',
- module: 'ESNext',
- moduleResolution: 'bundler',
- jsx: 'preserve',
- },
- }),
- );
- write(
- 'void.config.ts',
- `import { defineConfig } from 'void/config'; export default defineConfig({target:'node',head:{titleTemplate:'%s | Error tests'}});`,
- );
- write(
- 'middleware/shared.ts',
- `import { defineMiddleware } from 'void/handler'; export default defineMiddleware(async (c,next)=>{c.set('shared',{viewer:'alice',...(c.req.header('X-Test-No-Root') ? { noRoot: true } : {})}); c.header('X-Security','retained'); const guard=c.req.header('X-Test-Guard'); if(guard==='not-found') return c.notFound(); if(guard==='explicit') return c.text('Hidden by guard',404); await next(); if(guard==='after-not-found') c.res=await c.notFound();});`,
- );
- write('pages/style.css', 'nav { color: rgb(20, 80, 100); }');
- write(
- 'middleware/status.ts',
- `import { defineMiddleware } from 'void/handler';
-import { HTTPException } from 'hono/http-exception';
-export default defineMiddleware(async (c, next) => {
- const status = c.req.header('X-Test-Error-Status');
- if (status === '403' || status === '503') {
- c.header('Retry-After', '120');
- throw new HTTPException(status === '403' ? 403 : 503, {
- message: status === '403' ? 'Your account is banned' : 'Down for maintenance',
- });
- }
- await next();
-});`,
- );
- const nav =
- '';
- let rootLayout = component(nav, '', true);
- if (framework === 'vue' || framework === 'svelte') {
- rootLayout = rootLayout
-
- .replace('import { Link,', "import './style.css'; import { Link,");
- } else {
- rootLayout = `import './style.css'; ${rootLayout}`;
- }
- write(`pages/layout.${extension}`, rootLayout);
- write(
- `pages/index.${extension}`,
- component(
- 'Home page
',
- "const router = useRouter(); if(typeof window!=='undefined') window.testRouter=router;",
- ),
- );
- write(
- `pages/_not-found.${extension}`,
- component(
- 'Missing page
{error.message}
',
- "if(shared.noRoot) throw new Error('UNUSED_ROOT_BOUNDARY');",
- ),
- );
- write(`pages/_error.${extension}`, component('Error page
{error.message}
'));
- if (framework === 'vue') {
- write(
- `pages/_not-found.${extension}`,
- component(
- 'Missing page
{{error.message}}
',
- "if(shared.noRoot) throw new Error('UNUSED_ROOT_BOUNDARY');",
- ),
- );
- write(`pages/_error.${extension}`, component('Error page
{{error.message}}
'));
- }
- write(`pages/items/[id].${extension}`, component('Item
'));
- write(`pages/status/[code].${extension}`, component('Status page
'));
- write(
- 'pages/status/[code].server.ts',
- `import { defineHandler } from 'void/handler';
-export const loader = defineHandler(c => {
- c.status(c.req.param('code') === '403' ? 403 : 503);
- c.header('Retry-After', '120');
- return {};
-});`,
- );
- for (const name of ['falsy', 'island-falsy.island']) {
- write(`pages/${name}.${extension}`, component('Broken view
', 'throw undefined;'));
- }
- write(
- 'pages/items/[id].server.ts',
- `import { defineHandler } from 'void/handler'; import { HTTPException } from 'hono/http-exception'; export const loader = defineHandler(c=>{const id=c.req.param('id'); if(id==='returned') return c.notFound(); if(id==='thrown') throw new HTTPException(404,{message:'Deleted item'}); if(id==='unexpected') throw Object.assign(new Error('SECRET_SERVER_MARKER'),{secret:'SECRET_CUSTOM_MARKER'}); return {};});`,
- );
- write(
- `pages/crash.${extension}`,
- component(
- 'Crash route
',
- `if(typeof window!=='undefined') throw new Error('SECRET_CLIENT_MARKER');`,
- ),
- );
- write(
- `pages/nested/layout.${extension}`,
- component(
- '',
- "if(params.kind==='layout') throw new Error('SECRET_LAYOUT_MARKER');",
- true,
- ),
- );
- write(`pages/nested/_error.${extension}`, component('Nested error
'));
- write(
- `pages/nested/deep/_error.${extension}`,
- component('Broken fallback
', "throw new Error('SECRET_FALLBACK_MARKER');"),
- );
- for (const prefix of ['nested', 'nested/deep']) {
- write(
- `pages/${prefix}/[kind].${extension}`,
- component(
- 'Nested route
',
- "if(params.kind==='server'||(params.kind!=='healthy'&&typeof window!=='undefined')) throw new Error('SECRET_RENDER_MARKER');",
- ),
- );
- }
- write(
- `pages/client-only.${extension}`,
- component(
- 'Client only
',
- "if(typeof window==='undefined') throw new Error('SECRET_SSR_DISABLED');",
- ),
- );
- write(
- 'pages/client-only.server.ts',
- 'export const ssr = false; export const loader = () => new Response(null,{status:404});',
- );
- write(
- `pages/retry.${extension}`,
- component(
- 'Recovered page
',
- "if(typeof window!=='undefined'&&!window.recovered) throw new Error('SECRET_RETRY');",
- ),
- );
- write(
- `pages/fatal/[kind].${extension}`,
- component(
- 'Fatal route
',
- "if(typeof window!=='undefined') throw new Error('SECRET_FATAL');",
- ),
- );
- write(
- 'routes/old-terminal.ts',
- "export default (c) => c.redirect('/fatal/terminal?from=old');",
- );
- write(
- `pages/_error.${extension}`,
- component(
- framework === 'vue'
- ? 'Error page
{{error.message}}
'
- : 'Error page
{error.message}
',
- "if(params.kind==='terminal') throw new Error('SECRET_TERMINAL');",
- ),
- );
- write(`pages/nested/other.${extension}`, component('Other nested page
'));
- write(`pages/islands/index.island.${extension}`, component('Island document
'));
- write('pages/islands/index.server.ts', 'export const loader = c => c.notFound();');
- write(`pages/islands/_not-found.${extension}`, component('Missing island page
'));
- const counter =
- framework === 'react'
- ? "import {useState} from 'react'; export default function Counter(){const [n,setN]=useState(0);return }"
- : framework === 'solid'
- ? "import {createSignal} from 'solid-js'; export default function Counter(){const [n,setN]=createSignal(0);return }"
- : framework === 'vue'
- ? ''
- : '';
- write(`pages/islands/_Counter.${extension}`, counter);
- let islandLayout = component('', '', true);
- const counterImport = `import Counter from './_Counter.${extension}' with {island:'load'};`;
- islandLayout =
- framework === 'vue' || framework === 'svelte'
- ? islandLayout.replace('import { Link,', counterImport + '\n import { Link,')
- : counterImport + islandLayout;
- write(`pages/islands/layout.island.${extension}`, islandLayout);
- for (const section of ['alpha', 'beta']) {
- write(
- `pages/${section}/index.${extension}`,
- component(
- 'Section page
',
- "if(typeof window!=='undefined') throw new Error('SECRET_SECTION');",
- ),
- );
- write(`pages/${section}/_error.${extension}`, component(`${section} error
`));
- }
- write(`pages/hmr/index.${extension}`, component('HMR route
'));
- write(
- 'pages/hmr/index.server.ts',
- 'export const loader = () => new Response(null,{status:404});',
- );
- write('routes/api/missing.ts', `export const GET = c => c.text('API missing',404);`);
- execFileSync('vp', ['build'], {
- cwd: fixture.root,
- stdio: 'pipe',
- timeout: 60_000,
- env: { ...process.env, NODE_ENV: 'production' },
- });
- const server = await startServer(
- (port) =>
- (child = spawn(process.execPath, ['dist/ssr/index.js'], {
- cwd: fixture.root,
- stdio: ['ignore', 'pipe', 'pipe'],
- env: { ...process.env, PORT: String(port) },
- })),
- 30_000,
- );
- base = server.base;
- browser = await launchPagesBrowser();
- }, 90_000);
- afterAll(async () => {
- await browser?.close();
- if (child) {
- await killChild(child);
- }
- fixture?.cleanup();
- });
- it.each(['not-found', 'after-not-found'])(
- 'uses the root not-found for middleware guards (%s) and preserves explicit responses',
- async (guard) => {
- for (const pages of [false, true]) {
- const headers = {
- 'X-Test-Guard': guard,
- ...(pages && { 'X-VoidPages': 'true', 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION }),
- };
- const response = await fetch(base + '/islands', { headers });
- expect(response.status).toBe(404);
- expect(response.headers.get('X-Security')).toBe('retained');
- const body = await response.text();
- if (pages) {
- expect(response.headers.get('X-VoidPages')).toBe('true');
- const data = deserializePageData<{ component: string }>(body);
- expect(data.component).toContain('_void:boundary:root-not-found:');
- expect(data).toMatchObject({
- props: { error: { status: 404, message: 'Not Found' } },
- shared: { viewer: 'alice' },
- });
- } else {
- expect(body).toContain('Missing page');
- expect(body).toContain('data-layout="root"');
- expect(body).not.toContain('Missing island page');
- }
- const explicit = await fetch(base + '/islands', {
- headers: { ...headers, 'X-Test-Guard': 'explicit' },
- });
- expect(explicit.status).toBe(404);
- expect(explicit.headers.has('X-VoidPages')).toBe(false);
- expect(await explicit.text()).toBe('Hidden by guard');
- }
- },
- );
-
- it('renders a loader not-found without attempting an unused root boundary', async () => {
- const response = await fetch(base + '/islands', { headers: { 'X-Test-No-Root': 'true' } });
- expect(response.status).toBe(404);
- expect(await response.text()).toContain('Missing island page');
- });
-
- it.each(
- ([403, 503] as const).flatMap((status) =>
- (['HTML', 'Pages JSON'] as const).map((format) => ({ status, format })),
- ),
- )(
- 'renders middleware errors through the root page boundary with HTTP $status ($format)',
- async ({ status, format }) => {
- const message = status === 403 ? 'Your account is banned' : 'Down for maintenance';
- // This route throws a different error if its loader is reached.
- const response = await fetch(base + '/items/unexpected', {
- headers: {
- 'X-Test-Error-Status': String(status),
- ...(format === 'Pages JSON'
- ? { 'X-VoidPages': 'true', 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION }
- : { Accept: 'text/html' }),
- },
- });
- const body = await response.text();
- expect(response.status).toBe(status);
- expect(body).not.toContain('SECRET_');
- if (format === 'Pages JSON') {
- expect(response.headers.get('X-VoidPages')).toBe('true');
- expect(deserializePageData(body)).toMatchObject({
- props: { error: { status, message } },
- shared: { viewer: 'alice' },
- url: '/items/unexpected',
- });
- } else {
- expect(response.headers.get('Content-Type')).toContain('text/html');
- expect(body).toContain('Error page');
- expect(body).toContain(message);
- expect(body).toContain('data-layout="root"');
- expect(body).toContain('stylesheet');
- }
- expect(response.headers.get('Retry-After')).toBe('120');
- expect(response.headers.get('X-Security')).toBe('retained');
- expect(response.headers.get('Cache-Control')).toBe('no-store');
- },
- );
-
- it('returns status-correct documents and marked error payloads without exposing secrets', async () => {
- for (const [path, status] of [
- ['/unknown', 404],
- ['/items/returned', 404],
- ['/items/thrown', 404],
- ['/items/unexpected', 500],
- ] as const) {
- for (const pages of [false, true]) {
- const response = await fetch(base + path, {
- headers: pages
- ? { 'X-VoidPages': 'true', 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION }
- : { Accept: 'text/html' },
- });
- expect(response.status, path).toBe(status);
- expect(response.headers.get('Cache-Control')).toBe('no-store');
- expect(response.headers.get('X-Security')).toBe('retained');
- const text = await response.text();
- expect(text).not.toContain('SECRET_');
- const title = `${status === 404 ? 'Not Found' : 'Internal Server Error'} | Error tests`;
- if (pages) {
- expect(response.headers.get('X-VoidPages')).toBe('true');
- expect(deserializePageData(text)).toMatchObject({
- url: path,
- shared: { viewer: 'alice' },
- props: { error: { status } },
- head: { title },
- });
- } else {
- expect(text).toContain('data-layout="root"');
- expect(text).toContain(`${title}`);
- }
- }
- }
- for (const path of [
- '/nested/server',
- '/nested/deep/server',
- '/nested/layout',
- '/falsy',
- '/island-falsy',
- ]) {
- const document = await fetch(base + path);
- expect(document.status, path).toBe(500);
- const html = await document.text();
- expect(html).toContain(
- path.endsWith('/layout') || path.includes('falsy') ? 'Error page' : 'Nested error',
- );
- expect(html).not.toContain('SECRET_');
- }
- const response = await fetch(base + '/api/missing');
- expect(response.status).toBe(404);
- expect(await response.text()).toBe('API missing');
- });
- it('renders application-defined error statuses on document loads and client visits', async () => {
- const page = await browser.newPage();
- page.setDefaultTimeout(8_000);
- try {
- for (const status of [403, 503]) {
- const path = `/status/${status}`;
- const documentResponse = await fetch(base + path);
- expect(documentResponse.status).toBe(status);
- expect(documentResponse.headers.get('Retry-After')).toBe('120');
- expect(await documentResponse.text()).toContain('Status page');
-
- await page.goto(base);
- await page.waitForSelector('#app[data-hydrated="true"]');
- await page.evaluate(() =>
- document.querySelector('nav')!.setAttribute('data-retained', 'yes'),
- );
- const navigation = page.waitForResponse(
- (response) =>
- response.url() === base + path &&
- response.request().headers()['x-voidpages'] === 'true',
- );
- await page.evaluate(`window.testRouter.visit(${JSON.stringify(path)})`);
- const response = await navigation;
- expect(response.status()).toBe(status);
- expect(response.headers()['x-voidpages']).toBe('true');
- await expect.poll(() => page.locator('h1').textContent()).toBe('Status page');
- expect(await page.locator('nav').getAttribute('data-retained')).toBe('yes');
- }
- } finally {
- await page.close();
- }
- });
-
- it('keeps the app and outer layout mounted across 404s and client errors', async () => {
- const page = await browser.newPage();
- const errors: Array = [];
- page.on('pageerror', (e) => errors.push(e.stack ?? e.message));
- page.on('console', (m) => {
- if (m.type() === 'error') {
- errors.push(m.text());
- }
- });
- page.setDefaultTimeout(8_000);
- try {
- await page.goto(base);
- await page.waitForSelector('#app[data-hydrated="true"]');
- await page.evaluate(() => {
- (window as unknown as { marker: boolean }).marker = true;
- document.querySelector('nav')!.setAttribute('data-retained', 'yes');
- });
- for (const name of ['Returned', 'Thrown', 'Unexpected', 'Crash']) {
- await page.getByRole('link', { name, exact: true }).click();
- await expect
- .poll(() => page.locator('h1').textContent())
- .toBe(name === 'Returned' || name === 'Thrown' ? 'Missing page' : 'Error page');
- if (name !== 'Crash') {
- await expect
- .poll(() => page.title())
- .toBe(`${name === 'Unexpected' ? 'Internal Server Error' : 'Not Found'} | Error tests`);
- }
- expect(await page.evaluate(() => (window as unknown as { marker: boolean }).marker)).toBe(
- true,
- );
- expect(await page.locator('nav').getAttribute('data-retained')).toBe('yes');
- expect(await page.locator('body').textContent()).not.toContain('SECRET_');
- }
- } catch (error) {
- console.error(framework, page.url(), errors);
- throw error;
- } finally {
- await page.close();
- }
- });
- it('escalates failed fallbacks and layouts while retaining healthy ancestors', async () => {
- const page = await browser.newPage();
- const errors: Array = [];
- page.on('pageerror', (e) => errors.push(e.stack ?? e.message));
- page.on('console', (m) => {
- if (m.type() === 'error') {
- errors.push(m.text());
- }
- });
- page.setDefaultTimeout(8_000);
- try {
- await page.goto(base);
- await page.waitForSelector('#app[data-hydrated="true"]');
- await page.evaluate(() =>
- document.querySelector('nav')!.setAttribute('data-retained', 'yes'),
- );
- for (const [link, expected] of [
- ['Nested', 'Nested error'],
- ['Deep', 'Nested error'],
- ['Layout', 'Error page'],
- ['Client only', 'Missing page'],
- ]) {
- await page.getByRole('link', { name: link, exact: true }).click();
- await expect.poll(() => page.locator('h1').textContent()).toBe(expected);
- expect(await page.locator('nav').getAttribute('data-retained')).toBe('yes');
- expect(await page.locator('body').textContent()).not.toContain('SECRET_');
- await page.getByRole('link', { name: 'Home', exact: true }).click();
- await expect.poll(() => page.locator('h1').textContent()).toBe('Home page');
- }
- await page.goto(base + '/nested/deep/server');
- await page.waitForSelector('#app[data-hydrated="true"]');
- expect(await page.locator('h1').textContent()).toBe('Nested error');
- expect(await page.locator('body').textContent()).not.toContain('SECRET_');
- } catch (error) {
- console.error(framework, page.url(), errors);
- throw error;
- } finally {
- await page.close();
- }
- });
-
- it('refreshes a failed client page, preserves a common nested layout, and settles terminal navigation', async () => {
- const page = await browser.newPage();
- page.setDefaultTimeout(8_000);
- try {
- await page.goto(base);
- await page.waitForSelector('#app[data-hydrated="true"]');
- const visit = (url: string) =>
- page.evaluate(
- `window.testRouter.visit(${JSON.stringify(url)}).then(() => 'resolved', () => 'rejected')`,
- );
- await visit('/retry');
- await expect.poll(() => page.locator('h1').textContent()).toBe('Error page');
- await page.evaluate('window.recovered=true; window.testRouter.refresh()');
- await expect.poll(() => page.locator('h1').textContent()).toBe('Recovered page');
- for (const section of ['alpha', 'beta']) {
- await visit('/' + section);
- await expect.poll(() => page.locator('h1').textContent()).toBe(section + ' error');
- }
- await visit('/nested/healthy');
- await page
- .locator('section[data-layout="nested"]')
- .evaluate((el) => el.setAttribute('data-retained', 'yes'));
- await visit('/nested/other');
- expect(
- await page.locator('section[data-layout="nested"]').getAttribute('data-retained'),
- ).toBe('yes');
- await visit('/old-terminal');
- await expect.poll(() => page.locator('h1').textContent()).toBe('Something went wrong');
- expect(new URL(page.url()).pathname).toBe('/fatal/terminal');
- expect(new URL(page.url()).search).toBe('?from=old');
- expect(
- await page.getByRole('link', { name: 'Try again', exact: true }).getAttribute('href'),
- ).toBe(base + '/fatal/terminal?from=old');
- } finally {
- await page.close();
- }
- });
- it('hydrates retained layout islands in a server-only boundary document', async () => {
- const response = await fetch(base + '/islands');
- expect(response.status).toBe(404);
- const html = await response.text();
- expect(html).toContain('Missing island page');
- expect(html).not.toContain('__VOID_PAGE_DATA__');
- const page = await browser.newPage();
- try {
- await page.goto(base + '/islands');
- await page.waitForSelector('[data-island][data-hydrated="true"]');
- await page.getByRole('button', { name: 'Count: 0', exact: true }).click();
- await expect.poll(() => page.getByRole('button').textContent()).toBe('Count: 1');
- } finally {
- await page.close();
- }
- });
-
- it('refreshes boundary metadata when files are added and removed during development', async () => {
- await killChild(child);
- write('public/download', 'Download bytes');
- const dev = await startServer(
- (port) =>
- (child = spawn(
- 'vp',
- ['dev', '--host', '127.0.0.1', '--port', String(port), '--strictPort'],
- {
- cwd: fixture.root,
- stdio: ['ignore', 'pipe', 'pipe'],
- env: { ...process.env, NODE_ENV: 'development' },
- },
- )),
- 30_000,
- );
- try {
- const download = await fetch(dev.base + '/download');
- expect(download.status).toBe(200);
- expect(await download.text()).toBe('Download bytes');
- const missing = await fetch(dev.base + '/hmr');
- expect(missing.status).toBe(404);
- expect(await missing.text()).toContain('Missing page');
- const file = `pages/hmr/_not-found.${extension}`;
- write(file, component('HMR missing page
'));
- await expect
- .poll(async () => (await fetch(dev.base + '/hmr')).text(), { timeout: 10_000 })
- .toContain('HMR missing page');
- rmSync(join(fixture.root, file));
- await expect
- .poll(async () => (await fetch(dev.base + '/hmr')).text(), { timeout: 10_000 })
- .not.toContain('HMR missing page');
- const updated = await fetch(dev.base + '/hmr');
- expect(updated.status).toBe(404);
- expect(await updated.text()).toContain('Missing page');
- } finally {
- await killChild(child);
- rmSync(join(fixture.root, 'public/download'));
- }
-
- write('public/404.html', 'Static fallback
');
- write(
- 'void.config.ts',
- "import { defineConfig } from 'void/config'; export default defineConfig({target:'node',routing:{trailingSlash:true}});",
- );
- const trailing = await startServer(
- (port) =>
- (child = spawn(
- 'vp',
- ['dev', '--host', '127.0.0.1', '--port', String(port), '--strictPort'],
- {
- cwd: fixture.root,
- stdio: ['ignore', 'pipe', 'pipe'],
- env: { ...process.env, NODE_ENV: 'development' },
- },
- )),
- 30_000,
- );
- const page = await browser.newPage();
- try {
- const module = await fetch(trailing.base + '/pages/index.' + extension);
- expect(module.status).toBe(200);
- expect(await module.text()).not.toContain('Static fallback');
- await page.goto(trailing.base);
- await page.waitForSelector('#app[data-hydrated="true"]');
- await page.getByRole('link', { name: 'Returned', exact: true }).click();
- await expect.poll(() => page.locator('h1').textContent()).toBe('Missing page');
- } finally {
- await page.close();
- await killChild(child);
- rmSync(join(fixture.root, 'public/404.html'));
- }
- });
- it('generates a server-only static 404 without request middleware or hydration data', async () => {
- await killChild(child);
- for (const path of [
- 'pages/hmr',
- 'pages/alpha',
- 'pages/beta',
- 'pages/fatal',
- 'pages/retry.' + extension,
- 'pages/islands',
- 'pages/nested',
- 'pages/crash.' + extension,
- 'pages/client-only.' + extension,
- 'pages/client-only.server.ts',
- 'pages/items',
- 'pages/falsy.' + extension,
- 'pages/island-falsy.island.' + extension,
- ]) {
- rmSync(join(fixture.root, path), { recursive: true, force: true });
- }
- write(
- 'void.config.ts',
- "import { defineConfig } from 'void/config'; export default defineConfig({target:'node',output:'static'});",
- );
- execFileSync('vp', ['build'], {
- cwd: fixture.root,
- stdio: 'pipe',
- timeout: 60_000,
- env: { ...process.env, NODE_ENV: 'production' },
- });
- const html = readFileSync(join(fixture.root, 'dist/client/404.html'), 'utf8');
- expect(html).toContain('Missing page');
- expect(html).toContain('data-layout="root"');
- expect(html).toContain('stylesheet');
- expect(html).not.toContain('__VOID_PAGE_DATA__');
- expect(html).not.toContain('type="module"');
- expect(html).not.toContain('alice');
- expect(existsSync(join(fixture.root, 'dist/client/_void/pages/404.json'))).toBe(false);
- if (framework === 'react') {
- rmSync(join(fixture.root, 'pages/index.tsx'));
- write(
- 'void.config.ts',
- "import { defineConfig } from 'void/config'; export default defineConfig({target:'cloudflare',output:'static'});",
- );
- execFileSync('vp', ['build'], {
- cwd: fixture.root,
- stdio: 'pipe',
- timeout: 60_000,
- env: { ...process.env, NODE_ENV: 'production' },
- });
- const native404 = readFileSync(join(fixture.root, 'dist/client/404.html'), 'utf8');
- expect(native404).toContain('Missing page');
- expect(native404).not.toContain('__VOID_PAGE_DATA__');
- expect(native404).not.toContain('type="module"');
- }
- });
-});
diff --git a/packages/vue/test/integration/page-errors.test.ts b/packages/vue/test/integration/page-errors.test.ts
new file mode 100644
index 000000000..6569f6a70
--- /dev/null
+++ b/packages/vue/test/integration/page-errors.test.ts
@@ -0,0 +1,3 @@
+import { definePageErrorsTests } from '../../../void/test/integration/page-errors.cases.ts';
+
+definePageErrorsTests('vue');
diff --git a/test/integration-timings.ts b/test/integration-timings.ts
index ef386ccae..8fbcd168a 100644
--- a/test/integration-timings.ts
+++ b/test/integration-timings.ts
@@ -2,6 +2,10 @@
// Edited suites use conservative estimates adjusted for removed browser cases and duplicate builds.
// These values schedule shards only; every discovered test is still included.
export const integrationTimings: Readonly> = {
+ 'packages/solid/test/integration/page-errors.test.ts': 15000,
+ 'packages/svelte/test/integration/page-errors.test.ts': 15000,
+ 'packages/vue/test/integration/page-errors.test.ts': 15000,
+ 'packages/react/test/integration/page-errors.test.ts': 15000,
'packages/md/test/integration/markdown-blog.test.ts': 42014,
'packages/react/test/integration/react-pages-client.test.ts': 43000,
'packages/react/test/integration/react-pages-navigation-fallback.test.ts': 6920,
From 5c63fe4d78fdb6df990e91768e6884a90b93bb1e Mon Sep 17 00:00:00 2001
From: Christoph Nakazawa
Date: Tue, 17 Nov 2026 20:11:38 +0900
Subject: [PATCH 03/27] build: cache explicit prerequisites and prepare
integration artifacts safely
---
TESTING.md | 13 +++
package.json | 13 ---
packages/create-void/package.json | 1 -
packages/create-void/vite.config.ts | 8 ++
packages/deploy-cloudflare/package.json | 1 -
packages/deploy-cloudflare/vite.config.ts | 12 ++
packages/deploy-core/package.json | 1 -
packages/deploy-core/vite.config.ts | 12 ++
packages/edge/package.json | 1 -
packages/edge/vite.config.ts | 12 ++
packages/isr/package.json | 1 -
packages/isr/vite.config.ts | 8 ++
packages/md/package.json | 1 -
.../md/test/integration/markdown-blog.test.ts | 8 +-
packages/md/vite.config.ts | 8 ++
packages/platform/package.json | 1 -
packages/platform/vite.config.ts | 4 +
packages/react/package.json | 1 -
.../integration/react-pages-client.test.ts | 12 +-
packages/react/vite.config.ts | 8 ++
packages/solid/package.json | 1 -
.../solid-pages-playground.test.ts | 10 +-
packages/solid/vite.config.ts | 8 ++
packages/svelte/package.json | 1 -
.../integration/svelte-pages-client.test.ts | 12 +-
packages/svelte/vite.config.ts | 8 ++
packages/void/package.json | 1 -
.../test/integration/kitchen-sink.test.ts | 8 +-
.../void/test/integration/mysql-test.test.ts | 5 +-
.../test/integration/node-static-md.test.ts | 4 +-
.../void/test/integration/node-static.test.ts | 6 +-
.../void/test/integration/pg-api-test.test.ts | 5 +-
.../integration/plugin-cloudflare-v2.test.ts | 1 +
.../test/integration/react-router.test.ts | 2 +-
.../test/integration/ssr-playground.test.ts | 5 +-
.../test/integration/static-pages.test.ts | 4 +-
.../integration/websockets-playground.test.ts | 14 ++-
packages/void/vite.config.ts | 8 ++
packages/vue/package.json | 1 -
.../test/integration/vue-pages-client.test.ts | 12 +-
packages/vue/vite.config.ts | 8 ++
.../api/test/integration/global-setup.ts | 4 +-
platform/packages/dashboard/package.json | 1 -
platform/packages/dashboard/vite.config.ts | 8 ++
playground/analog/package.json | 1 -
playground/analog/vite.config.ts | 8 ++
playground/astro/package.json | 1 -
playground/astro/vite.config.ts | 12 ++
playground/http-errors/package.json | 1 -
playground/http-errors/vite.config.ts | 8 ++
playground/kitchen-sink/package.json | 1 -
playground/kitchen-sink/vite.config.ts | 8 ++
playground/markdown-blog/package.json | 1 -
playground/markdown-blog/vite.config.ts | 8 ++
playground/mysql-test/package.json | 1 -
playground/mysql-test/vite.config.ts | 8 ++
playground/named-layouts/package.json | 1 -
playground/named-layouts/vite.config.ts | 8 ++
playground/node-app/package.json | 1 -
playground/node-app/vite.config.ts | 8 ++
playground/node-static-md/package.json | 1 -
playground/node-static-md/vite.config.ts | 8 ++
playground/node-static/package.json | 1 -
playground/node-static/vite.config.ts | 8 ++
playground/nuxt/package.json | 1 -
playground/nuxt/vite.config.ts | 12 ++
playground/pg-api-test/package.json | 1 -
playground/pg-api-test/vite.config.ts | 8 ++
playground/pg-test/package.json | 1 -
playground/pg-test/vite.config.ts | 8 ++
playground/react-pages/package.json | 1 -
playground/react-pages/vite.config.ts | 8 ++
playground/react-router/build.mjs | 22 ++++
playground/react-router/package.json | 1 -
playground/react-router/vite.config.ts | 8 ++
playground/server-auth-errors/package.json | 1 -
playground/server-auth-errors/vite.config.ts | 8 ++
playground/solid-pages/package.json | 1 -
playground/solid-pages/vite.config.ts | 8 ++
playground/spa/package.json | 1 -
playground/spa/vite.config.ts | 8 ++
playground/ssr/package.json | 1 -
playground/ssr/vite.config.ts | 8 ++
playground/static-pages/package.json | 1 -
playground/static-pages/vite.config.ts | 8 ++
playground/svelte-pages/package.json | 1 -
playground/svelte-pages/vite.config.ts | 8 ++
playground/sveltekit/package.json | 1 -
playground/sveltekit/vite.config.ts | 8 ++
playground/tanstack-start/package.json | 1 -
playground/tanstack-start/vite.config.ts | 8 ++
playground/vinext-app/package.json | 1 -
playground/vinext-app/vite.config.ts | 8 ++
playground/vinext-pages/package.json | 1 -
playground/vinext-pages/vite.config.ts | 8 ++
playground/vue-pages/package.json | 1 -
playground/vue-pages/vite.config.ts | 8 ++
playground/websockets/package.json | 1 -
playground/websockets/vite.config.ts | 8 ++
playground/zero-js/package.json | 1 -
playground/zero-js/vite.config.ts | 8 ++
test/build-setup.ts | 43 ++++++++
test/integration-helpers.ts | 23 ++++
test/performance-reporter.ts | 3 +
vite.config.ts | 103 ++++++++++++++++--
105 files changed, 587 insertions(+), 130 deletions(-)
create mode 100644 packages/deploy-cloudflare/vite.config.ts
create mode 100644 packages/deploy-core/vite.config.ts
create mode 100644 packages/edge/vite.config.ts
create mode 100644 playground/astro/vite.config.ts
create mode 100644 playground/nuxt/vite.config.ts
create mode 100644 playground/react-router/build.mjs
create mode 100644 test/build-setup.ts
diff --git a/TESTING.md b/TESTING.md
index 74a22f9a4..af4b705c0 100644
--- a/TESTING.md
+++ b/TESTING.md
@@ -122,6 +122,19 @@ pre-existing generated playground or dashboard tsconfigs.
## Reusing transforms
+Package and playground `build` tasks are declared in their Vite+ configurations and cache their
+outputs through Vite Task. Their workspace prerequisites run before the consumer build. Use
+`vp run build`, `vp run build:all`, or `vp run --filter ./playground/react-pages build` for both
+fresh builds and cache restoration. Use `vp run --no-cache build:all` when verifying a fresh
+build. `vp run --dry-run -vv build:all` explains the selected tasks and cache misses.
+
+Test commands explicitly disable Vite Task result caching, including when `--cache` is passed
+to the task runner. Build prerequisites can reuse their artifacts while test assertions run.
+Shared integration setup prepares public packages in production mode before workers import them.
+Playground preparation validates its own cached build without restoring those shared packages
+again while other workers are using them. Source-mutating build regressions still execute their
+build commands directly.
+
Persistent `fsModuleCache` is enabled to reuse transformations across invocations. It does not
cache test results or remove per-file module isolation. The first run primes it; compare repeated
runs with the same selection and machine load. For a control use `--no-fsModuleCache`; use
diff --git a/package.json b/package.json
index cbf6b865f..ec1edc690 100644
--- a/package.json
+++ b/package.json
@@ -2,10 +2,7 @@
"private": true,
"type": "module",
"scripts": {
- "build": "vp run --filter './packages/**' --filter '!./packages/md' build && vp run --filter ./packages/md build",
- "build:core": "vp run --filter ./packages/deploy-core --filter ./packages/deploy-cloudflare --filter ./packages/edge --filter ./packages/isr --filter ./packages/platform --filter ./packages/void build",
"build:docs": "vp run --filter ./docs build",
- "build:platform": "vp run --filter './platform/packages/**' build",
"check:platform": "vp run --filter './platform/**' --parallel typecheck",
"check:sdk": "vp run --filter './packages/**' --parallel typecheck",
"check:types": "vp run --filter './**' --filter '!./playground-local/**' --parallel --concurrency-limit=4 typecheck",
@@ -16,16 +13,6 @@
"install:void-dev": "vp run build:core && node scripts/void-dev-link.mjs install",
"lint": "vp lint",
"prepare": "vp config && vp run build:core",
- "test": "node test/affected.mjs",
- "test:benchmark": "vp test run --reporter=default --reporter=./test/performance-reporter.ts",
- "test:full": "vp test run",
- "test:integration": "vp test run --project parallel-integration",
- "test:metaframeworks": "vp test run --project parallel-integration analog.test.ts astro.test.ts nitro-worker.test.ts nuxt.test.ts react-router.test.ts sveltekit.test.ts tanstack-start.test.ts vinext-app.test.ts vinext-pages.test.ts",
- "test:pages:react-vue": "vp test run --project parallel-integration packages/react packages/vue",
- "test:pages:svelte-solid": "vp test run --project parallel-integration packages/svelte packages/solid",
- "test:platform": "vp test run --project 'platform-*'",
- "test:profile": "vp test run --reporter=default --experimental.importDurations.print --experimental.importDurations.limit=20",
- "test:unit": "vp test run --project unit --project unit-pglite --project cli-unit",
"uninstall:void-dev": "node scripts/void-dev-link.mjs uninstall"
},
"devDependencies": {
diff --git a/packages/create-void/package.json b/packages/create-void/package.json
index 9ba1b67e9..3151e11f1 100644
--- a/packages/create-void/package.json
+++ b/packages/create-void/package.json
@@ -23,7 +23,6 @@
"access": "public"
},
"scripts": {
- "build": "vp pack",
"typecheck": "tsc --noEmit"
},
"devDependencies": {
diff --git a/packages/create-void/vite.config.ts b/packages/create-void/vite.config.ts
index 10db58e7a..768247eac 100644
--- a/packages/create-void/vite.config.ts
+++ b/packages/create-void/vite.config.ts
@@ -1,6 +1,14 @@
import { defineConfig } from 'vite-plus';
export default defineConfig({
+ run: {
+ tasks: {
+ build: {
+ command: 'vp pack',
+ dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
+ },
+ },
+ },
pack: {
entry: ['src/index.ts'],
format: 'esm',
diff --git a/packages/deploy-cloudflare/package.json b/packages/deploy-cloudflare/package.json
index 46253019c..5db6f72c1 100644
--- a/packages/deploy-cloudflare/package.json
+++ b/packages/deploy-cloudflare/package.json
@@ -26,7 +26,6 @@
"access": "public"
},
"scripts": {
- "build": "vp pack",
"dev": "vp pack --watch",
"typecheck": "tsc --noEmit"
},
diff --git a/packages/deploy-cloudflare/vite.config.ts b/packages/deploy-cloudflare/vite.config.ts
new file mode 100644
index 000000000..f825e4755
--- /dev/null
+++ b/packages/deploy-cloudflare/vite.config.ts
@@ -0,0 +1,12 @@
+import { defineConfig } from 'vite-plus';
+
+export default defineConfig({
+ run: {
+ tasks: {
+ build: {
+ command: 'vp pack',
+ dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
+ },
+ },
+ },
+});
diff --git a/packages/deploy-core/package.json b/packages/deploy-core/package.json
index 1a061c44a..4c5e1b7f2 100644
--- a/packages/deploy-core/package.json
+++ b/packages/deploy-core/package.json
@@ -26,7 +26,6 @@
"access": "public"
},
"scripts": {
- "build": "vp pack",
"dev": "vp pack --watch",
"typecheck": "tsc --noEmit"
},
diff --git a/packages/deploy-core/vite.config.ts b/packages/deploy-core/vite.config.ts
new file mode 100644
index 000000000..f825e4755
--- /dev/null
+++ b/packages/deploy-core/vite.config.ts
@@ -0,0 +1,12 @@
+import { defineConfig } from 'vite-plus';
+
+export default defineConfig({
+ run: {
+ tasks: {
+ build: {
+ command: 'vp pack',
+ dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
+ },
+ },
+ },
+});
diff --git a/packages/edge/package.json b/packages/edge/package.json
index cdd362817..e3707e6ee 100644
--- a/packages/edge/package.json
+++ b/packages/edge/package.json
@@ -26,7 +26,6 @@
"access": "public"
},
"scripts": {
- "build": "vp pack",
"dev": "vp pack --watch",
"typecheck": "tsc --noEmit"
},
diff --git a/packages/edge/vite.config.ts b/packages/edge/vite.config.ts
new file mode 100644
index 000000000..f825e4755
--- /dev/null
+++ b/packages/edge/vite.config.ts
@@ -0,0 +1,12 @@
+import { defineConfig } from 'vite-plus';
+
+export default defineConfig({
+ run: {
+ tasks: {
+ build: {
+ command: 'vp pack',
+ dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
+ },
+ },
+ },
+});
diff --git a/packages/isr/package.json b/packages/isr/package.json
index dc40af990..7d915069c 100644
--- a/packages/isr/package.json
+++ b/packages/isr/package.json
@@ -34,7 +34,6 @@
"access": "public"
},
"scripts": {
- "build": "vp pack",
"dev": "vp pack --watch",
"typecheck": "tsc --noEmit"
},
diff --git a/packages/isr/vite.config.ts b/packages/isr/vite.config.ts
index a111b503f..c6c0db6f3 100644
--- a/packages/isr/vite.config.ts
+++ b/packages/isr/vite.config.ts
@@ -30,6 +30,14 @@ function injectWorkersTypesReferencePlugin() {
}
export default defineConfig({
+ run: {
+ tasks: {
+ build: {
+ command: 'vp pack',
+ dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
+ },
+ },
+ },
pack: {
entry: ['src/index.ts', 'src/core.ts', 'src/runtime.ts'],
format: 'esm',
diff --git a/packages/md/package.json b/packages/md/package.json
index d663a92bb..19047fdbc 100644
--- a/packages/md/package.json
+++ b/packages/md/package.json
@@ -36,7 +36,6 @@
"access": "public"
},
"scripts": {
- "build": "vp pack",
"dev": "vp pack --watch",
"typecheck": "tsc --noEmit --rootDir ../.."
},
diff --git a/packages/md/test/integration/markdown-blog.test.ts b/packages/md/test/integration/markdown-blog.test.ts
index ae72d01c6..baea6d27c 100644
--- a/packages/md/test/integration/markdown-blog.test.ts
+++ b/packages/md/test/integration/markdown-blog.test.ts
@@ -1,9 +1,8 @@
-import { execSync } from 'node:child_process';
import { join } from 'node:path';
import spawn from 'cross-spawn';
import { chromium, type Browser, type Page } from 'playwright';
import { describe, expect, it, beforeAll, afterAll } from 'vite-plus/test';
-import { killChild, startServer } from '../../../../test/integration-helpers.ts';
+import { buildPlayground, killChild, startServer } from '../../../../test/integration-helpers.ts';
const ROOT = join(import.meta.dirname, '..', '..', '..', '..');
let DEV_BASE: string;
@@ -287,10 +286,7 @@ describe('markdown-blog playground', () => {
let child: ReturnType;
beforeAll(async () => {
- execSync('vp run --filter ./playground/markdown-blog build', {
- cwd: ROOT,
- stdio: 'pipe',
- });
+ buildPlayground(ROOT, 'markdown-blog');
const server = await startServer((port) => {
child = spawn(
diff --git a/packages/md/vite.config.ts b/packages/md/vite.config.ts
index 79ca21a0e..c7ae13972 100644
--- a/packages/md/vite.config.ts
+++ b/packages/md/vite.config.ts
@@ -2,6 +2,14 @@ import { cpSync } from 'node:fs';
import { defineConfig } from 'vite-plus';
export default defineConfig({
+ run: {
+ tasks: {
+ build: {
+ command: 'vp pack',
+ dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
+ },
+ },
+ },
pack: {
entry: ['src/index.ts', 'src/plugin.ts', 'src/runtime/index.ts'],
format: 'esm',
diff --git a/packages/platform/package.json b/packages/platform/package.json
index 48d29417f..41a42bdc6 100644
--- a/packages/platform/package.json
+++ b/packages/platform/package.json
@@ -46,7 +46,6 @@
"access": "public"
},
"scripts": {
- "build": "vp pack && node scripts/build-runtime.mjs && vp run build:stamp",
"dev": "vp pack --watch",
"typecheck": "tsc --noEmit"
},
diff --git a/packages/platform/vite.config.ts b/packages/platform/vite.config.ts
index 84c7423a5..387641f19 100644
--- a/packages/platform/vite.config.ts
+++ b/packages/platform/vite.config.ts
@@ -3,6 +3,10 @@ import { defineConfig } from 'vite-plus';
export default defineConfig({
run: {
tasks: {
+ build: {
+ command: 'vp pack && node scripts/build-runtime.mjs && vp run build:stamp',
+ dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
+ },
// The last step of the `build` script: records the source revision in the runtime manifest.
// It isn't cached, so a new revision reruns only this step, and it gets the full
// environment, including VOID_PLATFORM_SOURCE_REVISION.
diff --git a/packages/react/package.json b/packages/react/package.json
index 6f9359f24..9de451c2b 100644
--- a/packages/react/package.json
+++ b/packages/react/package.json
@@ -38,7 +38,6 @@
"access": "public"
},
"scripts": {
- "build": "vp pack",
"dev": "vp pack --watch",
"typecheck": "tsc --noEmit --rootDir ../.."
},
diff --git a/packages/react/test/integration/react-pages-client.test.ts b/packages/react/test/integration/react-pages-client.test.ts
index de5d91889..b4b8a2cbe 100644
--- a/packages/react/test/integration/react-pages-client.test.ts
+++ b/packages/react/test/integration/react-pages-client.test.ts
@@ -1,10 +1,11 @@
-import { execSync, type ChildProcess } from 'node:child_process';
-import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { type ChildProcess } from 'node:child_process';
+import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { type Browser, type Page } from 'playwright';
import { describe, expect, it, beforeAll, afterAll, vi } from 'vite-plus/test';
import { collectBrowserDiagnostics } from '../../../../test/browser-helpers.ts';
import {
+ buildPlayground,
killChild,
spawnPlaygroundServer,
startServer,
@@ -1333,12 +1334,7 @@ describe('react-pages client (preview)', { retry: 2 }, () => {
let serverOutput = () => '';
beforeAll(async () => {
- if (!existsSync(join(ROOT, 'playground/react-pages/dist'))) {
- execSync('vp run --filter ./playground/react-pages build', {
- cwd: ROOT,
- stdio: 'pipe',
- });
- }
+ buildPlayground(ROOT, 'react-pages');
const server = await startServer(
(port) => (child = spawnPlaygroundServer(ROOT, 'react-pages', 'preview', port)),
diff --git a/packages/react/vite.config.ts b/packages/react/vite.config.ts
index bc9da4932..58cd44022 100644
--- a/packages/react/vite.config.ts
+++ b/packages/react/vite.config.ts
@@ -1,6 +1,14 @@
import { defineConfig } from 'vite-plus';
export default defineConfig({
+ run: {
+ tasks: {
+ build: {
+ command: 'vp pack',
+ dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
+ },
+ },
+ },
pack: {
entry: [
'src/index.ts',
diff --git a/packages/solid/package.json b/packages/solid/package.json
index 70aa5a0ab..03567ad22 100644
--- a/packages/solid/package.json
+++ b/packages/solid/package.json
@@ -35,7 +35,6 @@
"access": "public"
},
"scripts": {
- "build": "vp pack",
"dev": "vp pack --watch",
"typecheck": "tsc --noEmit --rootDir ../.."
},
diff --git a/packages/solid/test/integration/solid-pages-playground.test.ts b/packages/solid/test/integration/solid-pages-playground.test.ts
index fb50c5977..d19faab0c 100644
--- a/packages/solid/test/integration/solid-pages-playground.test.ts
+++ b/packages/solid/test/integration/solid-pages-playground.test.ts
@@ -1,10 +1,11 @@
-import { execSync, type ChildProcess } from 'node:child_process';
+import { type ChildProcess } from 'node:child_process';
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { type Browser, type Page } from 'playwright';
import { afterAll, beforeAll, describe, expect, it } from 'vite-plus/test';
import { collectBrowserDiagnostics } from '../../../../test/browser-helpers.ts';
import {
+ buildPlayground,
killChild,
spawnPlaygroundServer,
startServer,
@@ -269,12 +270,7 @@ describe('solid-pages client (preview)', { retry: 2 }, () => {
let child: ChildProcess | undefined;
beforeAll(async () => {
- if (!existsSync(join(ROOT, 'playground/solid-pages/dist'))) {
- execSync('vp run --filter ./playground/solid-pages build', {
- cwd: ROOT,
- stdio: 'pipe',
- });
- }
+ buildPlayground(ROOT, 'solid-pages');
const server = await startServer(
(port) => (child = spawnPlaygroundServer(ROOT, 'solid-pages', 'preview', port)),
diff --git a/packages/solid/vite.config.ts b/packages/solid/vite.config.ts
index 29c65bb77..de2bbc11d 100644
--- a/packages/solid/vite.config.ts
+++ b/packages/solid/vite.config.ts
@@ -1,6 +1,14 @@
import { defineConfig } from 'vite-plus';
export default defineConfig({
+ run: {
+ tasks: {
+ build: {
+ command: 'vp pack',
+ dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
+ },
+ },
+ },
pack: {
entry: [
'src/runtime/PageErrorBoundary.ts',
diff --git a/packages/svelte/package.json b/packages/svelte/package.json
index d9740f729..21ccad7d4 100644
--- a/packages/svelte/package.json
+++ b/packages/svelte/package.json
@@ -35,7 +35,6 @@
"access": "public"
},
"scripts": {
- "build": "vp pack",
"dev": "vp pack --watch",
"typecheck": "tsc --noEmit --rootDir ../.."
},
diff --git a/packages/svelte/test/integration/svelte-pages-client.test.ts b/packages/svelte/test/integration/svelte-pages-client.test.ts
index aeb69a4f9..ac98b6632 100644
--- a/packages/svelte/test/integration/svelte-pages-client.test.ts
+++ b/packages/svelte/test/integration/svelte-pages-client.test.ts
@@ -1,10 +1,11 @@
-import { execSync, type ChildProcess } from 'node:child_process';
-import { existsSync } from 'node:fs';
+import { type ChildProcess } from 'node:child_process';
+import {} from 'node:fs';
import { join } from 'node:path';
import { type Browser, type Page } from 'playwright';
import { describe, expect, it, beforeAll, afterAll } from 'vite-plus/test';
import { collectBrowserDiagnostics } from '../../../../test/browser-helpers.ts';
import {
+ buildPlayground,
killChild,
spawnPlaygroundServer,
startServer,
@@ -159,12 +160,7 @@ describe('svelte-pages client (preview)', { retry: 2 }, () => {
let child: ChildProcess | undefined;
beforeAll(async () => {
- if (!existsSync(join(ROOT, 'playground/svelte-pages/dist'))) {
- execSync('vp run --filter ./playground/svelte-pages build', {
- cwd: ROOT,
- stdio: 'pipe',
- });
- }
+ buildPlayground(ROOT, 'svelte-pages');
const server = await startServer(
(port) => (child = spawnPlaygroundServer(ROOT, 'svelte-pages', 'preview', port)),
diff --git a/packages/svelte/vite.config.ts b/packages/svelte/vite.config.ts
index f4e2d6afb..fb3016f72 100644
--- a/packages/svelte/vite.config.ts
+++ b/packages/svelte/vite.config.ts
@@ -1,6 +1,14 @@
import { defineConfig } from 'vite-plus';
export default defineConfig({
+ run: {
+ tasks: {
+ build: {
+ command: 'vp pack',
+ dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
+ },
+ },
+ },
pack: {
entry: ['src/plugin.ts'],
format: 'esm',
diff --git a/packages/void/package.json b/packages/void/package.json
index f3106e33e..2d5ace41f 100644
--- a/packages/void/package.json
+++ b/packages/void/package.json
@@ -348,7 +348,6 @@
}
},
"scripts": {
- "build": "node scripts/sync-docs.mjs && vp pack",
"dev": "vp pack --watch",
"typecheck": "tsc --noEmit --rootDir ../.."
},
diff --git a/packages/void/test/integration/kitchen-sink.test.ts b/packages/void/test/integration/kitchen-sink.test.ts
index 9dda63c08..023e676dc 100644
--- a/packages/void/test/integration/kitchen-sink.test.ts
+++ b/packages/void/test/integration/kitchen-sink.test.ts
@@ -1,11 +1,10 @@
-import { execSync } from 'node:child_process';
import { readFileSync, rmSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { getWorkerConfigPath } from '@cloudflare/build-output-utils';
import spawn from 'cross-spawn';
import { chromium, type Browser, type Page } from 'playwright';
import { describe, expect, it, beforeAll, afterAll } from 'vite-plus/test';
-import { killChild, startServer } from '../../../../test/integration-helpers.ts';
+import { buildPlayground, killChild, startServer } from '../../../../test/integration-helpers.ts';
declare global {
interface Window {
@@ -47,10 +46,7 @@ describe('playground/kitchen-sink', () => {
// dev-mode dependency optimization makes browser checks unreliable.
const pg = join(ROOT, 'playground/kitchen-sink');
rmSync(join(pg, 'dist'), { recursive: true, force: true });
- execSync('vp run --filter ./playground/kitchen-sink build', {
- cwd: ROOT,
- stdio: 'pipe',
- });
+ buildPlayground(ROOT, 'kitchen-sink');
const previewDatabaseId = preparePreviewWranglerConfig(pg);
// Start preview server — pre-built assets, no lazy optimization.
diff --git a/packages/void/test/integration/mysql-test.test.ts b/packages/void/test/integration/mysql-test.test.ts
index 56639b2e8..708bdc831 100644
--- a/packages/void/test/integration/mysql-test.test.ts
+++ b/packages/void/test/integration/mysql-test.test.ts
@@ -1,8 +1,9 @@
-import { execSync, type ChildProcess } from 'node:child_process';
+import { type ChildProcess } from 'node:child_process';
import { rmSync, unlinkSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { afterAll, beforeAll, describe, expect, it } from 'vite-plus/test';
import {
+ buildPlayground,
killChild,
spawnPlaygroundServer,
startServer,
@@ -77,7 +78,7 @@ describe('playground/mysql-test', () => {
it('queries MySQL through void/db and createDb in the built Worker', async () => {
rmSync(join(PLAYGROUND, 'dist'), { recursive: true, force: true });
- execSync('vp run --filter ./playground/mysql-test build', { cwd: ROOT, stdio: 'pipe' });
+ buildPlayground(ROOT, 'mysql-test');
const server = await start('preview');
try {
await expectUsers(server);
diff --git a/packages/void/test/integration/node-static-md.test.ts b/packages/void/test/integration/node-static-md.test.ts
index fb9ca0ffb..b30a01442 100644
--- a/packages/void/test/integration/node-static-md.test.ts
+++ b/packages/void/test/integration/node-static-md.test.ts
@@ -1,7 +1,7 @@
-import { execSync } from 'node:child_process';
import { existsSync, readFileSync, rmSync } from 'node:fs';
import { join } from 'node:path';
import { beforeAll, describe, expect, it } from 'vite-plus/test';
+import { buildPlayground } from '../../../../test/integration-helpers.ts';
// A Markdown-only pages app still needs a client build: its closeBundle
// prerenders. Markdown pages are implicit islands, so the client input comes
@@ -15,7 +15,7 @@ describe('playground/node-static-md build (Markdown-only, target: node, output:
const pg = join(ROOT, PLAYGROUND);
rmSync(join(pg, 'dist'), { recursive: true, force: true });
rmSync(join(pg, '.void'), { recursive: true, force: true });
- execSync(`vp run --filter ./${PLAYGROUND} build`, { cwd: ROOT, stdio: 'pipe' });
+ buildPlayground(ROOT, PLAYGROUND.slice('playground/'.length));
});
it('emits the Node SSR entry', () => {
diff --git a/packages/void/test/integration/node-static.test.ts b/packages/void/test/integration/node-static.test.ts
index a7c0572a9..e58dc8313 100644
--- a/packages/void/test/integration/node-static.test.ts
+++ b/packages/void/test/integration/node-static.test.ts
@@ -1,10 +1,10 @@
-import { execSync } from 'node:child_process';
import { existsSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
import { createServer, type Server } from 'node:http';
import { extname, isAbsolute, join, relative, resolve } from 'node:path';
import { chromium } from 'playwright';
import { afterAll, beforeAll, describe, expect, it } from 'vite-plus/test';
import {
+ buildPlayground,
killChild,
spawnPlaygroundServer,
startServer,
@@ -118,7 +118,7 @@ describe('playground/node-static build (target: node, output: static)', () => {
const pg = join(ROOT, PLAYGROUND);
rmSync(join(pg, 'dist'), { recursive: true, force: true });
rmSync(join(pg, '.void'), { recursive: true, force: true });
- execSync(`vp run --filter ./${PLAYGROUND} build`, { cwd: ROOT, stdio: 'pipe' });
+ buildPlayground(ROOT, PLAYGROUND.slice('playground/'.length));
const clientDir = join(DIST, 'client');
staticServer = createServer((req, res) => {
@@ -437,7 +437,7 @@ describe('playground/node-static redirects (target: node, output: static)', () =
const pg = join(ROOT, PLAYGROUND);
rmSync(join(pg, 'dist'), { recursive: true, force: true });
rmSync(join(pg, '.void'), { recursive: true, force: true });
- execSync(`vp run --filter ./${PLAYGROUND} build`, { cwd: ROOT, stdio: 'pipe' });
+ buildPlayground(ROOT, PLAYGROUND.slice('playground/'.length));
writeFileSync(VOID_CONFIG, originalConfig);
externalServer = createServer((_req, res) => {
diff --git a/packages/void/test/integration/pg-api-test.test.ts b/packages/void/test/integration/pg-api-test.test.ts
index 3f94d647b..f9cfaea7f 100644
--- a/packages/void/test/integration/pg-api-test.test.ts
+++ b/packages/void/test/integration/pg-api-test.test.ts
@@ -1,4 +1,4 @@
-import { execSync, type ChildProcess } from 'node:child_process';
+import { type ChildProcess } from 'node:child_process';
import { once } from 'node:events';
import { rmSync, unlinkSync, writeFileSync } from 'node:fs';
import type { AddressInfo } from 'node:net';
@@ -7,6 +7,7 @@ import { PGlite } from '@electric-sql/pglite';
import { createServer } from 'pglite-server';
import { afterAll, beforeAll, describe, expect, it } from 'vite-plus/test';
import {
+ buildPlayground,
killChild,
spawnPlaygroundServer,
startServer,
@@ -99,7 +100,7 @@ describe('playground/pg-api-test', () => {
it('queries PostgreSQL through void/db and createDb in the built Worker', async () => {
rmSync(join(PLAYGROUND, 'dist'), { recursive: true, force: true });
- execSync('vp run --filter ./playground/pg-api-test build', { cwd: ROOT, stdio: 'pipe' });
+ buildPlayground(ROOT, 'pg-api-test');
const server = await start('preview');
try {
await expectUsers(server);
diff --git a/packages/void/test/integration/plugin-cloudflare-v2.test.ts b/packages/void/test/integration/plugin-cloudflare-v2.test.ts
index 075bc9b48..cef88af20 100644
--- a/packages/void/test/integration/plugin-cloudflare-v2.test.ts
+++ b/packages/void/test/integration/plugin-cloudflare-v2.test.ts
@@ -219,6 +219,7 @@ export default {
vi.stubEnv('WRANGLER_DOCKER_BIN', docker);
const plugins = () =>
cloudflare({
+ inspectorPort: false,
config: () => ({
name: 'container-app',
main: 'worker.js',
diff --git a/packages/void/test/integration/react-router.test.ts b/packages/void/test/integration/react-router.test.ts
index 31ab5102e..6c9238829 100644
--- a/packages/void/test/integration/react-router.test.ts
+++ b/packages/void/test/integration/react-router.test.ts
@@ -213,7 +213,7 @@ export async function loader() {
it('generates route types from scratch and queries MySQL in the built Worker', async () => {
// The dev server generates these too, so do not let the previous test mask a missing build step.
rmSync(join(playground.root, '.react-router'), { recursive: true, force: true });
- execFileSync('vp', ['run', 'build'], {
+ execFileSync('vp', ['run', '--ignore-depends-on', '--no-cache', 'build'], {
cwd: playground.root,
stdio: 'pipe',
env: { ...process.env, VOID_INSPECTOR_PORT: 'false' },
diff --git a/packages/void/test/integration/ssr-playground.test.ts b/packages/void/test/integration/ssr-playground.test.ts
index 088b2f916..a12271f56 100644
--- a/packages/void/test/integration/ssr-playground.test.ts
+++ b/packages/void/test/integration/ssr-playground.test.ts
@@ -1,10 +1,9 @@
-import { execSync } from 'node:child_process';
import { existsSync, readFileSync, rmSync } from 'node:fs';
import { join } from 'node:path';
import { getWorkerAssetsDir, getWorkerConfigPath } from '@cloudflare/build-output-utils';
import spawn from 'cross-spawn';
import { afterAll, beforeAll, describe, expect, it } from 'vite-plus/test';
-import { killChild, startServer } from '../../../../test/integration-helpers.ts';
+import { buildPlayground, killChild, startServer } from '../../../../test/integration-helpers.ts';
import { GENERATED_ASSET_HEADERS_MARKER } from '../../src/asset-worker-bypass.ts';
const ROOT = join(import.meta.dirname, '..', '..', '..', '..');
@@ -83,7 +82,7 @@ describe('playground/ssr build + preview', () => {
beforeAll(async () => {
rmSync(join(ROOT, 'playground/ssr/dist'), { recursive: true, force: true });
- execSync('vp run --filter ./playground/ssr build', { cwd: ROOT, stdio: 'pipe' });
+ buildPlayground(ROOT, 'ssr');
const server = await startServer((port) => {
child = spawn(
diff --git a/packages/void/test/integration/static-pages.test.ts b/packages/void/test/integration/static-pages.test.ts
index dc02e8630..062d3f0b0 100644
--- a/packages/void/test/integration/static-pages.test.ts
+++ b/packages/void/test/integration/static-pages.test.ts
@@ -1,8 +1,8 @@
-import { execSync } from 'node:child_process';
import { existsSync, readFileSync, rmSync } from 'node:fs';
import { join } from 'node:path';
import { Miniflare, convertV4MiniflareOptions } from 'miniflare';
import { beforeAll, describe, expect, it } from 'vite-plus/test';
+import { buildPlayground } from '../../../../test/integration-helpers.ts';
import { GENERATED_ASSET_HEADERS_MARKER } from '../../src/asset-worker-bypass.ts';
import { deserializePageData } from '../../src/pages/serialize.ts';
import { collectPrerenderPaths } from '../../src/prerender.ts';
@@ -22,7 +22,7 @@ describe('playground/static-pages build (output: static)', () => {
rmSync(join(pg, 'dist'), { recursive: true, force: true });
rmSync(join(pg, '.void'), { recursive: true, force: true });
removeWranglerConfig(pg);
- execSync(`vp run --filter ./${PLAYGROUND} build`, { cwd: ROOT, stdio: 'pipe' });
+ buildPlayground(ROOT, PLAYGROUND.slice('playground/'.length));
});
it('emits worker entry and client manifest', () => {
diff --git a/packages/void/test/integration/websockets-playground.test.ts b/packages/void/test/integration/websockets-playground.test.ts
index 7c8e46738..772b22a79 100644
--- a/packages/void/test/integration/websockets-playground.test.ts
+++ b/packages/void/test/integration/websockets-playground.test.ts
@@ -74,11 +74,15 @@ describe('playground/websockets', () => {
beforeAll(async () => {
const playground = join(ROOT, 'playground/websockets');
rmSync(join(playground, 'dist'), { recursive: true, force: true });
- const build = spawn.sync('vp', ['run', '--filter', './playground/websockets', 'build'], {
- cwd: ROOT,
- encoding: 'utf8',
- env: { ...process.env, VOID_INSPECTOR_PORT: 'false' },
- });
+ const build = spawn.sync(
+ 'vp',
+ ['run', '--ignore-depends-on', '--filter', './playground/websockets', 'build'],
+ {
+ cwd: ROOT,
+ encoding: 'utf8',
+ env: { ...process.env, VOID_INSPECTOR_PORT: 'false' },
+ },
+ );
expect(build.status).toBe(0);
browser = await chromium.launch();
diff --git a/packages/void/vite.config.ts b/packages/void/vite.config.ts
index faab5bdce..2abb77ba1 100644
--- a/packages/void/vite.config.ts
+++ b/packages/void/vite.config.ts
@@ -58,6 +58,14 @@ function injectWorkersTypesReferencePlugin() {
}
export default defineConfig({
+ run: {
+ tasks: {
+ build: {
+ command: 'node scripts/sync-docs.mjs && vp pack',
+ dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
+ },
+ },
+ },
pack: {
entry: [
'src/index.ts',
diff --git a/packages/vue/package.json b/packages/vue/package.json
index b34ae1379..6e7114be9 100644
--- a/packages/vue/package.json
+++ b/packages/vue/package.json
@@ -38,7 +38,6 @@
"access": "public"
},
"scripts": {
- "build": "vp pack",
"dev": "vp pack --watch",
"typecheck": "tsc --noEmit --rootDir ../.."
},
diff --git a/packages/vue/test/integration/vue-pages-client.test.ts b/packages/vue/test/integration/vue-pages-client.test.ts
index 19461b4f9..64750b08d 100644
--- a/packages/vue/test/integration/vue-pages-client.test.ts
+++ b/packages/vue/test/integration/vue-pages-client.test.ts
@@ -1,10 +1,11 @@
-import { execSync, type ChildProcess } from 'node:child_process';
-import { existsSync, readFileSync, writeFileSync } from 'node:fs';
+import { type ChildProcess } from 'node:child_process';
+import { readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { type Browser, type Page } from 'playwright';
import { describe, expect, it, beforeAll, afterAll } from 'vite-plus/test';
import { collectBrowserDiagnostics } from '../../../../test/browser-helpers.ts';
import {
+ buildPlayground,
killChild,
spawnPlaygroundServer,
startServer,
@@ -342,12 +343,7 @@ describe('vue-pages client (preview)', { retry: 2 }, () => {
let child: ChildProcess | undefined;
beforeAll(async () => {
- if (!existsSync(join(ROOT, 'playground/vue-pages/dist'))) {
- execSync('vp run --filter ./playground/vue-pages build', {
- cwd: ROOT,
- stdio: 'pipe',
- });
- }
+ buildPlayground(ROOT, 'vue-pages');
const server = await startServer(
(port) => (child = spawnPlaygroundServer(ROOT, 'vue-pages', 'preview', port)),
diff --git a/packages/vue/vite.config.ts b/packages/vue/vite.config.ts
index 47a8e0c01..8891e0745 100644
--- a/packages/vue/vite.config.ts
+++ b/packages/vue/vite.config.ts
@@ -1,6 +1,14 @@
import { defineConfig } from 'vite-plus';
export default defineConfig({
+ run: {
+ tasks: {
+ build: {
+ command: 'vp pack',
+ dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
+ },
+ },
+ },
pack: {
entry: [
'src/runtime/PageErrorBoundary.ts',
diff --git a/platform/packages/api/test/integration/global-setup.ts b/platform/packages/api/test/integration/global-setup.ts
index c585eefb7..ee5a9f4d6 100644
--- a/platform/packages/api/test/integration/global-setup.ts
+++ b/platform/packages/api/test/integration/global-setup.ts
@@ -1,5 +1,5 @@
-import { ensurePGliteTemplateBundlePath } from './db-template.ts';
-
export default async function setup(): Promise {
+ // The public package setup runs first; defer imports that use those exports until then.
+ const { ensurePGliteTemplateBundlePath } = await import('./db-template.ts');
await ensurePGliteTemplateBundlePath();
}
diff --git a/platform/packages/dashboard/package.json b/platform/packages/dashboard/package.json
index b49629eed..b029fbbca 100644
--- a/platform/packages/dashboard/package.json
+++ b/platform/packages/dashboard/package.json
@@ -4,7 +4,6 @@
"private": true,
"type": "module",
"scripts": {
- "build": "vp build",
"deploy": "node ../../scripts/wrangler-deploy.ts --build",
"deploy:staging": "node ../../scripts/wrangler-deploy.ts --build --env staging",
"dev": "node scripts/refresh-access-token.mjs && vp dev",
diff --git a/platform/packages/dashboard/vite.config.ts b/platform/packages/dashboard/vite.config.ts
index bbdbea930..5c0c329de 100644
--- a/platform/packages/dashboard/vite.config.ts
+++ b/platform/packages/dashboard/vite.config.ts
@@ -4,6 +4,14 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
+ run: {
+ tasks: {
+ build: {
+ command: 'vp build',
+ dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
+ },
+ },
+ },
plugins: [
voidPlugin({
persistTo: resolve(__dirname, '../api/.wrangler/state'),
diff --git a/playground/analog/package.json b/playground/analog/package.json
index b96a311a7..a4d02a362 100644
--- a/playground/analog/package.json
+++ b/playground/analog/package.json
@@ -3,7 +3,6 @@
"private": true,
"type": "module",
"scripts": {
- "build": "vp build",
"dev": "vp dev"
},
"dependencies": {
diff --git a/playground/analog/vite.config.ts b/playground/analog/vite.config.ts
index 06931bcdc..d4aa249d9 100644
--- a/playground/analog/vite.config.ts
+++ b/playground/analog/vite.config.ts
@@ -4,6 +4,14 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
+ run: {
+ tasks: {
+ build: {
+ command: 'vp build',
+ dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
+ },
+ },
+ },
resolve: {
mainFields: ['module'],
},
diff --git a/playground/astro/package.json b/playground/astro/package.json
index b42b4fc0c..ce16c9626 100644
--- a/playground/astro/package.json
+++ b/playground/astro/package.json
@@ -3,7 +3,6 @@
"private": true,
"type": "module",
"scripts": {
- "build": "astro build",
"dev": "astro dev"
},
"dependencies": {
diff --git a/playground/astro/vite.config.ts b/playground/astro/vite.config.ts
new file mode 100644
index 000000000..e3bb87232
--- /dev/null
+++ b/playground/astro/vite.config.ts
@@ -0,0 +1,12 @@
+import { defineConfig } from 'vite-plus';
+
+export default defineConfig({
+ run: {
+ tasks: {
+ build: {
+ command: 'astro build',
+ dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
+ },
+ },
+ },
+});
diff --git a/playground/http-errors/package.json b/playground/http-errors/package.json
index a0471f52f..271ee84d2 100644
--- a/playground/http-errors/package.json
+++ b/playground/http-errors/package.json
@@ -3,7 +3,6 @@
"private": true,
"type": "module",
"scripts": {
- "build": "vp build",
"dev": "vp dev",
"typecheck": "tsc --noEmit"
},
diff --git a/playground/http-errors/vite.config.ts b/playground/http-errors/vite.config.ts
index 48c1c0d91..d2d2b9647 100644
--- a/playground/http-errors/vite.config.ts
+++ b/playground/http-errors/vite.config.ts
@@ -3,6 +3,14 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
+ run: {
+ tasks: {
+ build: {
+ command: 'vp build',
+ dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
+ },
+ },
+ },
define: {
__HTTP_ERRORS_SOURCE_ROOT__: JSON.stringify(new URL('./', import.meta.url).href),
},
diff --git a/playground/kitchen-sink/package.json b/playground/kitchen-sink/package.json
index b4db24f78..e62aa3e2a 100644
--- a/playground/kitchen-sink/package.json
+++ b/playground/kitchen-sink/package.json
@@ -3,7 +3,6 @@
"private": true,
"type": "module",
"scripts": {
- "build": "vp build",
"dev": "vp dev",
"preview": "vp preview",
"remote": "VOID_REMOTE=1 vp dev",
diff --git a/playground/kitchen-sink/vite.config.ts b/playground/kitchen-sink/vite.config.ts
index 82eaf98e6..1fda86b89 100644
--- a/playground/kitchen-sink/vite.config.ts
+++ b/playground/kitchen-sink/vite.config.ts
@@ -3,5 +3,13 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
+ run: {
+ tasks: {
+ build: {
+ command: 'vp build',
+ dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
+ },
+ },
+ },
plugins: [voidPlugin(), voidVue()],
});
diff --git a/playground/markdown-blog/package.json b/playground/markdown-blog/package.json
index 070b464d2..806409a50 100644
--- a/playground/markdown-blog/package.json
+++ b/playground/markdown-blog/package.json
@@ -3,7 +3,6 @@
"private": true,
"type": "module",
"scripts": {
- "build": "vp build",
"dev": "vp dev",
"preview": "vp preview",
"typecheck": "tsc --noEmit"
diff --git a/playground/markdown-blog/vite.config.ts b/playground/markdown-blog/vite.config.ts
index 06823dabb..62dffb6d6 100644
--- a/playground/markdown-blog/vite.config.ts
+++ b/playground/markdown-blog/vite.config.ts
@@ -4,5 +4,13 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
+ run: {
+ tasks: {
+ build: {
+ command: 'vp build',
+ dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
+ },
+ },
+ },
plugins: [voidPlugin(), voidVue(), voidMarkdown()],
});
diff --git a/playground/mysql-test/package.json b/playground/mysql-test/package.json
index 6f8f11eb9..ddb5f57bd 100644
--- a/playground/mysql-test/package.json
+++ b/playground/mysql-test/package.json
@@ -3,7 +3,6 @@
"private": true,
"type": "module",
"scripts": {
- "build": "vp build",
"dev": "vp dev",
"preview": "vp preview",
"typecheck": "tsc --noEmit"
diff --git a/playground/mysql-test/vite.config.ts b/playground/mysql-test/vite.config.ts
index 2bae9de06..d36b4a924 100644
--- a/playground/mysql-test/vite.config.ts
+++ b/playground/mysql-test/vite.config.ts
@@ -2,5 +2,13 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
+ run: {
+ tasks: {
+ build: {
+ command: 'vp build',
+ dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
+ },
+ },
+ },
plugins: [voidPlugin()],
});
diff --git a/playground/named-layouts/package.json b/playground/named-layouts/package.json
index eb44da10e..7f06d4d56 100644
--- a/playground/named-layouts/package.json
+++ b/playground/named-layouts/package.json
@@ -3,7 +3,6 @@
"private": true,
"type": "module",
"scripts": {
- "build": "vp build",
"dev": "vp dev",
"preview": "vp preview"
},
diff --git a/playground/named-layouts/vite.config.ts b/playground/named-layouts/vite.config.ts
index f2669c611..cfddac695 100644
--- a/playground/named-layouts/vite.config.ts
+++ b/playground/named-layouts/vite.config.ts
@@ -4,5 +4,13 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
+ run: {
+ tasks: {
+ build: {
+ command: 'vp build',
+ dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
+ },
+ },
+ },
plugins: [voidPlugin(), voidReact(), voidMarkdown()],
});
diff --git a/playground/node-app/package.json b/playground/node-app/package.json
index a86261853..bce36f268 100644
--- a/playground/node-app/package.json
+++ b/playground/node-app/package.json
@@ -3,7 +3,6 @@
"private": true,
"type": "module",
"scripts": {
- "build": "vp build",
"dev": "vp dev",
"preview": "vp preview",
"start": "node dist/ssr/index.js"
diff --git a/playground/node-app/vite.config.ts b/playground/node-app/vite.config.ts
index 7dcd4c641..0a3c9ad47 100644
--- a/playground/node-app/vite.config.ts
+++ b/playground/node-app/vite.config.ts
@@ -3,5 +3,13 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
+ run: {
+ tasks: {
+ build: {
+ command: 'vp build',
+ dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
+ },
+ },
+ },
plugins: [voidPlugin(), voidReact()],
});
diff --git a/playground/node-static-md/package.json b/playground/node-static-md/package.json
index 1a355ebac..109e7a962 100644
--- a/playground/node-static-md/package.json
+++ b/playground/node-static-md/package.json
@@ -3,7 +3,6 @@
"private": true,
"type": "module",
"scripts": {
- "build": "vp build",
"dev": "vp dev",
"preview": "vp preview"
},
diff --git a/playground/node-static-md/vite.config.ts b/playground/node-static-md/vite.config.ts
index 0a7703ecd..f9a6a354d 100644
--- a/playground/node-static-md/vite.config.ts
+++ b/playground/node-static-md/vite.config.ts
@@ -5,5 +5,13 @@ import { voidPlugin } from 'void';
// Markdown-only: every page is an implicit island with no client-side JS.
export default defineConfig({
+ run: {
+ tasks: {
+ build: {
+ command: 'vp build',
+ dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
+ },
+ },
+ },
plugins: [voidPlugin(), voidReact(), voidMarkdown()],
});
diff --git a/playground/node-static/package.json b/playground/node-static/package.json
index 276f0b14b..daf3b86a9 100644
--- a/playground/node-static/package.json
+++ b/playground/node-static/package.json
@@ -3,7 +3,6 @@
"private": true,
"type": "module",
"scripts": {
- "build": "vp build",
"dev": "vp dev",
"preview": "vp preview",
"serve:static": "node scripts/serve-static.mjs"
diff --git a/playground/node-static/vite.config.ts b/playground/node-static/vite.config.ts
index 7dcd4c641..0a3c9ad47 100644
--- a/playground/node-static/vite.config.ts
+++ b/playground/node-static/vite.config.ts
@@ -3,5 +3,13 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
+ run: {
+ tasks: {
+ build: {
+ command: 'vp build',
+ dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
+ },
+ },
+ },
plugins: [voidPlugin(), voidReact()],
});
diff --git a/playground/nuxt/package.json b/playground/nuxt/package.json
index 8fad54eed..dc112493c 100644
--- a/playground/nuxt/package.json
+++ b/playground/nuxt/package.json
@@ -3,7 +3,6 @@
"private": true,
"type": "module",
"scripts": {
- "build": "nuxt build",
"dev": "nuxt dev"
},
"dependencies": {
diff --git a/playground/nuxt/vite.config.ts b/playground/nuxt/vite.config.ts
new file mode 100644
index 000000000..e9021c53b
--- /dev/null
+++ b/playground/nuxt/vite.config.ts
@@ -0,0 +1,12 @@
+import { defineConfig } from 'vite-plus';
+
+export default defineConfig({
+ run: {
+ tasks: {
+ build: {
+ command: 'nuxt build',
+ dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
+ },
+ },
+ },
+});
diff --git a/playground/pg-api-test/package.json b/playground/pg-api-test/package.json
index b844c5b08..99291ddf8 100644
--- a/playground/pg-api-test/package.json
+++ b/playground/pg-api-test/package.json
@@ -3,7 +3,6 @@
"private": true,
"type": "module",
"scripts": {
- "build": "vp build",
"dev": "vp dev",
"preview": "vp preview",
"typecheck": "tsc --noEmit"
diff --git a/playground/pg-api-test/vite.config.ts b/playground/pg-api-test/vite.config.ts
index 2bae9de06..d36b4a924 100644
--- a/playground/pg-api-test/vite.config.ts
+++ b/playground/pg-api-test/vite.config.ts
@@ -2,5 +2,13 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
+ run: {
+ tasks: {
+ build: {
+ command: 'vp build',
+ dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
+ },
+ },
+ },
plugins: [voidPlugin()],
});
diff --git a/playground/pg-test/package.json b/playground/pg-test/package.json
index 3d94d77f7..67d0d4e30 100644
--- a/playground/pg-test/package.json
+++ b/playground/pg-test/package.json
@@ -3,7 +3,6 @@
"private": true,
"type": "module",
"scripts": {
- "build": "vp build",
"dev": "vp dev",
"typecheck": "tsc --noEmit"
},
diff --git a/playground/pg-test/vite.config.ts b/playground/pg-test/vite.config.ts
index 7dcd4c641..0a3c9ad47 100644
--- a/playground/pg-test/vite.config.ts
+++ b/playground/pg-test/vite.config.ts
@@ -3,5 +3,13 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
+ run: {
+ tasks: {
+ build: {
+ command: 'vp build',
+ dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
+ },
+ },
+ },
plugins: [voidPlugin(), voidReact()],
});
diff --git a/playground/react-pages/package.json b/playground/react-pages/package.json
index fec075a96..b76f0932c 100644
--- a/playground/react-pages/package.json
+++ b/playground/react-pages/package.json
@@ -3,7 +3,6 @@
"private": true,
"type": "module",
"scripts": {
- "build": "vp build",
"dev": "vp dev",
"preview": "vp preview",
"typecheck": "tsc --noEmit"
diff --git a/playground/react-pages/vite.config.ts b/playground/react-pages/vite.config.ts
index de06ddc1e..c5d5a2e8d 100644
--- a/playground/react-pages/vite.config.ts
+++ b/playground/react-pages/vite.config.ts
@@ -3,6 +3,14 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
+ run: {
+ tasks: {
+ build: {
+ command: 'vp build',
+ dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
+ },
+ },
+ },
plugins: [voidPlugin(), voidReact()],
// stabilize dev server start for tests
optimizeDeps: { include: ['valibot', 'react-dom', 'react/jsx-dev-runtime'] },
diff --git a/playground/react-router/build.mjs b/playground/react-router/build.mjs
new file mode 100644
index 000000000..aef483f33
--- /dev/null
+++ b/playground/react-router/build.mjs
@@ -0,0 +1,22 @@
+import { spawnSync } from 'node:child_process';
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+
+const manifest = new URL(import.meta.resolve('@react-router/dev/package.json'));
+const { bin } = JSON.parse(readFileSync(manifest, 'utf8'));
+const reactRouter = fileURLToPath(new URL(bin['react-router'], manifest));
+
+// Type generation and the build both write framework configuration. Cache their final output
+// as one task so restoring the earlier stage cannot overwrite the completed build's files.
+for (const args of [
+ [reactRouter, 'typegen'],
+ [reactRouter, 'build', ...process.argv.slice(2)],
+]) {
+ const result = spawnSync(process.execPath, args, { stdio: 'inherit' });
+ if (result.error) {
+ throw result.error;
+ }
+ if (result.status !== 0) {
+ process.exit(result.status ?? 1);
+ }
+}
diff --git a/playground/react-router/package.json b/playground/react-router/package.json
index 03be98ec4..815b426d0 100644
--- a/playground/react-router/package.json
+++ b/playground/react-router/package.json
@@ -3,7 +3,6 @@
"private": true,
"type": "module",
"scripts": {
- "build": "react-router typegen && vp build",
"dev": "vp dev"
},
"dependencies": {
diff --git a/playground/react-router/vite.config.ts b/playground/react-router/vite.config.ts
index 81961d6c3..c068d402a 100644
--- a/playground/react-router/vite.config.ts
+++ b/playground/react-router/vite.config.ts
@@ -3,5 +3,13 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
+ run: {
+ tasks: {
+ build: {
+ command: 'node build.mjs',
+ dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
+ },
+ },
+ },
plugins: [voidPlugin(), reactRouter()],
});
diff --git a/playground/server-auth-errors/package.json b/playground/server-auth-errors/package.json
index 44c3376b8..134c9c511 100644
--- a/playground/server-auth-errors/package.json
+++ b/playground/server-auth-errors/package.json
@@ -3,7 +3,6 @@
"private": true,
"type": "module",
"scripts": {
- "build": "vp build",
"dev": "vp dev",
"typecheck": "tsc --noEmit"
},
diff --git a/playground/server-auth-errors/vite.config.ts b/playground/server-auth-errors/vite.config.ts
index 4a594243f..1b7bd521f 100644
--- a/playground/server-auth-errors/vite.config.ts
+++ b/playground/server-auth-errors/vite.config.ts
@@ -3,6 +3,14 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
+ run: {
+ tasks: {
+ build: {
+ command: 'vp build',
+ dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
+ },
+ },
+ },
define: {
__SERVER_AUTH_ERRORS_SOURCE_ROOT__: JSON.stringify(new URL('./', import.meta.url).href),
},
diff --git a/playground/solid-pages/package.json b/playground/solid-pages/package.json
index fc5b1bab6..66a8364ba 100644
--- a/playground/solid-pages/package.json
+++ b/playground/solid-pages/package.json
@@ -3,7 +3,6 @@
"private": true,
"type": "module",
"scripts": {
- "build": "vp build",
"dev": "vp dev",
"preview": "vp preview",
"typecheck": "tsc --noEmit"
diff --git a/playground/solid-pages/vite.config.ts b/playground/solid-pages/vite.config.ts
index bd458d256..16709a5b3 100644
--- a/playground/solid-pages/vite.config.ts
+++ b/playground/solid-pages/vite.config.ts
@@ -3,6 +3,14 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
+ run: {
+ tasks: {
+ build: {
+ command: 'vp build',
+ dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
+ },
+ },
+ },
plugins: [voidPlugin(), voidSolid()],
// stabilize dev server start for tests
optimizeDeps: { include: ['valibot'] },
diff --git a/playground/spa/package.json b/playground/spa/package.json
index 1baddb974..1556f1d14 100644
--- a/playground/spa/package.json
+++ b/playground/spa/package.json
@@ -3,7 +3,6 @@
"private": true,
"type": "module",
"scripts": {
- "build": "vp build",
"dev": "vp dev",
"preview": "vp preview",
"typecheck": "tsc --noEmit"
diff --git a/playground/spa/vite.config.ts b/playground/spa/vite.config.ts
index 36a2318f7..10301a857 100644
--- a/playground/spa/vite.config.ts
+++ b/playground/spa/vite.config.ts
@@ -3,5 +3,13 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
+ run: {
+ tasks: {
+ build: {
+ command: 'vp build',
+ dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
+ },
+ },
+ },
plugins: [react(), voidPlugin()],
});
diff --git a/playground/ssr/package.json b/playground/ssr/package.json
index 6a3b611f6..cb17db0cd 100644
--- a/playground/ssr/package.json
+++ b/playground/ssr/package.json
@@ -3,7 +3,6 @@
"private": true,
"type": "module",
"scripts": {
- "build": "vp build",
"dev": "vp dev",
"preview": "vp preview"
},
diff --git a/playground/ssr/vite.config.ts b/playground/ssr/vite.config.ts
index 36a2318f7..10301a857 100644
--- a/playground/ssr/vite.config.ts
+++ b/playground/ssr/vite.config.ts
@@ -3,5 +3,13 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
+ run: {
+ tasks: {
+ build: {
+ command: 'vp build',
+ dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
+ },
+ },
+ },
plugins: [react(), voidPlugin()],
});
diff --git a/playground/static-pages/package.json b/playground/static-pages/package.json
index a2fe6a8a6..7e22a9d95 100644
--- a/playground/static-pages/package.json
+++ b/playground/static-pages/package.json
@@ -3,7 +3,6 @@
"private": true,
"type": "module",
"scripts": {
- "build": "vp build",
"dev": "vp dev",
"preview": "vp preview"
},
diff --git a/playground/static-pages/vite.config.ts b/playground/static-pages/vite.config.ts
index b95685391..e3c800624 100644
--- a/playground/static-pages/vite.config.ts
+++ b/playground/static-pages/vite.config.ts
@@ -22,5 +22,13 @@ function virtualTagsPlugin(): Plugin {
}
export default defineConfig({
+ run: {
+ tasks: {
+ build: {
+ command: 'vp build',
+ dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
+ },
+ },
+ },
plugins: [voidPlugin(), voidVue(), virtualTagsPlugin()],
});
diff --git a/playground/svelte-pages/package.json b/playground/svelte-pages/package.json
index 94f507bd9..08fde873b 100644
--- a/playground/svelte-pages/package.json
+++ b/playground/svelte-pages/package.json
@@ -3,7 +3,6 @@
"private": true,
"type": "module",
"scripts": {
- "build": "vp build",
"dev": "vp dev",
"preview": "vp preview",
"typecheck": "tsc --noEmit"
diff --git a/playground/svelte-pages/vite.config.ts b/playground/svelte-pages/vite.config.ts
index c197a8f47..8d8ea628c 100644
--- a/playground/svelte-pages/vite.config.ts
+++ b/playground/svelte-pages/vite.config.ts
@@ -3,6 +3,14 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
+ run: {
+ tasks: {
+ build: {
+ command: 'vp build',
+ dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
+ },
+ },
+ },
plugins: [voidPlugin(), voidSvelte()],
// stabilize dev server start for tests
optimizeDeps: { include: ['valibot'] },
diff --git a/playground/sveltekit/package.json b/playground/sveltekit/package.json
index e83f29c3e..48318bb9b 100644
--- a/playground/sveltekit/package.json
+++ b/playground/sveltekit/package.json
@@ -3,7 +3,6 @@
"private": true,
"type": "module",
"scripts": {
- "build": "vp build",
"dev": "vp dev",
"typecheck": "void prepare && svelte-kit sync && tsc --noEmit"
},
diff --git a/playground/sveltekit/vite.config.ts b/playground/sveltekit/vite.config.ts
index a14191db7..803921b6f 100644
--- a/playground/sveltekit/vite.config.ts
+++ b/playground/sveltekit/vite.config.ts
@@ -3,6 +3,14 @@ import { sveltekit } from '@sveltejs/kit/vite';
import { voidPlugin } from 'void';
export default {
+ run: {
+ tasks: {
+ build: {
+ command: 'vp build',
+ dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
+ },
+ },
+ },
plugins: [
voidPlugin(),
sveltekit({
diff --git a/playground/tanstack-start/package.json b/playground/tanstack-start/package.json
index 4440c8761..7eadbeff9 100644
--- a/playground/tanstack-start/package.json
+++ b/playground/tanstack-start/package.json
@@ -3,7 +3,6 @@
"private": true,
"type": "module",
"scripts": {
- "build": "vp build",
"dev": "vp dev"
},
"dependencies": {
diff --git a/playground/tanstack-start/vite.config.ts b/playground/tanstack-start/vite.config.ts
index 22e73ec90..1bb14dcd2 100644
--- a/playground/tanstack-start/vite.config.ts
+++ b/playground/tanstack-start/vite.config.ts
@@ -4,6 +4,14 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
+ run: {
+ tasks: {
+ build: {
+ command: 'vp build',
+ dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
+ },
+ },
+ },
plugins: [
// voidPlugin wraps @cloudflare/vite-plugin — must come before tanstackStart
voidPlugin(),
diff --git a/playground/vinext-app/package.json b/playground/vinext-app/package.json
index be4b4811a..9c0494d90 100644
--- a/playground/vinext-app/package.json
+++ b/playground/vinext-app/package.json
@@ -3,7 +3,6 @@
"private": true,
"type": "module",
"scripts": {
- "build": "vp build",
"dev": "vp dev"
},
"dependencies": {
diff --git a/playground/vinext-app/vite.config.ts b/playground/vinext-app/vite.config.ts
index fa671ebd7..0b403cfcb 100644
--- a/playground/vinext-app/vite.config.ts
+++ b/playground/vinext-app/vite.config.ts
@@ -3,5 +3,13 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
+ run: {
+ tasks: {
+ build: {
+ command: 'vp build',
+ dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
+ },
+ },
+ },
plugins: [voidPlugin(), vinext()],
});
diff --git a/playground/vinext-pages/package.json b/playground/vinext-pages/package.json
index 7c1ee82fd..df1d556a7 100644
--- a/playground/vinext-pages/package.json
+++ b/playground/vinext-pages/package.json
@@ -3,7 +3,6 @@
"private": true,
"type": "module",
"scripts": {
- "build": "vp build",
"dev": "vp dev"
},
"dependencies": {
diff --git a/playground/vinext-pages/vite.config.ts b/playground/vinext-pages/vite.config.ts
index fa671ebd7..0b403cfcb 100644
--- a/playground/vinext-pages/vite.config.ts
+++ b/playground/vinext-pages/vite.config.ts
@@ -3,5 +3,13 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
+ run: {
+ tasks: {
+ build: {
+ command: 'vp build',
+ dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
+ },
+ },
+ },
plugins: [voidPlugin(), vinext()],
});
diff --git a/playground/vue-pages/package.json b/playground/vue-pages/package.json
index 86e3a3856..1cc7001ed 100644
--- a/playground/vue-pages/package.json
+++ b/playground/vue-pages/package.json
@@ -3,7 +3,6 @@
"private": true,
"type": "module",
"scripts": {
- "build": "vp build",
"dev": "vp dev",
"preview": "vp preview",
"typecheck": "tsc --noEmit"
diff --git a/playground/vue-pages/vite.config.ts b/playground/vue-pages/vite.config.ts
index 39ec3e1ab..cfe5350e6 100644
--- a/playground/vue-pages/vite.config.ts
+++ b/playground/vue-pages/vite.config.ts
@@ -3,6 +3,14 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
+ run: {
+ tasks: {
+ build: {
+ command: 'vp build',
+ dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
+ },
+ },
+ },
plugins: [voidPlugin(), voidVue()],
// stabilize dev server start for tests
optimizeDeps: { include: ['valibot'] },
diff --git a/playground/websockets/package.json b/playground/websockets/package.json
index 3f804b43f..5eb55e887 100644
--- a/playground/websockets/package.json
+++ b/playground/websockets/package.json
@@ -3,7 +3,6 @@
"private": true,
"type": "module",
"scripts": {
- "build": "vp build",
"dev": "vp dev",
"preview": "vp preview",
"typecheck": "tsc --noEmit"
diff --git a/playground/websockets/vite.config.ts b/playground/websockets/vite.config.ts
index d77f451a3..da39a5f2a 100644
--- a/playground/websockets/vite.config.ts
+++ b/playground/websockets/vite.config.ts
@@ -3,6 +3,14 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
+ run: {
+ tasks: {
+ build: {
+ command: 'vp build',
+ dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
+ },
+ },
+ },
plugins: [voidPlugin(), voidReact()],
optimizeDeps: { include: ['valibot'] },
});
diff --git a/playground/zero-js/package.json b/playground/zero-js/package.json
index 86d01659e..16b64816e 100644
--- a/playground/zero-js/package.json
+++ b/playground/zero-js/package.json
@@ -3,7 +3,6 @@
"private": true,
"type": "module",
"scripts": {
- "build": "vp build",
"dev": "vp dev",
"preview": "vp preview"
},
diff --git a/playground/zero-js/vite.config.ts b/playground/zero-js/vite.config.ts
index 06823dabb..62dffb6d6 100644
--- a/playground/zero-js/vite.config.ts
+++ b/playground/zero-js/vite.config.ts
@@ -4,5 +4,13 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
+ run: {
+ tasks: {
+ build: {
+ command: 'vp build',
+ dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
+ },
+ },
+ },
plugins: [voidPlugin(), voidVue(), voidMarkdown()],
});
diff --git a/test/build-setup.ts b/test/build-setup.ts
new file mode 100644
index 000000000..3847defee
--- /dev/null
+++ b/test/build-setup.ts
@@ -0,0 +1,43 @@
+import spawn from 'cross-spawn';
+import type { TestProject } from 'vite-plus/test/node';
+
+declare module 'vite-plus/test' {
+ export interface ProvidedContext {
+ publicBuildMilliseconds: number;
+ }
+}
+
+/** Restore/build public exports before any test worker imports them. */
+export default async function setup(project: TestProject): Promise {
+ const vitest = project.vitest;
+ if (vitest.getProvidedContext().publicBuildMilliseconds !== undefined) {
+ return;
+ }
+ const build = async () => {
+ const started = performance.now();
+ await new Promise((resolve, reject) => {
+ const child = spawn('vp', ['run', 'build'], {
+ cwd: vitest.config.root,
+ env: { ...process.env, NODE_ENV: 'production' },
+ stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ let output = '';
+ const collect = (chunk: Buffer) => {
+ output = (output + chunk.toString()).slice(-200_000);
+ };
+ child.stdout?.on('data', collect);
+ child.stderr?.on('data', collect);
+ child.once('error', reject);
+ child.once('close', (code) => {
+ if (code === 0) {
+ resolve();
+ } else {
+ reject(new Error(`Public package preparation failed (${code}).\n${output}`));
+ }
+ });
+ });
+ vitest.provide('publicBuildMilliseconds', performance.now() - started);
+ };
+ await build();
+ vitest.onTestsRerun(build);
+}
diff --git a/test/integration-helpers.ts b/test/integration-helpers.ts
index 8cbf4c539..23575cf7a 100644
--- a/test/integration-helpers.ts
+++ b/test/integration-helpers.ts
@@ -50,6 +50,29 @@ export type IsolatedPlayground = {
cleanup: () => void;
};
+/**
+ * Validate/restore a playground build without rewriting SDK artifacts while workers use them.
+ * The shared global setup prepares those prerequisites before any test file is imported.
+ */
+export function buildPlayground(workspaceRoot: string, playground: string): void {
+ const result = crossSpawn.sync(
+ 'vp',
+ ['run', '--ignore-depends-on', '--filter', `./playground/${playground}`, 'build'],
+ {
+ cwd: workspaceRoot,
+ encoding: 'utf8',
+ env: { ...process.env, NODE_ENV: 'production' },
+ maxBuffer: 10 * 1024 * 1024,
+ },
+ );
+ if (result.error || result.status !== 0) {
+ throw new Error(
+ `Could not prepare playground/${playground}.\n${result.stdout ?? ''}${result.stderr ?? ''}`,
+ { cause: result.error },
+ );
+ }
+}
+
function shouldCopyPlaygroundPath(sourceRoot: string, path: string): boolean {
const normalizedSourceRoot = sourceRoot.replaceAll('\\', '/');
const normalizedPath = path.replaceAll('\\', '/');
diff --git a/test/performance-reporter.ts b/test/performance-reporter.ts
index 8218061d4..8b670c39f 100644
--- a/test/performance-reporter.ts
+++ b/test/performance-reporter.ts
@@ -8,8 +8,10 @@ export default class PerformanceReporter implements Reporter {
private root = process.cwd();
private output = '';
private started = 0;
+ private vitest: Vitest | undefined;
onInit(vitest: Vitest): void {
+ this.vitest = vitest;
this.root = vitest.config.root;
const configured = vitest.config.outputFile;
this.output = resolve(
@@ -51,6 +53,7 @@ export default class PerformanceReporter implements Reporter {
version: 1,
recordedAt: new Date().toISOString(),
durationMs: performance.now() - this.started,
+ publicBuildMilliseconds: this.vitest?.getProvidedContext().publicBuildMilliseconds,
reason,
unhandledErrors: errors.length,
machine: {
diff --git a/vite.config.ts b/vite.config.ts
index e960c9262..8fa8ac1bd 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -75,9 +75,89 @@ const platformAlias = {
export default defineConfig({
run: {
tasks: {
- 'build:all': {
+ build: {
+ command: [],
+ dependsOn: [
+ 'create-void#build',
+ '@void/deploy-cloudflare#build',
+ '@void/deploy-core#build',
+ '@void/edge#build',
+ '@void/isr#build',
+ '@void/md#build',
+ '@void/platform#build',
+ '@void/react#build',
+ '@void/solid#build',
+ '@void/svelte#build',
+ 'void#build',
+ '@void/vue#build',
+ ],
+ },
+ 'build:core': { command: [], dependsOn: ['void#build'] },
+ 'build:platform': { command: [], dependsOn: ['@voidcloud/dashboard#build'] },
+ test: { command: 'node test/affected.mjs', cache: false },
+ 'test:benchmark': {
+ command: 'vp test run --reporter=default --reporter=./test/performance-reporter.ts',
+ cache: false,
+ },
+ 'test:full': { command: 'vp test run', cache: false },
+ 'test:integration': { command: 'vp test run --project parallel-integration', cache: false },
+ 'test:metaframeworks': {
+ command:
+ 'vp test run --project parallel-integration analog.test.ts astro.test.ts nitro-worker.test.ts nuxt.test.ts react-router.test.ts sveltekit.test.ts tanstack-start.test.ts vinext-app.test.ts vinext-pages.test.ts',
+ cache: false,
+ },
+ 'test:pages:react-vue': {
+ command: 'vp test run --project parallel-integration packages/react packages/vue',
+ cache: false,
+ },
+ 'test:pages:svelte-solid': {
+ command: 'vp test run --project parallel-integration packages/svelte packages/solid',
+ cache: false,
+ },
+ 'test:platform': { command: "vp test run --project 'platform-*'", cache: false },
+ 'test:profile': {
command:
- "vp run build && vp run --filter './platform/packages/**' build && vp run --filter './playground/**' --parallel build",
+ 'vp test run --reporter=default --experimental.importDurations.print --experimental.importDurations.limit=20',
+ cache: false,
+ },
+ 'test:unit': {
+ command: 'vp test run --project unit --project unit-pglite --project cli-unit',
+ cache: false,
+ },
+ 'build:all': {
+ command: [],
+ dependsOn: [
+ 'build',
+ 'build:platform',
+ 'playground-analog#build',
+ 'playground-astro#build',
+ 'playground-http-errors#build',
+ 'playground-kitchen-sink#build',
+ 'playground-markdown-blog#build',
+ 'playground-mysql-test#build',
+ 'playground-named-layouts#build',
+ 'playground-node-app#build',
+ 'playground-node-static#build',
+ 'playground-node-static-md#build',
+ 'playground-nuxt#build',
+ 'playground-pg-api-test#build',
+ 'playground-pg-test#build',
+ 'playground-react-pages#build',
+ 'playground-react-router#build',
+ 'playground-server-auth-errors#build',
+ 'playground-solid-pages#build',
+ 'playground-spa#build',
+ 'playground-ssr#build',
+ 'playground-static-pages#build',
+ 'playground-svelte-pages#build',
+ 'playground-sveltekit#build',
+ 'playground-tanstack-start#build',
+ 'playground-vinext-app#build',
+ 'playground-vinext-pages#build',
+ 'playground-vue-pages#build',
+ 'playground-websockets#build',
+ 'playground-zero-js#build',
+ ],
},
'lint:platform': {
command: 'vp lint platform --type-aware --tsconfig platform/tsconfig.json',
@@ -85,13 +165,7 @@ export default defineConfig({
'test:all': {
command:
'vp run --cache build:all && node test/check-playground-build-artifacts.mjs && vp check && vp run check:types && vp test run',
- // `vp run` passes ONLY the env vars a task declares to that task — not the full environment.
- // Without this, the gated live Cloudflare e2e's credentials never reach `vp test run`, so it
- // skips even when the CI job injects them. `untrackedEnv` forwards them without folding them
- // into the task's cache fingerprint (credentials must not bust the cache).
- cache: {
- untrackedEnv: ['VOID_E2E_CF_TOKEN', 'VOID_E2E_CF_ACCOUNT_ID', 'VOID_E2E_NAMESPACE'],
- },
+ cache: false,
},
},
},
@@ -526,7 +600,10 @@ export default defineConfig({
name: 'platform-api-integration',
fsModuleCache: true,
include: apiTimezoneTests,
- globalSetup: ['platform/packages/api/test/integration/global-setup.ts'],
+ globalSetup: [
+ 'test/build-setup.ts',
+ 'platform/packages/api/test/integration/global-setup.ts',
+ ],
setupFiles: ['platform/packages/api/test/integration/setup.ts'],
...(process.env.VOID_TEST_DATABASE_URL ? { fileParallelism: false } : {}),
maxWorkers,
@@ -543,7 +620,10 @@ export default defineConfig({
pool: ['linux', 'darwin'].includes(process.platform) ? 'forks' : 'threads',
include: ['platform/packages/api/test/integration/**/*.test.ts'],
exclude: apiTimezoneTests,
- globalSetup: ['platform/packages/api/test/integration/global-setup.ts'],
+ globalSetup: [
+ 'test/build-setup.ts',
+ 'platform/packages/api/test/integration/global-setup.ts',
+ ],
setupFiles: ['platform/packages/api/test/integration/setup.ts'],
...(process.env.VOID_TEST_DATABASE_URL ? { fileParallelism: false } : {}),
maxWorkers,
@@ -555,6 +635,7 @@ export default defineConfig({
// Every integration file here owns its fixture directory, so one worker pool can
// schedule the longest files first and fill idle slots across package boundaries.
name: 'parallel-integration',
+ globalSetup: ['test/build-setup.ts'],
fsModuleCache: true,
pool: 'forks',
// Bound simultaneous database engines and framework compilers locally.
From b5bfd9a5b6016ec0967e6285ab6c8e5e852d91d6 Mon Sep 17 00:00:00 2001
From: Christoph Nakazawa
Date: Tue, 17 Nov 2026 20:57:45 +0900
Subject: [PATCH 04/27] test: prepare owned application fixtures with native
build caching
---
TESTING.md | 4 +
packages/react/vite.config.ts | 18 ++
.../test/integration/test-build-cache.test.ts | 208 ++++++++++++++++++
.../test/unit/test-fixture-inputs.test.ts | 50 +++++
test/affected.mjs | 18 +-
test/build-setup.ts | 54 +++--
test/fixture-app.ts | 188 ++++++++++++++++
test/fixtures/private-pages.ts | 24 ++
test/fixtures/react.ts | 49 +++++
test/integration-helpers.ts | 82 ++++---
test/performance-reporter.ts | 1 +
test/prepare-fixture.ts | 13 ++
vite.config.ts | 1 +
13 files changed, 648 insertions(+), 62 deletions(-)
create mode 100644 packages/void/test/integration/test-build-cache.test.ts
create mode 100644 packages/void/test/unit/test-fixture-inputs.test.ts
create mode 100644 test/fixture-app.ts
create mode 100644 test/fixtures/private-pages.ts
create mode 100644 test/fixtures/react.ts
create mode 100644 test/prepare-fixture.ts
diff --git a/TESTING.md b/TESTING.md
index af4b705c0..e0b44104b 100644
--- a/TESTING.md
+++ b/TESTING.md
@@ -154,11 +154,15 @@ Capture machine information, per-file phases, and individual test durations with
```sh
vp run test:benchmark --outputFile=/tmp/void-test-baseline.json
vp run test:benchmark packages/react/test/integration --outputFile=/tmp/void-react-tests.json
+VOID_TEST_FRESH_BUILDS=1 vp run test:benchmark --outputFile=/tmp/void-fresh-fixtures.json
```
The reporter is opt-in and never skips tests. Keep the same selection, toolchain, cache state,
and machine load when comparing reports. Per-file and per-case durations overlap when tests
run concurrently; their sums are work estimates, not elapsed time or additive savings.
+`VOID_TEST_FRESH_BUILDS=1` bypasses fixture build caching while preserving the same test selection
+and assertions. Public package preparation still uses its task cache; use
+`vp run --no-cache build` separately when measuring a fresh SDK build too.
Vitest 5's import diagnostics are opt-in so ordinary runs stay quiet:
diff --git a/packages/react/vite.config.ts b/packages/react/vite.config.ts
index 58cd44022..91e31d82a 100644
--- a/packages/react/vite.config.ts
+++ b/packages/react/vite.config.ts
@@ -3,6 +3,24 @@ import { defineConfig } from 'vite-plus';
export default defineConfig({
run: {
tasks: {
+ 'prepare:test:islands': {
+ command: 'node ../../test/prepare-fixture.ts react islands',
+ dependsOn: ['build', '@void/md#build'],
+ cache: false,
+ },
+ 'build:test:islands': {
+ command: 'node ../../playground-local/.build-fixtures/react-islands/build.mjs',
+ dependsOn: ['prepare:test:islands'],
+ },
+ 'prepare:test:bare': {
+ command: 'node ../../test/prepare-fixture.ts react bare',
+ dependsOn: ['build', '@void/md#build'],
+ cache: false,
+ },
+ 'build:test:bare': {
+ command: 'node ../../playground-local/.build-fixtures/react-bare/build.mjs',
+ dependsOn: ['prepare:test:bare'],
+ },
build: {
command: 'vp pack',
dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
diff --git a/packages/void/test/integration/test-build-cache.test.ts b/packages/void/test/integration/test-build-cache.test.ts
new file mode 100644
index 000000000..7e9eaa6ba
--- /dev/null
+++ b/packages/void/test/integration/test-build-cache.test.ts
@@ -0,0 +1,208 @@
+import { createHash } from 'node:crypto';
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ realpathSync,
+ rmSync,
+ symlinkSync,
+ writeFileSync,
+} from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { pathToFileURL } from 'node:url';
+import { stripVTControlCharacters } from 'node:util';
+import spawn from 'cross-spawn';
+import { afterAll, beforeAll, beforeEach, expect, it } from 'vite-plus/test';
+import type { FixtureApp } from '../../../../test/fixture-app.ts';
+
+const repository = join(import.meta.dirname, '../../../..');
+let root: string;
+let fixture: FixtureApp;
+let initialHtml: string;
+
+function writeInputs(): void {
+ writeFileSync(join(root, 'fixture.json'), JSON.stringify(fixture));
+}
+
+function build() {
+ writeInputs();
+ const result = spawn.sync('vp', ['run', 'build'], {
+ cwd: root,
+ env: { ...process.env, NODE_ENV: undefined, NO_COLOR: '1', FORCE_COLOR: undefined },
+ encoding: 'utf8',
+ maxBuffer: 10 * 1024 * 1024,
+ });
+ return {
+ status: result.status,
+ output: stripVTControlCharacters(`${result.stdout ?? ''}${result.stderr ?? ''}`),
+ };
+}
+
+function succeed() {
+ const result = build();
+ expect(result.status, result.output).toBe(0);
+ return result.output;
+}
+
+function html(page = 'index'): string {
+ return readFileSync(join(root, 'app/dist/client', `${page}.html`), 'utf8');
+}
+
+function expectBuildHit(output: string): void {
+ expect(
+ output
+ .replaceAll('\\', '/')
+ .split('\n')
+ .some((line) => line.includes('app/build.mjs') && line.includes('cache hit')),
+ output,
+ ).toBe(true);
+}
+
+function baseline(): FixtureApp {
+ return {
+ framework: 'react',
+ name: 'cache-contract',
+ files: {
+ 'tsconfig.json': JSON.stringify({ compilerOptions: { jsx: 'react-jsx' } }),
+ 'pages/index.island.tsx': `import { message } from '../message';
+export default function Page() { return <>{message}
{__FIXTURE_LABEL__}
>; }`,
+ 'vite.config.mjs': `import { voidPlugin } from 'void';
+import { voidReact } from '@void/react/plugin';
+import { voidMarkdown } from '@void/md/plugin';
+import { loadEnv } from 'vite';
+export default ({ mode }) => ({ plugins: [voidPlugin(), voidReact(), voidMarkdown()],
+ define: { __FIXTURE_LABEL__: JSON.stringify(loadEnv(mode, process.cwd(), 'VITE_').VITE_FIXTURE_LABEL ?? '') }
+});`,
+ 'message.ts': "export const message = 'original fixture';",
+ 'pages/removed.island.tsx': 'export default function Removed() { return Removed
; }',
+ },
+ };
+}
+
+beforeAll(() => {
+ root = realpathSync(mkdtempSync(join(tmpdir(), 'void-build-cache-')));
+ mkdirSync(join(root, 'node_modules'));
+ symlinkSync(
+ realpathSync(join(repository, 'node_modules/vite-plus')),
+ join(root, 'node_modules/vite-plus'),
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+ writeFileSync(join(root, '.node-version'), readFileSync(join(repository, '.node-version')));
+ writeFileSync(
+ join(root, 'package.json'),
+ JSON.stringify({ name: 'void-build-cache-contract', private: true, type: 'module' }),
+ );
+ writeFileSync(
+ join(root, 'vite.config.mjs'),
+ `export default { run: { tasks: {
+ prepare: { command: 'node prepare.mjs', cache: false },
+ build: { command: 'node app/build.mjs', dependsOn: ['prepare'] },
+} } };
+`,
+ );
+ const materializer = pathToFileURL(join(repository, 'test/fixture-app.ts')).href;
+ writeFileSync(
+ join(root, 'prepare.mjs'),
+ `import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { prepareFixture } from ${JSON.stringify(materializer)};
+prepareFixture(JSON.parse(readFileSync(new URL('./fixture.json', import.meta.url), 'utf8')),
+ fileURLToPath(new URL('./app', import.meta.url)));
+`,
+ );
+ fixture = baseline();
+ succeed();
+ initialHtml = html();
+});
+
+beforeEach(() => {
+ fixture = baseline();
+});
+
+afterAll(() => {
+ if (root) {
+ rmSync(root, { recursive: true, force: true, maxRetries: 20, retryDelay: 50 });
+ }
+});
+
+it('restores deleted production artifacts byte-for-byte without compiling again', () => {
+ rmSync(join(root, 'app/dist'), { recursive: true, force: true });
+ rmSync(join(root, 'app/.cloudflare'), { recursive: true, force: true });
+ expectBuildHit(succeed());
+ const digest = (value: string) => createHash('sha256').update(value).digest('hex');
+ expect(digest(html())).toBe(digest(initialHtml));
+ expect(existsSync(join(root, 'app/.cloudflare/output/v1/config.json'))).toBe(true);
+});
+
+it('invalidates a transitive source dependency', () => {
+ fixture.files = {
+ ...fixture.files,
+ 'message.ts': "export const message = 'changed dependency';",
+ };
+ succeed();
+ expect(html()).toContain('changed dependency');
+ expect(html()).not.toContain('original fixture');
+});
+
+it('discovers a newly added route', () => {
+ fixture.files = {
+ ...fixture.files,
+ 'pages/added.island.tsx': 'export default function Added() { return Added route
; }',
+ };
+ succeed();
+ expect(html('added')).toContain('Added route');
+});
+
+it('removes deleted source and its old generated output', () => {
+ const files = { ...fixture.files };
+ delete files['pages/removed.island.tsx'];
+ fixture.files = files;
+ succeed();
+ expect(existsSync(join(root, 'app/pages/removed.island.tsx'))).toBe(false);
+ expect(existsSync(join(root, 'app/dist/client/removed.html'))).toBe(false);
+});
+
+it('rebuilds after application configuration changes', () => {
+ fixture.files = {
+ ...fixture.files,
+ 'void.config.ts': `import { defineConfig } from 'void/config';
+export default defineConfig({ output: 'static', head: { title: 'Changed fixture title' },
+ worker: { compatibility_date: '2026-02-24' } });`,
+ };
+ succeed();
+ expect(html()).toContain('Changed fixture title');
+});
+
+it('tracks environment files that were absent during the previous build', () => {
+ succeed();
+ fixture.files = {
+ ...fixture.files,
+ '.env': 'VITE_FIXTURE_LABEL=fixture environment',
+ };
+ succeed();
+ expect(html()).toContain('fixture environment');
+ fixture.files = { ...fixture.files, '.env': 'VITE_FIXTURE_LABEL=updated environment' };
+ succeed();
+ expect(html()).toContain('updated environment');
+});
+
+it('never turns a failed build into a cache hit and recovers after its inputs are fixed', () => {
+ fixture.files = {
+ ...fixture.files,
+ 'vite.config.mjs': "throw new Error('fixture build rejected');",
+ };
+ const failed = build();
+ expect(failed.status).not.toBe(0);
+ expect(failed.output).toContain('fixture build rejected');
+ const retry = build();
+ expect(retry.status).not.toBe(0);
+ expect(retry.output).not.toMatch(/app\/build\.mjs.*cache hit/);
+ fixture = baseline();
+ succeed();
+ const recovered = html();
+ expectBuildHit(succeed());
+ expect(html()).toBe(recovered);
+ expect(html()).toContain('original fixture');
+});
diff --git a/packages/void/test/unit/test-fixture-inputs.test.ts b/packages/void/test/unit/test-fixture-inputs.test.ts
new file mode 100644
index 000000000..cc728c89a
--- /dev/null
+++ b/packages/void/test/unit/test-fixture-inputs.test.ts
@@ -0,0 +1,50 @@
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterEach, beforeEach, expect, it } from 'vite-plus/test';
+import { prepareFixture, type FixtureApp } from '../../../../test/fixture-app.ts';
+
+let root: string;
+const fixture: FixtureApp = {
+ framework: 'react',
+ name: 'inputs',
+ files: { 'pages/old.island.tsx': 'export default function Page() { return Old
; }' },
+};
+
+beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'void-fixture-inputs-'));
+});
+afterEach(() => {
+ rmSync(root, { recursive: true, force: true, maxRetries: 20, retryDelay: 50 });
+});
+
+it('does not replace an existing directory it does not own', () => {
+ writeFileSync(join(root, 'keep.txt'), 'existing application');
+ expect(() => prepareFixture(fixture, root)).toThrow('unowned fixture directory');
+ expect(readFileSync(join(root, 'keep.txt'), 'utf8')).toBe('existing application');
+});
+
+it('does not give a different fixture ownership of the same directory', () => {
+ prepareFixture(fixture, root);
+ expect(() => prepareFixture({ ...fixture, name: 'different' }, root)).toThrow(
+ 'different application',
+ );
+ expect(existsSync(join(root, 'pages/old.island.tsx'))).toBe(true);
+});
+
+it('replaces the complete source tree while leaving build outputs to their owning task', () => {
+ prepareFixture(fixture, root);
+ mkdirSync(join(root, 'dist/client'), { recursive: true });
+ writeFileSync(join(root, 'dist/client/index.html'), 'previous build');
+ prepareFixture(
+ {
+ ...fixture,
+ files: { 'pages/new.island.tsx': 'export default function Page() { return New
; }' },
+ },
+ root,
+ );
+ expect(existsSync(join(root, 'pages/old.island.tsx'))).toBe(false);
+ expect(readFileSync(join(root, 'pages/new.island.tsx'), 'utf8')).toContain('New');
+ expect(readFileSync(join(root, 'dist/client/index.html'), 'utf8')).toBe('previous build');
+ expect(existsSync(join(root, 'node_modules/@void/react/package.json'))).toBe(true);
+});
diff --git a/test/affected.mjs b/test/affected.mjs
index d0759d5cb..48a7416f5 100644
--- a/test/affected.mjs
+++ b/test/affected.mjs
@@ -1,10 +1,10 @@
-import { spawnSync } from 'node:child_process';
import { globSync, readFileSync, realpathSync } from 'node:fs';
import { join, relative } from 'node:path';
import { fileURLToPath } from 'node:url';
import { parseArgs } from 'node:util';
import { deletedFiles, planAffectedTests } from './affected-tests.ts';
import { createAffectedVcsProvider } from './affected-vcs.ts';
+import { preparePublicPackages } from './build-setup.ts';
async function runAffected(root, values) {
root = realpathSync(root);
@@ -37,19 +37,10 @@ async function runAffected(root, values) {
console.log('Documentation-only changes: no runtime tests selected. Verify docs separately.');
return;
}
+ let publicBuildMilliseconds;
if (initial.build && !values.list) {
console.log('Refreshing public package builds before testing their installed exports.');
- const build = spawnSync('vp', ['run', 'build'], {
- cwd: root,
- stdio: 'inherit',
- shell: process.platform === 'win32',
- });
- if (build.error) {
- throw build.error;
- }
- if (build.status !== 0) {
- throw new Error(`Public package build failed (${build.status ?? build.signal}).`);
- }
+ publicBuildMilliseconds = await preparePublicPackages(root);
}
console.log('Initializing Vitest and discovering test files...');
const { createVitest } = await import('vite-plus/test/node');
@@ -62,6 +53,9 @@ async function runAffected(root, values) {
? { project: ['unit', 'unit-pglite', 'cli-unit', 'platform-unit', 'platform-unit-pglite'] }
: {}),
});
+ if (publicBuildMilliseconds !== undefined) {
+ vitest.provide('publicBuildMilliseconds', publicBuildMilliseconds);
+ }
try {
const all = await vitest.globTestSpecifications();
if (!all.length) {
diff --git a/test/build-setup.ts b/test/build-setup.ts
index 3847defee..08afd8dd6 100644
--- a/test/build-setup.ts
+++ b/test/build-setup.ts
@@ -7,36 +7,42 @@ declare module 'vite-plus/test' {
}
}
-/** Restore/build public exports before any test worker imports them. */
+export async function preparePublicPackages(root: string): Promise {
+ const started = performance.now();
+ await new Promise((resolve, reject) => {
+ const child = spawn('vp', ['run', 'build'], {
+ cwd: root,
+ // Clear Vitest's mode so build tools use their production defaults and the same cache
+ // fingerprint as a normal `vp run build` outside the test runner.
+ env: { ...process.env, NODE_ENV: undefined },
+ stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ let output = '';
+ const collect = (chunk: Buffer) => {
+ output = (output + chunk.toString()).slice(-200_000);
+ };
+ child.stdout?.on('data', collect);
+ child.stderr?.on('data', collect);
+ child.once('error', reject);
+ child.once('close', (code) => {
+ if (code === 0) {
+ resolve();
+ } else {
+ reject(new Error(`Public package preparation failed (${code}).\n${output}`));
+ }
+ });
+ });
+ return performance.now() - started;
+}
+
+/** Restore/build public exports before any integration worker imports them. */
export default async function setup(project: TestProject): Promise {
const vitest = project.vitest;
if (vitest.getProvidedContext().publicBuildMilliseconds !== undefined) {
return;
}
const build = async () => {
- const started = performance.now();
- await new Promise((resolve, reject) => {
- const child = spawn('vp', ['run', 'build'], {
- cwd: vitest.config.root,
- env: { ...process.env, NODE_ENV: 'production' },
- stdio: ['ignore', 'pipe', 'pipe'],
- });
- let output = '';
- const collect = (chunk: Buffer) => {
- output = (output + chunk.toString()).slice(-200_000);
- };
- child.stdout?.on('data', collect);
- child.stderr?.on('data', collect);
- child.once('error', reject);
- child.once('close', (code) => {
- if (code === 0) {
- resolve();
- } else {
- reject(new Error(`Public package preparation failed (${code}).\n${output}`));
- }
- });
- });
- vitest.provide('publicBuildMilliseconds', performance.now() - started);
+ vitest.provide('publicBuildMilliseconds', await preparePublicPackages(vitest.config.root));
};
await build();
vitest.onTestsRerun(build);
diff --git a/test/fixture-app.ts b/test/fixture-app.ts
new file mode 100644
index 000000000..639099204
--- /dev/null
+++ b/test/fixture-app.ts
@@ -0,0 +1,188 @@
+import {
+ cpSync,
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ readdirSync,
+ rmSync,
+ writeFileSync,
+} from 'node:fs';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import spawn from 'cross-spawn';
+import { fixtureBuildCacheArgs, linkFixtureDependencies } from './integration-helpers.ts';
+
+export type FixtureFramework = 'react' | 'vue' | 'svelte' | 'solid';
+export type FixtureApp = {
+ framework: FixtureFramework;
+ name: string;
+ files: Readonly>;
+};
+
+const repository = fileURLToPath(new URL('../', import.meta.url));
+const plugins = {
+ react: 'voidReact',
+ vue: 'voidVue',
+ svelte: 'voidSvelte',
+ solid: 'voidSolid',
+} as const;
+const ownershipFile = '.void-test-fixture.json';
+const generated = new Set([
+ ownershipFile,
+ 'node_modules',
+ 'dist',
+ '.cloudflare',
+ '.void',
+ '.wrangler',
+ '.vite',
+]);
+
+export function fixtureBuildRoot(fixture: FixtureApp): string {
+ return join(
+ repository,
+ 'playground-local',
+ '.build-fixtures',
+ `${fixture.framework}-${fixture.name}`,
+ );
+}
+
+/** Materialize inputs before Vite Task checks the build cache. No build results are cached here. */
+export function prepareFixture(fixture: FixtureApp, root = fixtureBuildRoot(fixture)): void {
+ mkdirSync(root, { recursive: true });
+ const ownership = JSON.stringify({ framework: fixture.framework, name: fixture.name });
+ const marker = join(root, ownershipFile);
+ if (existsSync(marker)) {
+ if (readFileSync(marker, 'utf8') !== ownership) {
+ throw new Error(`Fixture directory belongs to a different application: ${root}`);
+ }
+ } else {
+ if (readdirSync(root).length) {
+ throw new Error(`Refusing to replace files in an unowned fixture directory: ${root}`);
+ }
+ writeFileSync(marker, ownership, { flag: 'wx' });
+ }
+ // This directory belongs to the fixture. Preserve outputs so Vite Task can validate/restore
+ // them, but replace the complete authored input tree, including deleted routes.
+ for (const entry of readdirSync(root)) {
+ if (!generated.has(entry)) {
+ rmSync(join(root, entry), { recursive: true, force: true });
+ }
+ }
+ const packageRoot = join(repository, 'packages', fixture.framework);
+ linkFixtureDependencies(packageRoot, root, {
+ void: join(repository, 'packages/void'),
+ [`@void/${fixture.framework}`]: packageRoot,
+ '@void/md': join(repository, 'packages/md'),
+ });
+ const plugin = plugins[fixture.framework];
+ const files = {
+ 'package.json': JSON.stringify({
+ name: `void-test-${fixture.framework}-${fixture.name}`,
+ private: true,
+ type: 'module',
+ dependencies: {
+ void: 'workspace:*',
+ [`@void/${fixture.framework}`]: 'workspace:*',
+ '@void/md': 'workspace:*',
+ },
+ }),
+ 'vite.config.mjs': `import { voidPlugin } from 'void';
+import { ${plugin} } from '@void/${fixture.framework}/plugin';
+import { voidMarkdown } from '@void/md/plugin';
+export default { plugins: [voidPlugin(), ${plugin}(), voidMarkdown()] };
+`,
+ 'void.config.ts': `import { defineConfig } from 'void/config';
+export default defineConfig({ output: 'static', worker: { compatibility_date: '2026-02-24' } });
+`,
+ // Use the fixture's installed Vite instance and its public builder API. Running another
+ // task-runner CLI here would make workspace discovery part of this build's inputs.
+ 'build.mjs': `process.env.NODE_ENV = 'production';
+process.chdir(import.meta.dirname);
+const { createBuilder } = await import('vite');
+const builder = await createBuilder({ configLoader: 'native' });
+await builder.buildApp();
+`,
+ 'pages/about.md': '---\ntitle: About\n---\n\n# About\n',
+ ...fixture.files,
+ };
+ for (const [file, contents] of Object.entries(files)) {
+ const path = join(root, file);
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, contents);
+ }
+}
+
+export type BuiltFixture = {
+ root: string;
+ page(file: string): { html: string; css: string };
+ output(dir: 'client' | 'ssr'): Map;
+ cleanup(): void;
+};
+
+/** One immutable cached build can supply separate writable runtime copies. */
+export function buildFixture(fixture: FixtureApp): BuiltFixture {
+ prepareFixture(fixture);
+ const result = spawn.sync(
+ 'vp',
+ [
+ 'run',
+ '--ignore-depends-on',
+ ...fixtureBuildCacheArgs(),
+ `@void/${fixture.framework}#build:test:${fixture.name}`,
+ ],
+ {
+ cwd: repository,
+ env: { ...process.env, NODE_ENV: undefined },
+ encoding: 'utf8',
+ maxBuffer: 10 * 1024 * 1024,
+ },
+ );
+ if (result.error || result.status !== 0) {
+ throw new Error(`Fixture build failed.\n${result.stdout ?? ''}${result.stderr ?? ''}`, {
+ cause: result.error,
+ });
+ }
+ const runs = join(repository, 'playground-local', '.test-fixtures');
+ mkdirSync(runs, { recursive: true });
+ const root = mkdtempSync(join(runs, `${fixture.framework}-${fixture.name}-`));
+ try {
+ prepareFixture(fixture, root);
+ const built = fixtureBuildRoot(fixture);
+ for (const directory of ['dist', '.cloudflare']) {
+ if (existsSync(join(built, directory))) {
+ cpSync(join(built, directory), join(root, directory), { recursive: true });
+ }
+ }
+ } catch (error) {
+ rmSync(root, { recursive: true, force: true });
+ throw error;
+ }
+ const client = join(root, 'dist/client');
+ return {
+ root,
+ page(file) {
+ const html = readFileSync(join(client, file), 'utf8');
+ const css = html
+ .split(' readFileSync(join(client, href), 'utf8'))
+ .join('\n');
+ return { html, css };
+ },
+ output(dir) {
+ const output = join(root, 'dist', dir);
+ const files = new Map();
+ for (const file of readdirSync(output, { recursive: true, encoding: 'utf8' })) {
+ if (/\.(js|css|html)$/.test(file)) {
+ files.set(file, readFileSync(join(output, file), 'utf8'));
+ }
+ }
+ return files;
+ },
+ cleanup() {
+ rmSync(root, { recursive: true, force: true, maxRetries: 20, retryDelay: 50 });
+ },
+ };
+}
diff --git a/test/fixtures/private-pages.ts b/test/fixtures/private-pages.ts
new file mode 100644
index 000000000..0a0d8bd5c
--- /dev/null
+++ b/test/fixtures/private-pages.ts
@@ -0,0 +1,24 @@
+/** Shared application input, not a model of the adapter's implementation. */
+export function privatePages(
+ framework: 'react' | 'solid',
+ counter: string,
+): Record {
+ const attribute = framework === 'react' ? 'className' : 'class';
+ return {
+ 'pages/_ui/frame.tsx': `import './frame.css';
+export function Frame(props) {
+ return {props.children};
+}`,
+ 'pages/_ui/frame.css': '.private-frame { outline-offset: 11px; }',
+ 'pages/_ui/counter.tsx': counter,
+ 'pages/_layouts/docs.tsx': `import './docs.css';
+export default function Docs(props) {
+ return ;
+}`,
+ 'pages/_layouts/docs.css': '.private-layout { word-spacing: 3px; }',
+ 'pages/private.island.tsx': `import { Frame } from './_ui/frame';
+import Counter from './_ui/counter' with { island: 'load' };
+export const layout = 'docs';
+export default function Private() { return ; }`,
+ };
+}
diff --git a/test/fixtures/react.ts b/test/fixtures/react.ts
new file mode 100644
index 000000000..e18561213
--- /dev/null
+++ b/test/fixtures/react.ts
@@ -0,0 +1,49 @@
+import type { FixtureApp } from '../fixture-app.ts';
+import { privatePages } from './private-pages.ts';
+
+const tsconfig = JSON.stringify({ compilerOptions: { jsx: 'react-jsx' } });
+
+export const islands: FixtureApp = {
+ framework: 'react',
+ name: 'islands',
+ files: {
+ 'tsconfig.json': tsconfig,
+ 'src/shell.css': '.shell { outline-offset: 7px; }',
+ 'src/card.module.css': '.card { text-indent: 9px; }',
+ 'src/badge.css': '.badge { word-spacing: 5px; }',
+ 'src/Badge.tsx': `import './badge.css';
+export default function Badge() { return Badge; }`,
+ 'src/Shell.tsx': `import './shell.css';
+import styles from './card.module.css';
+import Badge from './Badge';
+export default function Shell({ children }) {
+ return {children};
+}`,
+ 'pages/layout.tsx': `import Shell from '../src/Shell';
+export default function Layout({ children }) { return {children}; }`,
+ 'pages/index.island.tsx': 'export default function Home() { return Home
; }',
+ 'pages/badge.island.tsx': `import Badge from '../src/Badge' with { island: 'load' };
+export default function BadgePage() { return ; }`,
+ ...privatePages(
+ 'react',
+ `import { useState } from 'react';
+export default function Counter() {
+ const [count, setCount] = useState(0);
+ return ;
+}`,
+ ),
+ },
+};
+
+export const bare: FixtureApp = {
+ framework: 'react',
+ name: 'bare',
+ files: {
+ 'tsconfig.json': tsconfig,
+ 'pages/layout.tsx':
+ 'export default function Layout({ children }) { return {children}; }',
+ 'pages/index.island.tsx': 'export default function Home() { return Home
; }',
+ },
+};
+
+export const fixtures: Readonly> = { islands, bare };
diff --git a/test/integration-helpers.ts b/test/integration-helpers.ts
index 23575cf7a..0b752b618 100644
--- a/test/integration-helpers.ts
+++ b/test/integration-helpers.ts
@@ -13,7 +13,7 @@ import {
writeFileSync,
} from 'node:fs';
import { createServer, type AddressInfo } from 'node:net';
-import { basename, join, relative } from 'node:path/posix';
+import { basename, dirname, join, relative } from 'node:path/posix';
import { setTimeout as delay } from 'node:timers/promises';
import { stripVTControlCharacters } from 'node:util';
import crossSpawn from 'cross-spawn';
@@ -50,6 +50,10 @@ export type IsolatedPlayground = {
cleanup: () => void;
};
+export function fixtureBuildCacheArgs(): Array {
+ return process.env.VOID_TEST_FRESH_BUILDS === '1' ? ['--no-cache'] : [];
+}
+
/**
* Validate/restore a playground build without rewriting SDK artifacts while workers use them.
* The shared global setup prepares those prerequisites before any test file is imported.
@@ -57,11 +61,18 @@ export type IsolatedPlayground = {
export function buildPlayground(workspaceRoot: string, playground: string): void {
const result = crossSpawn.sync(
'vp',
- ['run', '--ignore-depends-on', '--filter', `./playground/${playground}`, 'build'],
+ [
+ 'run',
+ '--ignore-depends-on',
+ ...fixtureBuildCacheArgs(),
+ '--filter',
+ `./playground/${playground}`,
+ 'build',
+ ],
{
cwd: workspaceRoot,
encoding: 'utf8',
- env: { ...process.env, NODE_ENV: 'production' },
+ env: { ...process.env, NODE_ENV: undefined },
maxBuffer: 10 * 1024 * 1024,
},
);
@@ -105,16 +116,46 @@ export function createIsolatedPlayground(
},
});
+ linkFixtureDependencies(sourceRoot, root);
+
+ // Avoid duplicate workspace package names when multiple copies exist concurrently.
+ const packagePath = join(root, 'package.json');
+ const packageJson = JSON.parse(readFileSync(packagePath, 'utf-8')) as { name?: string };
+ packageJson.name = `${packageJson.name ?? basename(sourceWorkspacePath)}-${basename(root)}`;
+ writeFileSync(packagePath, `${JSON.stringify(packageJson, null, 2)}\n`);
+
+ return {
+ root,
+ workspacePath: relative(workspaceRoot, root),
+ cleanup() {
+ rmSync(root, { recursive: true, force: true, maxRetries: 20, retryDelay: 50 });
+ },
+ };
+}
+
+/** Link installed dependencies into a fixture without archiving or copying node_modules. */
+export function linkFixtureDependencies(
+ sourceRoot: string,
+ root: string,
+ additionalPackages: Record = {},
+): void {
+ const fixtureNodeModules = join(root, 'node_modules');
+ mkdirSync(fixtureNodeModules, { recursive: true });
+ const linkDependency = (source: string, destination: string) => {
+ const target = realpathSync(source);
+ try {
+ if (realpathSync(destination) === target) {
+ return;
+ }
+ } catch {
+ // A fresh fixture has no links yet.
+ }
+ rmSync(destination, { recursive: true, force: true });
+ mkdirSync(dirname(destination), { recursive: true });
+ symlinkSync(target, destination, process.platform === 'win32' ? 'junction' : 'dir');
+ };
const sourceNodeModules = join(sourceRoot, 'node_modules');
if (existsSync(sourceNodeModules)) {
- const fixtureNodeModules = join(root, 'node_modules');
- mkdirSync(fixtureNodeModules);
- const linkDependency = (source: string, destination: string) =>
- symlinkSync(
- realpathSync(source),
- destination,
- process.platform === 'win32' ? 'junction' : 'dir',
- );
// Linking the whole directory leaves pnpm's relative package links behind
// a Windows junction at a different depth. Pin each package's real target.
for (const entry of readdirSync(sourceNodeModules, { withFileTypes: true })) {
@@ -131,7 +172,7 @@ export function createIsolatedPlayground(
const source = join(sourceNodeModules, entry.name);
const destination = join(fixtureNodeModules, entry.name);
if (entry.name.startsWith('@')) {
- mkdirSync(destination);
+ mkdirSync(destination, { recursive: true });
for (const name of readdirSync(source)) {
linkDependency(join(source, name), join(destination, name));
}
@@ -140,20 +181,9 @@ export function createIsolatedPlayground(
}
}
}
-
- // Avoid duplicate workspace package names when multiple copies exist concurrently.
- const packagePath = join(root, 'package.json');
- const packageJson = JSON.parse(readFileSync(packagePath, 'utf-8')) as { name?: string };
- packageJson.name = `${packageJson.name ?? basename(sourceWorkspacePath)}-${basename(root)}`;
- writeFileSync(packagePath, `${JSON.stringify(packageJson, null, 2)}\n`);
-
- return {
- root,
- workspacePath: relative(workspaceRoot, root),
- cleanup() {
- rmSync(root, { recursive: true, force: true, maxRetries: 20, retryDelay: 50 });
- },
- };
+ for (const [name, directory] of Object.entries(additionalPackages)) {
+ linkDependency(directory, join(fixtureNodeModules, name));
+ }
}
/** Returns a port that is free right now. Another process can still take it before use. */
diff --git a/test/performance-reporter.ts b/test/performance-reporter.ts
index 8b670c39f..bc70fdc89 100644
--- a/test/performance-reporter.ts
+++ b/test/performance-reporter.ts
@@ -54,6 +54,7 @@ export default class PerformanceReporter implements Reporter {
recordedAt: new Date().toISOString(),
durationMs: performance.now() - this.started,
publicBuildMilliseconds: this.vitest?.getProvidedContext().publicBuildMilliseconds,
+ fixtureTaskCache: process.env.VOID_TEST_FRESH_BUILDS === '1' ? 'disabled' : 'enabled',
reason,
unhandledErrors: errors.length,
machine: {
diff --git a/test/prepare-fixture.ts b/test/prepare-fixture.ts
new file mode 100644
index 000000000..cf1466908
--- /dev/null
+++ b/test/prepare-fixture.ts
@@ -0,0 +1,13 @@
+import { prepareFixture, type FixtureApp } from './fixture-app.ts';
+
+const [framework, name] = process.argv.slice(2);
+if (!['react', 'vue', 'svelte', 'solid'].includes(framework ?? '') || !name) {
+ throw new Error('Usage: node test/prepare-fixture.ts ');
+}
+const { fixtures }: { fixtures: Readonly> } = await import(
+ `./fixtures/${framework}.ts`
+);
+if (!Object.hasOwn(fixtures, name)) {
+ throw new Error(`Unknown ${framework} fixture: ${name}`);
+}
+prepareFixture(fixtures[name]!);
diff --git a/vite.config.ts b/vite.config.ts
index 8fa8ac1bd..e7d34334b 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -40,6 +40,7 @@ const sdkPgliteUnitTests = [
// core-markdown workers explicitly from this main config process (which has the runner's step env).
// Absent credentials become empty strings so ordinary test runs skip the live suite.
const e2eWorkerEnv = {
+ VOID_TEST_FRESH_BUILDS: process.env.VOID_TEST_FRESH_BUILDS ?? '',
VOID_TEST_BROWSER: process.env.VOID_TEST_BROWSER ?? 'chromium',
VOID_E2E_CF_TOKEN: process.env.VOID_E2E_CF_TOKEN ?? '',
VOID_E2E_CF_ACCOUNT_ID: process.env.VOID_E2E_CF_ACCOUNT_ID ?? '',
From d212114bc6a35dcfef236f430e6dbf75d15c3193 Mon Sep 17 00:00:00 2001
From: Christoph Nakazawa
Date: Tue, 17 Nov 2026 20:57:47 +0900
Subject: [PATCH 05/27] test(react): share immutable island build artifacts
across contracts
---
.../test/integration/island-css-build.test.ts | 56 +++-------------
test/island-css-build.ts | 16 ++++-
test/private-pages-build.ts | 65 +++++++++++--------
3 files changed, 61 insertions(+), 76 deletions(-)
diff --git a/packages/react/test/integration/island-css-build.test.ts b/packages/react/test/integration/island-css-build.test.ts
index f29cd8687..6f3e84c2e 100644
--- a/packages/react/test/integration/island-css-build.test.ts
+++ b/packages/react/test/integration/island-css-build.test.ts
@@ -1,34 +1,15 @@
-import { join } from 'node:path';
-import { expect, it } from 'vite-plus/test';
-import { buildIslandApp, defineIslandCssBuildTest } from '../../../../test/island-css-build.ts';
+import { afterAll, expect, it } from 'vite-plus/test';
+import { buildFixture, type BuiltFixture } from '../../../../test/fixture-app.ts';
+import { bare, islands } from '../../../../test/fixtures/react.ts';
+import { defineIslandCssBuildTest } from '../../../../test/island-css-build.ts';
import { definePrivatePagesBuildTest } from '../../../../test/private-pages-build.ts';
-const packageDir = join(import.meta.dirname, '../..');
-const tsconfig = JSON.stringify({ compilerOptions: { jsx: 'react-jsx' } });
+let shared: BuiltFixture | undefined;
+const buildIslands = () => (shared ??= buildFixture(islands));
+afterAll(() => shared?.cleanup());
defineIslandCssBuildTest({
- packageDir,
- pluginName: 'voidReact',
- files: {
- 'tsconfig.json': tsconfig,
- 'src/shell.css': '.shell { outline-offset: 7px; }',
- 'src/card.module.css': '.card { text-indent: 9px; }',
- 'src/badge.css': '.badge { word-spacing: 5px; }',
- 'src/Badge.tsx': `import './badge.css';
-export default function Badge() { return Badge; }`,
- 'src/Shell.tsx': `import './shell.css';
-import styles from './card.module.css';
-import Badge from './Badge';
-export default function Shell({ children }) {
- return {children};
-}`,
- 'pages/layout.tsx': `import Shell from '../src/Shell';
-export default function Layout({ children }) { return {children}; }`,
- 'pages/index.island.tsx': 'export default function Home() { return Home
; }',
- // The layout renders Badge without hydrating it; this page hydrates it.
- 'pages/badge.island.tsx': `import Badge from '../src/Badge' with { island: 'load' };
-export default function BadgePage() { return ; }`,
- },
+ build: buildIslands,
expectedCss: ['.shell{outline-offset:7px}', '{text-indent:9px}', '.badge{word-spacing:5px}'],
checkBuild(build) {
// Badge hydrates, so this build also covers the client/server entry boundary.
@@ -41,16 +22,7 @@ export default function BadgePage() { return ; }`,
});
it('builds island pages without CSS or JavaScript with no stylesheet, script or client runtime', () => {
- const build = buildIslandApp({
- packageDir,
- pluginName: 'voidReact',
- files: {
- 'tsconfig.json': tsconfig,
- 'pages/layout.tsx':
- 'export default function Layout({ children }) { return {children}; }',
- 'pages/index.island.tsx': 'export default function Home() { return Home
; }',
- },
- });
+ const build = buildFixture(bare);
try {
for (const file of ['index.html', 'about.html']) {
const { html } = build.page(file);
@@ -67,12 +39,4 @@ it('builds island pages without CSS or JavaScript with no stylesheet, script or
}
}, 120_000);
-definePrivatePagesBuildTest({
- packageDir,
- pluginName: 'voidReact',
- counter: `import { useState } from 'react';
-export default function Counter() {
- const [count, setCount] = useState(0);
- return ;
-}`,
-});
+definePrivatePagesBuildTest({ build: buildIslands });
diff --git a/test/island-css-build.ts b/test/island-css-build.ts
index b2c4fdd70..01af74ddf 100644
--- a/test/island-css-build.ts
+++ b/test/island-css-build.ts
@@ -3,6 +3,7 @@ import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSyn
import { dirname, join } from 'node:path';
import { pathToFileURL } from 'node:url';
import { expect, it } from 'vite-plus/test';
+import type { BuiltFixture } from './fixture-app.ts';
const MD_PLUGIN = join(import.meta.dirname, '../packages/md/dist/plugin.mjs');
@@ -102,9 +103,16 @@ export function countOf(text: string, part: string): number {
* Production must link that CSS on island and Markdown pages, as dev does,
* even though the pages ship no JavaScript.
*/
-export function defineIslandCssBuildTest(app: IslandCssApp): void {
+export function defineIslandCssBuildTest(
+ app:
+ | IslandCssApp
+ | (Pick & {
+ build: () => BuiltFixture;
+ }),
+): void {
it('links the CSS that a layout component imports on island and Markdown pages', () => {
- const build = buildIslandApp(app);
+ const supplied = 'build' in app;
+ const build = supplied ? app.build() : buildIslandApp(app);
try {
for (const file of ['index.html', 'about.html']) {
const { html, css } = build.page(file);
@@ -124,7 +132,9 @@ export function defineIslandCssBuildTest(app: IslandCssApp): void {
}
app.checkBuild?.(build);
} finally {
- build.cleanup();
+ if (!supplied) {
+ build.cleanup();
+ }
}
}, 120_000);
}
diff --git a/test/private-pages-build.ts b/test/private-pages-build.ts
index 3d61b3cd4..2c786cb58 100644
--- a/test/private-pages-build.ts
+++ b/test/private-pages-build.ts
@@ -4,42 +4,50 @@ import { chromium, type Browser } from 'playwright';
import { preview, type PreviewServer } from 'vite';
import { expect, it } from 'vite-plus/test';
import { waitForIslandsHydrated } from './browser-helpers.ts';
+import type { BuiltFixture } from './fixture-app.ts';
import { buildIslandApp } from './island-css-build.ts';
-export function definePrivatePagesBuildTest(app: {
- packageDir: string;
- pluginName: 'voidReact' | 'voidSolid';
- counter: string;
-}): void {
+export function definePrivatePagesBuildTest(
+ app:
+ | {
+ packageDir: string;
+ pluginName: 'voidReact' | 'voidSolid';
+ counter: string;
+ }
+ | { build: () => BuiltFixture },
+): void {
it('excludes private helpers from the Pages client and hydrates explicit private islands', async () => {
- const classAttribute = app.pluginName === 'voidReact' ? 'className' : 'class';
- const build = buildIslandApp({
- packageDir: app.packageDir,
- pluginName: app.pluginName,
- files: {
- 'tsconfig.json': JSON.stringify({
- compilerOptions: {
- jsx: app.pluginName === 'voidReact' ? 'react-jsx' : 'preserve',
- jsxImportSource: app.pluginName === 'voidReact' ? 'react' : 'solid-js',
- },
- }),
- 'pages/_ui/frame.tsx': `import './frame.css';
+ const supplied = 'build' in app;
+ const classAttribute = !supplied && app.pluginName === 'voidReact' ? 'className' : 'class';
+ const build = supplied
+ ? app.build()
+ : buildIslandApp({
+ packageDir: app.packageDir,
+ pluginName: app.pluginName,
+ files: {
+ 'tsconfig.json': JSON.stringify({
+ compilerOptions: {
+ jsx: app.pluginName === 'voidReact' ? 'react-jsx' : 'preserve',
+ jsxImportSource: app.pluginName === 'voidReact' ? 'react' : 'solid-js',
+ },
+ }),
+ 'pages/_ui/frame.tsx': `import './frame.css';
export function Frame(props) {
return {props.children};
}`,
- 'pages/_ui/frame.css': '.private-frame { outline-offset: 11px; }',
- 'pages/_ui/counter.tsx': app.counter,
- 'pages/_layouts/docs.tsx': `import './docs.css';
+ 'pages/_ui/frame.css': '.private-frame { outline-offset: 11px; }',
+ 'pages/_ui/counter.tsx': app.counter,
+ 'pages/_layouts/docs.tsx': `import './docs.css';
export default function Docs(props) {
return ;
}`,
- 'pages/_layouts/docs.css': '.private-layout { word-spacing: 3px; }',
- 'pages/index.island.tsx': `import { Frame } from './_ui/frame';
+ 'pages/_layouts/docs.css': '.private-layout { word-spacing: 3px; }',
+ 'pages/index.island.tsx': `import { Frame } from './_ui/frame';
import Counter from './_ui/counter' with { island: 'load' };
export const layout = 'docs';
export default function Home() { return ; }`,
- },
- });
+ },
+ });
let server: PreviewServer | undefined;
let browser: Browser | undefined;
try {
@@ -52,7 +60,8 @@ export default function Home() { return ; }`,
expect(Object.values(manifest)).toContainEqual(
expect.objectContaining({ name: 'islands-client', isEntry: true }),
);
- const { html, css } = build.page('index.html');
+ const pageFile = supplied ? 'private.html' : 'index.html';
+ const { html, css } = build.page(pageFile);
expect(html).toContain('data-frame="575_SERVER_FRAME"');
expect(html).toContain('data-layout="docs"');
expect(css).toContain('.private-frame{outline-offset:11px}');
@@ -78,7 +87,7 @@ export default function Home() { return ; }`,
const page = await browser.newPage();
const errors: Array = [];
page.on('pageerror', (error) => errors.push(error.message));
- await page.goto(base);
+ await page.goto(new URL(pageFile, base).href);
await waitForIslandsHydrated(page, 1, 15_000);
await page.getByRole('button', { name: 'Count: 0', exact: true }).click();
await expect.poll(() => page.getByRole('button').textContent()).toBe('Count: 1');
@@ -86,7 +95,9 @@ export default function Home() { return ; }`,
} finally {
await browser?.close();
await server?.close();
- build.cleanup();
+ if (!supplied) {
+ build.cleanup();
+ }
}
}, 120_000);
}
From b567908018c41d9e5f5b124e80bff97e33f727a6 Mon Sep 17 00:00:00 2001
From: Christoph Nakazawa
Date: Tue, 17 Nov 2026 21:01:53 +0900
Subject: [PATCH 06/27] test(vue): reuse the production island fixture build
---
.../test/integration/island-css-build.test.ts | 34 ++++---------------
packages/vue/vite.config.ts | 9 +++++
test/fixtures/vue.ts | 30 ++++++++++++++++
3 files changed, 46 insertions(+), 27 deletions(-)
create mode 100644 test/fixtures/vue.ts
diff --git a/packages/vue/test/integration/island-css-build.test.ts b/packages/vue/test/integration/island-css-build.test.ts
index 717819f6d..faa465156 100644
--- a/packages/vue/test/integration/island-css-build.test.ts
+++ b/packages/vue/test/integration/island-css-build.test.ts
@@ -1,33 +1,13 @@
-import { join } from 'node:path';
-import { expect } from 'vite-plus/test';
+import { afterAll, expect } from 'vite-plus/test';
+import { buildFixture, type BuiltFixture } from '../../../../test/fixture-app.ts';
+import { islands } from '../../../../test/fixtures/vue.ts';
import { defineIslandCssBuildTest } from '../../../../test/island-css-build.ts';
+let built: BuiltFixture | undefined;
+afterAll(() => built?.cleanup());
+
defineIslandCssBuildTest({
- packageDir: join(import.meta.dirname, '../..'),
- pluginName: 'voidVue',
- files: {
- 'src/shell.css': '.shell { outline-offset: 7px; }',
- 'src/Badge.vue': `Badge
-`,
- 'src/Shell.vue': `
-Note
Card
-
-
-`,
- 'pages/layout.vue': `
-`,
- 'pages/index.island.vue': 'Home
',
- // The layout renders Badge without hydrating it; this page hydrates it.
- 'pages/badge.island.vue': `
-`,
- },
+ build: () => (built ??= buildFixture(islands)),
expectedCss: [
'.shell{outline-offset:7px}',
'main{outline-width:9px}',
diff --git a/packages/vue/vite.config.ts b/packages/vue/vite.config.ts
index 8891e0745..af630a259 100644
--- a/packages/vue/vite.config.ts
+++ b/packages/vue/vite.config.ts
@@ -3,6 +3,15 @@ import { defineConfig } from 'vite-plus';
export default defineConfig({
run: {
tasks: {
+ 'prepare:test:islands': {
+ command: 'node ../../test/prepare-fixture.ts vue islands',
+ dependsOn: ['build', '@void/md#build'],
+ cache: false,
+ },
+ 'build:test:islands': {
+ command: 'node ../../playground-local/.build-fixtures/vue-islands/build.mjs',
+ dependsOn: ['prepare:test:islands'],
+ },
build: {
command: 'vp pack',
dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
diff --git a/test/fixtures/vue.ts b/test/fixtures/vue.ts
new file mode 100644
index 000000000..46bc0cb58
--- /dev/null
+++ b/test/fixtures/vue.ts
@@ -0,0 +1,30 @@
+import type { FixtureApp } from '../fixture-app.ts';
+
+export const islands: FixtureApp = {
+ framework: 'vue',
+ name: 'islands',
+ files: {
+ 'src/shell.css': '.shell { outline-offset: 7px; }',
+ 'src/Badge.vue': `Badge
+`,
+ 'src/Shell.vue': `
+Note
Card
+
+
+`,
+ 'pages/layout.vue': `
+`,
+ 'pages/index.island.vue': 'Home
',
+ 'pages/badge.island.vue': `
+`,
+ },
+};
+
+export const fixtures: Readonly> = { islands };
From ac22ed0d14ef57e817c51531f1de94653d3545f6 Mon Sep 17 00:00:00 2001
From: Christoph Nakazawa
Date: Tue, 17 Nov 2026 21:05:44 +0900
Subject: [PATCH 07/27] test(svelte): cache distinct island and mixed-page
builds
---
.../test/integration/island-css-build.test.ts | 48 ++++---------------
packages/svelte/vite.config.ts | 18 +++++++
test/fixtures/svelte.ts | 34 +++++++++++++
3 files changed, 60 insertions(+), 40 deletions(-)
create mode 100644 test/fixtures/svelte.ts
diff --git a/packages/svelte/test/integration/island-css-build.test.ts b/packages/svelte/test/integration/island-css-build.test.ts
index aafd2458b..1c485bfe2 100644
--- a/packages/svelte/test/integration/island-css-build.test.ts
+++ b/packages/svelte/test/integration/island-css-build.test.ts
@@ -1,41 +1,13 @@
-import { join } from 'node:path';
-import { expect, it } from 'vite-plus/test';
-import {
- buildIslandApp,
- countOf,
- defineIslandCssBuildTest,
-} from '../../../../test/island-css-build.ts';
+import { afterAll, expect, it } from 'vite-plus/test';
+import { buildFixture, type BuiltFixture } from '../../../../test/fixture-app.ts';
+import { islands, mixed } from '../../../../test/fixtures/svelte.ts';
+import { countOf, defineIslandCssBuildTest } from '../../../../test/island-css-build.ts';
-const packageDir = join(import.meta.dirname, '../..');
-const files = {
- 'src/shell.css': '.shell { outline-offset: 7px; }',
- 'src/card.module.css': '.card { text-indent: 9px; }',
- 'src/Badge.svelte': 'Badge\n',
- 'src/Shell.svelte': `
-{@render children()}
-`,
- 'pages/layout.svelte': `
-{@render children()}`,
- 'pages/index.island.svelte': 'Home
',
- // The layout renders Badge without hydrating it; this page hydrates it.
- 'pages/badge.island.svelte': `
-`,
-};
+let built: BuiltFixture | undefined;
+afterAll(() => built?.cleanup());
defineIslandCssBuildTest({
- packageDir,
- pluginName: 'voidSvelte',
- files,
+ build: () => (built ??= buildFixture(islands)),
expectedCss: ['.shell{outline-offset:7px}', '{text-indent:9px}', '{word-spacing:5px}'],
check({ file, html, css }) {
// The style block's rule carries the scope class that the server markup has.
@@ -48,11 +20,7 @@ defineIslandCssBuildTest({
});
it('links component styles once when a regular page also uses the layout', () => {
- const build = buildIslandApp({
- packageDir,
- pluginName: 'voidSvelte',
- files: { ...files, 'pages/regular.svelte': 'Regular
' },
- });
+ const build = buildFixture(mixed);
try {
for (const file of ['index.html', 'about.html', 'regular.html']) {
const { css } = build.page(file);
diff --git a/packages/svelte/vite.config.ts b/packages/svelte/vite.config.ts
index fb3016f72..5859e15b7 100644
--- a/packages/svelte/vite.config.ts
+++ b/packages/svelte/vite.config.ts
@@ -3,6 +3,24 @@ import { defineConfig } from 'vite-plus';
export default defineConfig({
run: {
tasks: {
+ 'prepare:test:islands': {
+ command: 'node ../../test/prepare-fixture.ts svelte islands',
+ dependsOn: ['build', '@void/md#build'],
+ cache: false,
+ },
+ 'build:test:islands': {
+ command: 'node ../../playground-local/.build-fixtures/svelte-islands/build.mjs',
+ dependsOn: ['prepare:test:islands'],
+ },
+ 'prepare:test:mixed': {
+ command: 'node ../../test/prepare-fixture.ts svelte mixed',
+ dependsOn: ['build', '@void/md#build'],
+ cache: false,
+ },
+ 'build:test:mixed': {
+ command: 'node ../../playground-local/.build-fixtures/svelte-mixed/build.mjs',
+ dependsOn: ['prepare:test:mixed'],
+ },
build: {
command: 'vp pack',
dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
diff --git a/test/fixtures/svelte.ts b/test/fixtures/svelte.ts
new file mode 100644
index 000000000..e1b57d97c
--- /dev/null
+++ b/test/fixtures/svelte.ts
@@ -0,0 +1,34 @@
+import type { FixtureApp } from '../fixture-app.ts';
+
+const files = {
+ 'src/shell.css': '.shell { outline-offset: 7px; }',
+ 'src/card.module.css': '.card { text-indent: 9px; }',
+ 'src/Badge.svelte': 'Badge\n',
+ 'src/Shell.svelte': `
+{@render children()}
+`,
+ 'pages/layout.svelte': `
+{@render children()}`,
+ 'pages/index.island.svelte': 'Home
',
+ // The layout renders Badge without hydrating it; this page hydrates it.
+ 'pages/badge.island.svelte': `
+`,
+};
+
+export const islands: FixtureApp = { framework: 'svelte', name: 'islands', files };
+export const mixed: FixtureApp = {
+ framework: 'svelte',
+ name: 'mixed',
+ files: { ...files, 'pages/regular.svelte': 'Regular
' },
+};
+export const fixtures: Readonly> = { islands, mixed };
From 72a10d11af63ba213b80e31e94b65dc85376bb59 Mon Sep 17 00:00:00 2001
From: Christoph Nakazawa
Date: Tue, 17 Nov 2026 21:08:52 +0900
Subject: [PATCH 08/27] test(solid): share the island and private-page
production build
---
.../test/integration/island-css-build.test.ts | 44 ++++---------------
packages/solid/vite.config.ts | 9 ++++
test/fixtures/solid.ts | 42 ++++++++++++++++++
3 files changed, 60 insertions(+), 35 deletions(-)
create mode 100644 test/fixtures/solid.ts
diff --git a/packages/solid/test/integration/island-css-build.test.ts b/packages/solid/test/integration/island-css-build.test.ts
index b621266fe..06d21f973 100644
--- a/packages/solid/test/integration/island-css-build.test.ts
+++ b/packages/solid/test/integration/island-css-build.test.ts
@@ -1,41 +1,15 @@
-import { join } from 'node:path';
+import { afterAll } from 'vite-plus/test';
+import { buildFixture, type BuiltFixture } from '../../../../test/fixture-app.ts';
+import { islands } from '../../../../test/fixtures/solid.ts';
import { defineIslandCssBuildTest } from '../../../../test/island-css-build.ts';
import { definePrivatePagesBuildTest } from '../../../../test/private-pages-build.ts';
+let shared: BuiltFixture | undefined;
+const buildIslands = () => (shared ??= buildFixture(islands));
+afterAll(() => shared?.cleanup());
+
defineIslandCssBuildTest({
- packageDir: join(import.meta.dirname, '../..'),
- pluginName: 'voidSolid',
- files: {
- 'tsconfig.json': JSON.stringify({
- compilerOptions: { jsx: 'preserve', jsxImportSource: 'solid-js' },
- }),
- 'src/shell.css': '.shell { outline-offset: 7px; }',
- 'src/card.module.css': '.card { text-indent: 9px; }',
- 'src/badge.css': '.badge { word-spacing: 5px; }',
- 'src/Badge.tsx': `import './badge.css';
-export default function Badge() { return Badge; }`,
- 'src/Shell.tsx': `import './shell.css';
-import styles from './card.module.css';
-import Badge from './Badge';
-export default function Shell(props) {
- return {props.children};
-}`,
- 'pages/layout.tsx': `import Shell from '../src/Shell';
-export default function Layout(props) { return {props.children}; }`,
- 'pages/index.island.tsx': 'export default function Home() { return Home
; }',
- // The layout renders Badge without hydrating it; this page hydrates it.
- 'pages/badge.island.tsx': `import Badge from '../src/Badge' with { island: 'load' };
-export default function BadgePage() { return ; }`,
- },
+ build: buildIslands,
expectedCss: ['.shell{outline-offset:7px}', '{text-indent:9px}', '.badge{word-spacing:5px}'],
});
-
-definePrivatePagesBuildTest({
- packageDir: join(import.meta.dirname, '../..'),
- pluginName: 'voidSolid',
- counter: `import { createSignal } from 'solid-js';
-export default function Counter() {
- const [count, setCount] = createSignal(0);
- return ;
-}`,
-});
+definePrivatePagesBuildTest({ build: buildIslands });
diff --git a/packages/solid/vite.config.ts b/packages/solid/vite.config.ts
index de2bbc11d..7715a5a2e 100644
--- a/packages/solid/vite.config.ts
+++ b/packages/solid/vite.config.ts
@@ -3,6 +3,15 @@ import { defineConfig } from 'vite-plus';
export default defineConfig({
run: {
tasks: {
+ 'prepare:test:islands': {
+ command: 'node ../../test/prepare-fixture.ts solid islands',
+ dependsOn: ['build', '@void/md#build'],
+ cache: false,
+ },
+ 'build:test:islands': {
+ command: 'node ../../playground-local/.build-fixtures/solid-islands/build.mjs',
+ dependsOn: ['prepare:test:islands'],
+ },
build: {
command: 'vp pack',
dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
diff --git a/test/fixtures/solid.ts b/test/fixtures/solid.ts
new file mode 100644
index 000000000..824fc347c
--- /dev/null
+++ b/test/fixtures/solid.ts
@@ -0,0 +1,42 @@
+import type { FixtureApp } from '../fixture-app.ts';
+import { privatePages } from './private-pages.ts';
+
+const cssFiles = {
+ 'tsconfig.json': JSON.stringify({
+ compilerOptions: { jsx: 'preserve', jsxImportSource: 'solid-js' },
+ }),
+ 'src/shell.css': '.shell { outline-offset: 7px; }',
+ 'src/card.module.css': '.card { text-indent: 9px; }',
+ 'src/badge.css': '.badge { word-spacing: 5px; }',
+ 'src/Badge.tsx': `import './badge.css';
+export default function Badge() { return Badge; }`,
+ 'src/Shell.tsx': `import './shell.css';
+import styles from './card.module.css';
+import Badge from './Badge';
+export default function Shell(props) {
+ return {props.children};
+}`,
+ 'pages/layout.tsx': `import Shell from '../src/Shell';
+export default function Layout(props) { return {props.children}; }`,
+ 'pages/index.island.tsx': 'export default function Home() { return Home
; }',
+ // The layout renders Badge without hydrating it; this page hydrates it.
+ 'pages/badge.island.tsx': `import Badge from '../src/Badge' with { island: 'load' };
+export default function BadgePage() { return ; }`,
+};
+
+export const islands: FixtureApp = {
+ framework: 'solid',
+ name: 'islands',
+ files: {
+ ...cssFiles,
+ ...privatePages(
+ 'solid',
+ `import { createSignal } from 'solid-js';
+export default function Counter() {
+ const [count, setCount] = createSignal(0);
+ return ;
+}`,
+ ),
+ },
+};
+export const fixtures: Readonly> = { islands };
From 0d3260490766f1aac9a0209f73bfcb866e5c661b Mon Sep 17 00:00:00 2001
From: Christoph Nakazawa
Date: Tue, 17 Nov 2026 21:12:31 +0900
Subject: [PATCH 09/27] test(solid): reuse the built hydration fixture without
changing dev coverage
---
.../test/integration/island-hydration.test.ts | 75 ++----------------
packages/solid/vite.config.ts | 9 +++
test/fixtures/solid-hydration.ts | 76 +++++++++++++++++++
test/fixtures/solid.ts | 3 +-
4 files changed, 92 insertions(+), 71 deletions(-)
create mode 100644 test/fixtures/solid-hydration.ts
diff --git a/packages/solid/test/integration/island-hydration.test.ts b/packages/solid/test/integration/island-hydration.test.ts
index fc263c4a1..3d32b8458 100644
--- a/packages/solid/test/integration/island-hydration.test.ts
+++ b/packages/solid/test/integration/island-hydration.test.ts
@@ -5,7 +5,8 @@ import { preview, type PreviewServer } from 'vite';
import solid from 'vite-plugin-solid';
import { afterAll, beforeAll, describe, expect, it } from 'vite-plus/test';
import { collectBrowserDiagnostics } from '../../../../test/browser-helpers.ts';
-import { buildIslandApp } from '../../../../test/island-css-build.ts';
+import { buildFixture, type BuiltFixture } from '../../../../test/fixture-app.ts';
+import { hydration } from '../../../../test/fixtures/solid-hydration.ts';
import { openIslandPage, type IslandPageVisit } from '../../../../test/island-page-browser.ts';
import { islandsPlugin } from '../../src/plugin-islands.ts';
@@ -13,69 +14,7 @@ type SnapshotWindow = Window & {
__ssrCounters?: Record;
};
-const counter = `import { createSignal, createUniqueId, useContext } from 'solid-js';
-import { FrontmatterContext } from '@void/solid';
-export default function Counter(props) {
- const [count, setCount] = createSignal(props.initial);
- const id = createUniqueId();
- return ;
-}`;
-
-const capture = `window.__ssrCounters = Object.fromEntries(
- Array.from(document.querySelectorAll('[data-counter]')).map(host => {
- const input = host.querySelector('input');
- input.value = 'draft-' + host.dataset.counter;
- return [host.dataset.counter, { button: host.querySelector('button'), input }];
- })
-);`;
-
-const files = {
- 'components/Counter.tsx': counter,
- 'components/AsyncCounter.tsx': `
-import { createResource, Suspense } from 'solid-js';
-import Counter from './Counter';
-export default function AsyncCounter() {
- const [name] = createResource(async () => {
- await new Promise(resolve => setTimeout(resolve, 10));
- return 'async';
- });
- return Loading
}>
-
- ;
-}`,
- 'pages/layout.island.tsx': `
-import Counter from '../components/Counter' with { island: 'load' };
-export default function Layout(props) {
- return {props.children}
;
-}`,
- 'pages/index.island.tsx': `
-import Counter from '../components/Counter' with { island: 'load' };
-import VisibleCounter from '../components/Counter' with { island: 'visible' };
-import AsyncCounter from '../components/AsyncCounter' with { island: 'load' };
-export const frontmatter = { title: 'Island metadata' };
-export default function Page() {
- return
-
-
-
-
-
-
-
- ;
-}`,
- 'pages/plain.island.tsx': `
-import Counter from '../components/Counter' with { island: 'load' };
-export default function Plain() {
- return
-
-
- ;
-}`,
-};
+const files = hydration.files;
async function visitFixture(): Promise<{ visit: IslandPageVisit; close(): Promise }> {
const root = mkdtempSync(join(import.meta.dirname, '__tmp_island_hydration_'));
@@ -159,17 +98,13 @@ async function expectReused(
}
describe.each(['dev', 'production'])('%s island hydration', (mode) => {
- let productionBuild: ReturnType | undefined;
+ let productionBuild: BuiltFixture | undefined;
let productionServer: PreviewServer | undefined;
let productionBrowser: Browser | undefined;
beforeAll(async () => {
if (mode === 'production') {
- productionBuild = buildIslandApp({
- packageDir: join(import.meta.dirname, '../..'),
- pluginName: 'voidSolid',
- files,
- });
+ productionBuild = buildFixture(hydration);
productionServer = await preview({
root: productionBuild.root,
configFile: false,
diff --git a/packages/solid/vite.config.ts b/packages/solid/vite.config.ts
index 7715a5a2e..afad8ffa3 100644
--- a/packages/solid/vite.config.ts
+++ b/packages/solid/vite.config.ts
@@ -3,6 +3,15 @@ import { defineConfig } from 'vite-plus';
export default defineConfig({
run: {
tasks: {
+ 'prepare:test:hydration': {
+ command: 'node ../../test/prepare-fixture.ts solid hydration',
+ dependsOn: ['build', '@void/md#build'],
+ cache: false,
+ },
+ 'build:test:hydration': {
+ command: 'node ../../playground-local/.build-fixtures/solid-hydration/build.mjs',
+ dependsOn: ['prepare:test:hydration'],
+ },
'prepare:test:islands': {
command: 'node ../../test/prepare-fixture.ts solid islands',
dependsOn: ['build', '@void/md#build'],
diff --git a/test/fixtures/solid-hydration.ts b/test/fixtures/solid-hydration.ts
new file mode 100644
index 000000000..6e2de1ca1
--- /dev/null
+++ b/test/fixtures/solid-hydration.ts
@@ -0,0 +1,76 @@
+import type { FixtureApp } from '../fixture-app.ts';
+
+const counter = `import { createSignal, createUniqueId, useContext } from 'solid-js';
+import { FrontmatterContext } from '@void/solid';
+export default function Counter(props) {
+ const [count, setCount] = createSignal(props.initial);
+ const id = createUniqueId();
+ return ;
+}`;
+
+const capture = `window.__ssrCounters = Object.fromEntries(
+ Array.from(document.querySelectorAll('[data-counter]')).map(host => {
+ const input = host.querySelector('input');
+ input.value = 'draft-' + host.dataset.counter;
+ return [host.dataset.counter, { button: host.querySelector('button'), input }];
+ })
+);`;
+
+const files = {
+ 'components/Counter.tsx': counter,
+ 'components/AsyncCounter.tsx': `
+import { createResource, Suspense } from 'solid-js';
+import Counter from './Counter';
+export default function AsyncCounter() {
+ const [name] = createResource(async () => {
+ await new Promise(resolve => setTimeout(resolve, 10));
+ return 'async';
+ });
+ return Loading}>
+
+ ;
+}`,
+ 'pages/layout.island.tsx': `
+import Counter from '../components/Counter' with { island: 'load' };
+export default function Layout(props) {
+ return {props.children}
;
+}`,
+ 'pages/index.island.tsx': `
+import Counter from '../components/Counter' with { island: 'load' };
+import VisibleCounter from '../components/Counter' with { island: 'visible' };
+import AsyncCounter from '../components/AsyncCounter' with { island: 'load' };
+export const frontmatter = { title: 'Island metadata' };
+export default function Page() {
+ return
+
+
+
+
+
+
+
+ ;
+}`,
+ 'pages/plain.island.tsx': `
+import Counter from '../components/Counter' with { island: 'load' };
+export default function Plain() {
+ return
+
+
+ ;
+}`,
+};
+
+export const hydration: FixtureApp = {
+ framework: 'solid',
+ name: 'hydration',
+ files: {
+ 'tsconfig.json': JSON.stringify({
+ compilerOptions: { jsx: 'preserve', jsxImportSource: 'solid-js' },
+ }),
+ ...files,
+ },
+};
diff --git a/test/fixtures/solid.ts b/test/fixtures/solid.ts
index 824fc347c..40d3ca877 100644
--- a/test/fixtures/solid.ts
+++ b/test/fixtures/solid.ts
@@ -1,5 +1,6 @@
import type { FixtureApp } from '../fixture-app.ts';
import { privatePages } from './private-pages.ts';
+import { hydration } from './solid-hydration.ts';
const cssFiles = {
'tsconfig.json': JSON.stringify({
@@ -39,4 +40,4 @@ export default function Counter() {
),
},
};
-export const fixtures: Readonly> = { islands };
+export const fixtures: Readonly> = { islands, hydration };
From d37ea03ebdd871d2b0aeb68aa03eb6f478e07b7f Mon Sep 17 00:00:00 2001
From: Christoph Nakazawa
Date: Tue, 17 Nov 2026 21:15:13 +0900
Subject: [PATCH 10/27] test(md): cache the standalone Markdown client-script
build
---
.../integration/client-script-build.test.ts | 35 ++-----------------
packages/react/vite.config.ts | 9 +++++
test/fixtures/markdown-scripts.ts | 33 +++++++++++++++++
test/fixtures/react.ts | 7 +++-
4 files changed, 51 insertions(+), 33 deletions(-)
create mode 100644 test/fixtures/markdown-scripts.ts
diff --git a/packages/md/test/integration/client-script-build.test.ts b/packages/md/test/integration/client-script-build.test.ts
index 97d5e200b..913bb9f44 100644
--- a/packages/md/test/integration/client-script-build.test.ts
+++ b/packages/md/test/integration/client-script-build.test.ts
@@ -4,40 +4,11 @@ import { chromium, type Browser } from 'playwright';
import { preview, type PreviewServer } from 'vite';
import { expect, it } from 'vite-plus/test';
import { waitForIslandsHydrated } from '../../../../test/browser-helpers.ts';
-import { buildIslandApp } from '../../../../test/island-css-build.ts';
+import { buildFixture } from '../../../../test/fixture-app.ts';
+import { markdownScripts } from '../../../../test/fixtures/markdown-scripts.ts';
it('runs client scripts in a production build with no .island. file in pages/', async () => {
- const build = buildIslandApp({
- packageDir: join(import.meta.dirname, '../../../react'),
- pluginName: 'voidReact',
- files: {
- 'tsconfig.json': JSON.stringify({ compilerOptions: { jsx: 'react-jsx' } }),
- 'components/Counter.island.tsx': `import { useState } from 'react';
-export default function Counter() {
- const [count, setCount] = useState(0);
- return ;
-}`,
- 'pages/script.md': `
-
-# Script
-
-unset
-`,
- 'pages/mixed.md': `
-
-# Mixed
-
-unset
-
-
-`,
- },
- });
+ const build = buildFixture(markdownScripts);
let server: PreviewServer | undefined;
let browser: Browser | undefined;
try {
diff --git a/packages/react/vite.config.ts b/packages/react/vite.config.ts
index 91e31d82a..ba02bb8ec 100644
--- a/packages/react/vite.config.ts
+++ b/packages/react/vite.config.ts
@@ -3,6 +3,15 @@ import { defineConfig } from 'vite-plus';
export default defineConfig({
run: {
tasks: {
+ 'prepare:test:markdown-scripts': {
+ command: 'node ../../test/prepare-fixture.ts react markdown-scripts',
+ dependsOn: ['build', '@void/md#build'],
+ cache: false,
+ },
+ 'build:test:markdown-scripts': {
+ command: 'node ../../playground-local/.build-fixtures/react-markdown-scripts/build.mjs',
+ dependsOn: ['prepare:test:markdown-scripts'],
+ },
'prepare:test:islands': {
command: 'node ../../test/prepare-fixture.ts react islands',
dependsOn: ['build', '@void/md#build'],
diff --git a/test/fixtures/markdown-scripts.ts b/test/fixtures/markdown-scripts.ts
new file mode 100644
index 000000000..b5e38b2de
--- /dev/null
+++ b/test/fixtures/markdown-scripts.ts
@@ -0,0 +1,33 @@
+import type { FixtureApp } from '../fixture-app.ts';
+
+export const markdownScripts: FixtureApp = {
+ framework: 'react',
+ name: 'markdown-scripts',
+ files: {
+ 'tsconfig.json': JSON.stringify({ compilerOptions: { jsx: 'react-jsx' } }),
+ 'components/Counter.island.tsx': `import { useState } from 'react';
+export default function Counter() {
+ const [count, setCount] = useState(0);
+ return ;
+}`,
+ 'pages/script.md': `
+
+# Script
+
+unset
+`,
+ 'pages/mixed.md': `
+
+# Mixed
+
+unset
+
+
+`,
+ },
+};
diff --git a/test/fixtures/react.ts b/test/fixtures/react.ts
index e18561213..93dd8a852 100644
--- a/test/fixtures/react.ts
+++ b/test/fixtures/react.ts
@@ -1,4 +1,5 @@
import type { FixtureApp } from '../fixture-app.ts';
+import { markdownScripts } from './markdown-scripts.ts';
import { privatePages } from './private-pages.ts';
const tsconfig = JSON.stringify({ compilerOptions: { jsx: 'react-jsx' } });
@@ -46,4 +47,8 @@ export const bare: FixtureApp = {
},
};
-export const fixtures: Readonly> = { islands, bare };
+export const fixtures: Readonly> = {
+ islands,
+ bare,
+ 'markdown-scripts': markdownScripts,
+};
From 938bd6fc94770cc365b8a2aa84d07d1898aeea03 Mon Sep 17 00:00:00 2001
From: Christoph Nakazawa
Date: Tue, 17 Nov 2026 21:17:52 +0900
Subject: [PATCH 11/27] test: consolidate named fixture preparation and remove
anonymous build helpers
---
TESTING.md | 19 +++++
test/island-css-build.ts | 143 +++++-------------------------------
test/private-pages-build.ts | 48 +-----------
vite.config.ts | 13 ++++
4 files changed, 55 insertions(+), 168 deletions(-)
diff --git a/TESTING.md b/TESTING.md
index e0b44104b..905e704cd 100644
--- a/TESTING.md
+++ b/TESTING.md
@@ -135,6 +135,25 @@ Playground preparation validates its own cached build without restoring those sh
again while other workers are using them. Source-mutating build regressions still execute their
build commands directly.
+Reusable application inputs live in `test/fixtures`. Their adapter's Vite+ config declares an
+uncached input-preparation task and a cached build task. For example:
+
+```sh
+vp run '@void/react#build:test:islands'
+vp run build:test-fixtures
+```
+
+Each named fixture has one test-file owner. Compatible contracts in that file can share a lazy
+`buildFixture()` result and clean it up in `afterAll`; runtime copies have their own source and
+storage directories. Only immutable build artifacts are shared. Keep variants that assert
+the absence of CSS, JavaScript, or regular Pages entries separate from fixtures that include
+those features. Build-behavior regressions continue to invoke real fresh builds.
+
+The materializer owns its generated directory and refuses to replace an unrelated application.
+It replaces authored inputs, including removed routes, before Vite Task validates the cached
+output. The build-cache integration contract covers edits, additions, deletions, environment
+files, failed builds, and restoring missing artifacts.
+
Persistent `fsModuleCache` is enabled to reuse transformations across invocations. It does not
cache test results or remove per-file module isolation. The first run primes it; compare repeated
runs with the same selection and machine load. For a control use `--no-fsModuleCache`; use
diff --git a/test/island-css-build.ts b/test/island-css-build.ts
index 01af74ddf..20bb4d3bd 100644
--- a/test/island-css-build.ts
+++ b/test/island-css-build.ts
@@ -1,140 +1,37 @@
-import { execSync } from 'node:child_process';
-import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
-import { dirname, join } from 'node:path';
-import { pathToFileURL } from 'node:url';
import { expect, it } from 'vite-plus/test';
import type { BuiltFixture } from './fixture-app.ts';
-const MD_PLUGIN = join(import.meta.dirname, '../packages/md/dist/plugin.mjs');
-
-type IslandCssApp = {
- /** The adapter package directory, e.g. `packages/react`. */
- packageDir: string;
- /** The adapter's plugin export in `dist/plugin.mjs`, e.g. `voidReact`. */
- pluginName: string;
- /** App files by path. `index` and `about` must ship no JavaScript. */
- files: Record;
- /** Rules (as minified CSS) every page must link, found once in the client build. */
+type IslandCssContract = {
+ build: () => BuiltFixture;
expectedCss: Array;
- /** Extra assertions for each page. */
check?: (page: { file: string; html: string; css: string }) => void;
- /** Extra assertions against this same production build. */
- checkBuild?: (build: ReturnType) => void;
+ checkBuild?: (build: BuiltFixture) => void;
};
-/** The stylesheet links of a page, without a regular expression. */
-function stylesheetHrefs(html: string): Array {
- const marker = '` resolves to the adapter package itself.
- */
-export function buildIslandApp(app: Omit): {
- root: string;
- page(file: string): { html: string; css: string };
- /** The text of every built file under `dist/`, by path. */
- output(dir: 'client' | 'ssr'): Map;
- cleanup(): void;
-} {
- const root = mkdtempSync(join(app.packageDir, 'test/integration/__tmp_island_css_'));
- try {
- const plugin = pathToFileURL(join(app.packageDir, 'dist/plugin.mjs')).href;
- const files: Record = {
- 'vite.config.mjs': `import { voidPlugin } from 'void';
-import { ${app.pluginName} } from ${JSON.stringify(plugin)};
-import { voidMarkdown } from ${JSON.stringify(pathToFileURL(MD_PLUGIN).href)};
-export default { plugins: [voidPlugin(), ${app.pluginName}(), voidMarkdown()] };
-`,
- 'void.config.ts': `import { defineConfig } from 'void/config';
-export default defineConfig({ output: 'static', worker: { compatibility_date: '2026-02-24' } });
-`,
- 'pages/about.md': '---\ntitle: About\n---\n\n# About\n',
- ...app.files,
- };
- for (const [file, content] of Object.entries(files)) {
- mkdirSync(dirname(join(root, file)), { recursive: true });
- writeFileSync(join(root, file), content);
- }
- // The native loader keeps the config's imports in the adapter package scope.
- execSync('vp build --configLoader native', { cwd: root, stdio: 'pipe' });
- } catch (error) {
- rmSync(root, { recursive: true, force: true });
- throw error;
- }
- const client = join(root, 'dist/client');
- return {
- root,
- page(file) {
- const html = readFileSync(join(client, file), 'utf-8');
- const css = stylesheetHrefs(html)
- .map((href) => readFileSync(join(client, href), 'utf-8'))
- .join('\n');
- return { html, css };
- },
- output(dir) {
- const out = join(root, 'dist', dir);
- const files = new Map();
- for (const file of readdirSync(out, { recursive: true, encoding: 'utf-8' })) {
- if (file.endsWith('.js') || file.endsWith('.css') || file.endsWith('.html')) {
- files.set(file, readFileSync(join(out, file), 'utf-8'));
- }
- }
- return files;
- },
- cleanup() {
- rmSync(root, { recursive: true, force: true });
- },
- };
-}
-
-/** How many times `text` contains `part`. */
export function countOf(text: string, part: string): number {
return text.split(part).length - 1;
}
-/**
- * Shared by the four adapters: a layout renders a component that imports CSS.
- * Production must link that CSS on island and Markdown pages, as dev does,
- * even though the pages ship no JavaScript.
- */
-export function defineIslandCssBuildTest(
- app:
- | IslandCssApp
- | (Pick & {
- build: () => BuiltFixture;
- }),
-): void {
+/** The caller owns the immutable build's runtime copy and releases it after its contracts. */
+export function defineIslandCssBuildTest(app: IslandCssContract): void {
it('links the CSS that a layout component imports on island and Markdown pages', () => {
- const supplied = 'build' in app;
- const build = supplied ? app.build() : buildIslandApp(app);
- try {
- for (const file of ['index.html', 'about.html']) {
- const { html, css } = build.page(file);
- for (const rule of app.expectedCss) {
- expect(countOf(css, rule), `${file}: ${rule}`).toBe(1);
- }
- expect(html, file).not.toContain('
+
+# Script
+
+unset
+`,
+ 'pages/mixed.md': `
+
+# Mixed
+
+unset
+
+
+`,
+ },
+ });
let server: PreviewServer | undefined;
let browser: Browser | undefined;
try {
diff --git a/packages/md/test/integration/markdown-blog.test.ts b/packages/md/test/integration/markdown-blog.test.ts
index baea6d27c..ae72d01c6 100644
--- a/packages/md/test/integration/markdown-blog.test.ts
+++ b/packages/md/test/integration/markdown-blog.test.ts
@@ -1,8 +1,9 @@
+import { execSync } from 'node:child_process';
import { join } from 'node:path';
import spawn from 'cross-spawn';
import { chromium, type Browser, type Page } from 'playwright';
import { describe, expect, it, beforeAll, afterAll } from 'vite-plus/test';
-import { buildPlayground, killChild, startServer } from '../../../../test/integration-helpers.ts';
+import { killChild, startServer } from '../../../../test/integration-helpers.ts';
const ROOT = join(import.meta.dirname, '..', '..', '..', '..');
let DEV_BASE: string;
@@ -286,7 +287,10 @@ describe('markdown-blog playground', () => {
let child: ReturnType;
beforeAll(async () => {
- buildPlayground(ROOT, 'markdown-blog');
+ execSync('vp run --filter ./playground/markdown-blog build', {
+ cwd: ROOT,
+ stdio: 'pipe',
+ });
const server = await startServer((port) => {
child = spawn(
diff --git a/packages/md/vite.config.ts b/packages/md/vite.config.ts
index c7ae13972..79ca21a0e 100644
--- a/packages/md/vite.config.ts
+++ b/packages/md/vite.config.ts
@@ -2,14 +2,6 @@ import { cpSync } from 'node:fs';
import { defineConfig } from 'vite-plus';
export default defineConfig({
- run: {
- tasks: {
- build: {
- command: 'vp pack',
- dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
- },
- },
- },
pack: {
entry: ['src/index.ts', 'src/plugin.ts', 'src/runtime/index.ts'],
format: 'esm',
diff --git a/packages/platform/package.json b/packages/platform/package.json
index 41a42bdc6..48d29417f 100644
--- a/packages/platform/package.json
+++ b/packages/platform/package.json
@@ -46,6 +46,7 @@
"access": "public"
},
"scripts": {
+ "build": "vp pack && node scripts/build-runtime.mjs && vp run build:stamp",
"dev": "vp pack --watch",
"typecheck": "tsc --noEmit"
},
diff --git a/packages/platform/vite.config.ts b/packages/platform/vite.config.ts
index 387641f19..84c7423a5 100644
--- a/packages/platform/vite.config.ts
+++ b/packages/platform/vite.config.ts
@@ -3,10 +3,6 @@ import { defineConfig } from 'vite-plus';
export default defineConfig({
run: {
tasks: {
- build: {
- command: 'vp pack && node scripts/build-runtime.mjs && vp run build:stamp',
- dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
- },
// The last step of the `build` script: records the source revision in the runtime manifest.
// It isn't cached, so a new revision reruns only this step, and it gets the full
// environment, including VOID_PLATFORM_SOURCE_REVISION.
diff --git a/packages/react/package.json b/packages/react/package.json
index 9de451c2b..6f9359f24 100644
--- a/packages/react/package.json
+++ b/packages/react/package.json
@@ -38,6 +38,7 @@
"access": "public"
},
"scripts": {
+ "build": "vp pack",
"dev": "vp pack --watch",
"typecheck": "tsc --noEmit --rootDir ../.."
},
diff --git a/packages/react/test/integration/island-css-build.test.ts b/packages/react/test/integration/island-css-build.test.ts
index 6f3e84c2e..f29cd8687 100644
--- a/packages/react/test/integration/island-css-build.test.ts
+++ b/packages/react/test/integration/island-css-build.test.ts
@@ -1,15 +1,34 @@
-import { afterAll, expect, it } from 'vite-plus/test';
-import { buildFixture, type BuiltFixture } from '../../../../test/fixture-app.ts';
-import { bare, islands } from '../../../../test/fixtures/react.ts';
-import { defineIslandCssBuildTest } from '../../../../test/island-css-build.ts';
+import { join } from 'node:path';
+import { expect, it } from 'vite-plus/test';
+import { buildIslandApp, defineIslandCssBuildTest } from '../../../../test/island-css-build.ts';
import { definePrivatePagesBuildTest } from '../../../../test/private-pages-build.ts';
-let shared: BuiltFixture | undefined;
-const buildIslands = () => (shared ??= buildFixture(islands));
-afterAll(() => shared?.cleanup());
+const packageDir = join(import.meta.dirname, '../..');
+const tsconfig = JSON.stringify({ compilerOptions: { jsx: 'react-jsx' } });
defineIslandCssBuildTest({
- build: buildIslands,
+ packageDir,
+ pluginName: 'voidReact',
+ files: {
+ 'tsconfig.json': tsconfig,
+ 'src/shell.css': '.shell { outline-offset: 7px; }',
+ 'src/card.module.css': '.card { text-indent: 9px; }',
+ 'src/badge.css': '.badge { word-spacing: 5px; }',
+ 'src/Badge.tsx': `import './badge.css';
+export default function Badge() { return Badge; }`,
+ 'src/Shell.tsx': `import './shell.css';
+import styles from './card.module.css';
+import Badge from './Badge';
+export default function Shell({ children }) {
+ return {children};
+}`,
+ 'pages/layout.tsx': `import Shell from '../src/Shell';
+export default function Layout({ children }) { return {children}; }`,
+ 'pages/index.island.tsx': 'export default function Home() { return Home
; }',
+ // The layout renders Badge without hydrating it; this page hydrates it.
+ 'pages/badge.island.tsx': `import Badge from '../src/Badge' with { island: 'load' };
+export default function BadgePage() { return ; }`,
+ },
expectedCss: ['.shell{outline-offset:7px}', '{text-indent:9px}', '.badge{word-spacing:5px}'],
checkBuild(build) {
// Badge hydrates, so this build also covers the client/server entry boundary.
@@ -22,7 +41,16 @@ defineIslandCssBuildTest({
});
it('builds island pages without CSS or JavaScript with no stylesheet, script or client runtime', () => {
- const build = buildFixture(bare);
+ const build = buildIslandApp({
+ packageDir,
+ pluginName: 'voidReact',
+ files: {
+ 'tsconfig.json': tsconfig,
+ 'pages/layout.tsx':
+ 'export default function Layout({ children }) { return {children}; }',
+ 'pages/index.island.tsx': 'export default function Home() { return Home
; }',
+ },
+ });
try {
for (const file of ['index.html', 'about.html']) {
const { html } = build.page(file);
@@ -39,4 +67,12 @@ it('builds island pages without CSS or JavaScript with no stylesheet, script or
}
}, 120_000);
-definePrivatePagesBuildTest({ build: buildIslands });
+definePrivatePagesBuildTest({
+ packageDir,
+ pluginName: 'voidReact',
+ counter: `import { useState } from 'react';
+export default function Counter() {
+ const [count, setCount] = useState(0);
+ return ;
+}`,
+});
diff --git a/packages/react/test/integration/page-errors.test.ts b/packages/react/test/integration/page-errors.test.ts
deleted file mode 100644
index 02b5fb2ad..000000000
--- a/packages/react/test/integration/page-errors.test.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import { definePageErrorsTests } from '../../../void/test/integration/page-errors.cases.ts';
-
-definePageErrorsTests('react');
diff --git a/packages/react/test/integration/react-pages-client.test.ts b/packages/react/test/integration/react-pages-client.test.ts
index b4b8a2cbe..de5d91889 100644
--- a/packages/react/test/integration/react-pages-client.test.ts
+++ b/packages/react/test/integration/react-pages-client.test.ts
@@ -1,11 +1,10 @@
-import { type ChildProcess } from 'node:child_process';
-import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { execSync, type ChildProcess } from 'node:child_process';
+import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { type Browser, type Page } from 'playwright';
import { describe, expect, it, beforeAll, afterAll, vi } from 'vite-plus/test';
import { collectBrowserDiagnostics } from '../../../../test/browser-helpers.ts';
import {
- buildPlayground,
killChild,
spawnPlaygroundServer,
startServer,
@@ -1334,7 +1333,12 @@ describe('react-pages client (preview)', { retry: 2 }, () => {
let serverOutput = () => '';
beforeAll(async () => {
- buildPlayground(ROOT, 'react-pages');
+ if (!existsSync(join(ROOT, 'playground/react-pages/dist'))) {
+ execSync('vp run --filter ./playground/react-pages build', {
+ cwd: ROOT,
+ stdio: 'pipe',
+ });
+ }
const server = await startServer(
(port) => (child = spawnPlaygroundServer(ROOT, 'react-pages', 'preview', port)),
diff --git a/packages/react/vite.config.ts b/packages/react/vite.config.ts
index ba02bb8ec..bc9da4932 100644
--- a/packages/react/vite.config.ts
+++ b/packages/react/vite.config.ts
@@ -1,41 +1,6 @@
import { defineConfig } from 'vite-plus';
export default defineConfig({
- run: {
- tasks: {
- 'prepare:test:markdown-scripts': {
- command: 'node ../../test/prepare-fixture.ts react markdown-scripts',
- dependsOn: ['build', '@void/md#build'],
- cache: false,
- },
- 'build:test:markdown-scripts': {
- command: 'node ../../playground-local/.build-fixtures/react-markdown-scripts/build.mjs',
- dependsOn: ['prepare:test:markdown-scripts'],
- },
- 'prepare:test:islands': {
- command: 'node ../../test/prepare-fixture.ts react islands',
- dependsOn: ['build', '@void/md#build'],
- cache: false,
- },
- 'build:test:islands': {
- command: 'node ../../playground-local/.build-fixtures/react-islands/build.mjs',
- dependsOn: ['prepare:test:islands'],
- },
- 'prepare:test:bare': {
- command: 'node ../../test/prepare-fixture.ts react bare',
- dependsOn: ['build', '@void/md#build'],
- cache: false,
- },
- 'build:test:bare': {
- command: 'node ../../playground-local/.build-fixtures/react-bare/build.mjs',
- dependsOn: ['prepare:test:bare'],
- },
- build: {
- command: 'vp pack',
- dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
- },
- },
- },
pack: {
entry: [
'src/index.ts',
diff --git a/packages/solid/package.json b/packages/solid/package.json
index 03567ad22..70aa5a0ab 100644
--- a/packages/solid/package.json
+++ b/packages/solid/package.json
@@ -35,6 +35,7 @@
"access": "public"
},
"scripts": {
+ "build": "vp pack",
"dev": "vp pack --watch",
"typecheck": "tsc --noEmit --rootDir ../.."
},
diff --git a/packages/solid/test/integration/island-css-build.test.ts b/packages/solid/test/integration/island-css-build.test.ts
index 06d21f973..b621266fe 100644
--- a/packages/solid/test/integration/island-css-build.test.ts
+++ b/packages/solid/test/integration/island-css-build.test.ts
@@ -1,15 +1,41 @@
-import { afterAll } from 'vite-plus/test';
-import { buildFixture, type BuiltFixture } from '../../../../test/fixture-app.ts';
-import { islands } from '../../../../test/fixtures/solid.ts';
+import { join } from 'node:path';
import { defineIslandCssBuildTest } from '../../../../test/island-css-build.ts';
import { definePrivatePagesBuildTest } from '../../../../test/private-pages-build.ts';
-let shared: BuiltFixture | undefined;
-const buildIslands = () => (shared ??= buildFixture(islands));
-afterAll(() => shared?.cleanup());
-
defineIslandCssBuildTest({
- build: buildIslands,
+ packageDir: join(import.meta.dirname, '../..'),
+ pluginName: 'voidSolid',
+ files: {
+ 'tsconfig.json': JSON.stringify({
+ compilerOptions: { jsx: 'preserve', jsxImportSource: 'solid-js' },
+ }),
+ 'src/shell.css': '.shell { outline-offset: 7px; }',
+ 'src/card.module.css': '.card { text-indent: 9px; }',
+ 'src/badge.css': '.badge { word-spacing: 5px; }',
+ 'src/Badge.tsx': `import './badge.css';
+export default function Badge() { return Badge; }`,
+ 'src/Shell.tsx': `import './shell.css';
+import styles from './card.module.css';
+import Badge from './Badge';
+export default function Shell(props) {
+ return {props.children};
+}`,
+ 'pages/layout.tsx': `import Shell from '../src/Shell';
+export default function Layout(props) { return {props.children}; }`,
+ 'pages/index.island.tsx': 'export default function Home() { return Home
; }',
+ // The layout renders Badge without hydrating it; this page hydrates it.
+ 'pages/badge.island.tsx': `import Badge from '../src/Badge' with { island: 'load' };
+export default function BadgePage() { return ; }`,
+ },
expectedCss: ['.shell{outline-offset:7px}', '{text-indent:9px}', '.badge{word-spacing:5px}'],
});
-definePrivatePagesBuildTest({ build: buildIslands });
+
+definePrivatePagesBuildTest({
+ packageDir: join(import.meta.dirname, '../..'),
+ pluginName: 'voidSolid',
+ counter: `import { createSignal } from 'solid-js';
+export default function Counter() {
+ const [count, setCount] = createSignal(0);
+ return ;
+}`,
+});
diff --git a/packages/solid/test/integration/island-hydration.test.ts b/packages/solid/test/integration/island-hydration.test.ts
index 3d32b8458..fc263c4a1 100644
--- a/packages/solid/test/integration/island-hydration.test.ts
+++ b/packages/solid/test/integration/island-hydration.test.ts
@@ -5,8 +5,7 @@ import { preview, type PreviewServer } from 'vite';
import solid from 'vite-plugin-solid';
import { afterAll, beforeAll, describe, expect, it } from 'vite-plus/test';
import { collectBrowserDiagnostics } from '../../../../test/browser-helpers.ts';
-import { buildFixture, type BuiltFixture } from '../../../../test/fixture-app.ts';
-import { hydration } from '../../../../test/fixtures/solid-hydration.ts';
+import { buildIslandApp } from '../../../../test/island-css-build.ts';
import { openIslandPage, type IslandPageVisit } from '../../../../test/island-page-browser.ts';
import { islandsPlugin } from '../../src/plugin-islands.ts';
@@ -14,7 +13,69 @@ type SnapshotWindow = Window & {
__ssrCounters?: Record;
};
-const files = hydration.files;
+const counter = `import { createSignal, createUniqueId, useContext } from 'solid-js';
+import { FrontmatterContext } from '@void/solid';
+export default function Counter(props) {
+ const [count, setCount] = createSignal(props.initial);
+ const id = createUniqueId();
+ return ;
+}`;
+
+const capture = `window.__ssrCounters = Object.fromEntries(
+ Array.from(document.querySelectorAll('[data-counter]')).map(host => {
+ const input = host.querySelector('input');
+ input.value = 'draft-' + host.dataset.counter;
+ return [host.dataset.counter, { button: host.querySelector('button'), input }];
+ })
+);`;
+
+const files = {
+ 'components/Counter.tsx': counter,
+ 'components/AsyncCounter.tsx': `
+import { createResource, Suspense } from 'solid-js';
+import Counter from './Counter';
+export default function AsyncCounter() {
+ const [name] = createResource(async () => {
+ await new Promise(resolve => setTimeout(resolve, 10));
+ return 'async';
+ });
+ return Loading}>
+
+ ;
+}`,
+ 'pages/layout.island.tsx': `
+import Counter from '../components/Counter' with { island: 'load' };
+export default function Layout(props) {
+ return {props.children}
;
+}`,
+ 'pages/index.island.tsx': `
+import Counter from '../components/Counter' with { island: 'load' };
+import VisibleCounter from '../components/Counter' with { island: 'visible' };
+import AsyncCounter from '../components/AsyncCounter' with { island: 'load' };
+export const frontmatter = { title: 'Island metadata' };
+export default function Page() {
+ return
+
+
+
+
+
+
+
+ ;
+}`,
+ 'pages/plain.island.tsx': `
+import Counter from '../components/Counter' with { island: 'load' };
+export default function Plain() {
+ return
+
+
+ ;
+}`,
+};
async function visitFixture(): Promise<{ visit: IslandPageVisit; close(): Promise }> {
const root = mkdtempSync(join(import.meta.dirname, '__tmp_island_hydration_'));
@@ -98,13 +159,17 @@ async function expectReused(
}
describe.each(['dev', 'production'])('%s island hydration', (mode) => {
- let productionBuild: BuiltFixture | undefined;
+ let productionBuild: ReturnType | undefined;
let productionServer: PreviewServer | undefined;
let productionBrowser: Browser | undefined;
beforeAll(async () => {
if (mode === 'production') {
- productionBuild = buildFixture(hydration);
+ productionBuild = buildIslandApp({
+ packageDir: join(import.meta.dirname, '../..'),
+ pluginName: 'voidSolid',
+ files,
+ });
productionServer = await preview({
root: productionBuild.root,
configFile: false,
diff --git a/packages/solid/test/integration/page-errors.test.ts b/packages/solid/test/integration/page-errors.test.ts
deleted file mode 100644
index 26f692d95..000000000
--- a/packages/solid/test/integration/page-errors.test.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import { definePageErrorsTests } from '../../../void/test/integration/page-errors.cases.ts';
-
-definePageErrorsTests('solid');
diff --git a/packages/solid/test/integration/solid-pages-playground.test.ts b/packages/solid/test/integration/solid-pages-playground.test.ts
index d19faab0c..fb50c5977 100644
--- a/packages/solid/test/integration/solid-pages-playground.test.ts
+++ b/packages/solid/test/integration/solid-pages-playground.test.ts
@@ -1,11 +1,10 @@
-import { type ChildProcess } from 'node:child_process';
+import { execSync, type ChildProcess } from 'node:child_process';
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { type Browser, type Page } from 'playwright';
import { afterAll, beforeAll, describe, expect, it } from 'vite-plus/test';
import { collectBrowserDiagnostics } from '../../../../test/browser-helpers.ts';
import {
- buildPlayground,
killChild,
spawnPlaygroundServer,
startServer,
@@ -270,7 +269,12 @@ describe('solid-pages client (preview)', { retry: 2 }, () => {
let child: ChildProcess | undefined;
beforeAll(async () => {
- buildPlayground(ROOT, 'solid-pages');
+ if (!existsSync(join(ROOT, 'playground/solid-pages/dist'))) {
+ execSync('vp run --filter ./playground/solid-pages build', {
+ cwd: ROOT,
+ stdio: 'pipe',
+ });
+ }
const server = await startServer(
(port) => (child = spawnPlaygroundServer(ROOT, 'solid-pages', 'preview', port)),
diff --git a/packages/solid/vite.config.ts b/packages/solid/vite.config.ts
index afad8ffa3..29c65bb77 100644
--- a/packages/solid/vite.config.ts
+++ b/packages/solid/vite.config.ts
@@ -1,32 +1,6 @@
import { defineConfig } from 'vite-plus';
export default defineConfig({
- run: {
- tasks: {
- 'prepare:test:hydration': {
- command: 'node ../../test/prepare-fixture.ts solid hydration',
- dependsOn: ['build', '@void/md#build'],
- cache: false,
- },
- 'build:test:hydration': {
- command: 'node ../../playground-local/.build-fixtures/solid-hydration/build.mjs',
- dependsOn: ['prepare:test:hydration'],
- },
- 'prepare:test:islands': {
- command: 'node ../../test/prepare-fixture.ts solid islands',
- dependsOn: ['build', '@void/md#build'],
- cache: false,
- },
- 'build:test:islands': {
- command: 'node ../../playground-local/.build-fixtures/solid-islands/build.mjs',
- dependsOn: ['prepare:test:islands'],
- },
- build: {
- command: 'vp pack',
- dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
- },
- },
- },
pack: {
entry: [
'src/runtime/PageErrorBoundary.ts',
diff --git a/packages/svelte/package.json b/packages/svelte/package.json
index 21ccad7d4..d9740f729 100644
--- a/packages/svelte/package.json
+++ b/packages/svelte/package.json
@@ -35,6 +35,7 @@
"access": "public"
},
"scripts": {
+ "build": "vp pack",
"dev": "vp pack --watch",
"typecheck": "tsc --noEmit --rootDir ../.."
},
diff --git a/packages/svelte/test/integration/island-css-build.test.ts b/packages/svelte/test/integration/island-css-build.test.ts
index 1c485bfe2..aafd2458b 100644
--- a/packages/svelte/test/integration/island-css-build.test.ts
+++ b/packages/svelte/test/integration/island-css-build.test.ts
@@ -1,13 +1,41 @@
-import { afterAll, expect, it } from 'vite-plus/test';
-import { buildFixture, type BuiltFixture } from '../../../../test/fixture-app.ts';
-import { islands, mixed } from '../../../../test/fixtures/svelte.ts';
-import { countOf, defineIslandCssBuildTest } from '../../../../test/island-css-build.ts';
+import { join } from 'node:path';
+import { expect, it } from 'vite-plus/test';
+import {
+ buildIslandApp,
+ countOf,
+ defineIslandCssBuildTest,
+} from '../../../../test/island-css-build.ts';
-let built: BuiltFixture | undefined;
-afterAll(() => built?.cleanup());
+const packageDir = join(import.meta.dirname, '../..');
+const files = {
+ 'src/shell.css': '.shell { outline-offset: 7px; }',
+ 'src/card.module.css': '.card { text-indent: 9px; }',
+ 'src/Badge.svelte': 'Badge\n',
+ 'src/Shell.svelte': `
+{@render children()}
+`,
+ 'pages/layout.svelte': `
+{@render children()}`,
+ 'pages/index.island.svelte': 'Home
',
+ // The layout renders Badge without hydrating it; this page hydrates it.
+ 'pages/badge.island.svelte': `
+`,
+};
defineIslandCssBuildTest({
- build: () => (built ??= buildFixture(islands)),
+ packageDir,
+ pluginName: 'voidSvelte',
+ files,
expectedCss: ['.shell{outline-offset:7px}', '{text-indent:9px}', '{word-spacing:5px}'],
check({ file, html, css }) {
// The style block's rule carries the scope class that the server markup has.
@@ -20,7 +48,11 @@ defineIslandCssBuildTest({
});
it('links component styles once when a regular page also uses the layout', () => {
- const build = buildFixture(mixed);
+ const build = buildIslandApp({
+ packageDir,
+ pluginName: 'voidSvelte',
+ files: { ...files, 'pages/regular.svelte': 'Regular
' },
+ });
try {
for (const file of ['index.html', 'about.html', 'regular.html']) {
const { css } = build.page(file);
diff --git a/packages/svelte/test/integration/page-errors.test.ts b/packages/svelte/test/integration/page-errors.test.ts
deleted file mode 100644
index e421f7ad6..000000000
--- a/packages/svelte/test/integration/page-errors.test.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import { definePageErrorsTests } from '../../../void/test/integration/page-errors.cases.ts';
-
-definePageErrorsTests('svelte');
diff --git a/packages/svelte/test/integration/svelte-pages-client.test.ts b/packages/svelte/test/integration/svelte-pages-client.test.ts
index ac98b6632..aeb69a4f9 100644
--- a/packages/svelte/test/integration/svelte-pages-client.test.ts
+++ b/packages/svelte/test/integration/svelte-pages-client.test.ts
@@ -1,11 +1,10 @@
-import { type ChildProcess } from 'node:child_process';
-import {} from 'node:fs';
+import { execSync, type ChildProcess } from 'node:child_process';
+import { existsSync } from 'node:fs';
import { join } from 'node:path';
import { type Browser, type Page } from 'playwright';
import { describe, expect, it, beforeAll, afterAll } from 'vite-plus/test';
import { collectBrowserDiagnostics } from '../../../../test/browser-helpers.ts';
import {
- buildPlayground,
killChild,
spawnPlaygroundServer,
startServer,
@@ -160,7 +159,12 @@ describe('svelte-pages client (preview)', { retry: 2 }, () => {
let child: ChildProcess | undefined;
beforeAll(async () => {
- buildPlayground(ROOT, 'svelte-pages');
+ if (!existsSync(join(ROOT, 'playground/svelte-pages/dist'))) {
+ execSync('vp run --filter ./playground/svelte-pages build', {
+ cwd: ROOT,
+ stdio: 'pipe',
+ });
+ }
const server = await startServer(
(port) => (child = spawnPlaygroundServer(ROOT, 'svelte-pages', 'preview', port)),
diff --git a/packages/svelte/vite.config.ts b/packages/svelte/vite.config.ts
index 5859e15b7..f4e2d6afb 100644
--- a/packages/svelte/vite.config.ts
+++ b/packages/svelte/vite.config.ts
@@ -1,32 +1,6 @@
import { defineConfig } from 'vite-plus';
export default defineConfig({
- run: {
- tasks: {
- 'prepare:test:islands': {
- command: 'node ../../test/prepare-fixture.ts svelte islands',
- dependsOn: ['build', '@void/md#build'],
- cache: false,
- },
- 'build:test:islands': {
- command: 'node ../../playground-local/.build-fixtures/svelte-islands/build.mjs',
- dependsOn: ['prepare:test:islands'],
- },
- 'prepare:test:mixed': {
- command: 'node ../../test/prepare-fixture.ts svelte mixed',
- dependsOn: ['build', '@void/md#build'],
- cache: false,
- },
- 'build:test:mixed': {
- command: 'node ../../playground-local/.build-fixtures/svelte-mixed/build.mjs',
- dependsOn: ['prepare:test:mixed'],
- },
- build: {
- command: 'vp pack',
- dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
- },
- },
- },
pack: {
entry: ['src/plugin.ts'],
format: 'esm',
diff --git a/packages/void/package.json b/packages/void/package.json
index 2d5ace41f..f3106e33e 100644
--- a/packages/void/package.json
+++ b/packages/void/package.json
@@ -348,6 +348,7 @@
}
},
"scripts": {
+ "build": "node scripts/sync-docs.mjs && vp pack",
"dev": "vp pack --watch",
"typecheck": "tsc --noEmit --rootDir ../.."
},
diff --git a/packages/void/test/integration/http-errors-dev.test.ts b/packages/void/test/integration/http-errors-dev.test.ts
deleted file mode 100644
index c947b109e..000000000
--- a/packages/void/test/integration/http-errors-dev.test.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import { defineHttpErrorTests } from './http-errors-playground.cases.ts';
-
-defineHttpErrorTests('dev');
diff --git a/packages/void/test/integration/http-errors-playground.cases.ts b/packages/void/test/integration/http-errors-playground.cases.ts
deleted file mode 100644
index 41b765392..000000000
--- a/packages/void/test/integration/http-errors-playground.cases.ts
+++ /dev/null
@@ -1,374 +0,0 @@
-import { join } from 'node:path';
-import spawn from 'cross-spawn';
-import type { Browser, Page } from 'playwright';
-import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from 'vite-plus/test';
-import {
- createBuiltPlayground,
- createIsolatedPlayground,
- killChild,
- startServer,
- type IsolatedPlayground,
- type StartedServer,
-} from '../../../../test/integration-helpers.ts';
-import { launchPagesBrowser } from '../../../../test/pages-browser.ts';
-import { PAGES_PROTOCOL_VERSION } from '../../../edge/src/pages-protocol.ts';
-import { deserializePageData } from '../../src/pages/serialize.ts';
-
-const repository = join(import.meta.dirname, '../../../..');
-const pagesHeaders = {
- 'X-VoidPages': 'true',
- 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION,
-};
-const renderedExamples = [
- {
- path: '/loaders/status/403',
- status: 403,
- heading: 'Status set in a loader',
- message: 'Your account is banned',
- retryAfter: '120',
- },
- {
- path: '/loaders/status/503',
- status: 503,
- heading: 'Status set in a loader',
- message: 'Down for maintenance',
- retryAfter: '120',
- },
- {
- path: '/loaders/validated',
- status: 503,
- heading: 'Status set in a validated loader',
- message: 'Down for maintenance',
- retryAfter: null,
- },
- {
- path: '/loaders/deferred',
- status: 429,
- heading: 'Status set before deferred streaming',
- message: 'Too many requests',
- retryAfter: '120',
- },
- {
- path: '/middleware/application',
- status: 503,
- heading: 'Status set in application middleware',
- message: 'Down for maintenance',
- retryAfter: '120',
- },
- {
- path: '/middleware/handler',
- status: 403,
- heading: 'Status set in handler middleware',
- message: 'Your account is banned',
- retryAfter: null,
- },
- {
- path: '/loaders/unexpected',
- status: 500,
- heading: 'Root error boundary',
- message: 'Internal Server Error',
- retryAfter: null,
- },
- {
- path: '/loaders/not-found',
- status: 404,
- heading: 'Not-found boundary',
- message: 'This page does not exist',
- retryAfter: null,
- },
- ...(
- [
- { status: 401, message: 'Please sign in' },
- { status: 403, message: 'Your account is banned' },
- { status: 410, message: 'This page is permanently gone' },
- { status: 429, message: 'Too many requests' },
- { status: 503, message: 'Down for maintenance' },
- ] as const
- ).map(({ status, message }) => ({
- path: `/loaders/errors/${status}`,
- status,
- heading: 'Nested error boundary',
- message,
- retryAfter: null,
- })),
- ...(
- [
- { status: 403, message: 'Your account is banned' },
- { status: 503, message: 'Down for maintenance' },
- ] as const
- ).map(({ status, message }) => ({
- path: `/middleware/errors/${status}`,
- status,
- heading: 'Root error boundary',
- message,
- retryAfter: null,
- })),
-] as const;
-
-type PageData = {
- component: string;
- props: Record;
- url: string;
- deferredKeys?: Record;
-};
-
-export function defineHttpErrorTests(mode: 'dev' | 'production'): void {
- describe(`HTTP errors playground (${mode})`, () => {
- let playground: IsolatedPlayground;
- let server: StartedServer;
- let browser: Browser;
- let base: string;
-
- function expectedMessage(example: (typeof renderedExamples)[number]) {
- return mode === 'dev' && example.path === '/loaders/unexpected'
- ? 'Unexpected loader failure'
- : example.message;
- }
-
- beforeAll(async () => {
- playground =
- mode === 'production'
- ? createBuiltPlayground(repository, 'http-errors')
- : createIsolatedPlayground(repository, 'playground/http-errors');
- server = await startServer(
- (port) =>
- mode === 'dev'
- ? spawn('vp', ['dev', '--host', '127.0.0.1', '--port', String(port), '--strictPort'], {
- cwd: playground.root,
- stdio: ['ignore', 'pipe', 'pipe'],
- })
- : spawn(process.execPath, ['dist/ssr/index.js'], {
- cwd: playground.root,
- stdio: ['ignore', 'pipe', 'pipe'],
- env: { ...process.env, PORT: String(port), NODE_ENV: 'production' },
- }),
- 30_000,
- { expectBody: 'HTTP Errors Example' },
- );
- base = server.base;
- browser = await launchPagesBrowser();
- });
-
- afterAll(async () => {
- await browser?.close();
- if (server) {
- await killChild(server.child);
- }
- playground?.cleanup();
- });
-
- for (const representation of ['HTML', 'Pages'] as const) {
- it.each(renderedExamples)(
- `${representation}: $path renders $heading with HTTP $status`,
- async (example) => {
- const pages = representation === 'Pages';
- const response = await fetch(base + example.path, { headers: pages ? pagesHeaders : {} });
- expect(response.status).toBe(example.status);
- expect(response.headers.get('Retry-After')).toBe(example.retryAfter);
- const body = await response.text();
- if (!pages) {
- expect(response.headers.get('content-type')).toContain('text/html');
- expect(body).toContain(example.heading);
- expect(body).toContain(expectedMessage(example));
- expect(body).toContain('aria-label="Example sections"');
- expect(body).toContain('example-page-loaded-toast');
- if (example.path === '/loaders/deferred') {
- expect(body).toContain('Waiting one second for deferred props');
- expect(body).toContain('window.__resolveDeferred("details"');
- }
- } else {
- expect(response.headers.get('X-VoidPages')).toBe('true');
- const lines = body.trim().split('\n');
- const data = deserializePageData(lines[0]);
- expect(data.url).toBe(example.path);
- if (example.path === '/loaders/deferred') {
- expect(response.headers.get('content-type')).toContain('application/x-ndjson');
- expect(data.deferredKeys).toEqual({ details: 'details' });
- expect(lines).toHaveLength(2);
- expect(deserializePageData(lines[1])).toMatchObject({
- __deferred: 'details',
- data: example.message,
- });
- } else {
- expect(response.headers.get('content-type')).toContain('application/json');
- expect(data.props).toMatchObject(
- example.path.includes('/errors/') ||
- example.status === 404 ||
- example.status === 500
- ? { error: { status: example.status, message: expectedMessage(example) } }
- : { status: example.status, message: example.message },
- );
- }
- }
- if (example.path.startsWith('/middleware/errors/')) {
- expect(server.output()).not.toContain('Middleware-error page loader ran');
- }
- },
- );
- }
-
- describe('browser navigation', () => {
- let page: Page;
-
- beforeEach(async () => {
- page = await browser.newPage();
- page.setDefaultTimeout(10_000);
- });
- afterEach(async () => {
- await page?.close();
- });
-
- async function openHome() {
- await page.goto(base);
- // The layout effect is also the example's observable hydration signal.
- await page.waitForSelector('.example-page-loaded-toast:popover-open');
- await page.evaluate(() => Reflect.set(globalThis, '__HTTP_ERRORS_DOCUMENT__', true));
- await page
- .locator('header')
- .evaluate((element) => element.setAttribute('data-retained', 'yes'));
- }
-
- for (const navigation of ['Document load', 'Client navigation'] as const) {
- it.each(renderedExamples)(
- `${navigation}: $path renders $heading with HTTP $status`,
- async (example) => {
- await openHome();
- const responsePromise = page.waitForResponse(
- (response) =>
- response.url() === base + example.path &&
- (navigation === 'Document load'
- ? response.request().isNavigationRequest()
- : response.request().headers()['x-voidpages'] === 'true'),
- );
- await page
- .locator(`a[href="${example.path}"]`)
- .getByText(navigation, { exact: true })
- .click();
- const response = await responsePromise;
- expect(response.status()).toBe(example.status);
- expect(response.headers()['retry-after'] ?? null).toBe(example.retryAfter);
- if (navigation === 'Document load') {
- expect(response.headers()['content-type']).toContain('text/html');
- await page.waitForSelector('.example-page-loaded-toast:popover-open');
- } else {
- expect(response.headers()['x-voidpages']).toBe('true');
- }
- await expect.poll(() => page.locator('main h1').textContent()).toBe(example.heading);
- await expect
- .poll(() => page.locator('main').textContent(), { timeout: 10_000 })
- .toContain(expectedMessage(example));
- expect(await page.locator('header').count()).toBe(1);
- if (example.path.startsWith('/loaders/errors/')) {
- expect(
- await page
- .getByText('Nested layout for HTTP exception examples.', { exact: true })
- .count(),
- ).toBe(1);
- expect(
- await page
- .getByRole('heading', { name: 'Loader exception example', exact: true })
- .count(),
- ).toBe(0);
- }
- if (example.path.startsWith('/middleware/errors/')) {
- expect(server.output()).not.toContain('Middleware-error page loader ran');
- expect(
- await page
- .getByRole('heading', { name: 'Middleware exception example', exact: true })
- .count(),
- ).toBe(0);
- }
- const retained = navigation === 'Client navigation';
- expect(
- await page.evaluate(() => Reflect.get(globalThis, '__HTTP_ERRORS_DOCUMENT__')),
- ).toBe(retained ? true : undefined);
- expect(await page.locator('header').getAttribute('data-retained')).toBe(
- retained ? 'yes' : null,
- );
- },
- );
- }
-
- it('offers document and client navigation for every example', async () => {
- await openHome();
- const paths = renderedExamples.map(({ path }) => path).sort();
- for (const name of ['Document load', 'Client navigation']) {
- const links = await page.getByRole('link', { name, exact: true }).all();
- const targets = await Promise.all(links.map((link) => link.getAttribute('href')));
- expect(targets.sort()).toEqual(paths);
- }
- });
-
- it.each(['/loaders/errors/403', '/middleware/errors/403'])(
- 'navigates away from %s and restores it through history without reloading',
- async (path) => {
- await openHome();
- const heading = path.startsWith('/loaders/')
- ? 'Nested error boundary'
- : 'Root error boundary';
- await page
- .locator(`a[href="${path}"]`)
- .getByText('Client navigation', { exact: true })
- .click();
- await expect.poll(() => page.locator('main h1').textContent()).toBe(heading);
- await page.getByRole('link', { name: 'HTTP Errors Example', exact: true }).click();
- await expect
- .poll(() => page.locator('main h1').textContent())
- .toBe('HTTP Errors Example');
- await page.goBack();
- await expect.poll(() => page.locator('main h1').textContent()).toBe(heading);
- await page.goForward();
- await expect
- .poll(() => page.locator('main h1').textContent())
- .toBe('HTTP Errors Example');
- expect(await page.locator('header').getAttribute('data-retained')).toBe('yes');
- expect(
- await page.evaluate(() => Reflect.get(globalThis, '__HTTP_ERRORS_DOCUMENT__')),
- ).toBe(true);
- },
- );
-
- it.each(['hover', 'focus'] as const)(
- 'prefetches complete deferred props on %s without navigating',
- async (interaction) => {
- await openHome();
- const responsePromise = page.waitForResponse(
- (response) =>
- response.url() === base + '/loaders/deferred' &&
- response.request().headers().purpose === 'prefetch',
- );
- const link = page.getByRole('link', { name: 'Hover or focus to prefetch deferred data' });
- await link[interaction]();
- const response = await responsePromise;
- expect(response.status()).toBe(429);
- expect(response.headers()['retry-after']).toBe('120');
- expect(response.headers()['content-type']).toContain('application/json');
- expect(response.request().headers()['x-voidpages-version']).toBe(PAGES_PROTOCOL_VERSION);
- expect(deserializePageData(await response.text())).toMatchObject({
- props: { details: 'Too many requests' },
- });
- expect(page.url()).toBe(base + '/');
- expect(await page.locator('header').getAttribute('data-retained')).toBe('yes');
- },
- );
-
- it('shows the document-load toast once and does not reopen it on client navigation', async () => {
- await openHome();
- await page.waitForSelector('.example-page-loaded-toast:popover-open', { state: 'hidden' });
- await page
- .locator('a[href="/loaders/status/403"]')
- .getByText('Client navigation', { exact: true })
- .click();
- await expect
- .poll(() => page.locator('main h1').textContent())
- .toBe('Status set in a loader');
- expect(await page.locator('.example-page-loaded-toast:popover-open').count()).toBe(0);
- expect(await page.locator('header').getAttribute('data-retained')).toBe('yes');
- await page.getByRole('link', { name: 'HTTP Errors Example', exact: true }).click();
- await expect.poll(() => page.locator('main h1').textContent()).toBe('HTTP Errors Example');
- expect(await page.locator('.example-page-loaded-toast:popover-open').count()).toBe(0);
- expect(await page.title()).toBe('HTTP Errors Example');
- });
- });
- });
-}
diff --git a/packages/void/test/integration/http-errors-playground.test.ts b/packages/void/test/integration/http-errors-playground.test.ts
new file mode 100644
index 000000000..3f7a9bb6f
--- /dev/null
+++ b/packages/void/test/integration/http-errors-playground.test.ts
@@ -0,0 +1,370 @@
+import { join } from 'node:path';
+import spawn from 'cross-spawn';
+import type { Browser, Page } from 'playwright';
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from 'vite-plus/test';
+import {
+ createIsolatedPlayground,
+ killChild,
+ startServer,
+ type IsolatedPlayground,
+ type StartedServer,
+} from '../../../../test/integration-helpers.ts';
+import { launchPagesBrowser } from '../../../../test/pages-browser.ts';
+import { PAGES_PROTOCOL_VERSION } from '../../../edge/src/pages-protocol.ts';
+import { deserializePageData } from '../../src/pages/serialize.ts';
+
+const repository = join(import.meta.dirname, '../../../..');
+const pagesHeaders = {
+ 'X-VoidPages': 'true',
+ 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION,
+};
+const renderedExamples = [
+ {
+ path: '/loaders/status/403',
+ status: 403,
+ heading: 'Status set in a loader',
+ message: 'Your account is banned',
+ retryAfter: '120',
+ },
+ {
+ path: '/loaders/status/503',
+ status: 503,
+ heading: 'Status set in a loader',
+ message: 'Down for maintenance',
+ retryAfter: '120',
+ },
+ {
+ path: '/loaders/validated',
+ status: 503,
+ heading: 'Status set in a validated loader',
+ message: 'Down for maintenance',
+ retryAfter: null,
+ },
+ {
+ path: '/loaders/deferred',
+ status: 429,
+ heading: 'Status set before deferred streaming',
+ message: 'Too many requests',
+ retryAfter: '120',
+ },
+ {
+ path: '/middleware/application',
+ status: 503,
+ heading: 'Status set in application middleware',
+ message: 'Down for maintenance',
+ retryAfter: '120',
+ },
+ {
+ path: '/middleware/handler',
+ status: 403,
+ heading: 'Status set in handler middleware',
+ message: 'Your account is banned',
+ retryAfter: null,
+ },
+ {
+ path: '/loaders/unexpected',
+ status: 500,
+ heading: 'Root error boundary',
+ message: 'Internal Server Error',
+ retryAfter: null,
+ },
+ {
+ path: '/loaders/not-found',
+ status: 404,
+ heading: 'Not-found boundary',
+ message: 'This page does not exist',
+ retryAfter: null,
+ },
+ ...(
+ [
+ { status: 401, message: 'Please sign in' },
+ { status: 403, message: 'Your account is banned' },
+ { status: 410, message: 'This page is permanently gone' },
+ { status: 429, message: 'Too many requests' },
+ { status: 503, message: 'Down for maintenance' },
+ ] as const
+ ).map(({ status, message }) => ({
+ path: `/loaders/errors/${status}`,
+ status,
+ heading: 'Nested error boundary',
+ message,
+ retryAfter: null,
+ })),
+ ...(
+ [
+ { status: 403, message: 'Your account is banned' },
+ { status: 503, message: 'Down for maintenance' },
+ ] as const
+ ).map(({ status, message }) => ({
+ path: `/middleware/errors/${status}`,
+ status,
+ heading: 'Root error boundary',
+ message,
+ retryAfter: null,
+ })),
+] as const;
+
+type PageData = {
+ component: string;
+ props: Record;
+ url: string;
+ deferredKeys?: Record;
+};
+
+describe.each(['dev', 'production'] as const)('HTTP errors playground (%s)', (mode) => {
+ let playground: IsolatedPlayground;
+ let server: StartedServer;
+ let browser: Browser;
+ let base: string;
+
+ function expectedMessage(example: (typeof renderedExamples)[number]) {
+ return mode === 'dev' && example.path === '/loaders/unexpected'
+ ? 'Unexpected loader failure'
+ : example.message;
+ }
+
+ beforeAll(async () => {
+ playground = createIsolatedPlayground(repository, 'playground/http-errors');
+ if (mode === 'production') {
+ const build = spawn.sync('vp', ['build'], {
+ cwd: playground.root,
+ encoding: 'utf8',
+ timeout: 60_000,
+ maxBuffer: 10 * 1024 * 1024,
+ env: { ...process.env, NODE_ENV: 'production' },
+ });
+ expect(build.status, `${build.stdout ?? ''}${build.stderr ?? ''}`).toBe(0);
+ }
+ server = await startServer(
+ (port) =>
+ mode === 'dev'
+ ? spawn('vp', ['dev', '--host', '127.0.0.1', '--port', String(port), '--strictPort'], {
+ cwd: playground.root,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ })
+ : spawn(process.execPath, ['dist/ssr/index.js'], {
+ cwd: playground.root,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ env: { ...process.env, PORT: String(port), NODE_ENV: 'production' },
+ }),
+ 30_000,
+ { expectBody: 'HTTP Errors Example' },
+ );
+ base = server.base;
+ browser = await launchPagesBrowser();
+ });
+
+ afterAll(async () => {
+ await browser?.close();
+ if (server) {
+ await killChild(server.child);
+ }
+ playground?.cleanup();
+ });
+
+ for (const representation of ['HTML', 'Pages'] as const) {
+ it.each(renderedExamples)(
+ `${representation}: $path renders $heading with HTTP $status`,
+ async (example) => {
+ const pages = representation === 'Pages';
+ const response = await fetch(base + example.path, { headers: pages ? pagesHeaders : {} });
+ expect(response.status).toBe(example.status);
+ expect(response.headers.get('Retry-After')).toBe(example.retryAfter);
+ const body = await response.text();
+ if (!pages) {
+ expect(response.headers.get('content-type')).toContain('text/html');
+ expect(body).toContain(example.heading);
+ expect(body).toContain(expectedMessage(example));
+ expect(body).toContain('aria-label="Example sections"');
+ expect(body).toContain('example-page-loaded-toast');
+ if (example.path === '/loaders/deferred') {
+ expect(body).toContain('Waiting one second for deferred props');
+ expect(body).toContain('window.__resolveDeferred("details"');
+ }
+ } else {
+ expect(response.headers.get('X-VoidPages')).toBe('true');
+ const lines = body.trim().split('\n');
+ const data = deserializePageData(lines[0]);
+ expect(data.url).toBe(example.path);
+ if (example.path === '/loaders/deferred') {
+ expect(response.headers.get('content-type')).toContain('application/x-ndjson');
+ expect(data.deferredKeys).toEqual({ details: 'details' });
+ expect(lines).toHaveLength(2);
+ expect(deserializePageData(lines[1])).toMatchObject({
+ __deferred: 'details',
+ data: example.message,
+ });
+ } else {
+ expect(response.headers.get('content-type')).toContain('application/json');
+ expect(data.props).toMatchObject(
+ example.path.includes('/errors/') || example.status === 404 || example.status === 500
+ ? { error: { status: example.status, message: expectedMessage(example) } }
+ : { status: example.status, message: example.message },
+ );
+ }
+ }
+ if (example.path.startsWith('/middleware/errors/')) {
+ expect(server.output()).not.toContain('Middleware-error page loader ran');
+ }
+ },
+ );
+ }
+
+ describe('browser navigation', () => {
+ let page: Page;
+
+ beforeEach(async () => {
+ page = await browser.newPage();
+ page.setDefaultTimeout(10_000);
+ });
+ afterEach(async () => {
+ await page?.close();
+ });
+
+ async function openHome() {
+ await page.goto(base);
+ // The layout effect is also the example's observable hydration signal.
+ await page.waitForSelector('.example-page-loaded-toast:popover-open');
+ await page.evaluate(() => Reflect.set(globalThis, '__HTTP_ERRORS_DOCUMENT__', true));
+ await page
+ .locator('header')
+ .evaluate((element) => element.setAttribute('data-retained', 'yes'));
+ }
+
+ for (const navigation of ['Document load', 'Client navigation'] as const) {
+ it.each(renderedExamples)(
+ `${navigation}: $path renders $heading with HTTP $status`,
+ async (example) => {
+ await openHome();
+ const responsePromise = page.waitForResponse(
+ (response) =>
+ response.url() === base + example.path &&
+ (navigation === 'Document load'
+ ? response.request().isNavigationRequest()
+ : response.request().headers()['x-voidpages'] === 'true'),
+ );
+ await page
+ .locator(`a[href="${example.path}"]`)
+ .getByText(navigation, { exact: true })
+ .click();
+ const response = await responsePromise;
+ expect(response.status()).toBe(example.status);
+ expect(response.headers()['retry-after'] ?? null).toBe(example.retryAfter);
+ if (navigation === 'Document load') {
+ expect(response.headers()['content-type']).toContain('text/html');
+ await page.waitForSelector('.example-page-loaded-toast:popover-open');
+ } else {
+ expect(response.headers()['x-voidpages']).toBe('true');
+ }
+ await expect.poll(() => page.locator('main h1').textContent()).toBe(example.heading);
+ await expect
+ .poll(() => page.locator('main').textContent(), { timeout: 10_000 })
+ .toContain(expectedMessage(example));
+ expect(await page.locator('header').count()).toBe(1);
+ if (example.path.startsWith('/loaders/errors/')) {
+ expect(
+ await page
+ .getByText('Nested layout for HTTP exception examples.', { exact: true })
+ .count(),
+ ).toBe(1);
+ expect(
+ await page
+ .getByRole('heading', { name: 'Loader exception example', exact: true })
+ .count(),
+ ).toBe(0);
+ }
+ if (example.path.startsWith('/middleware/errors/')) {
+ expect(server.output()).not.toContain('Middleware-error page loader ran');
+ expect(
+ await page
+ .getByRole('heading', { name: 'Middleware exception example', exact: true })
+ .count(),
+ ).toBe(0);
+ }
+ const retained = navigation === 'Client navigation';
+ expect(
+ await page.evaluate(() => Reflect.get(globalThis, '__HTTP_ERRORS_DOCUMENT__')),
+ ).toBe(retained ? true : undefined);
+ expect(await page.locator('header').getAttribute('data-retained')).toBe(
+ retained ? 'yes' : null,
+ );
+ },
+ );
+ }
+
+ it('offers document and client navigation for every example', async () => {
+ await openHome();
+ const paths = renderedExamples.map(({ path }) => path).sort();
+ for (const name of ['Document load', 'Client navigation']) {
+ const links = await page.getByRole('link', { name, exact: true }).all();
+ const targets = await Promise.all(links.map((link) => link.getAttribute('href')));
+ expect(targets.sort()).toEqual(paths);
+ }
+ });
+
+ it.each(['/loaders/errors/403', '/middleware/errors/403'])(
+ 'navigates away from %s and restores it through history without reloading',
+ async (path) => {
+ await openHome();
+ const heading = path.startsWith('/loaders/')
+ ? 'Nested error boundary'
+ : 'Root error boundary';
+ await page
+ .locator(`a[href="${path}"]`)
+ .getByText('Client navigation', { exact: true })
+ .click();
+ await expect.poll(() => page.locator('main h1').textContent()).toBe(heading);
+ await page.getByRole('link', { name: 'HTTP Errors Example', exact: true }).click();
+ await expect.poll(() => page.locator('main h1').textContent()).toBe('HTTP Errors Example');
+ await page.goBack();
+ await expect.poll(() => page.locator('main h1').textContent()).toBe(heading);
+ await page.goForward();
+ await expect.poll(() => page.locator('main h1').textContent()).toBe('HTTP Errors Example');
+ expect(await page.locator('header').getAttribute('data-retained')).toBe('yes');
+ expect(await page.evaluate(() => Reflect.get(globalThis, '__HTTP_ERRORS_DOCUMENT__'))).toBe(
+ true,
+ );
+ },
+ );
+
+ it.each(['hover', 'focus'] as const)(
+ 'prefetches complete deferred props on %s without navigating',
+ async (interaction) => {
+ await openHome();
+ const responsePromise = page.waitForResponse(
+ (response) =>
+ response.url() === base + '/loaders/deferred' &&
+ response.request().headers().purpose === 'prefetch',
+ );
+ const link = page.getByRole('link', { name: 'Hover or focus to prefetch deferred data' });
+ await link[interaction]();
+ const response = await responsePromise;
+ expect(response.status()).toBe(429);
+ expect(response.headers()['retry-after']).toBe('120');
+ expect(response.headers()['content-type']).toContain('application/json');
+ expect(response.request().headers()['x-voidpages-version']).toBe(PAGES_PROTOCOL_VERSION);
+ expect(deserializePageData(await response.text())).toMatchObject({
+ props: { details: 'Too many requests' },
+ });
+ expect(page.url()).toBe(base + '/');
+ expect(await page.locator('header').getAttribute('data-retained')).toBe('yes');
+ },
+ );
+
+ it('shows the document-load toast once and does not reopen it on client navigation', async () => {
+ await openHome();
+ await page.waitForSelector('.example-page-loaded-toast:popover-open', { state: 'hidden' });
+ await page
+ .locator('a[href="/loaders/status/403"]')
+ .getByText('Client navigation', { exact: true })
+ .click();
+ await expect.poll(() => page.locator('main h1').textContent()).toBe('Status set in a loader');
+ expect(await page.locator('.example-page-loaded-toast:popover-open').count()).toBe(0);
+ expect(await page.locator('header').getAttribute('data-retained')).toBe('yes');
+ await page.getByRole('link', { name: 'HTTP Errors Example', exact: true }).click();
+ await expect.poll(() => page.locator('main h1').textContent()).toBe('HTTP Errors Example');
+ expect(await page.locator('.example-page-loaded-toast:popover-open').count()).toBe(0);
+ expect(await page.title()).toBe('HTTP Errors Example');
+ });
+ });
+});
diff --git a/packages/void/test/integration/http-errors-production.test.ts b/packages/void/test/integration/http-errors-production.test.ts
deleted file mode 100644
index 2add0fbf5..000000000
--- a/packages/void/test/integration/http-errors-production.test.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import { defineHttpErrorTests } from './http-errors-playground.cases.ts';
-
-defineHttpErrorTests('production');
diff --git a/packages/void/test/integration/kitchen-sink.test.ts b/packages/void/test/integration/kitchen-sink.test.ts
index 023e676dc..9dda63c08 100644
--- a/packages/void/test/integration/kitchen-sink.test.ts
+++ b/packages/void/test/integration/kitchen-sink.test.ts
@@ -1,10 +1,11 @@
+import { execSync } from 'node:child_process';
import { readFileSync, rmSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { getWorkerConfigPath } from '@cloudflare/build-output-utils';
import spawn from 'cross-spawn';
import { chromium, type Browser, type Page } from 'playwright';
import { describe, expect, it, beforeAll, afterAll } from 'vite-plus/test';
-import { buildPlayground, killChild, startServer } from '../../../../test/integration-helpers.ts';
+import { killChild, startServer } from '../../../../test/integration-helpers.ts';
declare global {
interface Window {
@@ -46,7 +47,10 @@ describe('playground/kitchen-sink', () => {
// dev-mode dependency optimization makes browser checks unreliable.
const pg = join(ROOT, 'playground/kitchen-sink');
rmSync(join(pg, 'dist'), { recursive: true, force: true });
- buildPlayground(ROOT, 'kitchen-sink');
+ execSync('vp run --filter ./playground/kitchen-sink build', {
+ cwd: ROOT,
+ stdio: 'pipe',
+ });
const previewDatabaseId = preparePreviewWranglerConfig(pg);
// Start preview server — pre-built assets, no lazy optimization.
diff --git a/packages/void/test/integration/mysql-test.test.ts b/packages/void/test/integration/mysql-test.test.ts
index 708bdc831..56639b2e8 100644
--- a/packages/void/test/integration/mysql-test.test.ts
+++ b/packages/void/test/integration/mysql-test.test.ts
@@ -1,9 +1,8 @@
-import { type ChildProcess } from 'node:child_process';
+import { execSync, type ChildProcess } from 'node:child_process';
import { rmSync, unlinkSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { afterAll, beforeAll, describe, expect, it } from 'vite-plus/test';
import {
- buildPlayground,
killChild,
spawnPlaygroundServer,
startServer,
@@ -78,7 +77,7 @@ describe('playground/mysql-test', () => {
it('queries MySQL through void/db and createDb in the built Worker', async () => {
rmSync(join(PLAYGROUND, 'dist'), { recursive: true, force: true });
- buildPlayground(ROOT, 'mysql-test');
+ execSync('vp run --filter ./playground/mysql-test build', { cwd: ROOT, stdio: 'pipe' });
const server = await start('preview');
try {
await expectUsers(server);
diff --git a/packages/void/test/integration/node-static-md.test.ts b/packages/void/test/integration/node-static-md.test.ts
index b30a01442..fb9ca0ffb 100644
--- a/packages/void/test/integration/node-static-md.test.ts
+++ b/packages/void/test/integration/node-static-md.test.ts
@@ -1,7 +1,7 @@
+import { execSync } from 'node:child_process';
import { existsSync, readFileSync, rmSync } from 'node:fs';
import { join } from 'node:path';
import { beforeAll, describe, expect, it } from 'vite-plus/test';
-import { buildPlayground } from '../../../../test/integration-helpers.ts';
// A Markdown-only pages app still needs a client build: its closeBundle
// prerenders. Markdown pages are implicit islands, so the client input comes
@@ -15,7 +15,7 @@ describe('playground/node-static-md build (Markdown-only, target: node, output:
const pg = join(ROOT, PLAYGROUND);
rmSync(join(pg, 'dist'), { recursive: true, force: true });
rmSync(join(pg, '.void'), { recursive: true, force: true });
- buildPlayground(ROOT, PLAYGROUND.slice('playground/'.length));
+ execSync(`vp run --filter ./${PLAYGROUND} build`, { cwd: ROOT, stdio: 'pipe' });
});
it('emits the Node SSR entry', () => {
diff --git a/packages/void/test/integration/node-static.test.ts b/packages/void/test/integration/node-static.test.ts
index e58dc8313..a7c0572a9 100644
--- a/packages/void/test/integration/node-static.test.ts
+++ b/packages/void/test/integration/node-static.test.ts
@@ -1,10 +1,10 @@
+import { execSync } from 'node:child_process';
import { existsSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
import { createServer, type Server } from 'node:http';
import { extname, isAbsolute, join, relative, resolve } from 'node:path';
import { chromium } from 'playwright';
import { afterAll, beforeAll, describe, expect, it } from 'vite-plus/test';
import {
- buildPlayground,
killChild,
spawnPlaygroundServer,
startServer,
@@ -118,7 +118,7 @@ describe('playground/node-static build (target: node, output: static)', () => {
const pg = join(ROOT, PLAYGROUND);
rmSync(join(pg, 'dist'), { recursive: true, force: true });
rmSync(join(pg, '.void'), { recursive: true, force: true });
- buildPlayground(ROOT, PLAYGROUND.slice('playground/'.length));
+ execSync(`vp run --filter ./${PLAYGROUND} build`, { cwd: ROOT, stdio: 'pipe' });
const clientDir = join(DIST, 'client');
staticServer = createServer((req, res) => {
@@ -437,7 +437,7 @@ describe('playground/node-static redirects (target: node, output: static)', () =
const pg = join(ROOT, PLAYGROUND);
rmSync(join(pg, 'dist'), { recursive: true, force: true });
rmSync(join(pg, '.void'), { recursive: true, force: true });
- buildPlayground(ROOT, PLAYGROUND.slice('playground/'.length));
+ execSync(`vp run --filter ./${PLAYGROUND} build`, { cwd: ROOT, stdio: 'pipe' });
writeFileSync(VOID_CONFIG, originalConfig);
externalServer = createServer((_req, res) => {
diff --git a/packages/void/test/integration/page-errors.cases.ts b/packages/void/test/integration/page-errors.cases.ts
deleted file mode 100644
index 2b1b9a6e0..000000000
--- a/packages/void/test/integration/page-errors.cases.ts
+++ /dev/null
@@ -1,717 +0,0 @@
-import { execFileSync } from 'node:child_process';
-import {
- mkdirSync,
- rmSync,
- writeFileSync,
- symlinkSync,
- realpathSync,
- existsSync,
- readFileSync,
-} from 'node:fs';
-import { join } from 'node:path';
-import spawn from 'cross-spawn';
-import type { Browser } from 'playwright';
-import { afterAll, beforeAll, describe, expect, it } from 'vite-plus/test';
-import {
- createIsolatedPlayground,
- killChild,
- startServer,
- type IsolatedPlayground,
-} from '../../../../test/integration-helpers.ts';
-import { launchPagesBrowser } from '../../../../test/pages-browser.ts';
-import { PAGES_PROTOCOL_VERSION } from '../../../edge/src/pages-protocol.ts';
-import { deserializePageData } from '../../src/pages/serialize.ts';
-
-const repository = join(import.meta.dirname, '../../../..');
-
-export function definePageErrorsTests(framework: 'react' | 'vue' | 'svelte' | 'solid'): void {
- describe(`Pages errors with ${framework}`, () => {
- let fixture: IsolatedPlayground;
- let child: ReturnType;
- let browser: Browser;
- let base: string;
- const extension = framework === 'vue' ? 'vue' : framework === 'svelte' ? 'svelte' : 'tsx';
- function write(path: string, source: string) {
- const file = join(fixture.root, path);
- mkdirSync(join(file, '..'), { recursive: true });
- writeFileSync(file, source);
- }
- function component(content: string, script = '', layout = false) {
- if (framework === 'vue') {
- return `${content}${layout ? '' : ''}`;
- }
- if (framework === 'svelte') {
- return `${content}${layout ? '{@render children?.()}' : ''}`;
- }
- return `import { Link, useShared, useParams, useRouter } from '@void/${framework}'; export default function Component(props) { const shared = useShared(); const params = useParams(); const error = props.error; ${script} return <>${content}${layout ? '{props.children}' : ''}>; }`;
- }
- beforeAll(async () => {
- fixture = createIsolatedPlayground(
- repository,
- framework === 'react' ? 'playground/node-app' : `playground/${framework}-pages`,
- );
- const nodeServer = join(fixture.root, 'node_modules/@hono/node-server');
- if (!existsSync(nodeServer)) {
- mkdirSync(join(nodeServer, '..'), { recursive: true });
- symlinkSync(
- realpathSync(join(repository, 'playground/node-app/node_modules/@hono/node-server')),
- nodeServer,
- process.platform === 'win32' ? 'junction' : 'dir',
- );
- }
- for (const dir of ['pages', 'routes', 'middleware', 'db']) {
- rmSync(join(fixture.root, dir), { recursive: true, force: true });
- }
- write(
- 'tsconfig.json',
- JSON.stringify({
- compilerOptions: {
- target: 'ESNext',
- module: 'ESNext',
- moduleResolution: 'bundler',
- jsx: 'preserve',
- },
- }),
- );
- write(
- 'void.config.ts',
- `import { defineConfig } from 'void/config'; export default defineConfig({target:'node',head:{titleTemplate:'%s | Error tests'}});`,
- );
- write(
- 'middleware/shared.ts',
- `import { defineMiddleware } from 'void/handler'; export default defineMiddleware(async (c,next)=>{c.set('shared',{viewer:'alice',...(c.req.header('X-Test-No-Root') ? { noRoot: true } : {})}); c.header('X-Security','retained'); const guard=c.req.header('X-Test-Guard'); if(guard==='not-found') return c.notFound(); if(guard==='explicit') return c.text('Hidden by guard',404); await next(); if(guard==='after-not-found') c.res=await c.notFound();});`,
- );
- write('pages/style.css', 'nav { color: rgb(20, 80, 100); }');
- write(
- 'middleware/status.ts',
- `import { defineMiddleware } from 'void/handler';
-import { HTTPException } from 'hono/http-exception';
-export default defineMiddleware(async (c, next) => {
- const status = c.req.header('X-Test-Error-Status');
- if (status === '403' || status === '503') {
- c.header('Retry-After', '120');
- throw new HTTPException(status === '403' ? 403 : 503, {
- message: status === '403' ? 'Your account is banned' : 'Down for maintenance',
- });
- }
- await next();
-});`,
- );
- const nav =
- '';
- let rootLayout = component(nav, '', true);
- if (framework === 'vue' || framework === 'svelte') {
- rootLayout = rootLayout
-
- .replace('import { Link,', "import './style.css'; import { Link,");
- } else {
- rootLayout = `import './style.css'; ${rootLayout}`;
- }
- write(`pages/layout.${extension}`, rootLayout);
- write(
- `pages/index.${extension}`,
- component(
- 'Home page
',
- "const router = useRouter(); if(typeof window!=='undefined') window.testRouter=router;",
- ),
- );
- write(
- `pages/_not-found.${extension}`,
- component(
- 'Missing page
{error.message}
',
- "if(shared.noRoot) throw new Error('UNUSED_ROOT_BOUNDARY');",
- ),
- );
- write(`pages/_error.${extension}`, component('Error page
{error.message}
'));
- if (framework === 'vue') {
- write(
- `pages/_not-found.${extension}`,
- component(
- 'Missing page
{{error.message}}
',
- "if(shared.noRoot) throw new Error('UNUSED_ROOT_BOUNDARY');",
- ),
- );
- write(
- `pages/_error.${extension}`,
- component('Error page
{{error.message}}
'),
- );
- }
- write(`pages/items/[id].${extension}`, component('Item
'));
- write(`pages/status/[code].${extension}`, component('Status page
'));
- write(
- 'pages/status/[code].server.ts',
- `import { defineHandler } from 'void/handler';
-export const loader = defineHandler(c => {
- c.status(c.req.param('code') === '403' ? 403 : 503);
- c.header('Retry-After', '120');
- return {};
-});`,
- );
- for (const name of ['falsy', 'island-falsy.island']) {
- write(`pages/${name}.${extension}`, component('Broken view
', 'throw undefined;'));
- }
- write(
- 'pages/items/[id].server.ts',
- `import { defineHandler } from 'void/handler'; import { HTTPException } from 'hono/http-exception'; export const loader = defineHandler(c=>{const id=c.req.param('id'); if(id==='returned') return c.notFound(); if(id==='thrown') throw new HTTPException(404,{message:'Deleted item'}); if(id==='unexpected') throw Object.assign(new Error('SECRET_SERVER_MARKER'),{secret:'SECRET_CUSTOM_MARKER'}); return {};});`,
- );
- write(
- `pages/crash.${extension}`,
- component(
- 'Crash route
',
- `if(typeof window!=='undefined') throw new Error('SECRET_CLIENT_MARKER');`,
- ),
- );
- write(
- `pages/nested/layout.${extension}`,
- component(
- '',
- "if(params.kind==='layout') throw new Error('SECRET_LAYOUT_MARKER');",
- true,
- ),
- );
- write(`pages/nested/_error.${extension}`, component('Nested error
'));
- write(
- `pages/nested/deep/_error.${extension}`,
- component('Broken fallback
', "throw new Error('SECRET_FALLBACK_MARKER');"),
- );
- for (const prefix of ['nested', 'nested/deep']) {
- write(
- `pages/${prefix}/[kind].${extension}`,
- component(
- 'Nested route
',
- "if(params.kind==='server'||(params.kind!=='healthy'&&typeof window!=='undefined')) throw new Error('SECRET_RENDER_MARKER');",
- ),
- );
- }
- write(
- `pages/client-only.${extension}`,
- component(
- 'Client only
',
- "if(typeof window==='undefined') throw new Error('SECRET_SSR_DISABLED');",
- ),
- );
- write(
- 'pages/client-only.server.ts',
- 'export const ssr = false; export const loader = () => new Response(null,{status:404});',
- );
- write(
- `pages/retry.${extension}`,
- component(
- 'Recovered page
',
- "if(typeof window!=='undefined'&&!window.recovered) throw new Error('SECRET_RETRY');",
- ),
- );
- write(
- `pages/fatal/[kind].${extension}`,
- component(
- 'Fatal route
',
- "if(typeof window!=='undefined') throw new Error('SECRET_FATAL');",
- ),
- );
- write(
- 'routes/old-terminal.ts',
- "export default (c) => c.redirect('/fatal/terminal?from=old');",
- );
- write(
- `pages/_error.${extension}`,
- component(
- framework === 'vue'
- ? 'Error page
{{error.message}}
'
- : 'Error page
{error.message}
',
- "if(params.kind==='terminal') throw new Error('SECRET_TERMINAL');",
- ),
- );
- write(`pages/nested/other.${extension}`, component('Other nested page
'));
- write(`pages/islands/index.island.${extension}`, component('Island document
'));
- write('pages/islands/index.server.ts', 'export const loader = c => c.notFound();');
- write(`pages/islands/_not-found.${extension}`, component('Missing island page
'));
- const counter =
- framework === 'react'
- ? "import {useState} from 'react'; export default function Counter(){const [n,setN]=useState(0);return }"
- : framework === 'solid'
- ? "import {createSignal} from 'solid-js'; export default function Counter(){const [n,setN]=createSignal(0);return }"
- : framework === 'vue'
- ? ''
- : '';
- write(`pages/islands/_Counter.${extension}`, counter);
- let islandLayout = component('', '', true);
- const counterImport = `import Counter from './_Counter.${extension}' with {island:'load'};`;
- islandLayout =
- framework === 'vue' || framework === 'svelte'
- ? islandLayout.replace('import { Link,', counterImport + '\n import { Link,')
- : counterImport + islandLayout;
- write(`pages/islands/layout.island.${extension}`, islandLayout);
- for (const section of ['alpha', 'beta']) {
- write(
- `pages/${section}/index.${extension}`,
- component(
- 'Section page
',
- "if(typeof window!=='undefined') throw new Error('SECRET_SECTION');",
- ),
- );
- write(`pages/${section}/_error.${extension}`, component(`${section} error
`));
- }
- write(`pages/hmr/index.${extension}`, component('HMR route
'));
- write(
- 'pages/hmr/index.server.ts',
- 'export const loader = () => new Response(null,{status:404});',
- );
- write('routes/api/missing.ts', `export const GET = c => c.text('API missing',404);`);
- execFileSync('vp', ['build'], {
- cwd: fixture.root,
- stdio: 'pipe',
- timeout: 60_000,
- env: { ...process.env, NODE_ENV: 'production' },
- });
- const server = await startServer(
- (port) =>
- (child = spawn(process.execPath, ['dist/ssr/index.js'], {
- cwd: fixture.root,
- stdio: ['ignore', 'pipe', 'pipe'],
- env: { ...process.env, PORT: String(port) },
- })),
- 30_000,
- );
- base = server.base;
- browser = await launchPagesBrowser();
- }, 90_000);
- afterAll(async () => {
- await browser?.close();
- if (child) {
- await killChild(child);
- }
- fixture?.cleanup();
- });
- it.each(['not-found', 'after-not-found'])(
- 'uses the root not-found for middleware guards (%s) and preserves explicit responses',
- async (guard) => {
- for (const pages of [false, true]) {
- const headers = {
- 'X-Test-Guard': guard,
- ...(pages && { 'X-VoidPages': 'true', 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION }),
- };
- const response = await fetch(base + '/islands', { headers });
- expect(response.status).toBe(404);
- expect(response.headers.get('X-Security')).toBe('retained');
- const body = await response.text();
- if (pages) {
- expect(response.headers.get('X-VoidPages')).toBe('true');
- const data = deserializePageData<{ component: string }>(body);
- expect(data.component).toContain('_void:boundary:root-not-found:');
- expect(data).toMatchObject({
- props: { error: { status: 404, message: 'Not Found' } },
- shared: { viewer: 'alice' },
- });
- } else {
- expect(body).toContain('Missing page');
- expect(body).toContain('data-layout="root"');
- expect(body).not.toContain('Missing island page');
- }
- const explicit = await fetch(base + '/islands', {
- headers: { ...headers, 'X-Test-Guard': 'explicit' },
- });
- expect(explicit.status).toBe(404);
- expect(explicit.headers.has('X-VoidPages')).toBe(false);
- expect(await explicit.text()).toBe('Hidden by guard');
- }
- },
- );
-
- it('renders a loader not-found without attempting an unused root boundary', async () => {
- const response = await fetch(base + '/islands', { headers: { 'X-Test-No-Root': 'true' } });
- expect(response.status).toBe(404);
- expect(await response.text()).toContain('Missing island page');
- });
-
- it.each(
- ([403, 503] as const).flatMap((status) =>
- (['HTML', 'Pages JSON'] as const).map((format) => ({ status, format })),
- ),
- )(
- 'renders middleware errors through the root page boundary with HTTP $status ($format)',
- async ({ status, format }) => {
- const message = status === 403 ? 'Your account is banned' : 'Down for maintenance';
- // This route throws a different error if its loader is reached.
- const response = await fetch(base + '/items/unexpected', {
- headers: {
- 'X-Test-Error-Status': String(status),
- ...(format === 'Pages JSON'
- ? { 'X-VoidPages': 'true', 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION }
- : { Accept: 'text/html' }),
- },
- });
- const body = await response.text();
- expect(response.status).toBe(status);
- expect(body).not.toContain('SECRET_');
- if (format === 'Pages JSON') {
- expect(response.headers.get('X-VoidPages')).toBe('true');
- expect(deserializePageData(body)).toMatchObject({
- props: { error: { status, message } },
- shared: { viewer: 'alice' },
- url: '/items/unexpected',
- });
- } else {
- expect(response.headers.get('Content-Type')).toContain('text/html');
- expect(body).toContain('Error page');
- expect(body).toContain(message);
- expect(body).toContain('data-layout="root"');
- expect(body).toContain('stylesheet');
- }
- expect(response.headers.get('Retry-After')).toBe('120');
- expect(response.headers.get('X-Security')).toBe('retained');
- expect(response.headers.get('Cache-Control')).toBe('no-store');
- },
- );
-
- it('returns status-correct documents and marked error payloads without exposing secrets', async () => {
- for (const [path, status] of [
- ['/unknown', 404],
- ['/items/returned', 404],
- ['/items/thrown', 404],
- ['/items/unexpected', 500],
- ] as const) {
- for (const pages of [false, true]) {
- const response = await fetch(base + path, {
- headers: pages
- ? { 'X-VoidPages': 'true', 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION }
- : { Accept: 'text/html' },
- });
- expect(response.status, path).toBe(status);
- expect(response.headers.get('Cache-Control')).toBe('no-store');
- expect(response.headers.get('X-Security')).toBe('retained');
- const text = await response.text();
- expect(text).not.toContain('SECRET_');
- const title = `${status === 404 ? 'Not Found' : 'Internal Server Error'} | Error tests`;
- if (pages) {
- expect(response.headers.get('X-VoidPages')).toBe('true');
- expect(deserializePageData(text)).toMatchObject({
- url: path,
- shared: { viewer: 'alice' },
- props: { error: { status } },
- head: { title },
- });
- } else {
- expect(text).toContain('data-layout="root"');
- expect(text).toContain(`${title}`);
- }
- }
- }
- for (const path of [
- '/nested/server',
- '/nested/deep/server',
- '/nested/layout',
- '/falsy',
- '/island-falsy',
- ]) {
- const document = await fetch(base + path);
- expect(document.status, path).toBe(500);
- const html = await document.text();
- expect(html).toContain(
- path.endsWith('/layout') || path.includes('falsy') ? 'Error page' : 'Nested error',
- );
- expect(html).not.toContain('SECRET_');
- }
- const response = await fetch(base + '/api/missing');
- expect(response.status).toBe(404);
- expect(await response.text()).toBe('API missing');
- });
- it('renders application-defined error statuses on document loads and client visits', async () => {
- const page = await browser.newPage();
- page.setDefaultTimeout(8_000);
- try {
- for (const status of [403, 503]) {
- const path = `/status/${status}`;
- const documentResponse = await fetch(base + path);
- expect(documentResponse.status).toBe(status);
- expect(documentResponse.headers.get('Retry-After')).toBe('120');
- expect(await documentResponse.text()).toContain('Status page');
-
- await page.goto(base);
- await page.waitForSelector('#app[data-hydrated="true"]');
- await page.evaluate(() =>
- document.querySelector('nav')!.setAttribute('data-retained', 'yes'),
- );
- const navigation = page.waitForResponse(
- (response) =>
- response.url() === base + path &&
- response.request().headers()['x-voidpages'] === 'true',
- );
- await page.evaluate(`window.testRouter.visit(${JSON.stringify(path)})`);
- const response = await navigation;
- expect(response.status()).toBe(status);
- expect(response.headers()['x-voidpages']).toBe('true');
- await expect.poll(() => page.locator('h1').textContent()).toBe('Status page');
- expect(await page.locator('nav').getAttribute('data-retained')).toBe('yes');
- }
- } finally {
- await page.close();
- }
- });
-
- it('keeps the app and outer layout mounted across 404s and client errors', async () => {
- const page = await browser.newPage();
- const errors: Array = [];
- page.on('pageerror', (e) => errors.push(e.stack ?? e.message));
- page.on('console', (m) => {
- if (m.type() === 'error') {
- errors.push(m.text());
- }
- });
- page.setDefaultTimeout(8_000);
- try {
- await page.goto(base);
- await page.waitForSelector('#app[data-hydrated="true"]');
- await page.evaluate(() => {
- (window as unknown as { marker: boolean }).marker = true;
- document.querySelector('nav')!.setAttribute('data-retained', 'yes');
- });
- for (const name of ['Returned', 'Thrown', 'Unexpected', 'Crash']) {
- await page.getByRole('link', { name, exact: true }).click();
- await expect
- .poll(() => page.locator('h1').textContent())
- .toBe(name === 'Returned' || name === 'Thrown' ? 'Missing page' : 'Error page');
- if (name !== 'Crash') {
- await expect
- .poll(() => page.title())
- .toBe(
- `${name === 'Unexpected' ? 'Internal Server Error' : 'Not Found'} | Error tests`,
- );
- }
- expect(await page.evaluate(() => (window as unknown as { marker: boolean }).marker)).toBe(
- true,
- );
- expect(await page.locator('nav').getAttribute('data-retained')).toBe('yes');
- expect(await page.locator('body').textContent()).not.toContain('SECRET_');
- }
- } catch (error) {
- console.error(framework, page.url(), errors);
- throw error;
- } finally {
- await page.close();
- }
- });
- it('escalates failed fallbacks and layouts while retaining healthy ancestors', async () => {
- const page = await browser.newPage();
- const errors: Array = [];
- page.on('pageerror', (e) => errors.push(e.stack ?? e.message));
- page.on('console', (m) => {
- if (m.type() === 'error') {
- errors.push(m.text());
- }
- });
- page.setDefaultTimeout(8_000);
- try {
- await page.goto(base);
- await page.waitForSelector('#app[data-hydrated="true"]');
- await page.evaluate(() =>
- document.querySelector('nav')!.setAttribute('data-retained', 'yes'),
- );
- for (const [link, expected] of [
- ['Nested', 'Nested error'],
- ['Deep', 'Nested error'],
- ['Layout', 'Error page'],
- ['Client only', 'Missing page'],
- ]) {
- await page.getByRole('link', { name: link, exact: true }).click();
- await expect.poll(() => page.locator('h1').textContent()).toBe(expected);
- expect(await page.locator('nav').getAttribute('data-retained')).toBe('yes');
- expect(await page.locator('body').textContent()).not.toContain('SECRET_');
- await page.getByRole('link', { name: 'Home', exact: true }).click();
- await expect.poll(() => page.locator('h1').textContent()).toBe('Home page');
- }
- await page.goto(base + '/nested/deep/server');
- await page.waitForSelector('#app[data-hydrated="true"]');
- expect(await page.locator('h1').textContent()).toBe('Nested error');
- expect(await page.locator('body').textContent()).not.toContain('SECRET_');
- } catch (error) {
- console.error(framework, page.url(), errors);
- throw error;
- } finally {
- await page.close();
- }
- });
-
- it('refreshes a failed client page, preserves a common nested layout, and settles terminal navigation', async () => {
- const page = await browser.newPage();
- page.setDefaultTimeout(8_000);
- try {
- await page.goto(base);
- await page.waitForSelector('#app[data-hydrated="true"]');
- const visit = (url: string) =>
- page.evaluate(
- `window.testRouter.visit(${JSON.stringify(url)}).then(() => 'resolved', () => 'rejected')`,
- );
- await visit('/retry');
- await expect.poll(() => page.locator('h1').textContent()).toBe('Error page');
- await page.evaluate('window.recovered=true; window.testRouter.refresh()');
- await expect.poll(() => page.locator('h1').textContent()).toBe('Recovered page');
- for (const section of ['alpha', 'beta']) {
- await visit('/' + section);
- await expect.poll(() => page.locator('h1').textContent()).toBe(section + ' error');
- }
- await visit('/nested/healthy');
- await page
- .locator('section[data-layout="nested"]')
- .evaluate((el) => el.setAttribute('data-retained', 'yes'));
- await visit('/nested/other');
- expect(
- await page.locator('section[data-layout="nested"]').getAttribute('data-retained'),
- ).toBe('yes');
- await visit('/old-terminal');
- await expect.poll(() => page.locator('h1').textContent()).toBe('Something went wrong');
- expect(new URL(page.url()).pathname).toBe('/fatal/terminal');
- expect(new URL(page.url()).search).toBe('?from=old');
- expect(
- await page.getByRole('link', { name: 'Try again', exact: true }).getAttribute('href'),
- ).toBe(base + '/fatal/terminal?from=old');
- } finally {
- await page.close();
- }
- });
- it('hydrates retained layout islands in a server-only boundary document', async () => {
- const response = await fetch(base + '/islands');
- expect(response.status).toBe(404);
- const html = await response.text();
- expect(html).toContain('Missing island page');
- expect(html).not.toContain('__VOID_PAGE_DATA__');
- const page = await browser.newPage();
- try {
- await page.goto(base + '/islands');
- await page.waitForSelector('[data-island][data-hydrated="true"]');
- await page.getByRole('button', { name: 'Count: 0', exact: true }).click();
- await expect.poll(() => page.getByRole('button').textContent()).toBe('Count: 1');
- } finally {
- await page.close();
- }
- });
-
- it('refreshes boundary metadata when files are added and removed during development', async () => {
- await killChild(child);
- write('public/download', 'Download bytes');
- const dev = await startServer(
- (port) =>
- (child = spawn(
- 'vp',
- ['dev', '--host', '127.0.0.1', '--port', String(port), '--strictPort'],
- {
- cwd: fixture.root,
- stdio: ['ignore', 'pipe', 'pipe'],
- env: { ...process.env, NODE_ENV: 'development' },
- },
- )),
- 30_000,
- );
- try {
- const download = await fetch(dev.base + '/download');
- expect(download.status).toBe(200);
- expect(await download.text()).toBe('Download bytes');
- const missing = await fetch(dev.base + '/hmr');
- expect(missing.status).toBe(404);
- expect(await missing.text()).toContain('Missing page');
- const file = `pages/hmr/_not-found.${extension}`;
- write(file, component('HMR missing page
'));
- await expect
- .poll(async () => (await fetch(dev.base + '/hmr')).text(), { timeout: 10_000 })
- .toContain('HMR missing page');
- rmSync(join(fixture.root, file));
- await expect
- .poll(async () => (await fetch(dev.base + '/hmr')).text(), { timeout: 10_000 })
- .not.toContain('HMR missing page');
- const updated = await fetch(dev.base + '/hmr');
- expect(updated.status).toBe(404);
- expect(await updated.text()).toContain('Missing page');
- } finally {
- await killChild(child);
- rmSync(join(fixture.root, 'public/download'));
- }
-
- write('public/404.html', 'Static fallback
');
- write(
- 'void.config.ts',
- "import { defineConfig } from 'void/config'; export default defineConfig({target:'node',routing:{trailingSlash:true}});",
- );
- const trailing = await startServer(
- (port) =>
- (child = spawn(
- 'vp',
- ['dev', '--host', '127.0.0.1', '--port', String(port), '--strictPort'],
- {
- cwd: fixture.root,
- stdio: ['ignore', 'pipe', 'pipe'],
- env: { ...process.env, NODE_ENV: 'development' },
- },
- )),
- 30_000,
- );
- const page = await browser.newPage();
- try {
- const module = await fetch(trailing.base + '/pages/index.' + extension);
- expect(module.status).toBe(200);
- expect(await module.text()).not.toContain('Static fallback');
- await page.goto(trailing.base);
- await page.waitForSelector('#app[data-hydrated="true"]');
- await page.getByRole('link', { name: 'Returned', exact: true }).click();
- await expect.poll(() => page.locator('h1').textContent()).toBe('Missing page');
- } finally {
- await page.close();
- await killChild(child);
- rmSync(join(fixture.root, 'public/404.html'));
- }
- });
- it('generates a server-only static 404 without request middleware or hydration data', async () => {
- await killChild(child);
- for (const path of [
- 'pages/hmr',
- 'pages/alpha',
- 'pages/beta',
- 'pages/fatal',
- 'pages/retry.' + extension,
- 'pages/islands',
- 'pages/nested',
- 'pages/crash.' + extension,
- 'pages/client-only.' + extension,
- 'pages/client-only.server.ts',
- 'pages/items',
- 'pages/falsy.' + extension,
- 'pages/island-falsy.island.' + extension,
- ]) {
- rmSync(join(fixture.root, path), { recursive: true, force: true });
- }
- write(
- 'void.config.ts',
- "import { defineConfig } from 'void/config'; export default defineConfig({target:'node',output:'static'});",
- );
- execFileSync('vp', ['build'], {
- cwd: fixture.root,
- stdio: 'pipe',
- timeout: 60_000,
- env: { ...process.env, NODE_ENV: 'production' },
- });
- const html = readFileSync(join(fixture.root, 'dist/client/404.html'), 'utf8');
- expect(html).toContain('Missing page');
- expect(html).toContain('data-layout="root"');
- expect(html).toContain('stylesheet');
- expect(html).not.toContain('__VOID_PAGE_DATA__');
- expect(html).not.toContain('type="module"');
- expect(html).not.toContain('alice');
- expect(existsSync(join(fixture.root, 'dist/client/_void/pages/404.json'))).toBe(false);
- if (framework === 'react') {
- rmSync(join(fixture.root, 'pages/index.tsx'));
- write(
- 'void.config.ts',
- "import { defineConfig } from 'void/config'; export default defineConfig({target:'cloudflare',output:'static'});",
- );
- execFileSync('vp', ['build'], {
- cwd: fixture.root,
- stdio: 'pipe',
- timeout: 60_000,
- env: { ...process.env, NODE_ENV: 'production' },
- });
- const native404 = readFileSync(join(fixture.root, 'dist/client/404.html'), 'utf8');
- expect(native404).toContain('Missing page');
- expect(native404).not.toContain('__VOID_PAGE_DATA__');
- expect(native404).not.toContain('type="module"');
- }
- });
- });
-}
diff --git a/packages/void/test/integration/page-errors.test.ts b/packages/void/test/integration/page-errors.test.ts
new file mode 100644
index 000000000..5c284eef7
--- /dev/null
+++ b/packages/void/test/integration/page-errors.test.ts
@@ -0,0 +1,711 @@
+import { execFileSync } from 'node:child_process';
+import {
+ mkdirSync,
+ rmSync,
+ writeFileSync,
+ symlinkSync,
+ realpathSync,
+ existsSync,
+ readFileSync,
+} from 'node:fs';
+import { join } from 'node:path';
+import spawn from 'cross-spawn';
+import type { Browser } from 'playwright';
+import { afterAll, beforeAll, describe, expect, it } from 'vite-plus/test';
+import {
+ createIsolatedPlayground,
+ killChild,
+ startServer,
+ type IsolatedPlayground,
+} from '../../../../test/integration-helpers.ts';
+import { launchPagesBrowser } from '../../../../test/pages-browser.ts';
+import { PAGES_PROTOCOL_VERSION } from '../../../edge/src/pages-protocol.ts';
+import { deserializePageData } from '../../src/pages/serialize.ts';
+
+const repository = join(import.meta.dirname, '../../../..');
+const frameworks = ['react', 'vue', 'svelte', 'solid'] as const;
+
+describe.each(frameworks)('Pages errors with %s', (framework) => {
+ let fixture: IsolatedPlayground;
+ let child: ReturnType;
+ let browser: Browser;
+ let base: string;
+ const extension = framework === 'vue' ? 'vue' : framework === 'svelte' ? 'svelte' : 'tsx';
+ function write(path: string, source: string) {
+ const file = join(fixture.root, path);
+ mkdirSync(join(file, '..'), { recursive: true });
+ writeFileSync(file, source);
+ }
+ function component(content: string, script = '', layout = false) {
+ if (framework === 'vue') {
+ return `${content}${layout ? '' : ''}`;
+ }
+ if (framework === 'svelte') {
+ return `${content}${layout ? '{@render children?.()}' : ''}`;
+ }
+ return `import { Link, useShared, useParams, useRouter } from '@void/${framework}'; export default function Component(props) { const shared = useShared(); const params = useParams(); const error = props.error; ${script} return <>${content}${layout ? '{props.children}' : ''}>; }`;
+ }
+ beforeAll(async () => {
+ fixture = createIsolatedPlayground(
+ repository,
+ framework === 'react' ? 'playground/node-app' : `playground/${framework}-pages`,
+ );
+ const nodeServer = join(fixture.root, 'node_modules/@hono/node-server');
+ if (!existsSync(nodeServer)) {
+ mkdirSync(join(nodeServer, '..'), { recursive: true });
+ symlinkSync(
+ realpathSync(join(repository, 'playground/node-app/node_modules/@hono/node-server')),
+ nodeServer,
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+ }
+ for (const dir of ['pages', 'routes', 'middleware', 'db']) {
+ rmSync(join(fixture.root, dir), { recursive: true, force: true });
+ }
+ write(
+ 'tsconfig.json',
+ JSON.stringify({
+ compilerOptions: {
+ target: 'ESNext',
+ module: 'ESNext',
+ moduleResolution: 'bundler',
+ jsx: 'preserve',
+ },
+ }),
+ );
+ write(
+ 'void.config.ts',
+ `import { defineConfig } from 'void/config'; export default defineConfig({target:'node',head:{titleTemplate:'%s | Error tests'}});`,
+ );
+ write(
+ 'middleware/shared.ts',
+ `import { defineMiddleware } from 'void/handler'; export default defineMiddleware(async (c,next)=>{c.set('shared',{viewer:'alice',...(c.req.header('X-Test-No-Root') ? { noRoot: true } : {})}); c.header('X-Security','retained'); const guard=c.req.header('X-Test-Guard'); if(guard==='not-found') return c.notFound(); if(guard==='explicit') return c.text('Hidden by guard',404); await next(); if(guard==='after-not-found') c.res=await c.notFound();});`,
+ );
+ write('pages/style.css', 'nav { color: rgb(20, 80, 100); }');
+ write(
+ 'middleware/status.ts',
+ `import { defineMiddleware } from 'void/handler';
+import { HTTPException } from 'hono/http-exception';
+export default defineMiddleware(async (c, next) => {
+ const status = c.req.header('X-Test-Error-Status');
+ if (status === '403' || status === '503') {
+ c.header('Retry-After', '120');
+ throw new HTTPException(status === '403' ? 403 : 503, {
+ message: status === '403' ? 'Your account is banned' : 'Down for maintenance',
+ });
+ }
+ await next();
+});`,
+ );
+ const nav =
+ '';
+ let rootLayout = component(nav, '', true);
+ if (framework === 'vue' || framework === 'svelte') {
+ rootLayout = rootLayout
+
+ .replace('import { Link,', "import './style.css'; import { Link,");
+ } else {
+ rootLayout = `import './style.css'; ${rootLayout}`;
+ }
+ write(`pages/layout.${extension}`, rootLayout);
+ write(
+ `pages/index.${extension}`,
+ component(
+ 'Home page
',
+ "const router = useRouter(); if(typeof window!=='undefined') window.testRouter=router;",
+ ),
+ );
+ write(
+ `pages/_not-found.${extension}`,
+ component(
+ 'Missing page
{error.message}
',
+ "if(shared.noRoot) throw new Error('UNUSED_ROOT_BOUNDARY');",
+ ),
+ );
+ write(`pages/_error.${extension}`, component('Error page
{error.message}
'));
+ if (framework === 'vue') {
+ write(
+ `pages/_not-found.${extension}`,
+ component(
+ 'Missing page
{{error.message}}
',
+ "if(shared.noRoot) throw new Error('UNUSED_ROOT_BOUNDARY');",
+ ),
+ );
+ write(`pages/_error.${extension}`, component('Error page
{{error.message}}
'));
+ }
+ write(`pages/items/[id].${extension}`, component('Item
'));
+ write(`pages/status/[code].${extension}`, component('Status page
'));
+ write(
+ 'pages/status/[code].server.ts',
+ `import { defineHandler } from 'void/handler';
+export const loader = defineHandler(c => {
+ c.status(c.req.param('code') === '403' ? 403 : 503);
+ c.header('Retry-After', '120');
+ return {};
+});`,
+ );
+ for (const name of ['falsy', 'island-falsy.island']) {
+ write(`pages/${name}.${extension}`, component('Broken view
', 'throw undefined;'));
+ }
+ write(
+ 'pages/items/[id].server.ts',
+ `import { defineHandler } from 'void/handler'; import { HTTPException } from 'hono/http-exception'; export const loader = defineHandler(c=>{const id=c.req.param('id'); if(id==='returned') return c.notFound(); if(id==='thrown') throw new HTTPException(404,{message:'Deleted item'}); if(id==='unexpected') throw Object.assign(new Error('SECRET_SERVER_MARKER'),{secret:'SECRET_CUSTOM_MARKER'}); return {};});`,
+ );
+ write(
+ `pages/crash.${extension}`,
+ component(
+ 'Crash route
',
+ `if(typeof window!=='undefined') throw new Error('SECRET_CLIENT_MARKER');`,
+ ),
+ );
+ write(
+ `pages/nested/layout.${extension}`,
+ component(
+ '',
+ "if(params.kind==='layout') throw new Error('SECRET_LAYOUT_MARKER');",
+ true,
+ ),
+ );
+ write(`pages/nested/_error.${extension}`, component('Nested error
'));
+ write(
+ `pages/nested/deep/_error.${extension}`,
+ component('Broken fallback
', "throw new Error('SECRET_FALLBACK_MARKER');"),
+ );
+ for (const prefix of ['nested', 'nested/deep']) {
+ write(
+ `pages/${prefix}/[kind].${extension}`,
+ component(
+ 'Nested route
',
+ "if(params.kind==='server'||(params.kind!=='healthy'&&typeof window!=='undefined')) throw new Error('SECRET_RENDER_MARKER');",
+ ),
+ );
+ }
+ write(
+ `pages/client-only.${extension}`,
+ component(
+ 'Client only
',
+ "if(typeof window==='undefined') throw new Error('SECRET_SSR_DISABLED');",
+ ),
+ );
+ write(
+ 'pages/client-only.server.ts',
+ 'export const ssr = false; export const loader = () => new Response(null,{status:404});',
+ );
+ write(
+ `pages/retry.${extension}`,
+ component(
+ 'Recovered page
',
+ "if(typeof window!=='undefined'&&!window.recovered) throw new Error('SECRET_RETRY');",
+ ),
+ );
+ write(
+ `pages/fatal/[kind].${extension}`,
+ component(
+ 'Fatal route
',
+ "if(typeof window!=='undefined') throw new Error('SECRET_FATAL');",
+ ),
+ );
+ write(
+ 'routes/old-terminal.ts',
+ "export default (c) => c.redirect('/fatal/terminal?from=old');",
+ );
+ write(
+ `pages/_error.${extension}`,
+ component(
+ framework === 'vue'
+ ? 'Error page
{{error.message}}
'
+ : 'Error page
{error.message}
',
+ "if(params.kind==='terminal') throw new Error('SECRET_TERMINAL');",
+ ),
+ );
+ write(`pages/nested/other.${extension}`, component('Other nested page
'));
+ write(`pages/islands/index.island.${extension}`, component('Island document
'));
+ write('pages/islands/index.server.ts', 'export const loader = c => c.notFound();');
+ write(`pages/islands/_not-found.${extension}`, component('Missing island page
'));
+ const counter =
+ framework === 'react'
+ ? "import {useState} from 'react'; export default function Counter(){const [n,setN]=useState(0);return }"
+ : framework === 'solid'
+ ? "import {createSignal} from 'solid-js'; export default function Counter(){const [n,setN]=createSignal(0);return }"
+ : framework === 'vue'
+ ? ''
+ : '';
+ write(`pages/islands/_Counter.${extension}`, counter);
+ let islandLayout = component('', '', true);
+ const counterImport = `import Counter from './_Counter.${extension}' with {island:'load'};`;
+ islandLayout =
+ framework === 'vue' || framework === 'svelte'
+ ? islandLayout.replace('import { Link,', counterImport + '\n import { Link,')
+ : counterImport + islandLayout;
+ write(`pages/islands/layout.island.${extension}`, islandLayout);
+ for (const section of ['alpha', 'beta']) {
+ write(
+ `pages/${section}/index.${extension}`,
+ component(
+ 'Section page
',
+ "if(typeof window!=='undefined') throw new Error('SECRET_SECTION');",
+ ),
+ );
+ write(`pages/${section}/_error.${extension}`, component(`${section} error
`));
+ }
+ write(`pages/hmr/index.${extension}`, component('HMR route
'));
+ write(
+ 'pages/hmr/index.server.ts',
+ 'export const loader = () => new Response(null,{status:404});',
+ );
+ write('routes/api/missing.ts', `export const GET = c => c.text('API missing',404);`);
+ execFileSync('vp', ['build'], {
+ cwd: fixture.root,
+ stdio: 'pipe',
+ timeout: 60_000,
+ env: { ...process.env, NODE_ENV: 'production' },
+ });
+ const server = await startServer(
+ (port) =>
+ (child = spawn(process.execPath, ['dist/ssr/index.js'], {
+ cwd: fixture.root,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ env: { ...process.env, PORT: String(port) },
+ })),
+ 30_000,
+ );
+ base = server.base;
+ browser = await launchPagesBrowser();
+ }, 90_000);
+ afterAll(async () => {
+ await browser?.close();
+ if (child) {
+ await killChild(child);
+ }
+ fixture?.cleanup();
+ });
+ it.each(['not-found', 'after-not-found'])(
+ 'uses the root not-found for middleware guards (%s) and preserves explicit responses',
+ async (guard) => {
+ for (const pages of [false, true]) {
+ const headers = {
+ 'X-Test-Guard': guard,
+ ...(pages && { 'X-VoidPages': 'true', 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION }),
+ };
+ const response = await fetch(base + '/islands', { headers });
+ expect(response.status).toBe(404);
+ expect(response.headers.get('X-Security')).toBe('retained');
+ const body = await response.text();
+ if (pages) {
+ expect(response.headers.get('X-VoidPages')).toBe('true');
+ const data = deserializePageData<{ component: string }>(body);
+ expect(data.component).toContain('_void:boundary:root-not-found:');
+ expect(data).toMatchObject({
+ props: { error: { status: 404, message: 'Not Found' } },
+ shared: { viewer: 'alice' },
+ });
+ } else {
+ expect(body).toContain('Missing page');
+ expect(body).toContain('data-layout="root"');
+ expect(body).not.toContain('Missing island page');
+ }
+ const explicit = await fetch(base + '/islands', {
+ headers: { ...headers, 'X-Test-Guard': 'explicit' },
+ });
+ expect(explicit.status).toBe(404);
+ expect(explicit.headers.has('X-VoidPages')).toBe(false);
+ expect(await explicit.text()).toBe('Hidden by guard');
+ }
+ },
+ );
+
+ it('renders a loader not-found without attempting an unused root boundary', async () => {
+ const response = await fetch(base + '/islands', { headers: { 'X-Test-No-Root': 'true' } });
+ expect(response.status).toBe(404);
+ expect(await response.text()).toContain('Missing island page');
+ });
+
+ it.each(
+ ([403, 503] as const).flatMap((status) =>
+ (['HTML', 'Pages JSON'] as const).map((format) => ({ status, format })),
+ ),
+ )(
+ 'renders middleware errors through the root page boundary with HTTP $status ($format)',
+ async ({ status, format }) => {
+ const message = status === 403 ? 'Your account is banned' : 'Down for maintenance';
+ // This route throws a different error if its loader is reached.
+ const response = await fetch(base + '/items/unexpected', {
+ headers: {
+ 'X-Test-Error-Status': String(status),
+ ...(format === 'Pages JSON'
+ ? { 'X-VoidPages': 'true', 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION }
+ : { Accept: 'text/html' }),
+ },
+ });
+ const body = await response.text();
+ expect(response.status).toBe(status);
+ expect(body).not.toContain('SECRET_');
+ if (format === 'Pages JSON') {
+ expect(response.headers.get('X-VoidPages')).toBe('true');
+ expect(deserializePageData(body)).toMatchObject({
+ props: { error: { status, message } },
+ shared: { viewer: 'alice' },
+ url: '/items/unexpected',
+ });
+ } else {
+ expect(response.headers.get('Content-Type')).toContain('text/html');
+ expect(body).toContain('Error page');
+ expect(body).toContain(message);
+ expect(body).toContain('data-layout="root"');
+ expect(body).toContain('stylesheet');
+ }
+ expect(response.headers.get('Retry-After')).toBe('120');
+ expect(response.headers.get('X-Security')).toBe('retained');
+ expect(response.headers.get('Cache-Control')).toBe('no-store');
+ },
+ );
+
+ it('returns status-correct documents and marked error payloads without exposing secrets', async () => {
+ for (const [path, status] of [
+ ['/unknown', 404],
+ ['/items/returned', 404],
+ ['/items/thrown', 404],
+ ['/items/unexpected', 500],
+ ] as const) {
+ for (const pages of [false, true]) {
+ const response = await fetch(base + path, {
+ headers: pages
+ ? { 'X-VoidPages': 'true', 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION }
+ : { Accept: 'text/html' },
+ });
+ expect(response.status, path).toBe(status);
+ expect(response.headers.get('Cache-Control')).toBe('no-store');
+ expect(response.headers.get('X-Security')).toBe('retained');
+ const text = await response.text();
+ expect(text).not.toContain('SECRET_');
+ const title = `${status === 404 ? 'Not Found' : 'Internal Server Error'} | Error tests`;
+ if (pages) {
+ expect(response.headers.get('X-VoidPages')).toBe('true');
+ expect(deserializePageData(text)).toMatchObject({
+ url: path,
+ shared: { viewer: 'alice' },
+ props: { error: { status } },
+ head: { title },
+ });
+ } else {
+ expect(text).toContain('data-layout="root"');
+ expect(text).toContain(`${title}`);
+ }
+ }
+ }
+ for (const path of [
+ '/nested/server',
+ '/nested/deep/server',
+ '/nested/layout',
+ '/falsy',
+ '/island-falsy',
+ ]) {
+ const document = await fetch(base + path);
+ expect(document.status, path).toBe(500);
+ const html = await document.text();
+ expect(html).toContain(
+ path.endsWith('/layout') || path.includes('falsy') ? 'Error page' : 'Nested error',
+ );
+ expect(html).not.toContain('SECRET_');
+ }
+ const response = await fetch(base + '/api/missing');
+ expect(response.status).toBe(404);
+ expect(await response.text()).toBe('API missing');
+ });
+ it('renders application-defined error statuses on document loads and client visits', async () => {
+ const page = await browser.newPage();
+ page.setDefaultTimeout(8_000);
+ try {
+ for (const status of [403, 503]) {
+ const path = `/status/${status}`;
+ const documentResponse = await fetch(base + path);
+ expect(documentResponse.status).toBe(status);
+ expect(documentResponse.headers.get('Retry-After')).toBe('120');
+ expect(await documentResponse.text()).toContain('Status page');
+
+ await page.goto(base);
+ await page.waitForSelector('#app[data-hydrated="true"]');
+ await page.evaluate(() =>
+ document.querySelector('nav')!.setAttribute('data-retained', 'yes'),
+ );
+ const navigation = page.waitForResponse(
+ (response) =>
+ response.url() === base + path &&
+ response.request().headers()['x-voidpages'] === 'true',
+ );
+ await page.evaluate(`window.testRouter.visit(${JSON.stringify(path)})`);
+ const response = await navigation;
+ expect(response.status()).toBe(status);
+ expect(response.headers()['x-voidpages']).toBe('true');
+ await expect.poll(() => page.locator('h1').textContent()).toBe('Status page');
+ expect(await page.locator('nav').getAttribute('data-retained')).toBe('yes');
+ }
+ } finally {
+ await page.close();
+ }
+ });
+
+ it('keeps the app and outer layout mounted across 404s and client errors', async () => {
+ const page = await browser.newPage();
+ const errors: Array = [];
+ page.on('pageerror', (e) => errors.push(e.stack ?? e.message));
+ page.on('console', (m) => {
+ if (m.type() === 'error') {
+ errors.push(m.text());
+ }
+ });
+ page.setDefaultTimeout(8_000);
+ try {
+ await page.goto(base);
+ await page.waitForSelector('#app[data-hydrated="true"]');
+ await page.evaluate(() => {
+ (window as unknown as { marker: boolean }).marker = true;
+ document.querySelector('nav')!.setAttribute('data-retained', 'yes');
+ });
+ for (const name of ['Returned', 'Thrown', 'Unexpected', 'Crash']) {
+ await page.getByRole('link', { name, exact: true }).click();
+ await expect
+ .poll(() => page.locator('h1').textContent())
+ .toBe(name === 'Returned' || name === 'Thrown' ? 'Missing page' : 'Error page');
+ if (name !== 'Crash') {
+ await expect
+ .poll(() => page.title())
+ .toBe(`${name === 'Unexpected' ? 'Internal Server Error' : 'Not Found'} | Error tests`);
+ }
+ expect(await page.evaluate(() => (window as unknown as { marker: boolean }).marker)).toBe(
+ true,
+ );
+ expect(await page.locator('nav').getAttribute('data-retained')).toBe('yes');
+ expect(await page.locator('body').textContent()).not.toContain('SECRET_');
+ }
+ } catch (error) {
+ console.error(framework, page.url(), errors);
+ throw error;
+ } finally {
+ await page.close();
+ }
+ });
+ it('escalates failed fallbacks and layouts while retaining healthy ancestors', async () => {
+ const page = await browser.newPage();
+ const errors: Array = [];
+ page.on('pageerror', (e) => errors.push(e.stack ?? e.message));
+ page.on('console', (m) => {
+ if (m.type() === 'error') {
+ errors.push(m.text());
+ }
+ });
+ page.setDefaultTimeout(8_000);
+ try {
+ await page.goto(base);
+ await page.waitForSelector('#app[data-hydrated="true"]');
+ await page.evaluate(() =>
+ document.querySelector('nav')!.setAttribute('data-retained', 'yes'),
+ );
+ for (const [link, expected] of [
+ ['Nested', 'Nested error'],
+ ['Deep', 'Nested error'],
+ ['Layout', 'Error page'],
+ ['Client only', 'Missing page'],
+ ]) {
+ await page.getByRole('link', { name: link, exact: true }).click();
+ await expect.poll(() => page.locator('h1').textContent()).toBe(expected);
+ expect(await page.locator('nav').getAttribute('data-retained')).toBe('yes');
+ expect(await page.locator('body').textContent()).not.toContain('SECRET_');
+ await page.getByRole('link', { name: 'Home', exact: true }).click();
+ await expect.poll(() => page.locator('h1').textContent()).toBe('Home page');
+ }
+ await page.goto(base + '/nested/deep/server');
+ await page.waitForSelector('#app[data-hydrated="true"]');
+ expect(await page.locator('h1').textContent()).toBe('Nested error');
+ expect(await page.locator('body').textContent()).not.toContain('SECRET_');
+ } catch (error) {
+ console.error(framework, page.url(), errors);
+ throw error;
+ } finally {
+ await page.close();
+ }
+ });
+
+ it('refreshes a failed client page, preserves a common nested layout, and settles terminal navigation', async () => {
+ const page = await browser.newPage();
+ page.setDefaultTimeout(8_000);
+ try {
+ await page.goto(base);
+ await page.waitForSelector('#app[data-hydrated="true"]');
+ const visit = (url: string) =>
+ page.evaluate(
+ `window.testRouter.visit(${JSON.stringify(url)}).then(() => 'resolved', () => 'rejected')`,
+ );
+ await visit('/retry');
+ await expect.poll(() => page.locator('h1').textContent()).toBe('Error page');
+ await page.evaluate('window.recovered=true; window.testRouter.refresh()');
+ await expect.poll(() => page.locator('h1').textContent()).toBe('Recovered page');
+ for (const section of ['alpha', 'beta']) {
+ await visit('/' + section);
+ await expect.poll(() => page.locator('h1').textContent()).toBe(section + ' error');
+ }
+ await visit('/nested/healthy');
+ await page
+ .locator('section[data-layout="nested"]')
+ .evaluate((el) => el.setAttribute('data-retained', 'yes'));
+ await visit('/nested/other');
+ expect(
+ await page.locator('section[data-layout="nested"]').getAttribute('data-retained'),
+ ).toBe('yes');
+ await visit('/old-terminal');
+ await expect.poll(() => page.locator('h1').textContent()).toBe('Something went wrong');
+ expect(new URL(page.url()).pathname).toBe('/fatal/terminal');
+ expect(new URL(page.url()).search).toBe('?from=old');
+ expect(
+ await page.getByRole('link', { name: 'Try again', exact: true }).getAttribute('href'),
+ ).toBe(base + '/fatal/terminal?from=old');
+ } finally {
+ await page.close();
+ }
+ });
+ it('hydrates retained layout islands in a server-only boundary document', async () => {
+ const response = await fetch(base + '/islands');
+ expect(response.status).toBe(404);
+ const html = await response.text();
+ expect(html).toContain('Missing island page');
+ expect(html).not.toContain('__VOID_PAGE_DATA__');
+ const page = await browser.newPage();
+ try {
+ await page.goto(base + '/islands');
+ await page.waitForSelector('[data-island][data-hydrated="true"]');
+ await page.getByRole('button', { name: 'Count: 0', exact: true }).click();
+ await expect.poll(() => page.getByRole('button').textContent()).toBe('Count: 1');
+ } finally {
+ await page.close();
+ }
+ });
+
+ it('refreshes boundary metadata when files are added and removed during development', async () => {
+ await killChild(child);
+ write('public/download', 'Download bytes');
+ const dev = await startServer(
+ (port) =>
+ (child = spawn(
+ 'vp',
+ ['dev', '--host', '127.0.0.1', '--port', String(port), '--strictPort'],
+ {
+ cwd: fixture.root,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ env: { ...process.env, NODE_ENV: 'development' },
+ },
+ )),
+ 30_000,
+ );
+ try {
+ const download = await fetch(dev.base + '/download');
+ expect(download.status).toBe(200);
+ expect(await download.text()).toBe('Download bytes');
+ const missing = await fetch(dev.base + '/hmr');
+ expect(missing.status).toBe(404);
+ expect(await missing.text()).toContain('Missing page');
+ const file = `pages/hmr/_not-found.${extension}`;
+ write(file, component('HMR missing page
'));
+ await expect
+ .poll(async () => (await fetch(dev.base + '/hmr')).text(), { timeout: 10_000 })
+ .toContain('HMR missing page');
+ rmSync(join(fixture.root, file));
+ await expect
+ .poll(async () => (await fetch(dev.base + '/hmr')).text(), { timeout: 10_000 })
+ .not.toContain('HMR missing page');
+ const updated = await fetch(dev.base + '/hmr');
+ expect(updated.status).toBe(404);
+ expect(await updated.text()).toContain('Missing page');
+ } finally {
+ await killChild(child);
+ rmSync(join(fixture.root, 'public/download'));
+ }
+
+ write('public/404.html', 'Static fallback
');
+ write(
+ 'void.config.ts',
+ "import { defineConfig } from 'void/config'; export default defineConfig({target:'node',routing:{trailingSlash:true}});",
+ );
+ const trailing = await startServer(
+ (port) =>
+ (child = spawn(
+ 'vp',
+ ['dev', '--host', '127.0.0.1', '--port', String(port), '--strictPort'],
+ {
+ cwd: fixture.root,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ env: { ...process.env, NODE_ENV: 'development' },
+ },
+ )),
+ 30_000,
+ );
+ const page = await browser.newPage();
+ try {
+ const module = await fetch(trailing.base + '/pages/index.' + extension);
+ expect(module.status).toBe(200);
+ expect(await module.text()).not.toContain('Static fallback');
+ await page.goto(trailing.base);
+ await page.waitForSelector('#app[data-hydrated="true"]');
+ await page.getByRole('link', { name: 'Returned', exact: true }).click();
+ await expect.poll(() => page.locator('h1').textContent()).toBe('Missing page');
+ } finally {
+ await page.close();
+ await killChild(child);
+ rmSync(join(fixture.root, 'public/404.html'));
+ }
+ });
+ it('generates a server-only static 404 without request middleware or hydration data', async () => {
+ await killChild(child);
+ for (const path of [
+ 'pages/hmr',
+ 'pages/alpha',
+ 'pages/beta',
+ 'pages/fatal',
+ 'pages/retry.' + extension,
+ 'pages/islands',
+ 'pages/nested',
+ 'pages/crash.' + extension,
+ 'pages/client-only.' + extension,
+ 'pages/client-only.server.ts',
+ 'pages/items',
+ 'pages/falsy.' + extension,
+ 'pages/island-falsy.island.' + extension,
+ ]) {
+ rmSync(join(fixture.root, path), { recursive: true, force: true });
+ }
+ write(
+ 'void.config.ts',
+ "import { defineConfig } from 'void/config'; export default defineConfig({target:'node',output:'static'});",
+ );
+ execFileSync('vp', ['build'], {
+ cwd: fixture.root,
+ stdio: 'pipe',
+ timeout: 60_000,
+ env: { ...process.env, NODE_ENV: 'production' },
+ });
+ const html = readFileSync(join(fixture.root, 'dist/client/404.html'), 'utf8');
+ expect(html).toContain('Missing page');
+ expect(html).toContain('data-layout="root"');
+ expect(html).toContain('stylesheet');
+ expect(html).not.toContain('__VOID_PAGE_DATA__');
+ expect(html).not.toContain('type="module"');
+ expect(html).not.toContain('alice');
+ expect(existsSync(join(fixture.root, 'dist/client/_void/pages/404.json'))).toBe(false);
+ if (framework === 'react') {
+ rmSync(join(fixture.root, 'pages/index.tsx'));
+ write(
+ 'void.config.ts',
+ "import { defineConfig } from 'void/config'; export default defineConfig({target:'cloudflare',output:'static'});",
+ );
+ execFileSync('vp', ['build'], {
+ cwd: fixture.root,
+ stdio: 'pipe',
+ timeout: 60_000,
+ env: { ...process.env, NODE_ENV: 'production' },
+ });
+ const native404 = readFileSync(join(fixture.root, 'dist/client/404.html'), 'utf8');
+ expect(native404).toContain('Missing page');
+ expect(native404).not.toContain('__VOID_PAGE_DATA__');
+ expect(native404).not.toContain('type="module"');
+ }
+ });
+});
diff --git a/packages/void/test/integration/pg-api-test.test.ts b/packages/void/test/integration/pg-api-test.test.ts
index f9cfaea7f..3f94d647b 100644
--- a/packages/void/test/integration/pg-api-test.test.ts
+++ b/packages/void/test/integration/pg-api-test.test.ts
@@ -1,4 +1,4 @@
-import { type ChildProcess } from 'node:child_process';
+import { execSync, type ChildProcess } from 'node:child_process';
import { once } from 'node:events';
import { rmSync, unlinkSync, writeFileSync } from 'node:fs';
import type { AddressInfo } from 'node:net';
@@ -7,7 +7,6 @@ import { PGlite } from '@electric-sql/pglite';
import { createServer } from 'pglite-server';
import { afterAll, beforeAll, describe, expect, it } from 'vite-plus/test';
import {
- buildPlayground,
killChild,
spawnPlaygroundServer,
startServer,
@@ -100,7 +99,7 @@ describe('playground/pg-api-test', () => {
it('queries PostgreSQL through void/db and createDb in the built Worker', async () => {
rmSync(join(PLAYGROUND, 'dist'), { recursive: true, force: true });
- buildPlayground(ROOT, 'pg-api-test');
+ execSync('vp run --filter ./playground/pg-api-test build', { cwd: ROOT, stdio: 'pipe' });
const server = await start('preview');
try {
await expectUsers(server);
diff --git a/packages/void/test/integration/plugin-cloudflare-v2.test.ts b/packages/void/test/integration/plugin-cloudflare-v2.test.ts
index cef88af20..075bc9b48 100644
--- a/packages/void/test/integration/plugin-cloudflare-v2.test.ts
+++ b/packages/void/test/integration/plugin-cloudflare-v2.test.ts
@@ -219,7 +219,6 @@ export default {
vi.stubEnv('WRANGLER_DOCKER_BIN', docker);
const plugins = () =>
cloudflare({
- inspectorPort: false,
config: () => ({
name: 'container-app',
main: 'worker.js',
diff --git a/packages/void/test/integration/react-router.test.ts b/packages/void/test/integration/react-router.test.ts
index 6c9238829..31ab5102e 100644
--- a/packages/void/test/integration/react-router.test.ts
+++ b/packages/void/test/integration/react-router.test.ts
@@ -213,7 +213,7 @@ export async function loader() {
it('generates route types from scratch and queries MySQL in the built Worker', async () => {
// The dev server generates these too, so do not let the previous test mask a missing build step.
rmSync(join(playground.root, '.react-router'), { recursive: true, force: true });
- execFileSync('vp', ['run', '--ignore-depends-on', '--no-cache', 'build'], {
+ execFileSync('vp', ['run', 'build'], {
cwd: playground.root,
stdio: 'pipe',
env: { ...process.env, VOID_INSPECTOR_PORT: 'false' },
diff --git a/packages/void/test/integration/server-auth-errors-session.test.ts b/packages/void/test/integration/server-auth-errors-session.test.ts
deleted file mode 100644
index aaecc36cc..000000000
--- a/packages/void/test/integration/server-auth-errors-session.test.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import { defineServerAuthTests } from './server-auth-errors.cases.ts';
-
-defineServerAuthTests('session');
diff --git a/packages/void/test/integration/server-auth-errors-signed-in.test.ts b/packages/void/test/integration/server-auth-errors-signed-in.test.ts
deleted file mode 100644
index 50120fb82..000000000
--- a/packages/void/test/integration/server-auth-errors-signed-in.test.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import { defineServerAuthTests } from './server-auth-errors.cases.ts';
-
-defineServerAuthTests('signed-in');
diff --git a/packages/void/test/integration/server-auth-errors-signed-out.test.ts b/packages/void/test/integration/server-auth-errors-signed-out.test.ts
deleted file mode 100644
index 3204b8708..000000000
--- a/packages/void/test/integration/server-auth-errors-signed-out.test.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import { defineServerAuthTests } from './server-auth-errors.cases.ts';
-
-defineServerAuthTests('signed-out');
diff --git a/packages/void/test/integration/server-auth-errors.cases.ts b/packages/void/test/integration/server-auth-errors.cases.ts
deleted file mode 100644
index 1ae9f9d8c..000000000
--- a/packages/void/test/integration/server-auth-errors.cases.ts
+++ /dev/null
@@ -1,439 +0,0 @@
-import { join } from 'node:path';
-import spawn from 'cross-spawn';
-import type { Browser, BrowserContext, Page, Response } from 'playwright';
-import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from 'vite-plus/test';
-import { collectBrowserDiagnostics } from '../../../../test/browser-helpers.ts';
-import {
- createIsolatedPlayground,
- killChild,
- startServer,
- type IsolatedPlayground,
- type StartedServer,
-} from '../../../../test/integration-helpers.ts';
-import { launchPagesBrowser } from '../../../../test/pages-browser.ts';
-
-const ROOT = join(import.meta.dirname, '../../../..');
-const PLAYGROUND = 'playground/server-auth-errors';
-const EMAIL = 'demo@example.com';
-const guards = ['require-auth', 'return-redirect', 'throw-redirect', 'auth-redirect'] as const;
-const visits = ['Document load', 'Client navigation'] as const;
-const forms = ['Native form POST', 'Enhanced form POST'] as const;
-const pages = [
- { path: '/loaders/optional-user', status: 200, heading: 'Loader rendered the page' },
- { path: '/loaders/optional-session', status: 200, heading: 'Loader rendered the page' },
- { path: '/loaders/require-auth', status: 401, heading: 'Root error boundary' },
- { path: '/loaders/return-redirect', status: 302, heading: 'Sign in' },
- { path: '/loaders/throw-redirect', status: 302, heading: 'Sign in' },
- { path: '/loaders/auth-redirect', status: 302, heading: 'Sign in' },
- { path: '/loaders/not-found', status: 404, heading: 'Not-found boundary' },
- { path: '/loaders/unexpected', status: 500, heading: 'Root error boundary' },
- { path: '/middleware/require-auth', status: 401, heading: 'Root error boundary' },
- { path: '/middleware/return-redirect', status: 302, heading: 'Sign in' },
- { path: '/middleware/throw-redirect', status: 302, heading: 'Sign in' },
- { path: '/middleware/auth-redirect', status: 302, heading: 'Sign in' },
-] as const;
-
-export function defineServerAuthTests(group: 'signed-out' | 'signed-in' | 'session'): void {
- let playground: IsolatedPlayground;
- let server: StartedServer;
- let browser: Browser;
- let context: BrowserContext;
- let signedInState: Awaited>;
- let page: Page;
- let diagnostics: () => string;
-
- beforeAll(async () => {
- playground = createIsolatedPlayground(ROOT, PLAYGROUND);
- server = await startServer(
- (port) =>
- spawn('vp', ['dev', '--host', '127.0.0.1', '--port', String(port), '--strictPort'], {
- cwd: playground.root,
- stdio: ['ignore', 'pipe', 'pipe'],
- env: { ...process.env, VOID_INSPECTOR_PORT: 'false' },
- }),
- 60_000,
- { expectStatus: 200, expectBody: 'Server Auth Errors Example' },
- );
- browser = await launchPagesBrowser();
-
- // A fresh copy has its own D1 database. Create a real session once and
- // restore its cookies before each signed-in scenario.
- context = await browser.newContext();
- const response = await context.request.post(`${server.base}/api/demo-login`);
- expect(response.status(), await response.text()).toBe(200);
- const profile = await context.request.get(`${server.base}/api/profile`);
- expect(profile.status()).toBe(200);
- expect(await profile.json()).toEqual({ name: 'Demo user', email: EMAIL });
- signedInState = await context.storageState();
- });
-
- afterEach(async ({ task }) => {
- if (task.result?.state === 'fail') {
- console.error(`${diagnostics?.() ?? ''}\n${server?.output() ?? ''}`);
- }
- await page?.close();
- });
-
- afterAll(async () => {
- await browser?.close();
- if (server) {
- await killChild(server.child);
- }
- playground?.cleanup();
- });
-
- async function newPage(signedIn = false) {
- // Keep the dev server's connections and module cache across this large
- // matrix. Recreating the network context exhausts Chromium socket buffers
- // on Windows. Each test still gets a fresh page and reset browser storage.
- await context.setStorageState(signedIn ? signedInState : { cookies: [], origins: [] });
- page = await context.newPage();
- page.setDefaultTimeout(10_000);
- diagnostics = collectBrowserDiagnostics(page);
- }
-
- async function open(path = '/', signedIn = false) {
- const response = await page.goto(`${server.base}${path}`);
- expect(response?.status()).toBe(200);
- await page
- .getByRole('navigation')
- .getByRole('link', {
- name: signedIn ? 'Sign out' : 'Sign in',
- exact: true,
- })
- .waitFor();
- }
-
- async function markLayout() {
- await page
- .locator('header')
- .evaluate((header) => header.setAttribute('data-test-layout', 'retained'));
- return page.evaluate(() => performance.timeOrigin);
- }
-
- async function expectLayout(timeOrigin: number, retained: boolean) {
- expect((await page.evaluate(() => performance.timeOrigin)) === timeOrigin).toBe(retained);
- expect(await page.locator('header[data-test-layout="retained"]').count()).toBe(
- retained ? 1 : 0,
- );
- }
-
- function responseFor(path: string, method = 'GET') {
- return page.waitForResponse(
- (response) =>
- response.url() === `${server.base}${path}` && response.request().method() === method,
- );
- }
-
- async function expectRedirect(
- response: Response,
- destination: string,
- status: number,
- enhanced = false,
- ) {
- // Pages negotiates redirects as HTTP 200 so fetch can read Location (including
- // fragments). Document requests keep the original HTTP redirect status.
- expect(response.status()).toBe(enhanced ? 200 : status);
- expect(await response.request().headerValue('X-VoidPages-Redirect')).toBe(
- enhanced ? 'manual' : null,
- );
- expect(await response.headerValue('X-VoidPages-Redirect')).toBe(
- enhanced ? String(status) : null,
- );
- expect(await response.headerValue('location')).toBe(destination);
- await page.waitForURL(`${server.base}${destination}`);
- }
-
- if (group !== 'session') {
- describe(group === 'signed-in' ? 'server auth: signed in' : 'server auth: signed out', () => {
- const signedIn = group === 'signed-in';
- beforeEach(() => newPage(signedIn));
-
- describe.each(visits)('%s', (visit) => {
- it.each(pages)('handles $path', async ({ path, status, heading }) => {
- await open('/', signedIn);
- const timeOrigin = await markLayout();
- const pending = responseFor(path);
- await page.locator(`a[href="${path}"]`).filter({ hasText: visit }).click();
- const response = await pending;
- const expectedStatus = signedIn ? 200 : status;
- if (expectedStatus !== 302) {
- expect(response.status()).toBe(expectedStatus);
- }
-
- if (expectedStatus === 401) {
- expect(await response.headerValue('content-type')).toContain(
- visit === 'Client navigation' ? 'application/json' : 'text/html',
- );
- expect(await response.headerValue('X-VoidPages')).toBe(
- visit === 'Client navigation' ? 'true' : null,
- );
- expect(await response.headerValue('cache-control')).toBe('no-store');
- }
-
- if (expectedStatus === 302) {
- await expectRedirect(response, '/login', 302, visit === 'Client navigation');
- } else {
- await page.waitForURL(`${server.base}${path}`);
- }
- await page
- .getByRole('heading', {
- name: signedIn ? 'Loader rendered the page' : heading,
- exact: true,
- })
- .waitFor();
- await expectLayout(timeOrigin, visit === 'Client navigation');
-
- if (signedIn) {
- expect(await page.locator('main').innerText()).toContain(`Signed in as ${EMAIL}.`);
- if (path === '/loaders/optional-session') {
- expect(await page.locator('main').innerText()).toMatch(
- /Session expires: \d{4}-\d{2}-\d{2}T/,
- );
- }
- } else if (status === 401) {
- expect(await page.locator('main').innerText()).toContain('401: Unauthorized');
- } else if (status === 200) {
- expect(await page.locator('main').innerText()).toContain(
- 'Anonymous visitor: user is null.',
- );
- expect(await page.locator('main').innerText()).not.toContain('Session expires:');
- }
- });
- });
-
- describe.each(forms)('%s', (form) => {
- it.each(guards)('checks authentication for the %s action', async (guard) => {
- const path = `/actions/${guard}`;
- await open(path, signedIn);
- const timeOrigin = await markLayout();
- const pending = responseFor(path, 'POST');
- const destination = signedIn ? '/actions/success' : '/login';
- const followUp =
- signedIn || guard !== 'require-auth' ? responseFor(destination) : undefined;
- await page.getByRole('button', { name: form, exact: true }).click();
- const response = await pending;
-
- if (!signedIn && guard === 'require-auth') {
- expect(response.status()).toBe(401);
- expect(await response.text()).toBe('Unauthorized');
- if (form === 'Native form POST') {
- await expect.poll(() => page.locator('body').innerText()).toBe('Unauthorized');
- expect(await page.locator('header').count()).toBe(0);
- expect(await page.evaluate(() => performance.timeOrigin)).not.toBe(timeOrigin);
- } else {
- await expect
- .poll(() => page.getByRole('alert').innerText())
- .toBe('401: Unauthorized');
- expect(await page.getByRole('heading', { name: `Action: ${guard}` }).count()).toBe(1);
- await expectLayout(timeOrigin, true);
- }
- expect(page.url()).toBe(`${server.base}${path}`);
- return;
- }
-
- await expectRedirect(response, destination, 303, form === 'Enhanced form POST');
- expect((await followUp)?.status()).toBe(200);
- if (form === 'Native form POST') {
- expect(response.request().redirectedTo()?.method()).toBe('GET');
- }
- await page
- .getByRole('heading', {
- name: signedIn ? 'Action authorized' : 'Sign in',
- exact: true,
- })
- .waitFor();
- await expectLayout(timeOrigin, form === 'Enhanced form POST');
- });
- });
-
- it('returns the API profile as a document', async () => {
- await open('/', signedIn);
- const timeOrigin = await markLayout();
- const pending = responseFor('/api/profile');
- await page.locator('a[href="/api/profile"]').click();
- const response = await pending;
- expect(response.status()).toBe(signedIn ? 200 : 401);
- if (signedIn) {
- expect(await response.json()).toEqual({ name: 'Demo user', email: EMAIL });
- } else {
- expect(await response.text()).toBe('Unauthorized');
- }
- await page.waitForURL(`${server.base}/api/profile`);
- expect(await page.evaluate(() => performance.timeOrigin)).not.toBe(timeOrigin);
- expect(await page.locator('header').count()).toBe(0);
- });
-
- it('displays the API profile fetch result without navigating', async () => {
- await open('/', signedIn);
- const timeOrigin = await markLayout();
- await page.getByRole('button', { name: 'Fetch API response' }).click();
- const result = page.locator('#api').locator('..').getByRole('status');
- await expect.poll(() => result.innerText()).toContain(signedIn ? 'HTTP 200' : 'HTTP 401');
- expect(await result.innerText()).toContain(signedIn ? EMAIL : 'Unauthorized');
- expect(await result.innerText()).toContain(signedIn ? 'application/json' : 'text/plain');
- expect(page.url()).toBe(`${server.base}/`);
- await expectLayout(timeOrigin, true);
- });
- });
- }
-
- if (group === 'session') {
- describe('demo session and navigation', () => {
- beforeEach(() => newPage());
-
- it.each(['throw-redirect', 'auth-redirect'])(
- 'signs in after the %s guard and updates the auth links',
- async (guard) => {
- const destination = `/loaders/${guard}`;
- await open();
- const timeOrigin = await markLayout();
- await page
- .locator(`a[href="${destination}"]`)
- .filter({ hasText: 'Client navigation' })
- .click();
- await page.getByRole('heading', { name: 'Sign in', exact: true }).waitFor();
- expect(await page.getByLabel('Email', { exact: true }).inputValue()).toBe(EMAIL);
- expect(await page.getByLabel('Email', { exact: true }).isDisabled()).toBe(true);
- expect(await page.getByLabel('Password', { exact: true }).inputValue()).toBe(
- 'demo-password',
- );
- expect(await page.getByLabel('Password', { exact: true }).isDisabled()).toBe(true);
- await page.getByRole('button', { name: 'Sign in', exact: true }).click();
- await page
- .getByRole('heading', { name: 'Server Auth Errors Example', exact: true })
- .waitFor();
- expect(page.url()).toBe(`${server.base}/`);
- await page.getByRole('link', { name: 'Sign out', exact: true }).waitFor();
- await page
- .locator(`a[href="${destination}"]`)
- .filter({ hasText: 'Client navigation' })
- .click();
- await page.getByRole('heading', { name: 'Loader rendered the page' }).waitFor();
- expect(await page.getByRole('link', { name: 'Sign in', exact: true }).count()).toBe(0);
- await expectLayout(timeOrigin, true);
-
- await page.reload();
- await page.getByRole('link', { name: 'Sign out', exact: true }).waitFor();
- await page.getByRole('link', { name: 'Sign out', exact: true }).click();
- await page.getByRole('heading', { name: 'Sign in', exact: true }).waitFor();
- await page.getByRole('link', { name: 'Sign in', exact: true }).waitFor();
- expect(await page.getByRole('link', { name: 'Sign out', exact: true }).count()).toBe(0);
- expect((await page.request.get(`${server.base}/api/profile`)).status()).toBe(401);
- },
- );
-
- it('uses the demo credentials regardless of the submitted fields', async () => {
- const response = await page.request.post(`${server.base}/api/demo-login`, {
- data: { email: 'other@example.com', password: 'different-password' },
- });
- expect(response.status()).toBe(200);
- const profile = await page.request.get(`${server.base}/api/profile`);
- expect(await profile.json()).toEqual({ name: 'Demo user', email: EMAIL });
- });
-
- describe.each(forms)('%s after the session ends', (form) => {
- it.each(guards)('rechecks authentication for the %s action', async (guard) => {
- expect((await page.request.post(`${server.base}/api/demo-login`)).status()).toBe(200);
- const path = `/actions/${guard}`;
- await open(path, true);
- expect(await page.locator('main').innerText()).toContain(`Signed in as ${EMAIL}.`);
-
- // End the session without refreshing the already-rendered form.
- const signedOut = await page.request.post(`${server.base}/api/auth/sign-out`, {
- headers: { Origin: server.base },
- data: {},
- });
- expect(signedOut.status()).toBe(200);
- const pending = responseFor(path, 'POST');
- const followUp = guard !== 'require-auth' ? responseFor('/login') : undefined;
- await page.getByRole('button', { name: form, exact: true }).click();
- const response = await pending;
-
- if (guard === 'require-auth') {
- expect(response.status()).toBe(401);
- if (form === 'Native form POST') {
- await expect.poll(() => page.locator('body').innerText()).toBe('Unauthorized');
- } else {
- await expect
- .poll(() => page.getByRole('alert').innerText())
- .toBe('401: Unauthorized');
- }
- } else {
- await expectRedirect(response, '/login', 303, form === 'Enhanced form POST');
- expect((await followUp)?.status()).toBe(200);
- await page.getByRole('heading', { name: 'Sign in', exact: true }).waitFor();
- }
- expect(await page.getByRole('heading', { name: 'Action authorized' }).count()).toBe(0);
- });
- });
-
- it.each(['return-redirect', 'throw-redirect', 'auth-redirect'])(
- 'does not replay the %s action after login',
- async (guard) => {
- const path = `/actions/${guard}`;
- await open(path);
- const submissions: Array = [];
- page.on('request', (request) => {
- if (request.url() === `${server.base}${path}` && request.method() === 'POST') {
- submissions.push(request.method());
- }
- });
- await page.getByRole('button', { name: 'Enhanced form POST' }).click();
- await page.getByRole('heading', { name: 'Sign in', exact: true }).waitFor();
- await page.getByRole('button', { name: 'Sign in', exact: true }).click();
- await page
- .getByRole('heading', { name: 'Server Auth Errors Example', exact: true })
- .waitFor();
- expect(submissions).toEqual(['POST']);
- expect(page.url()).toBe(`${server.base}/`);
- await page.locator(`a[href="${path}"]`).filter({ hasText: 'Client navigation' }).click();
- await page.getByRole('heading', { name: `Action: ${guard}` }).waitFor();
- await page.getByRole('button', { name: 'Enhanced form POST' }).click();
- await page.getByRole('heading', { name: 'Action authorized' }).waitFor();
- expect(submissions).toEqual(['POST', 'POST']);
- },
- );
-
- it('renders the client error boundary when an enhanced form throws its 401', async () => {
- await open('/actions/require-auth');
- const timeOrigin = await markLayout();
- await page.getByRole('checkbox', { name: /Throw enhanced-form errors/ }).check();
- await page.getByRole('button', { name: 'Enhanced form POST' }).click();
- await page.getByRole('heading', { name: 'Root error boundary' }).waitFor();
- expect(await page.locator('main').innerText()).toContain('401: Unauthorized');
- await expectLayout(timeOrigin, true);
- await page.getByRole('link', { name: 'Server Auth Errors Example', exact: true }).click();
- await page
- .getByRole('heading', { name: 'Server Auth Errors Example', exact: true })
- .waitFor();
- expect(await page.getByRole('heading', { name: 'Root error boundary' }).count()).toBe(0);
- });
-
- it('shows a temporary page-loaded popover only on document loads', async () => {
- await open();
- const toast = page.locator('.page-loaded-toast');
- await expect
- .poll(() => toast.evaluate((element) => element.matches(':popover-open')))
- .toBe(true);
- const timeOrigin = await markLayout();
- await page
- .locator('a[href="/loaders/optional-user"]')
- .filter({ hasText: 'Client navigation' })
- .click();
- await page.getByRole('heading', { name: 'Loader rendered the page' }).waitFor();
- expect(await toast.evaluate((element) => element.matches(':popover-open'))).toBe(false);
- await expectLayout(timeOrigin, true);
- await page.reload();
- await expect
- .poll(() => toast.evaluate((element) => element.matches(':popover-open')))
- .toBe(true);
- await expect
- .poll(() => toast.evaluate((element) => element.matches(':popover-open')), {
- timeout: 5000,
- })
- .toBe(false);
- });
- });
- }
-}
diff --git a/packages/void/test/integration/server-auth-errors.test.ts b/packages/void/test/integration/server-auth-errors.test.ts
new file mode 100644
index 000000000..62a2d5c10
--- /dev/null
+++ b/packages/void/test/integration/server-auth-errors.test.ts
@@ -0,0 +1,422 @@
+import { join } from 'node:path';
+import spawn from 'cross-spawn';
+import type { Browser, BrowserContext, Page, Response } from 'playwright';
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from 'vite-plus/test';
+import { collectBrowserDiagnostics } from '../../../../test/browser-helpers.ts';
+import {
+ createIsolatedPlayground,
+ killChild,
+ startServer,
+ type IsolatedPlayground,
+ type StartedServer,
+} from '../../../../test/integration-helpers.ts';
+import { launchPagesBrowser } from '../../../../test/pages-browser.ts';
+
+const ROOT = join(import.meta.dirname, '../../../..');
+const PLAYGROUND = 'playground/server-auth-errors';
+const EMAIL = 'demo@example.com';
+const guards = ['require-auth', 'return-redirect', 'throw-redirect', 'auth-redirect'] as const;
+const visits = ['Document load', 'Client navigation'] as const;
+const forms = ['Native form POST', 'Enhanced form POST'] as const;
+const pages = [
+ { path: '/loaders/optional-user', status: 200, heading: 'Loader rendered the page' },
+ { path: '/loaders/optional-session', status: 200, heading: 'Loader rendered the page' },
+ { path: '/loaders/require-auth', status: 401, heading: 'Root error boundary' },
+ { path: '/loaders/return-redirect', status: 302, heading: 'Sign in' },
+ { path: '/loaders/throw-redirect', status: 302, heading: 'Sign in' },
+ { path: '/loaders/auth-redirect', status: 302, heading: 'Sign in' },
+ { path: '/loaders/not-found', status: 404, heading: 'Not-found boundary' },
+ { path: '/loaders/unexpected', status: 500, heading: 'Root error boundary' },
+ { path: '/middleware/require-auth', status: 401, heading: 'Root error boundary' },
+ { path: '/middleware/return-redirect', status: 302, heading: 'Sign in' },
+ { path: '/middleware/throw-redirect', status: 302, heading: 'Sign in' },
+ { path: '/middleware/auth-redirect', status: 302, heading: 'Sign in' },
+] as const;
+
+let playground: IsolatedPlayground;
+let server: StartedServer;
+let browser: Browser;
+let context: BrowserContext;
+let signedInState: Awaited>;
+let page: Page;
+let diagnostics: () => string;
+
+beforeAll(async () => {
+ playground = createIsolatedPlayground(ROOT, PLAYGROUND);
+ server = await startServer(
+ (port) =>
+ spawn('vp', ['dev', '--host', '127.0.0.1', '--port', String(port), '--strictPort'], {
+ cwd: playground.root,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ env: { ...process.env, VOID_INSPECTOR_PORT: 'false' },
+ }),
+ 60_000,
+ { expectStatus: 200, expectBody: 'Server Auth Errors Example' },
+ );
+ browser = await launchPagesBrowser();
+
+ // A fresh copy has its own D1 database. Create a real session once and
+ // restore its cookies before each signed-in scenario.
+ context = await browser.newContext();
+ const response = await context.request.post(`${server.base}/api/demo-login`);
+ expect(response.status(), await response.text()).toBe(200);
+ const profile = await context.request.get(`${server.base}/api/profile`);
+ expect(profile.status()).toBe(200);
+ expect(await profile.json()).toEqual({ name: 'Demo user', email: EMAIL });
+ signedInState = await context.storageState();
+});
+
+afterEach(async ({ task }) => {
+ if (task.result?.state === 'fail') {
+ console.error(`${diagnostics?.() ?? ''}\n${server?.output() ?? ''}`);
+ }
+ await page?.close();
+});
+
+afterAll(async () => {
+ await browser?.close();
+ if (server) {
+ await killChild(server.child);
+ }
+ playground?.cleanup();
+});
+
+async function newPage(signedIn = false) {
+ // Keep the dev server's connections and module cache across this large
+ // matrix. Recreating the network context exhausts Chromium socket buffers
+ // on Windows. Each test still gets a fresh page and reset browser storage.
+ await context.setStorageState(signedIn ? signedInState : { cookies: [], origins: [] });
+ page = await context.newPage();
+ page.setDefaultTimeout(10_000);
+ diagnostics = collectBrowserDiagnostics(page);
+}
+
+async function open(path = '/', signedIn = false) {
+ const response = await page.goto(`${server.base}${path}`);
+ expect(response?.status()).toBe(200);
+ await page
+ .getByRole('navigation')
+ .getByRole('link', {
+ name: signedIn ? 'Sign out' : 'Sign in',
+ exact: true,
+ })
+ .waitFor();
+}
+
+async function markLayout() {
+ await page
+ .locator('header')
+ .evaluate((header) => header.setAttribute('data-test-layout', 'retained'));
+ return page.evaluate(() => performance.timeOrigin);
+}
+
+async function expectLayout(timeOrigin: number, retained: boolean) {
+ expect((await page.evaluate(() => performance.timeOrigin)) === timeOrigin).toBe(retained);
+ expect(await page.locator('header[data-test-layout="retained"]').count()).toBe(retained ? 1 : 0);
+}
+
+function responseFor(path: string, method = 'GET') {
+ return page.waitForResponse(
+ (response) =>
+ response.url() === `${server.base}${path}` && response.request().method() === method,
+ );
+}
+
+async function expectRedirect(
+ response: Response,
+ destination: string,
+ status: number,
+ enhanced = false,
+) {
+ // Pages negotiates redirects as HTTP 200 so fetch can read Location (including
+ // fragments). Document requests keep the original HTTP redirect status.
+ expect(response.status()).toBe(enhanced ? 200 : status);
+ expect(await response.request().headerValue('X-VoidPages-Redirect')).toBe(
+ enhanced ? 'manual' : null,
+ );
+ expect(await response.headerValue('X-VoidPages-Redirect')).toBe(enhanced ? String(status) : null);
+ expect(await response.headerValue('location')).toBe(destination);
+ await page.waitForURL(`${server.base}${destination}`);
+}
+
+describe.each([
+ { state: 'signed out', signedIn: false },
+ { state: 'signed in', signedIn: true },
+])('server auth: $state', ({ signedIn }) => {
+ beforeEach(() => newPage(signedIn));
+
+ describe.each(visits)('%s', (visit) => {
+ it.each(pages)('handles $path', async ({ path, status, heading }) => {
+ await open('/', signedIn);
+ const timeOrigin = await markLayout();
+ const pending = responseFor(path);
+ await page.locator(`a[href="${path}"]`).filter({ hasText: visit }).click();
+ const response = await pending;
+ const expectedStatus = signedIn ? 200 : status;
+ if (expectedStatus !== 302) {
+ expect(response.status()).toBe(expectedStatus);
+ }
+
+ if (expectedStatus === 401) {
+ expect(await response.headerValue('content-type')).toContain(
+ visit === 'Client navigation' ? 'application/json' : 'text/html',
+ );
+ expect(await response.headerValue('X-VoidPages')).toBe(
+ visit === 'Client navigation' ? 'true' : null,
+ );
+ expect(await response.headerValue('cache-control')).toBe('no-store');
+ }
+
+ if (expectedStatus === 302) {
+ await expectRedirect(response, '/login', 302, visit === 'Client navigation');
+ } else {
+ await page.waitForURL(`${server.base}${path}`);
+ }
+ await page
+ .getByRole('heading', {
+ name: signedIn ? 'Loader rendered the page' : heading,
+ exact: true,
+ })
+ .waitFor();
+ await expectLayout(timeOrigin, visit === 'Client navigation');
+
+ if (signedIn) {
+ expect(await page.locator('main').innerText()).toContain(`Signed in as ${EMAIL}.`);
+ if (path === '/loaders/optional-session') {
+ expect(await page.locator('main').innerText()).toMatch(
+ /Session expires: \d{4}-\d{2}-\d{2}T/,
+ );
+ }
+ } else if (status === 401) {
+ expect(await page.locator('main').innerText()).toContain('401: Unauthorized');
+ } else if (status === 200) {
+ expect(await page.locator('main').innerText()).toContain(
+ 'Anonymous visitor: user is null.',
+ );
+ expect(await page.locator('main').innerText()).not.toContain('Session expires:');
+ }
+ });
+ });
+
+ describe.each(forms)('%s', (form) => {
+ it.each(guards)('checks authentication for the %s action', async (guard) => {
+ const path = `/actions/${guard}`;
+ await open(path, signedIn);
+ const timeOrigin = await markLayout();
+ const pending = responseFor(path, 'POST');
+ const destination = signedIn ? '/actions/success' : '/login';
+ const followUp = signedIn || guard !== 'require-auth' ? responseFor(destination) : undefined;
+ await page.getByRole('button', { name: form, exact: true }).click();
+ const response = await pending;
+
+ if (!signedIn && guard === 'require-auth') {
+ expect(response.status()).toBe(401);
+ expect(await response.text()).toBe('Unauthorized');
+ if (form === 'Native form POST') {
+ await expect.poll(() => page.locator('body').innerText()).toBe('Unauthorized');
+ expect(await page.locator('header').count()).toBe(0);
+ expect(await page.evaluate(() => performance.timeOrigin)).not.toBe(timeOrigin);
+ } else {
+ await expect.poll(() => page.getByRole('alert').innerText()).toBe('401: Unauthorized');
+ expect(await page.getByRole('heading', { name: `Action: ${guard}` }).count()).toBe(1);
+ await expectLayout(timeOrigin, true);
+ }
+ expect(page.url()).toBe(`${server.base}${path}`);
+ return;
+ }
+
+ await expectRedirect(response, destination, 303, form === 'Enhanced form POST');
+ expect((await followUp)?.status()).toBe(200);
+ if (form === 'Native form POST') {
+ expect(response.request().redirectedTo()?.method()).toBe('GET');
+ }
+ await page
+ .getByRole('heading', {
+ name: signedIn ? 'Action authorized' : 'Sign in',
+ exact: true,
+ })
+ .waitFor();
+ await expectLayout(timeOrigin, form === 'Enhanced form POST');
+ });
+ });
+
+ it('returns the API profile as a document', async () => {
+ await open('/', signedIn);
+ const timeOrigin = await markLayout();
+ const pending = responseFor('/api/profile');
+ await page.locator('a[href="/api/profile"]').click();
+ const response = await pending;
+ expect(response.status()).toBe(signedIn ? 200 : 401);
+ if (signedIn) {
+ expect(await response.json()).toEqual({ name: 'Demo user', email: EMAIL });
+ } else {
+ expect(await response.text()).toBe('Unauthorized');
+ }
+ await page.waitForURL(`${server.base}/api/profile`);
+ expect(await page.evaluate(() => performance.timeOrigin)).not.toBe(timeOrigin);
+ expect(await page.locator('header').count()).toBe(0);
+ });
+
+ it('displays the API profile fetch result without navigating', async () => {
+ await open('/', signedIn);
+ const timeOrigin = await markLayout();
+ await page.getByRole('button', { name: 'Fetch API response' }).click();
+ const result = page.locator('#api').locator('..').getByRole('status');
+ await expect.poll(() => result.innerText()).toContain(signedIn ? 'HTTP 200' : 'HTTP 401');
+ expect(await result.innerText()).toContain(signedIn ? EMAIL : 'Unauthorized');
+ expect(await result.innerText()).toContain(signedIn ? 'application/json' : 'text/plain');
+ expect(page.url()).toBe(`${server.base}/`);
+ await expectLayout(timeOrigin, true);
+ });
+});
+
+describe('demo session and navigation', () => {
+ beforeEach(() => newPage());
+
+ it.each(['throw-redirect', 'auth-redirect'])(
+ 'signs in after the %s guard and updates the auth links',
+ async (guard) => {
+ const destination = `/loaders/${guard}`;
+ await open();
+ const timeOrigin = await markLayout();
+ await page
+ .locator(`a[href="${destination}"]`)
+ .filter({ hasText: 'Client navigation' })
+ .click();
+ await page.getByRole('heading', { name: 'Sign in', exact: true }).waitFor();
+ expect(await page.getByLabel('Email', { exact: true }).inputValue()).toBe(EMAIL);
+ expect(await page.getByLabel('Email', { exact: true }).isDisabled()).toBe(true);
+ expect(await page.getByLabel('Password', { exact: true }).inputValue()).toBe('demo-password');
+ expect(await page.getByLabel('Password', { exact: true }).isDisabled()).toBe(true);
+ await page.getByRole('button', { name: 'Sign in', exact: true }).click();
+ await page
+ .getByRole('heading', { name: 'Server Auth Errors Example', exact: true })
+ .waitFor();
+ expect(page.url()).toBe(`${server.base}/`);
+ await page.getByRole('link', { name: 'Sign out', exact: true }).waitFor();
+ await page
+ .locator(`a[href="${destination}"]`)
+ .filter({ hasText: 'Client navigation' })
+ .click();
+ await page.getByRole('heading', { name: 'Loader rendered the page' }).waitFor();
+ expect(await page.getByRole('link', { name: 'Sign in', exact: true }).count()).toBe(0);
+ await expectLayout(timeOrigin, true);
+
+ await page.reload();
+ await page.getByRole('link', { name: 'Sign out', exact: true }).waitFor();
+ await page.getByRole('link', { name: 'Sign out', exact: true }).click();
+ await page.getByRole('heading', { name: 'Sign in', exact: true }).waitFor();
+ await page.getByRole('link', { name: 'Sign in', exact: true }).waitFor();
+ expect(await page.getByRole('link', { name: 'Sign out', exact: true }).count()).toBe(0);
+ expect((await page.request.get(`${server.base}/api/profile`)).status()).toBe(401);
+ },
+ );
+
+ it('uses the demo credentials regardless of the submitted fields', async () => {
+ const response = await page.request.post(`${server.base}/api/demo-login`, {
+ data: { email: 'other@example.com', password: 'different-password' },
+ });
+ expect(response.status()).toBe(200);
+ const profile = await page.request.get(`${server.base}/api/profile`);
+ expect(await profile.json()).toEqual({ name: 'Demo user', email: EMAIL });
+ });
+
+ describe.each(forms)('%s after the session ends', (form) => {
+ it.each(guards)('rechecks authentication for the %s action', async (guard) => {
+ expect((await page.request.post(`${server.base}/api/demo-login`)).status()).toBe(200);
+ const path = `/actions/${guard}`;
+ await open(path, true);
+ expect(await page.locator('main').innerText()).toContain(`Signed in as ${EMAIL}.`);
+
+ // End the session without refreshing the already-rendered form.
+ const signedOut = await page.request.post(`${server.base}/api/auth/sign-out`, {
+ headers: { Origin: server.base },
+ data: {},
+ });
+ expect(signedOut.status()).toBe(200);
+ const pending = responseFor(path, 'POST');
+ const followUp = guard !== 'require-auth' ? responseFor('/login') : undefined;
+ await page.getByRole('button', { name: form, exact: true }).click();
+ const response = await pending;
+
+ if (guard === 'require-auth') {
+ expect(response.status()).toBe(401);
+ if (form === 'Native form POST') {
+ await expect.poll(() => page.locator('body').innerText()).toBe('Unauthorized');
+ } else {
+ await expect.poll(() => page.getByRole('alert').innerText()).toBe('401: Unauthorized');
+ }
+ } else {
+ await expectRedirect(response, '/login', 303, form === 'Enhanced form POST');
+ expect((await followUp)?.status()).toBe(200);
+ await page.getByRole('heading', { name: 'Sign in', exact: true }).waitFor();
+ }
+ expect(await page.getByRole('heading', { name: 'Action authorized' }).count()).toBe(0);
+ });
+ });
+
+ it.each(['return-redirect', 'throw-redirect', 'auth-redirect'])(
+ 'does not replay the %s action after login',
+ async (guard) => {
+ const path = `/actions/${guard}`;
+ await open(path);
+ const submissions: Array = [];
+ page.on('request', (request) => {
+ if (request.url() === `${server.base}${path}` && request.method() === 'POST') {
+ submissions.push(request.method());
+ }
+ });
+ await page.getByRole('button', { name: 'Enhanced form POST' }).click();
+ await page.getByRole('heading', { name: 'Sign in', exact: true }).waitFor();
+ await page.getByRole('button', { name: 'Sign in', exact: true }).click();
+ await page
+ .getByRole('heading', { name: 'Server Auth Errors Example', exact: true })
+ .waitFor();
+ expect(submissions).toEqual(['POST']);
+ expect(page.url()).toBe(`${server.base}/`);
+ await page.locator(`a[href="${path}"]`).filter({ hasText: 'Client navigation' }).click();
+ await page.getByRole('heading', { name: `Action: ${guard}` }).waitFor();
+ await page.getByRole('button', { name: 'Enhanced form POST' }).click();
+ await page.getByRole('heading', { name: 'Action authorized' }).waitFor();
+ expect(submissions).toEqual(['POST', 'POST']);
+ },
+ );
+
+ it('renders the client error boundary when an enhanced form throws its 401', async () => {
+ await open('/actions/require-auth');
+ const timeOrigin = await markLayout();
+ await page.getByRole('checkbox', { name: /Throw enhanced-form errors/ }).check();
+ await page.getByRole('button', { name: 'Enhanced form POST' }).click();
+ await page.getByRole('heading', { name: 'Root error boundary' }).waitFor();
+ expect(await page.locator('main').innerText()).toContain('401: Unauthorized');
+ await expectLayout(timeOrigin, true);
+ await page.getByRole('link', { name: 'Server Auth Errors Example', exact: true }).click();
+ await page.getByRole('heading', { name: 'Server Auth Errors Example', exact: true }).waitFor();
+ expect(await page.getByRole('heading', { name: 'Root error boundary' }).count()).toBe(0);
+ });
+
+ it('shows a temporary page-loaded popover only on document loads', async () => {
+ await open();
+ const toast = page.locator('.page-loaded-toast');
+ await expect
+ .poll(() => toast.evaluate((element) => element.matches(':popover-open')))
+ .toBe(true);
+ const timeOrigin = await markLayout();
+ await page
+ .locator('a[href="/loaders/optional-user"]')
+ .filter({ hasText: 'Client navigation' })
+ .click();
+ await page.getByRole('heading', { name: 'Loader rendered the page' }).waitFor();
+ expect(await toast.evaluate((element) => element.matches(':popover-open'))).toBe(false);
+ await expectLayout(timeOrigin, true);
+ await page.reload();
+ await expect
+ .poll(() => toast.evaluate((element) => element.matches(':popover-open')))
+ .toBe(true);
+ await expect
+ .poll(() => toast.evaluate((element) => element.matches(':popover-open')), {
+ timeout: 5000,
+ })
+ .toBe(false);
+ });
+});
diff --git a/packages/void/test/integration/shared-build-preparation.test.ts b/packages/void/test/integration/shared-build-preparation.test.ts
deleted file mode 100644
index 99a076673..000000000
--- a/packages/void/test/integration/shared-build-preparation.test.ts
+++ /dev/null
@@ -1,101 +0,0 @@
-import { execFile } from 'node:child_process';
-import {
- existsSync,
- mkdirSync,
- mkdtempSync,
- readFileSync,
- realpathSync,
- rmSync,
- symlinkSync,
- writeFileSync,
-} from 'node:fs';
-import { tmpdir } from 'node:os';
-import { join } from 'node:path';
-import { promisify } from 'node:util';
-import { afterEach, expect, it } from 'vite-plus/test';
-import { prepareCompatibilityBuild } from '../../../../.github/scripts/schema-compat-tests.ts';
-
-const exec = promisify(execFile);
-const repository = join(import.meta.dirname, '../../../..');
-const roots: Array = [];
-
-function workspace(): string {
- const root = realpathSync.native(mkdtempSync(join(tmpdir(), 'void-shared-build-')));
- roots.push(root);
- mkdirSync(join(root, 'node_modules'));
- symlinkSync(
- realpathSync.native(join(repository, 'node_modules/vite-plus')),
- join(root, 'node_modules/vite-plus'),
- process.platform === 'win32' ? 'junction' : 'dir',
- );
- mkdirSync(join(root, 'test'));
- writeFileSync(join(root, 'test/build-setup.ts'), '// This fixture uses the shared setup below.');
- writeFileSync(join(root, '.node-version'), readFileSync(join(repository, '.node-version')));
- writeFileSync(
- join(root, 'package.json'),
- JSON.stringify({ name: 'void-shared-build-test', private: true, type: 'module' }),
- );
- writeFileSync(
- join(root, 'vite.config.mjs'),
- `export default {
- run: { tasks: { build: { command: 'node build.mjs', cache: false } } },
- test: { projects: [{ extends: false, test: {
- name: 'platform-api-integration-probe', include: ['probe.test.ts'], maxWorkers: 1,
- globalSetup: [${JSON.stringify(join(repository, 'test/build-setup.ts'))}]
- } }] }
-};`,
- );
- writeFileSync(
- join(root, 'build.mjs'),
- `import {existsSync,readFileSync,writeFileSync} from 'node:fs';
-const count=existsSync('build-count.txt')?Number(readFileSync('build-count.txt','utf8')):0;
-writeFileSync('build-count.txt',String(count+1));
-writeFileSync('artifact.txt','prepared');`,
- );
- writeFileSync(
- join(root, 'probe.test.ts'),
- `import {readFileSync} from 'node:fs';import {expect,it} from 'vite-plus/test';
-it('consumes shared immutable artifacts',()=>{
- expect(readFileSync('artifact.txt','utf8')).toBe('prepared');
- expect(readFileSync('build-count.txt','utf8')).toBe('1');
-});`,
- );
- return root;
-}
-
-afterEach(() => {
- for (const root of roots.splice(0)) {
- rmSync(root, { recursive: true, force: true, maxRetries: 20, retryDelay: 50 });
- }
-});
-
-it('prepares once before independent Vitest processes import the same artifacts', async () => {
- const root = workspace();
- const config = prepareCompatibilityBuild(root);
- expect(config).toBeDefined();
- await Promise.all(
- [0, 1].map(() =>
- exec('vp', ['test', 'run', '--config', config!], {
- cwd: root,
- env: { ...process.env, NODE_ENV: undefined },
- }),
- ),
- );
- expect(readFileSync(join(root, 'build-count.txt'), 'utf8')).toBe('1');
-});
-
-it('does not hand off a failed preparation as ready', () => {
- const root = workspace();
- writeFileSync(join(root, 'build.mjs'), "throw new Error('intentional preparation failure');");
- expect(() => prepareCompatibilityBuild(root)).toThrow('Could not prepare public artifacts');
- expect(existsSync(join(root, 'node_modules/.cache/void-schema-compat/vite.config.mjs'))).toBe(
- false,
- );
-});
-
-it('leaves older deployed test harnesses on their original configuration', () => {
- const root = workspace();
- rmSync(join(root, 'test/build-setup.ts'));
- expect(prepareCompatibilityBuild(root)).toBeUndefined();
- expect(existsSync(join(root, 'build-count.txt'))).toBe(false);
-});
diff --git a/packages/void/test/integration/ssr-playground.test.ts b/packages/void/test/integration/ssr-playground.test.ts
index a12271f56..088b2f916 100644
--- a/packages/void/test/integration/ssr-playground.test.ts
+++ b/packages/void/test/integration/ssr-playground.test.ts
@@ -1,9 +1,10 @@
+import { execSync } from 'node:child_process';
import { existsSync, readFileSync, rmSync } from 'node:fs';
import { join } from 'node:path';
import { getWorkerAssetsDir, getWorkerConfigPath } from '@cloudflare/build-output-utils';
import spawn from 'cross-spawn';
import { afterAll, beforeAll, describe, expect, it } from 'vite-plus/test';
-import { buildPlayground, killChild, startServer } from '../../../../test/integration-helpers.ts';
+import { killChild, startServer } from '../../../../test/integration-helpers.ts';
import { GENERATED_ASSET_HEADERS_MARKER } from '../../src/asset-worker-bypass.ts';
const ROOT = join(import.meta.dirname, '..', '..', '..', '..');
@@ -82,7 +83,7 @@ describe('playground/ssr build + preview', () => {
beforeAll(async () => {
rmSync(join(ROOT, 'playground/ssr/dist'), { recursive: true, force: true });
- buildPlayground(ROOT, 'ssr');
+ execSync('vp run --filter ./playground/ssr build', { cwd: ROOT, stdio: 'pipe' });
const server = await startServer((port) => {
child = spawn(
diff --git a/packages/void/test/integration/static-pages.test.ts b/packages/void/test/integration/static-pages.test.ts
index 062d3f0b0..dc02e8630 100644
--- a/packages/void/test/integration/static-pages.test.ts
+++ b/packages/void/test/integration/static-pages.test.ts
@@ -1,8 +1,8 @@
+import { execSync } from 'node:child_process';
import { existsSync, readFileSync, rmSync } from 'node:fs';
import { join } from 'node:path';
import { Miniflare, convertV4MiniflareOptions } from 'miniflare';
import { beforeAll, describe, expect, it } from 'vite-plus/test';
-import { buildPlayground } from '../../../../test/integration-helpers.ts';
import { GENERATED_ASSET_HEADERS_MARKER } from '../../src/asset-worker-bypass.ts';
import { deserializePageData } from '../../src/pages/serialize.ts';
import { collectPrerenderPaths } from '../../src/prerender.ts';
@@ -22,7 +22,7 @@ describe('playground/static-pages build (output: static)', () => {
rmSync(join(pg, 'dist'), { recursive: true, force: true });
rmSync(join(pg, '.void'), { recursive: true, force: true });
removeWranglerConfig(pg);
- buildPlayground(ROOT, PLAYGROUND.slice('playground/'.length));
+ execSync(`vp run --filter ./${PLAYGROUND} build`, { cwd: ROOT, stdio: 'pipe' });
});
it('emits worker entry and client manifest', () => {
diff --git a/packages/void/test/integration/test-build-cache.test.ts b/packages/void/test/integration/test-build-cache.test.ts
deleted file mode 100644
index 541cf3fac..000000000
--- a/packages/void/test/integration/test-build-cache.test.ts
+++ /dev/null
@@ -1,208 +0,0 @@
-import { createHash } from 'node:crypto';
-import {
- existsSync,
- mkdirSync,
- mkdtempSync,
- readFileSync,
- realpathSync,
- rmSync,
- symlinkSync,
- writeFileSync,
-} from 'node:fs';
-import { tmpdir } from 'node:os';
-import { join } from 'node:path';
-import { pathToFileURL } from 'node:url';
-import { stripVTControlCharacters } from 'node:util';
-import spawn from 'cross-spawn';
-import { afterAll, beforeAll, beforeEach, expect, it } from 'vite-plus/test';
-import type { FixtureApp } from '../../../../test/fixture-app.ts';
-
-const repository = join(import.meta.dirname, '../../../..');
-let root: string;
-let fixture: FixtureApp;
-let initialHtml: string;
-
-function writeInputs(): void {
- writeFileSync(join(root, 'fixture.json'), JSON.stringify(fixture));
-}
-
-function build() {
- writeInputs();
- const result = spawn.sync('vp', ['run', 'build'], {
- cwd: root,
- env: { ...process.env, NODE_ENV: undefined, NO_COLOR: '1', FORCE_COLOR: undefined },
- encoding: 'utf8',
- maxBuffer: 10 * 1024 * 1024,
- });
- return {
- status: result.status,
- output: stripVTControlCharacters(`${result.stdout ?? ''}${result.stderr ?? ''}`),
- };
-}
-
-function succeed() {
- const result = build();
- expect(result.status, result.output).toBe(0);
- return result.output;
-}
-
-function html(page = 'index'): string {
- return readFileSync(join(root, 'app/dist/client', `${page}.html`), 'utf8');
-}
-
-function expectBuildHit(output: string): void {
- expect(
- output
- .replaceAll('\\', '/')
- .split('\n')
- .some((line) => line.includes('app/build.mjs') && line.includes('cache hit')),
- output,
- ).toBe(true);
-}
-
-function baseline(): FixtureApp {
- return {
- framework: 'react',
- name: 'cache-contract',
- files: {
- 'tsconfig.json': JSON.stringify({ compilerOptions: { jsx: 'react-jsx' } }),
- 'pages/index.island.tsx': `import { message } from '../message';
-export default function Page() { return <>{message}
{__FIXTURE_LABEL__}
>; }`,
- 'vite.config.mjs': `import { voidPlugin } from 'void';
-import { voidReact } from '@void/react/plugin';
-import { voidMarkdown } from '@void/md/plugin';
-import { loadEnv } from 'vite';
-export default ({ mode }) => ({ plugins: [voidPlugin(), voidReact(), voidMarkdown()],
- define: { __FIXTURE_LABEL__: JSON.stringify(loadEnv(mode, process.cwd(), 'VITE_').VITE_FIXTURE_LABEL ?? '') }
-});`,
- 'message.ts': "export const message = 'original fixture';",
- 'pages/removed.island.tsx': 'export default function Removed() { return Removed
; }',
- },
- };
-}
-
-beforeAll(() => {
- root = realpathSync.native(mkdtempSync(join(tmpdir(), 'void-build-cache-')));
- mkdirSync(join(root, 'node_modules'));
- symlinkSync(
- realpathSync(join(repository, 'node_modules/vite-plus')),
- join(root, 'node_modules/vite-plus'),
- process.platform === 'win32' ? 'junction' : 'dir',
- );
- writeFileSync(join(root, '.node-version'), readFileSync(join(repository, '.node-version')));
- writeFileSync(
- join(root, 'package.json'),
- JSON.stringify({ name: 'void-build-cache-contract', private: true, type: 'module' }),
- );
- writeFileSync(
- join(root, 'vite.config.mjs'),
- `export default { run: { tasks: {
- prepare: { command: 'node prepare.mjs', cache: false },
- build: { command: 'node app/build.mjs', dependsOn: ['prepare'] },
-} } };
-`,
- );
- const materializer = pathToFileURL(join(repository, 'test/fixture-app.ts')).href;
- writeFileSync(
- join(root, 'prepare.mjs'),
- `import { readFileSync } from 'node:fs';
-import { fileURLToPath } from 'node:url';
-import { prepareFixture } from ${JSON.stringify(materializer)};
-prepareFixture(JSON.parse(readFileSync(new URL('./fixture.json', import.meta.url), 'utf8')),
- fileURLToPath(new URL('./app', import.meta.url)));
-`,
- );
- fixture = baseline();
- succeed();
- initialHtml = html();
-});
-
-beforeEach(() => {
- fixture = baseline();
-});
-
-afterAll(() => {
- if (root) {
- rmSync(root, { recursive: true, force: true, maxRetries: 20, retryDelay: 50 });
- }
-});
-
-it('restores deleted production artifacts byte-for-byte without compiling again', () => {
- rmSync(join(root, 'app/dist'), { recursive: true, force: true });
- rmSync(join(root, 'app/.cloudflare'), { recursive: true, force: true });
- expectBuildHit(succeed());
- const digest = (value: string) => createHash('sha256').update(value).digest('hex');
- expect(digest(html())).toBe(digest(initialHtml));
- expect(existsSync(join(root, 'app/.cloudflare/output/v1/config.json'))).toBe(true);
-});
-
-it('invalidates a transitive source dependency', () => {
- fixture.files = {
- ...fixture.files,
- 'message.ts': "export const message = 'changed dependency';",
- };
- succeed();
- expect(html()).toContain('changed dependency');
- expect(html()).not.toContain('original fixture');
-});
-
-it('discovers a newly added route', () => {
- fixture.files = {
- ...fixture.files,
- 'pages/added.island.tsx': 'export default function Added() { return Added route
; }',
- };
- succeed();
- expect(html('added')).toContain('Added route');
-});
-
-it('removes deleted source and its old generated output', () => {
- const files = { ...fixture.files };
- delete files['pages/removed.island.tsx'];
- fixture.files = files;
- succeed();
- expect(existsSync(join(root, 'app/pages/removed.island.tsx'))).toBe(false);
- expect(existsSync(join(root, 'app/dist/client/removed.html'))).toBe(false);
-});
-
-it('rebuilds after application configuration changes', () => {
- fixture.files = {
- ...fixture.files,
- 'void.config.ts': `import { defineConfig } from 'void/config';
-export default defineConfig({ output: 'static', head: { title: 'Changed fixture title' },
- worker: { compatibility_date: '2026-02-24' } });`,
- };
- succeed();
- expect(html()).toContain('Changed fixture title');
-});
-
-it('tracks environment files that were absent during the previous build', () => {
- succeed();
- fixture.files = {
- ...fixture.files,
- '.env': 'VITE_FIXTURE_LABEL=fixture environment',
- };
- succeed();
- expect(html()).toContain('fixture environment');
- fixture.files = { ...fixture.files, '.env': 'VITE_FIXTURE_LABEL=updated environment' };
- succeed();
- expect(html()).toContain('updated environment');
-});
-
-it('never turns a failed build into a cache hit and recovers after its inputs are fixed', () => {
- fixture.files = {
- ...fixture.files,
- 'vite.config.mjs': "throw new Error('fixture build rejected');",
- };
- const failed = build();
- expect(failed.status).not.toBe(0);
- expect(failed.output).toContain('fixture build rejected');
- const retry = build();
- expect(retry.status).not.toBe(0);
- expect(retry.output).not.toMatch(/app\/build\.mjs.*cache hit/);
- fixture = baseline();
- succeed();
- const recovered = html();
- expectBuildHit(succeed());
- expect(html()).toBe(recovered);
- expect(html()).toContain('original fixture');
-});
diff --git a/packages/void/test/integration/websockets-playground.test.ts b/packages/void/test/integration/websockets-playground.test.ts
index 772b22a79..7c8e46738 100644
--- a/packages/void/test/integration/websockets-playground.test.ts
+++ b/packages/void/test/integration/websockets-playground.test.ts
@@ -74,15 +74,11 @@ describe('playground/websockets', () => {
beforeAll(async () => {
const playground = join(ROOT, 'playground/websockets');
rmSync(join(playground, 'dist'), { recursive: true, force: true });
- const build = spawn.sync(
- 'vp',
- ['run', '--ignore-depends-on', '--filter', './playground/websockets', 'build'],
- {
- cwd: ROOT,
- encoding: 'utf8',
- env: { ...process.env, VOID_INSPECTOR_PORT: 'false' },
- },
- );
+ const build = spawn.sync('vp', ['run', '--filter', './playground/websockets', 'build'], {
+ cwd: ROOT,
+ encoding: 'utf8',
+ env: { ...process.env, VOID_INSPECTOR_PORT: 'false' },
+ });
expect(build.status).toBe(0);
browser = await chromium.launch();
diff --git a/packages/void/test/unit/cloudflare-operation-process-deployments.test.ts b/packages/void/test/unit/cloudflare-operation-process-deployments.test.ts
deleted file mode 100644
index 0f5427eb5..000000000
--- a/packages/void/test/unit/cloudflare-operation-process-deployments.test.ts
+++ /dev/null
@@ -1,564 +0,0 @@
-import { readFileSync, writeFileSync } from 'node:fs';
-import { createServer, request as httpRequest } from 'node:http';
-import { connect } from 'node:net';
-import { join } from 'node:path';
-import { expect, it } from 'vite-plus/test';
-import { isVoidSecretOnlyDraft } from '../../../deploy-cloudflare/src/secret-draft.ts';
-import { voidSecretDraftVersion } from '../../../deploy-cloudflare/test/secret-draft-fixture.ts';
-import { decodeCloudflareOperationResult } from '../../src/cli/cloudflare-process.ts';
-import { Buffer } from '../../src/cli/node-buffer.ts';
-import {
- listen,
- runOperation,
- temporaryDirectory,
- tokenEnv,
-} from '../helpers/cloudflare-operation-process.ts';
-
-const voidVersion = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8'))
- .version as string;
-const cfVersion = JSON.parse(readFileSync(new URL(import.meta.resolve('cf/package.json')), 'utf8'))
- .version as string;
-function unproxiedEnv(api: string): NodeJS.ProcessEnv {
- return {
- ...process.env,
- CF_API_TOKEN: 'synthetic-token',
- CLOUDFLARE_ACCOUNT_ID: 'test-account',
- CLOUDFLARE_API_BASE_URL: `${api}/client/v4`,
- HTTP_PROXY: '',
- HTTPS_PROXY: '',
- http_proxy: '',
- https_proxy: '',
- };
-}
-
-it.each([
- { observability: { enabled: true } },
- { observability: { enabled: false } },
- { logpush: true },
- { logpush: false },
- { observability: { enabled: false }, logpush: false },
-])(
- 'publishes explicit Worker settings from the trigger operation: %j',
- async (settings) => {
- const directory = temporaryDirectory('void-cf-observability-');
- const configPath = join(directory, 'wrangler.json');
- writeFileSync(
- configPath,
- JSON.stringify({
- name: 'test-worker',
- workers_dev: false,
- preview_urls: false,
- ...settings,
- }),
- );
- const patches: Array<{ path: string; body: unknown; authorization?: string }> = [];
- const api = await listen(
- createServer(async (request, response) => {
- const chunks: Array = [];
- for await (const chunk of request) {
- chunks.push(Buffer.from(chunk));
- }
- if (request.method === 'PATCH') {
- patches.push({
- path: request.url ?? '',
- body: JSON.parse(Buffer.concat(chunks).toString()),
- authorization: request.headers.authorization,
- });
- }
- response.writeHead(200, { 'Content-Type': 'application/json' });
- response.end(
- JSON.stringify({
- success: true,
- result: request.url?.endsWith('/workers/subdomain')
- ? { subdomain: 'fixture' }
- : { subdomain: { enabled: false, previews_enabled: false }, ...settings },
- }),
- );
- }),
- );
- const output = await runOperation(
- directory,
- {
- type: 'triggers.deploy',
- workerName: 'test-worker',
- configPath,
- },
- tokenEnv(api),
- );
- expect(output.status, output.stderr).toBe(0);
- expect(patches).toEqual([
- {
- path: '/client/v4/accounts/test-account/workers/scripts/test-worker/script-settings',
- body: settings,
- authorization: 'Bearer synthetic-token',
- },
- ]);
- },
- 15_000,
-);
-
-it.each([false, true])(
- 'requests immutable version source without provisioning (large=%s)',
- async (large) => {
- const directory = temporaryDirectory('void-cf-secret-source-');
- const draft = voidSecretDraftVersion();
- if (large) {
- draft.modules[0]!.content_base64 = Buffer.from(
- `/* ${'x'.repeat(1024 * 1024)} */\nexport default { fetch() { return new Response("ok"); } };`,
- ).toString('base64');
- }
- const requests: Array = [];
- const userAgents: Array = [];
- const api = await listen(
- createServer((request, response) => {
- requests.push(request.url ?? '');
- userAgents.push(request.headers['user-agent']);
- request.resume();
- response.writeHead(200, { 'Content-Type': 'application/json' });
- response.end(JSON.stringify({ success: true, errors: [], messages: [], result: draft }));
- }),
- );
- const configPath = join(directory, 'wrangler.json');
- writeFileSync(configPath, JSON.stringify({ name: 'test-worker', account_id: 'test-account' }));
- const output = await runOperation(
- directory,
- {
- type: 'versions.view',
- versionId: draft.id,
- includeSource: true,
- configPath,
- workerName: 'test-worker',
- },
- { ...tokenEnv(api), CLI_VERSION: 'inherited-version void/stale' },
- );
- expect(output.status, output.stderr).toBe(0);
- const result = decodeCloudflareOperationResult({
- status: 0,
- stdout: output.stdout,
- stderr: '',
- });
- expect(result.status, result.stderr).toBe(0);
- expect(result.data).toEqual(draft);
- expect(isVoidSecretOnlyDraft(result.data as Record)).toBe(!large);
- expect(requests).toEqual([
- `/client/v4/accounts/test-account/workers/workers/test-worker/versions/${draft.id}?include=modules`,
- ]);
- expect(output.stdout).not.toContain('synthetic-token');
- expect(userAgents).toEqual([`cf-cli/${cfVersion} void/${voidVersion}`]);
- },
-);
-
-it.each([undefined, false, true])(
- 'sends bypassDeploymentChecks=%s through cf alongside the deployment body',
- async (bypassDeploymentChecks) => {
- const directory = temporaryDirectory('void-cf-deployment-checks-');
- const requests: Array<{ url: string | undefined; body: unknown }> = [];
- const api = await listen(
- createServer(async (request, response) => {
- let body = '';
- for await (const chunk of request) {
- body += chunk;
- }
- requests.push({ url: request.url, body: JSON.parse(body) });
- response.setHeader('Content-Type', 'application/json');
- response.end(JSON.stringify({ success: true, result: { id: 'deployment-id' } }));
- }),
- );
- const preload = join(directory, 'capture-cf.mjs');
- const callsPath = join(directory, 'calls.json');
- writeFileSync(
- preload,
- `import child from 'node:child_process';
-import { syncBuiltinESMExports } from 'node:module';
-import { writeFileSync } from 'node:fs';
-const spawnSync = child.spawnSync;
-child.spawnSync = (binary, args, options) => {
- writeFileSync(${JSON.stringify(callsPath)}, JSON.stringify(args.slice(1)));
- return spawnSync(binary, args, options);
-};
-syncBuiltinESMExports();
-`,
- );
- const versionId = '11111111-1111-4111-8111-111111111111';
- const message = 'Void automatic rollback after readiness failed.';
- const output = await runOperation(
- directory,
- {
- type: 'versions.deploy',
- workerName: 'test-worker',
- versions: [{ versionId, percentage: 100 }],
- message,
- bypassDeploymentChecks,
- },
- tokenEnv(api),
- preload,
- );
- expect(output.status, output.stderr).toBe(0);
- expect(decodeCloudflareOperationResult({ ...output, status: 0 }).status).toBe(0);
- const args = JSON.parse(readFileSync(callsPath, 'utf8')) as Array;
- expect(args.includes('--bypass-deployment-checks')).toBe(bypassDeploymentChecks === true);
- expect(args).toContain('--body');
- expect(requests).toEqual([
- {
- url: `/client/v4/accounts/test-account/workers/scripts/test-worker/deployments${bypassDeploymentChecks === true ? '?force=true' : ''}`,
- body: {
- strategy: 'percentage',
- versions: [{ version_id: versionId, percentage: 100 }],
- annotations: { 'workers/message': message },
- },
- },
- ]);
- },
-);
-
-it.each([401, 403, 404, 503])(
- 'stops a prebuilt platform upload before cf can provision an unavailable R2 bucket (HTTP %s)',
- async (status) => {
- const directory = temporaryDirectory('void-cf-platform-r2-preflight-');
- const requests: Array = [];
- const api = await listen(
- createServer((request, response) => {
- requests.push(`${request.method} ${request.url}`);
- response.statusCode = status;
- response.setHeader('Content-Type', 'application/json');
- response.end(JSON.stringify({ success: false, errors: [{ code: 10006 }] }));
- }),
- );
- const configPath = join(directory, 'wrangler.json');
- writeFileSync(
- join(directory, 'index.js'),
- 'export default { fetch() { return new Response("ok") } };',
- );
- writeFileSync(
- configPath,
- JSON.stringify({
- name: 'test-worker',
- account_id: 'test-account',
- compatibility_date: '2026-09-29',
- main: 'index.js',
- no_bundle: true,
- r2_buckets: [{ binding: 'ASSETS', bucket_name: 'missing-bucket' }],
- }),
- );
- const output = await runOperation(
- directory,
- { type: 'versions.upload', configPath },
- unproxiedEnv(api),
- );
- expect(output.status).toBe(1);
- expect(output.stderr).toContain('refusing automatic provisioning');
- expect(output.stderr).toContain(`HTTP ${status}`);
- expect(requests).toEqual(['GET /client/v4/accounts/test-account/r2/buckets/missing-bucket']);
- },
- 30_000,
-);
-
-it.each(['ordinary', 'versions.upload', 'worker.deploy'] as const)(
- 'allows a prebuilt %s upload and scopes installation attribution to the cf child',
- async (uploadType) => {
- const directory = temporaryDirectory('void-cf-platform-resource-preflight-');
- const requests: Array = [];
- const jurisdictions: Array = [];
- const api = await listen(
- createServer((request, response) => {
- const path = request.url ?? '';
- requests.push(`${request.method} ${path}`);
- if (path.includes('/r2/buckets/')) {
- jurisdictions.push(request.headers['cf-r2-jurisdiction'] as string | undefined);
- }
- response.setHeader('Content-Type', 'application/json');
- response.end(
- JSON.stringify({
- success: true,
- result:
- path.endsWith('/queues') || path.includes('/queues?page=')
- ? [{ queue_id: 'queue-id', queue_name: 'existing-queue' }]
- : {},
- ...(path.includes('/queues?page=') ? { result_info: { page: 1, total_pages: 1 } } : {}),
- }),
- );
- }),
- );
- const configPath = join(directory, 'wrangler.json');
- writeFileSync(
- join(directory, 'index.js'),
- 'export default { fetch() { return new Response("ok") } };',
- );
- writeFileSync(
- configPath,
- JSON.stringify({
- name: 'test-worker',
- account_id: 'test-account',
- compatibility_date: '2026-09-29',
- main: 'index.js',
- no_bundle: true,
- r2_buckets: [{ binding: 'ASSETS', bucket_name: 'existing-bucket', jurisdiction: 'eu' }],
- queues: { producers: [{ binding: 'JOBS', queue: 'existing-queue' }] },
- dispatch_namespaces: [{ binding: 'DISPATCH', namespace: 'existing-namespace' }],
- ...(uploadType === 'ordinary'
- ? {}
- : {
- vars: {
- PLATFORM_VERSION: '0.27.0',
- PLATFORM_OWNERSHIP_MARKER: JSON.stringify({
- schemaVersion: 1,
- accountId: 'test-account',
- installationId: 'installation-one',
- ownershipNonce: 'private-ownership-proof',
- resourceId: 'test-worker',
- resourceName: 'test-worker',
- resourceKey: 'api-worker',
- resourceKind: 'worker',
- }),
- },
- }),
- }),
- );
- const preload = join(directory, 'mock-version-upload.mjs');
- writeFileSync(
- preload,
- `import child from 'node:child_process';
-import { writeFileSync } from 'node:fs';
-import { syncBuiltinESMExports } from 'node:module';
-const actualSpawnSync=child.spawnSync;
-child.spawnSync = (binary, args, options) => {
- if(args.slice(1,4).join(' ') !== 'workers versions create' && args[1] !== 'deploy') return actualSpawnSync(binary,args,options);
- writeFileSync(${JSON.stringify(join(directory, 'upload-environment.json'))}, JSON.stringify({version:options.env.CLI_VERSION,telemetry:options.env.CF_SEND_TELEMETRY}));
- return ${
- uploadType === 'worker.deploy'
- ? // cf 1.0.0-beta.21 and later print the uploaded version on stderr.
- "{ status:0, stdout:'', stderr:'│ Current Version ID: 11111111-1111-4111-8111-111111111111\\n' }"
- : "{ status:0, stdout:JSON.stringify({id:'11111111-1111-4111-8111-111111111111'}), stderr:'' }"
- };
-};
-syncBuiltinESMExports();`,
- );
- const output = await runOperation(
- directory,
- { type: uploadType === 'ordinary' ? 'versions.upload' : uploadType, configPath },
- unproxiedEnv(api),
- preload,
- );
- expect(output.status, output.stderr).toBe(0);
- expect(JSON.parse(output.stdout).data).toEqual({
- versionId: '11111111-1111-4111-8111-111111111111',
- });
- expect(requests).toEqual([
- 'GET /client/v4/accounts/test-account/r2/buckets/existing-bucket',
- 'GET /client/v4/accounts/test-account/workers/dispatch/namespaces/existing-namespace',
- 'GET /client/v4/accounts/test-account/queues?page=1',
- ]);
- expect(jurisdictions).toEqual(['eu']);
- const uploadEnvironment = JSON.parse(
- readFileSync(join(directory, 'upload-environment.json'), 'utf8'),
- );
- expect(uploadEnvironment).toEqual({
- version:
- cfVersion +
- ' void/' +
- voidVersion +
- (uploadType === 'ordinary'
- ? ''
- : ' void-platform-install/0.27.0 void-role/api-worker void-installation/installation-one'),
- telemetry: 'false',
- });
- expect(JSON.stringify(uploadEnvironment)).not.toContain('private-ownership-proof');
- },
- 30_000,
-);
-
-it.each([
- { label: 'uppercase proxy variables', lowercase: false, bypass: false, authenticated: false },
- { label: 'lowercase proxy variables', lowercase: true, bypass: false, authenticated: false },
- { label: 'NO_PROXY bypass', lowercase: false, bypass: true, authenticated: false },
- { label: 'no_proxy bypass', lowercase: true, bypass: true, authenticated: false },
- { label: 'authenticated proxy', lowercase: false, bypass: false, authenticated: true },
-])(
- 'inspects existing Worker versions with $label',
- async ({ lowercase, bypass, authenticated }) => {
- const directory = temporaryDirectory('void-cf-proxy-contract-');
- const versionId = '11111111-1111-4111-8111-111111111111';
- let proxied = 0;
- let inspected = 0;
- const proxyAuthorizations: Array = [];
- // Node passes only one case variant of each environment key on Windows.
- // Clear inherited variants so the lowercase case does not lose to an empty uppercase value.
- const proxyEnvironment = Object.fromEntries(
- Object.entries(process.env).filter(
- ([key]) =>
- !['HTTP_PROXY', 'HTTPS_PROXY', 'NO_PROXY', 'NODE_USE_ENV_PROXY'].includes(
- key.toUpperCase(),
- ),
- ),
- );
- const api = await listen(
- createServer((request, response) => {
- inspected++;
- expect(request.headers.authorization).toBe('Bearer synthetic-token');
- expect(request.headers['proxy-authorization']).toBeUndefined();
- expect(request.url).toBe(
- `/client/v4/accounts/test-account/workers/scripts/test-worker/versions/${versionId}`,
- );
- response.setHeader('Content-Type', 'application/json');
- response.end(
- JSON.stringify({
- success: true,
- result: {
- resources: { bindings: [], script: { handlers: ['fetch'] }, script_runtime: {} },
- },
- }),
- );
- }),
- );
- const proxy = createServer((request, response) => {
- proxied++;
- proxyAuthorizations.push(request.headers['proxy-authorization']);
- const { 'proxy-authorization': _proxyAuthorization, ...headers } = request.headers;
- const upstream = httpRequest(
- new URL(request.url!),
- { method: request.method, headers },
- (upstreamResponse) => {
- response.writeHead(upstreamResponse.statusCode ?? 502, upstreamResponse.headers);
- upstreamResponse.pipe(response);
- },
- );
- upstream.on('error', () => response.destroy());
- request.pipe(upstream);
- });
- proxy.on('connect', (request, socket, head) => {
- proxied++;
- proxyAuthorizations.push(request.headers['proxy-authorization']);
- const [host, port] = request.url!.split(':');
- const upstream = connect(Number(port), host!, () => {
- socket.write('HTTP/1.1 200 Connection Established\r\n\r\n');
- if (head.length) {
- upstream.write(head);
- }
- socket.pipe(upstream).pipe(socket);
- });
- upstream.on('error', () => socket.destroy());
- });
- const proxyOrigin = await listen(proxy);
- const proxyUrl = authenticated
- ? proxyOrigin.replace('http://', 'http://proxy-user:proxy-pass@')
- : proxyOrigin;
- const configPath = join(directory, 'wrangler.json');
- const preload = join(directory, 'mock-cf.mjs');
- writeFileSync(configPath, JSON.stringify({ name: 'test-worker', account_id: 'test-account' }));
- writeFileSync(
- preload,
- `import child from 'node:child_process';
-import { syncBuiltinESMExports } from 'node:module';
-child.spawnSync = () => ({ status: 0, stdout: JSON.stringify({ id: '${versionId}', bindings: [] }), stderr: '' });
-syncBuiltinESMExports();
-`,
- );
- const output = await runOperation(
- directory,
- { type: 'versions.view', versionId, configPath },
- {
- ...proxyEnvironment,
- CLOUDFLARE_ACCOUNT_ID: 'test-account',
- CLOUDFLARE_API_TOKEN: 'synthetic-token',
- CLOUDFLARE_API_BASE_URL: `${api}/client/v4`,
- [lowercase ? 'http_proxy' : 'HTTP_PROXY']: proxyUrl,
- [lowercase ? 'no_proxy' : 'NO_PROXY']: bypass ? '127.0.0.1' : '',
- NODE_USE_ENV_PROXY: '',
- },
- preload,
- );
- expect(output.status, output.stderr).toBe(0);
- expect(JSON.parse(output.stdout).data.resources.bindings).toEqual([]);
- expect(proxied).toBe(bypass ? 0 : 1);
- expect(proxyAuthorizations).toEqual(
- bypass
- ? []
- : [
- authenticated
- ? `Basic ${Buffer.from('proxy-user:proxy-pass').toString('base64')}`
- : undefined,
- ],
- );
- expect(inspected).toBe(1);
- },
- 30_000,
-);
-
-it.each([false, true])(
- 'attaches cf to the terminal only for an interactive platform upload (interactive: %s)',
- async (interactive) => {
- const directory = temporaryDirectory('void-cf-interactive-upload-');
- const requests: Array = [];
- const api = await listen(
- createServer((request, response) => {
- requests.push(`${request.method} ${request.url}`);
- response.statusCode = 500;
- response.end();
- }),
- );
- const configPath = join(directory, 'wrangler.json');
- writeFileSync(
- join(directory, 'index.js'),
- 'export default { fetch() { return new Response("ok") } };',
- );
- writeFileSync(
- configPath,
- JSON.stringify({
- name: 'test-worker',
- account_id: 'test-account',
- compatibility_date: '2026-09-29',
- main: 'index.js',
- no_bundle: true,
- }),
- );
- const record = join(directory, 'cf-stdio.json');
- const preload = join(directory, 'mock-interactive-upload.mjs');
- writeFileSync(
- preload,
- `import child from 'node:child_process';
-import { writeFileSync } from 'node:fs';
-import { syncBuiltinESMExports } from 'node:module';
-const actualSpawnSync=child.spawnSync;
-child.spawnSync = (binary, args, options) => {
- if(args.slice(1,4).join(' ') !== 'workers versions create') return actualSpawnSync(binary,args,options);
- writeFileSync(${JSON.stringify(record)}, JSON.stringify({stdio:options.stdio,args:args.slice(1)}));
- return options.stdio === 'inherit'
- ? { status:0, stdout:null, stderr:null }
- : { status:0, stdout:JSON.stringify({id:'11111111-1111-4111-8111-111111111111'}), stderr:'' };
-};
-syncBuiltinESMExports();`,
- );
- const output = await runOperation(
- directory,
- {
- type: 'versions.upload',
- configPath,
- message: '-review',
- ...(interactive ? { interactive } : {}),
- },
- unproxiedEnv(api),
- preload,
- );
- expect(output.status, output.stderr).toBe(0);
- const called = JSON.parse(readFileSync(record, 'utf8'));
- expect(called.args).toEqual([
- 'workers',
- 'versions',
- 'create',
- '--prebuilt',
- '--message=-review',
- ]);
- if (interactive) {
- expect(called.stdio).toBe('inherit');
- // The terminal shows cf's own output; no result envelope follows it.
- expect(output.stdout).toBe('');
- } else {
- expect(called.stdio).toEqual(['ignore', 'pipe', 'pipe']);
- expect(JSON.parse(output.stdout).data).toEqual({
- versionId: '11111111-1111-4111-8111-111111111111',
- });
- }
- expect(requests).toEqual([]);
- },
- 30_000,
-);
diff --git a/packages/void/test/unit/cloudflare-operation-process-services.test.ts b/packages/void/test/unit/cloudflare-operation-process-services.test.ts
deleted file mode 100644
index 0e842a025..000000000
--- a/packages/void/test/unit/cloudflare-operation-process-services.test.ts
+++ /dev/null
@@ -1,552 +0,0 @@
-import { readFileSync, writeFileSync } from 'node:fs';
-import { createServer } from 'node:http';
-import { join } from 'node:path';
-import { expect, it } from 'vite-plus/test';
-import { Buffer } from '../../src/cli/node-buffer.ts';
-import {
- listen,
- runOperation,
- systemEnv,
- temporaryDirectory,
- tokenEnv,
-} from '../helpers/cloudflare-operation-process.ts';
-
-const voidVersion = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8'))
- .version as string;
-
-it.each(['apac', undefined] as const)(
- 'creates R2 buckets with location hint %s through installed cf',
- async (locationHint) => {
- const directory = temporaryDirectory('void-cf-r2-location-');
- const configPath = join(directory, 'wrangler.json');
- writeFileSync(configPath, JSON.stringify({ name: 'test-worker', account_id: 'test-account' }));
- const requests: Array<{ path: string; body: Record }> = [];
- const api = await listen(
- createServer(async (request, response) => {
- const chunks: Array = [];
- for await (const chunk of request) {
- chunks.push(Buffer.from(chunk));
- }
- requests.push({
- path: request.url ?? '',
- body: JSON.parse(Buffer.concat(chunks).toString()),
- });
- response.writeHead(200, { 'Content-Type': 'application/json' });
- response.end(
- JSON.stringify({ success: true, errors: [], result: { name: 'test-storage' } }),
- );
- }),
- );
- const result = await runOperation(
- directory,
- {
- type: 'r2.bucket.create',
- name: 'test-storage',
- binding: 'STORAGE',
- configPath,
- locationHint,
- },
- tokenEnv(api),
- );
- expect(result.status, result.stderr).toBe(0);
- expect(requests).toEqual([
- {
- path: '/client/v4/accounts/test-account/r2/buckets',
- body: expect.objectContaining({
- name: 'test-storage',
- ...(locationHint ? { locationHint } : {}),
- }),
- },
- ]);
- if (!locationHint) {
- expect(requests[0]!.body).not.toHaveProperty('locationHint');
- }
- expect(JSON.parse(readFileSync(configPath, 'utf8')).r2_buckets).toEqual([
- { binding: 'STORAGE', bucket_name: 'test-storage' },
- ]);
- },
-);
-
-it.each([200, 503])(
- 'reports HTTP %i without loading the build toolchain when domain cleanup returns non-JSON',
- async (status) => {
- const directory = temporaryDirectory('void-cf-domain-error-');
- const api = await listen(
- createServer((request, response) => {
- request.resume();
- response.statusCode = status;
- response.end('temporary upstream response');
- }),
- );
- const configPath = join(directory, 'wrangler.json');
- const preload = join(directory, 'reject-build-imports.mjs');
- writeFileSync(
- preload,
- `import { registerHooks } from 'node:module';
-registerHooks({
- resolve(specifier, context, nextResolve) {
- if (['vite', '@cloudflare/build-output-utils'].includes(specifier) || specifier.endsWith('/cf-build-output.ts')) {
- throw new Error('Ancillary operations must not load the build toolchain');
- }
- return nextResolve(specifier, context);
- },
-});
-`,
- );
- writeFileSync(configPath, JSON.stringify({ name: 'test-worker', account_id: 'test-account' }));
- const output = await runOperation(
- directory,
- { type: 'triggers.clear-domains', configPath, workerName: 'test-worker' },
- tokenEnv(api),
- preload,
- );
- expect(output.status).toBe(1);
- expect(output.stderr).toContain(`HTTP ${status}`);
- expect(output.stderr).not.toContain('synthetic-token');
- },
- 30_000,
-);
-
-it.each(['clear-crons', 'clear-domains'])(
- 'clears %s through the pinned account API',
- async (operation) => {
- const directory = temporaryDirectory('void-cf-clear-crons-');
- let requested = false;
- const api = await listen(
- createServer(async (request, response) => {
- requested = true;
- expect(request.method).toBe('PUT');
- expect(request.url).toBe(
- `/client/v4/accounts/test-account/workers/scripts/test-worker/${operation === 'clear-crons' ? 'schedules' : 'domains/records'}`,
- );
- expect(request.headers.authorization).toBe('Bearer synthetic-token');
- expect(request.headers['user-agent']).toBe(`void/${voidVersion}`);
- let body = '';
- for await (const chunk of request) {
- body += chunk;
- }
- expect(JSON.parse(body)).toEqual(
- operation === 'clear-crons'
- ? []
- : {
- override_scope: true,
- override_existing_origin: false,
- override_existing_dns_record: false,
- origins: [],
- },
- );
- response.setHeader('Content-Type', 'application/json');
- response.end(JSON.stringify({ success: true, result: { schedules: [] } }));
- }),
- );
- const configPath = join(directory, 'wrangler.json');
- writeFileSync(configPath, JSON.stringify({ name: 'test-worker', account_id: 'test-account' }));
- const output = await runOperation(
- directory,
- {
- type: `triggers.${operation}` as 'triggers.clear-crons' | 'triggers.clear-domains',
- configPath,
- workerName: 'test-worker',
- },
- tokenEnv(api),
- );
- expect(output.status, output.stderr).toBe(0);
- expect(requested).toBe(true);
- },
- 30_000,
-);
-
-it('discovers KV namespaces beyond the first cf API page', async () => {
- const directory = temporaryDirectory('void-cf-kv-pages-');
- const requestedPages: Array = [];
- const namespaces = Array.from({ length: 100 }, (_, index) => ({
- id: (index + 1).toString(16).padStart(32, '0'),
- title: `other-${index}`,
- }));
- const target = { id: 'f'.repeat(32), title: 'existing-void-kv' };
- const api = await listen(
- createServer((request, response) => {
- const url = new URL(request.url ?? '', 'http://127.0.0.1');
- expect(url.pathname).toBe('/client/v4/accounts/test-account/storage/kv/namespaces');
- expect(url.searchParams.get('per_page')).toBe('100');
- expect(url.searchParams.get('order')).toBe('id');
- expect(url.searchParams.get('direction')).toBe('asc');
- const page = Number(url.searchParams.get('page'));
- requestedPages.push(page);
- response.setHeader('Content-Type', 'application/json');
- response.end(
- JSON.stringify({
- success: true,
- errors: [],
- messages: [],
- result: page === 1 ? namespaces : page === 2 ? [target] : [],
- }),
- );
- }),
- );
- const configPath = join(directory, 'wrangler.json');
- writeFileSync(configPath, JSON.stringify({ account_id: 'test-account' }));
- const output = await runOperation(
- directory,
- { type: 'kv.namespace.list', configPath },
- tokenEnv(api, 'CF_API_TOKEN'),
- );
- expect(output.status, output.stderr).toBe(0);
- expect(JSON.parse(output.stdout).data).toEqual([...namespaces, target]);
- expect(requestedPages).toEqual([1, 2]);
-}, 30_000);
-
-it('finds existing Queues beyond the first cf API page', async () => {
- const directory = temporaryDirectory('void-cf-queue-pages-');
- const requestedPages: Array = [];
- const api = await listen(
- createServer((request, response) => {
- const url = new URL(request.url ?? '', 'http://127.0.0.1');
- expect(url.pathname).toBe('/client/v4/accounts/test-account/queues');
- const page = Number(url.searchParams.get('page'));
- requestedPages.push(page);
- response.setHeader('Content-Type', 'application/json');
- response.end(
- JSON.stringify({
- success: true,
- result: [
- page === 1
- ? { queue_id: 'first-queue', queue_name: 'another-queue' }
- : { queue_id: 'target-queue', queue_name: 'existing-void-queue' },
- ],
- result_info: { page, per_page: 1, total_pages: 2, total_count: 2 },
- }),
- );
- }),
- );
- const configPath = join(directory, 'wrangler.json');
- writeFileSync(configPath, JSON.stringify({ account_id: 'test-account' }));
- const output = await runOperation(
- directory,
- { type: 'queues.info', name: 'existing-void-queue', configPath },
- tokenEnv(api, 'CF_API_TOKEN'),
- );
- expect(output.status, output.stderr).toBe(0);
- expect(JSON.parse(output.stdout).data).toMatchObject({ name: 'existing-void-queue' });
- expect(requestedPages).toEqual([1, 2]);
-}, 30_000);
-
-it.each([
- {
- label: 'Worker and HTTP pull consumers',
- queue: {
- consumers: [
- { type: 'worker', script_name: 'app-production', consumer_id: 'one' },
- { type: 'http_pull', consumer_id: 'two' },
- ],
- consumers_total_count: 2,
- },
- consumers: ['app-production', null],
- },
- { label: 'no consumer', queue: { consumers: [], consumers_total_count: 0 }, consumers: [] },
- {
- label: 'an incomplete consumer list',
- queue: { consumers: [], consumers_total_count: 1 },
- consumers: undefined,
- },
- { label: 'no consumer list', queue: {}, consumers: undefined },
- {
- label: 'a legacy script field',
- queue: { consumers: [{ type: 'worker', script: 'app' }], consumers_total_count: 1 },
- consumers: ['app'],
- },
- {
- label: 'a Worker consumer without a name',
- queue: { consumers: [{ type: 'worker', script_name: '' }], consumers_total_count: 1 },
- consumers: undefined,
- },
- {
- label: 'two different Worker names on one consumer',
- queue: {
- consumers: [{ type: 'worker', script_name: 'app', script: 'other' }],
- consumers_total_count: 1,
- },
- consumers: undefined,
- },
- {
- label: 'a consumer of an unknown type',
- queue: { consumers: [{ type: 'other' }], consumers_total_count: 1 },
- consumers: undefined,
- },
-])(
- 'reports a queue with $label',
- async ({ queue, consumers }) => {
- const directory = temporaryDirectory('void-cf-queue-consumers-');
- const api = await listen(
- createServer((_request, response) => {
- response.setHeader('Content-Type', 'application/json');
- response.end(
- JSON.stringify({
- success: true,
- result: [{ queue_id: 'queue-id', queue_name: 'jobs', ...queue }],
- result_info: { page: 1, per_page: 1, total_pages: 1, total_count: 1 },
- }),
- );
- }),
- );
- const configPath = join(directory, 'wrangler.json');
- writeFileSync(configPath, JSON.stringify({ account_id: 'test-account' }));
- const output = await runOperation(
- directory,
- { type: 'queues.info', name: 'jobs', configPath },
- tokenEnv(api, 'CF_API_TOKEN'),
- );
- expect(output.status, output.stderr).toBe(0);
- // Without a complete list the field is left out; only queue naming needs it.
- expect(JSON.parse(output.stdout).data).toEqual({
- id: 'queue-id',
- name: 'jobs',
- ...(consumers ? { consumers } : {}),
- });
- },
- 30_000,
-);
-
-it.each([
- {
- label: 'Cloudflare script_name',
- consumers: [{ script_name: 'test-worker', consumer_id: 'owned-consumer', type: 'worker' }],
- deleted: ['owned-consumer'],
- status: 0,
- },
- {
- label: 'matching legacy alias',
- consumers: [
- { script_name: 'test-worker', script: 'test-worker', consumer_id: 'owned-consumer' },
- ],
- deleted: ['owned-consumer'],
- status: 0,
- },
- {
- label: 'foreign Worker and HTTP pull consumers',
- consumers: [
- { script_name: 'other-worker', consumer_id: 'foreign-consumer', type: 'worker' },
- { consumer_id: 'pull-consumer', type: 'http_pull' },
- ],
- deleted: [],
- status: 0,
- },
- {
- label: 'conflicting aliases',
- consumers: [
- { script_name: 'other-worker', script: 'test-worker', consumer_id: 'foreign-consumer' },
- ],
- deleted: [],
- status: 1,
- },
- {
- label: 'missing Worker identity',
- consumers: [{ consumer_id: 'unknown-consumer', type: 'worker' }],
- deleted: [],
- status: 1,
- },
- {
- label: 'null Worker identity',
- consumers: [{ script_name: null, consumer_id: 'unknown-consumer' }],
- deleted: [],
- status: 1,
- },
- {
- label: 'missing consumer ID',
- consumers: [{ script_name: 'test-worker', type: 'worker' }],
- deleted: [],
- status: 1,
- },
- {
- label: 'duplicate owned consumers',
- consumers: [
- { script_name: 'test-worker', consumer_id: 'first-consumer', type: 'worker' },
- { script_name: 'test-worker', consumer_id: 'second-consumer', type: 'worker' },
- ],
- deleted: [],
- status: 1,
- },
- {
- label: 'option-shaped consumer ID',
- consumers: [{ script_name: 'test-worker', consumer_id: '--help', type: 'worker' }],
- deleted: [],
- status: 1,
- },
-])(
- 'cleans up Queue consumers using verified identities: $label',
- async ({ consumers, deleted, status }) => {
- const directory = temporaryDirectory('void-cf-queue-cleanup-');
- const deletes: Array = [];
- const api = await listen(
- createServer((request, response) => {
- const url = new URL(request.url ?? '', 'http://127.0.0.1');
- request.resume();
- response.setHeader('Content-Type', 'application/json');
- const queuePath = '/client/v4/accounts/test-account/queues';
- if (request.method === 'GET' && url.pathname === queuePath) {
- response.end(
- JSON.stringify({
- success: true,
- result: [{ queue_id: 'queue-id', queue_name: 'existing-queue' }],
- result_info: { page: 1, total_pages: 1 },
- }),
- );
- } else if (request.method === 'GET' && url.pathname === `${queuePath}/queue-id/consumers`) {
- response.end(JSON.stringify({ success: true, result: consumers }));
- } else if (
- request.method === 'DELETE' &&
- url.pathname.startsWith(`${queuePath}/queue-id/consumers/`)
- ) {
- deletes.push(url.pathname.split('/').at(-1)!);
- response.end(JSON.stringify({ success: true, result: {} }));
- } else {
- response.statusCode = 400;
- response.end(
- JSON.stringify({ success: false, errors: [{ message: 'Unexpected request' }] }),
- );
- }
- }),
- );
- const configPath = join(directory, 'wrangler.json');
- writeFileSync(configPath, JSON.stringify({ account_id: 'test-account', name: 'test-worker' }));
- const output = await runOperation(
- directory,
- {
- type: 'queues.consumer.remove',
- queueName: 'existing-queue',
- workerName: 'test-worker',
- configPath,
- },
- tokenEnv(api, 'CF_API_TOKEN'),
- );
- expect(output.status, output.stderr).toBe(status);
- expect(deletes).toEqual(deleted);
- expect(output.stderr).not.toContain('synthetic-token');
- },
- 30_000,
-);
-
-it.each([
- {
- operation: { type: 'email.routing.settings' as const, domain: 'acme.com' },
- commands: [
- {
- command: ['email-routing', 'settings', 'get', '--zone', 'acme.com'],
- data: {
- name: 'acme.com',
- enabled: true,
- status: 'ready',
- tag: '11111111111111111111111111111111',
- },
- },
- ],
- expected: {
- name: 'acme.com',
- enabled: true,
- status: 'ready',
- tag: '11111111111111111111111111111111',
- },
- },
- {
- operation: { type: 'email.sending.settings' as const, domain: 'mail.acme.com' },
- commands: [
- {
- command: ['email-routing', 'settings', 'get', '--zone', 'mail.acme.com'],
- status: 1,
- stderr: 'Zone not found: mail.acme.com',
- },
- {
- command: ['email-routing', 'settings', 'get', '--zone', 'acme.com'],
- data: {
- name: 'acme.com',
- enabled: true,
- status: 'ready',
- tag: '11111111111111111111111111111111',
- },
- },
- {
- command: ['email-sending', 'subdomains', 'list', '--zone', 'acme.com'],
- data: [{ name: 'mail.acme.com', enabled: true, id: '22222222222222222222222222222222' }],
- },
- ],
- expected: { name: 'mail.acme.com', enabled: true, id: '22222222222222222222222222222222' },
- },
- {
- operation: { type: 'email.routing.rules.list' as const, domain: 'acme.com' },
- commands: [
- {
- command: [
- 'email-routing',
- 'rules',
- 'list-account',
- '--page',
- '1',
- '--per-page',
- '100',
- '--zone',
- 'acme.com',
- ],
- data: Array.from({ length: 100 }, (_, index) => ({
- id: `rule-${index}`,
- name: 'support',
- enabled: index % 2 === 0,
- matchers: [{ type: 'literal', field: 'to', value: `support-${index}@acme.com` }],
- actions: [{ type: 'worker', value: ['my-worker'] }],
- })),
- },
- {
- command: [
- 'email-routing',
- 'rules',
- 'list-account',
- '--page',
- '2',
- '--per-page',
- '100',
- '--zone',
- 'acme.com',
- ],
- data: [{ enabled: false, matchers: [{ type: 'all' }], actions: [{ type: 'drop' }] }],
- },
- ],
- },
-])('returns structured email data for $operation', async ({ operation, commands, ...example }) => {
- const directory = temporaryDirectory('void-cf-email-json-');
- const preload = join(directory, 'mock-cf.mjs');
- const callsPath = join(directory, 'calls.json');
- writeFileSync(
- preload,
- `import child from 'node:child_process';
-import { syncBuiltinESMExports } from 'node:module';
-import { writeFileSync } from 'node:fs';
-const commands = ${JSON.stringify(commands)};
-const calls = [];
-child.spawnSync = (_executable, args) => {
- const command = args.slice(1);
- calls.push(command);
- writeFileSync(${JSON.stringify(callsPath)}, JSON.stringify(calls));
- const response = commands[calls.length - 1];
- if (JSON.stringify(command) !== JSON.stringify(response?.command)) {
- return { status: 1, stdout: '', stderr: 'Unexpected email transport command' };
- }
- return { status: response.status ?? 0, stdout: response.data === undefined ? '' : JSON.stringify(response.data), stderr: response.stderr ?? '' };
-};
-syncBuiltinESMExports();
-`,
- );
- const output = await runOperation(
- directory,
- operation,
- { ...systemEnv, CI: 'true', CLOUDFLARE_AUTH_USE_KEYRING: 'false' },
- preload,
- );
- expect(output.status, output.stderr).toBe(0);
- expect(JSON.parse(output.stdout).data).toEqual(
- 'expected' in example
- ? example.expected
- : commands.flatMap((command) => command.data ?? []),
- );
- expect(JSON.parse(readFileSync(callsPath, 'utf8'))).toEqual(
- commands.map((command) => command.command),
- );
-});
diff --git a/packages/void/test/unit/cloudflare-operation-process.test.ts b/packages/void/test/unit/cloudflare-operation-process.test.ts
index b35f62058..77d7148af 100644
--- a/packages/void/test/unit/cloudflare-operation-process.test.ts
+++ b/packages/void/test/unit/cloudflare-operation-process.test.ts
@@ -1,11 +1,13 @@
import { createHash } from 'node:crypto';
-import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { createServer, request as httpRequest } from 'node:http';
import type { AddressInfo } from 'node:net';
import { connect } from 'node:net';
import { join } from 'node:path';
import type { Duplex } from 'node:stream';
import { expect, it } from 'vite-plus/test';
+import { isVoidSecretOnlyDraft } from '../../../deploy-cloudflare/src/secret-draft.ts';
+import { voidSecretDraftVersion } from '../../../deploy-cloudflare/test/secret-draft-fixture.ts';
import { decodeCloudflareOperationResult } from '../../src/cli/cloudflare-process.ts';
import { Buffer } from '../../src/cli/node-buffer.ts';
import {
@@ -77,6 +79,346 @@ syncBuiltinESMExports();`,
expect(result.stdout).toContain('https://example.test/device');
});
+const voidVersion = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8'))
+ .version as string;
+const cfVersion = JSON.parse(readFileSync(new URL(import.meta.resolve('cf/package.json')), 'utf8'))
+ .version as string;
+
+function unproxiedEnv(api: string): NodeJS.ProcessEnv {
+ return {
+ ...process.env,
+ CF_API_TOKEN: 'synthetic-token',
+ CLOUDFLARE_ACCOUNT_ID: 'test-account',
+ CLOUDFLARE_API_BASE_URL: `${api}/client/v4`,
+ HTTP_PROXY: '',
+ HTTPS_PROXY: '',
+ http_proxy: '',
+ https_proxy: '',
+ };
+}
+
+it.each(['apac', undefined] as const)(
+ 'creates R2 buckets with location hint %s through installed cf',
+ async (locationHint) => {
+ const directory = temporaryDirectory('void-cf-r2-location-');
+ const configPath = join(directory, 'wrangler.json');
+ writeFileSync(configPath, JSON.stringify({ name: 'test-worker', account_id: 'test-account' }));
+ const requests: Array<{ path: string; body: Record }> = [];
+ const api = await listen(
+ createServer(async (request, response) => {
+ const chunks: Array = [];
+ for await (const chunk of request) {
+ chunks.push(Buffer.from(chunk));
+ }
+ requests.push({
+ path: request.url ?? '',
+ body: JSON.parse(Buffer.concat(chunks).toString()),
+ });
+ response.writeHead(200, { 'Content-Type': 'application/json' });
+ response.end(
+ JSON.stringify({ success: true, errors: [], result: { name: 'test-storage' } }),
+ );
+ }),
+ );
+ const result = await runOperation(
+ directory,
+ {
+ type: 'r2.bucket.create',
+ name: 'test-storage',
+ binding: 'STORAGE',
+ configPath,
+ locationHint,
+ },
+ tokenEnv(api),
+ );
+ expect(result.status, result.stderr).toBe(0);
+ expect(requests).toEqual([
+ {
+ path: '/client/v4/accounts/test-account/r2/buckets',
+ body: expect.objectContaining({
+ name: 'test-storage',
+ ...(locationHint ? { locationHint } : {}),
+ }),
+ },
+ ]);
+ if (!locationHint) {
+ expect(requests[0]!.body).not.toHaveProperty('locationHint');
+ }
+ expect(JSON.parse(readFileSync(configPath, 'utf8')).r2_buckets).toEqual([
+ { binding: 'STORAGE', bucket_name: 'test-storage' },
+ ]);
+ },
+);
+
+it.each([
+ { observability: { enabled: true } },
+ { observability: { enabled: false } },
+ { logpush: true },
+ { logpush: false },
+ { observability: { enabled: false }, logpush: false },
+])(
+ 'publishes explicit Worker settings from the trigger operation: %j',
+ async (settings) => {
+ const directory = temporaryDirectory('void-cf-observability-');
+ const configPath = join(directory, 'wrangler.json');
+ writeFileSync(
+ configPath,
+ JSON.stringify({
+ name: 'test-worker',
+ workers_dev: false,
+ preview_urls: false,
+ ...settings,
+ }),
+ );
+ const patches: Array<{ path: string; body: unknown; authorization?: string }> = [];
+ const api = await listen(
+ createServer(async (request, response) => {
+ const chunks: Array = [];
+ for await (const chunk of request) {
+ chunks.push(Buffer.from(chunk));
+ }
+ if (request.method === 'PATCH') {
+ patches.push({
+ path: request.url ?? '',
+ body: JSON.parse(Buffer.concat(chunks).toString()),
+ authorization: request.headers.authorization,
+ });
+ }
+ response.writeHead(200, { 'Content-Type': 'application/json' });
+ response.end(
+ JSON.stringify({
+ success: true,
+ result: request.url?.endsWith('/workers/subdomain')
+ ? { subdomain: 'fixture' }
+ : { subdomain: { enabled: false, previews_enabled: false }, ...settings },
+ }),
+ );
+ }),
+ );
+ const output = await runOperation(
+ directory,
+ {
+ type: 'triggers.deploy',
+ workerName: 'test-worker',
+ configPath,
+ },
+ tokenEnv(api),
+ );
+ expect(output.status, output.stderr).toBe(0);
+ expect(patches).toEqual([
+ {
+ path: '/client/v4/accounts/test-account/workers/scripts/test-worker/script-settings',
+ body: settings,
+ authorization: 'Bearer synthetic-token',
+ },
+ ]);
+ },
+ 15_000,
+);
+
+it.each([false, true])(
+ 'requests immutable version source without provisioning (large=%s)',
+ async (large) => {
+ const directory = temporaryDirectory('void-cf-secret-source-');
+ const draft = voidSecretDraftVersion();
+ if (large) {
+ draft.modules[0]!.content_base64 = Buffer.from(
+ `/* ${'x'.repeat(1024 * 1024)} */\nexport default { fetch() { return new Response("ok"); } };`,
+ ).toString('base64');
+ }
+ const requests: Array = [];
+ const userAgents: Array = [];
+ const api = await listen(
+ createServer((request, response) => {
+ requests.push(request.url ?? '');
+ userAgents.push(request.headers['user-agent']);
+ request.resume();
+ response.writeHead(200, { 'Content-Type': 'application/json' });
+ response.end(JSON.stringify({ success: true, errors: [], messages: [], result: draft }));
+ }),
+ );
+ const configPath = join(directory, 'wrangler.json');
+ writeFileSync(configPath, JSON.stringify({ name: 'test-worker', account_id: 'test-account' }));
+ const output = await runOperation(
+ directory,
+ {
+ type: 'versions.view',
+ versionId: draft.id,
+ includeSource: true,
+ configPath,
+ workerName: 'test-worker',
+ },
+ { ...tokenEnv(api), CLI_VERSION: 'inherited-version void/stale' },
+ );
+ expect(output.status, output.stderr).toBe(0);
+ const result = decodeCloudflareOperationResult({
+ status: 0,
+ stdout: output.stdout,
+ stderr: '',
+ });
+ expect(result.status, result.stderr).toBe(0);
+ expect(result.data).toEqual(draft);
+ expect(isVoidSecretOnlyDraft(result.data as Record)).toBe(!large);
+ expect(requests).toEqual([
+ `/client/v4/accounts/test-account/workers/workers/test-worker/versions/${draft.id}?include=modules`,
+ ]);
+ expect(output.stdout).not.toContain('synthetic-token');
+ expect(userAgents).toEqual([`cf-cli/${cfVersion} void/${voidVersion}`]);
+ },
+);
+
+it.each([undefined, false, true])(
+ 'sends bypassDeploymentChecks=%s through cf alongside the deployment body',
+ async (bypassDeploymentChecks) => {
+ const directory = temporaryDirectory('void-cf-deployment-checks-');
+ const requests: Array<{ url: string | undefined; body: unknown }> = [];
+ const api = await listen(
+ createServer(async (request, response) => {
+ let body = '';
+ for await (const chunk of request) {
+ body += chunk;
+ }
+ requests.push({ url: request.url, body: JSON.parse(body) });
+ response.setHeader('Content-Type', 'application/json');
+ response.end(JSON.stringify({ success: true, result: { id: 'deployment-id' } }));
+ }),
+ );
+ const preload = join(directory, 'capture-cf.mjs');
+ const callsPath = join(directory, 'calls.json');
+ writeFileSync(
+ preload,
+ `import child from 'node:child_process';
+import { syncBuiltinESMExports } from 'node:module';
+import { writeFileSync } from 'node:fs';
+const spawnSync = child.spawnSync;
+child.spawnSync = (binary, args, options) => {
+ writeFileSync(${JSON.stringify(callsPath)}, JSON.stringify(args.slice(1)));
+ return spawnSync(binary, args, options);
+};
+syncBuiltinESMExports();
+`,
+ );
+ const versionId = '11111111-1111-4111-8111-111111111111';
+ const message = 'Void automatic rollback after readiness failed.';
+ const output = await runOperation(
+ directory,
+ {
+ type: 'versions.deploy',
+ workerName: 'test-worker',
+ versions: [{ versionId, percentage: 100 }],
+ message,
+ bypassDeploymentChecks,
+ },
+ tokenEnv(api),
+ preload,
+ );
+ expect(output.status, output.stderr).toBe(0);
+ expect(decodeCloudflareOperationResult({ ...output, status: 0 }).status).toBe(0);
+ const args = JSON.parse(readFileSync(callsPath, 'utf8')) as Array;
+ expect(args.includes('--bypass-deployment-checks')).toBe(bypassDeploymentChecks === true);
+ expect(args).toContain('--body');
+ expect(requests).toEqual([
+ {
+ url: `/client/v4/accounts/test-account/workers/scripts/test-worker/deployments${bypassDeploymentChecks === true ? '?force=true' : ''}`,
+ body: {
+ strategy: 'percentage',
+ versions: [{ version_id: versionId, percentage: 100 }],
+ annotations: { 'workers/message': message },
+ },
+ },
+ ]);
+ },
+);
+
+it.each([200, 503])(
+ 'reports HTTP %i without loading the build toolchain when domain cleanup returns non-JSON',
+ async (status) => {
+ const directory = temporaryDirectory('void-cf-domain-error-');
+ const api = await listen(
+ createServer((request, response) => {
+ request.resume();
+ response.statusCode = status;
+ response.end('temporary upstream response');
+ }),
+ );
+ const configPath = join(directory, 'wrangler.json');
+ const preload = join(directory, 'reject-build-imports.mjs');
+ writeFileSync(
+ preload,
+ `import { registerHooks } from 'node:module';
+registerHooks({
+ resolve(specifier, context, nextResolve) {
+ if (['vite', '@cloudflare/build-output-utils'].includes(specifier) || specifier.endsWith('/cf-build-output.ts')) {
+ throw new Error('Ancillary operations must not load the build toolchain');
+ }
+ return nextResolve(specifier, context);
+ },
+});
+`,
+ );
+ writeFileSync(configPath, JSON.stringify({ name: 'test-worker', account_id: 'test-account' }));
+ const output = await runOperation(
+ directory,
+ { type: 'triggers.clear-domains', configPath, workerName: 'test-worker' },
+ tokenEnv(api),
+ preload,
+ );
+ expect(output.status).toBe(1);
+ expect(output.stderr).toContain(`HTTP ${status}`);
+ expect(output.stderr).not.toContain('synthetic-token');
+ },
+ 30_000,
+);
+
+it.each(['clear-crons', 'clear-domains'])(
+ 'clears %s through the pinned account API',
+ async (operation) => {
+ const directory = temporaryDirectory('void-cf-clear-crons-');
+ let requested = false;
+ const api = await listen(
+ createServer(async (request, response) => {
+ requested = true;
+ expect(request.method).toBe('PUT');
+ expect(request.url).toBe(
+ `/client/v4/accounts/test-account/workers/scripts/test-worker/${operation === 'clear-crons' ? 'schedules' : 'domains/records'}`,
+ );
+ expect(request.headers.authorization).toBe('Bearer synthetic-token');
+ expect(request.headers['user-agent']).toBe(`void/${voidVersion}`);
+ let body = '';
+ for await (const chunk of request) {
+ body += chunk;
+ }
+ expect(JSON.parse(body)).toEqual(
+ operation === 'clear-crons'
+ ? []
+ : {
+ override_scope: true,
+ override_existing_origin: false,
+ override_existing_dns_record: false,
+ origins: [],
+ },
+ );
+ response.setHeader('Content-Type', 'application/json');
+ response.end(JSON.stringify({ success: true, result: { schedules: [] } }));
+ }),
+ );
+ const configPath = join(directory, 'wrangler.json');
+ writeFileSync(configPath, JSON.stringify({ name: 'test-worker', account_id: 'test-account' }));
+ const output = await runOperation(
+ directory,
+ {
+ type: `triggers.${operation}` as 'triggers.clear-crons' | 'triggers.clear-domains',
+ configPath,
+ workerName: 'test-worker',
+ },
+ tokenEnv(api),
+ );
+ expect(output.status, output.stderr).toBe(0);
+ expect(requested).toBe(true);
+ },
+ 30_000,
+);
+
it.each([
['clear-crons', 'true'],
['clear-domains', 'false'],
@@ -225,6 +567,276 @@ syncBuiltinESMExports();
30_000,
);
+it('discovers KV namespaces beyond the first cf API page', async () => {
+ const directory = temporaryDirectory('void-cf-kv-pages-');
+ const requestedPages: Array = [];
+ const namespaces = Array.from({ length: 100 }, (_, index) => ({
+ id: (index + 1).toString(16).padStart(32, '0'),
+ title: `other-${index}`,
+ }));
+ const target = { id: 'f'.repeat(32), title: 'existing-void-kv' };
+ const api = await listen(
+ createServer((request, response) => {
+ const url = new URL(request.url ?? '', 'http://127.0.0.1');
+ expect(url.pathname).toBe('/client/v4/accounts/test-account/storage/kv/namespaces');
+ expect(url.searchParams.get('per_page')).toBe('100');
+ expect(url.searchParams.get('order')).toBe('id');
+ expect(url.searchParams.get('direction')).toBe('asc');
+ const page = Number(url.searchParams.get('page'));
+ requestedPages.push(page);
+ response.setHeader('Content-Type', 'application/json');
+ response.end(
+ JSON.stringify({
+ success: true,
+ errors: [],
+ messages: [],
+ result: page === 1 ? namespaces : page === 2 ? [target] : [],
+ }),
+ );
+ }),
+ );
+ const configPath = join(directory, 'wrangler.json');
+ writeFileSync(configPath, JSON.stringify({ account_id: 'test-account' }));
+ const output = await runOperation(
+ directory,
+ { type: 'kv.namespace.list', configPath },
+ tokenEnv(api, 'CF_API_TOKEN'),
+ );
+ expect(output.status, output.stderr).toBe(0);
+ expect(JSON.parse(output.stdout).data).toEqual([...namespaces, target]);
+ expect(requestedPages).toEqual([1, 2]);
+}, 30_000);
+
+it('finds existing Queues beyond the first cf API page', async () => {
+ const directory = temporaryDirectory('void-cf-queue-pages-');
+ const requestedPages: Array = [];
+ const api = await listen(
+ createServer((request, response) => {
+ const url = new URL(request.url ?? '', 'http://127.0.0.1');
+ expect(url.pathname).toBe('/client/v4/accounts/test-account/queues');
+ const page = Number(url.searchParams.get('page'));
+ requestedPages.push(page);
+ response.setHeader('Content-Type', 'application/json');
+ response.end(
+ JSON.stringify({
+ success: true,
+ result: [
+ page === 1
+ ? { queue_id: 'first-queue', queue_name: 'another-queue' }
+ : { queue_id: 'target-queue', queue_name: 'existing-void-queue' },
+ ],
+ result_info: { page, per_page: 1, total_pages: 2, total_count: 2 },
+ }),
+ );
+ }),
+ );
+ const configPath = join(directory, 'wrangler.json');
+ writeFileSync(configPath, JSON.stringify({ account_id: 'test-account' }));
+ const output = await runOperation(
+ directory,
+ { type: 'queues.info', name: 'existing-void-queue', configPath },
+ tokenEnv(api, 'CF_API_TOKEN'),
+ );
+ expect(output.status, output.stderr).toBe(0);
+ expect(JSON.parse(output.stdout).data).toMatchObject({ name: 'existing-void-queue' });
+ expect(requestedPages).toEqual([1, 2]);
+}, 30_000);
+
+it.each([
+ {
+ label: 'Worker and HTTP pull consumers',
+ queue: {
+ consumers: [
+ { type: 'worker', script_name: 'app-production', consumer_id: 'one' },
+ { type: 'http_pull', consumer_id: 'two' },
+ ],
+ consumers_total_count: 2,
+ },
+ consumers: ['app-production', null],
+ },
+ { label: 'no consumer', queue: { consumers: [], consumers_total_count: 0 }, consumers: [] },
+ {
+ label: 'an incomplete consumer list',
+ queue: { consumers: [], consumers_total_count: 1 },
+ consumers: undefined,
+ },
+ { label: 'no consumer list', queue: {}, consumers: undefined },
+ {
+ label: 'a legacy script field',
+ queue: { consumers: [{ type: 'worker', script: 'app' }], consumers_total_count: 1 },
+ consumers: ['app'],
+ },
+ {
+ label: 'a Worker consumer without a name',
+ queue: { consumers: [{ type: 'worker', script_name: '' }], consumers_total_count: 1 },
+ consumers: undefined,
+ },
+ {
+ label: 'two different Worker names on one consumer',
+ queue: {
+ consumers: [{ type: 'worker', script_name: 'app', script: 'other' }],
+ consumers_total_count: 1,
+ },
+ consumers: undefined,
+ },
+ {
+ label: 'a consumer of an unknown type',
+ queue: { consumers: [{ type: 'other' }], consumers_total_count: 1 },
+ consumers: undefined,
+ },
+])(
+ 'reports a queue with $label',
+ async ({ queue, consumers }) => {
+ const directory = temporaryDirectory('void-cf-queue-consumers-');
+ const api = await listen(
+ createServer((_request, response) => {
+ response.setHeader('Content-Type', 'application/json');
+ response.end(
+ JSON.stringify({
+ success: true,
+ result: [{ queue_id: 'queue-id', queue_name: 'jobs', ...queue }],
+ result_info: { page: 1, per_page: 1, total_pages: 1, total_count: 1 },
+ }),
+ );
+ }),
+ );
+ const configPath = join(directory, 'wrangler.json');
+ writeFileSync(configPath, JSON.stringify({ account_id: 'test-account' }));
+ const output = await runOperation(
+ directory,
+ { type: 'queues.info', name: 'jobs', configPath },
+ tokenEnv(api, 'CF_API_TOKEN'),
+ );
+ expect(output.status, output.stderr).toBe(0);
+ // Without a complete list the field is left out; only queue naming needs it.
+ expect(JSON.parse(output.stdout).data).toEqual({
+ id: 'queue-id',
+ name: 'jobs',
+ ...(consumers ? { consumers } : {}),
+ });
+ },
+ 30_000,
+);
+
+it.each([
+ {
+ label: 'Cloudflare script_name',
+ consumers: [{ script_name: 'test-worker', consumer_id: 'owned-consumer', type: 'worker' }],
+ deleted: ['owned-consumer'],
+ status: 0,
+ },
+ {
+ label: 'matching legacy alias',
+ consumers: [
+ { script_name: 'test-worker', script: 'test-worker', consumer_id: 'owned-consumer' },
+ ],
+ deleted: ['owned-consumer'],
+ status: 0,
+ },
+ {
+ label: 'foreign Worker and HTTP pull consumers',
+ consumers: [
+ { script_name: 'other-worker', consumer_id: 'foreign-consumer', type: 'worker' },
+ { consumer_id: 'pull-consumer', type: 'http_pull' },
+ ],
+ deleted: [],
+ status: 0,
+ },
+ {
+ label: 'conflicting aliases',
+ consumers: [
+ { script_name: 'other-worker', script: 'test-worker', consumer_id: 'foreign-consumer' },
+ ],
+ deleted: [],
+ status: 1,
+ },
+ {
+ label: 'missing Worker identity',
+ consumers: [{ consumer_id: 'unknown-consumer', type: 'worker' }],
+ deleted: [],
+ status: 1,
+ },
+ {
+ label: 'null Worker identity',
+ consumers: [{ script_name: null, consumer_id: 'unknown-consumer' }],
+ deleted: [],
+ status: 1,
+ },
+ {
+ label: 'missing consumer ID',
+ consumers: [{ script_name: 'test-worker', type: 'worker' }],
+ deleted: [],
+ status: 1,
+ },
+ {
+ label: 'duplicate owned consumers',
+ consumers: [
+ { script_name: 'test-worker', consumer_id: 'first-consumer', type: 'worker' },
+ { script_name: 'test-worker', consumer_id: 'second-consumer', type: 'worker' },
+ ],
+ deleted: [],
+ status: 1,
+ },
+ {
+ label: 'option-shaped consumer ID',
+ consumers: [{ script_name: 'test-worker', consumer_id: '--help', type: 'worker' }],
+ deleted: [],
+ status: 1,
+ },
+])(
+ 'cleans up Queue consumers using verified identities: $label',
+ async ({ consumers, deleted, status }) => {
+ const directory = temporaryDirectory('void-cf-queue-cleanup-');
+ const deletes: Array = [];
+ const api = await listen(
+ createServer((request, response) => {
+ const url = new URL(request.url ?? '', 'http://127.0.0.1');
+ request.resume();
+ response.setHeader('Content-Type', 'application/json');
+ const queuePath = '/client/v4/accounts/test-account/queues';
+ if (request.method === 'GET' && url.pathname === queuePath) {
+ response.end(
+ JSON.stringify({
+ success: true,
+ result: [{ queue_id: 'queue-id', queue_name: 'existing-queue' }],
+ result_info: { page: 1, total_pages: 1 },
+ }),
+ );
+ } else if (request.method === 'GET' && url.pathname === `${queuePath}/queue-id/consumers`) {
+ response.end(JSON.stringify({ success: true, result: consumers }));
+ } else if (
+ request.method === 'DELETE' &&
+ url.pathname.startsWith(`${queuePath}/queue-id/consumers/`)
+ ) {
+ deletes.push(url.pathname.split('/').at(-1)!);
+ response.end(JSON.stringify({ success: true, result: {} }));
+ } else {
+ response.statusCode = 400;
+ response.end(
+ JSON.stringify({ success: false, errors: [{ message: 'Unexpected request' }] }),
+ );
+ }
+ }),
+ );
+ const configPath = join(directory, 'wrangler.json');
+ writeFileSync(configPath, JSON.stringify({ account_id: 'test-account', name: 'test-worker' }));
+ const output = await runOperation(
+ directory,
+ {
+ type: 'queues.consumer.remove',
+ queueName: 'existing-queue',
+ workerName: 'test-worker',
+ configPath,
+ },
+ tokenEnv(api, 'CF_API_TOKEN'),
+ );
+ expect(output.status, output.stderr).toBe(status);
+ expect(deletes).toEqual(deleted);
+ expect(output.stderr).not.toContain('synthetic-token');
+ },
+ 30_000,
+);
+
it('uses pinned cf despite a project-local CLI and preserves D1 results and the CF token alias', async () => {
const directory = temporaryDirectory('void-cf-d1-contract-');
const requests: Array<{ method: string; path: string; authorization: string | undefined }> = [];
@@ -384,6 +996,404 @@ it('uses the configured HTTP proxy for cf resource requests', async () => {
expect(proxied).toBe(1);
}, 30_000);
+it.each([401, 403, 404, 503])(
+ 'stops a prebuilt platform upload before cf can provision an unavailable R2 bucket (HTTP %s)',
+ async (status) => {
+ const directory = temporaryDirectory('void-cf-platform-r2-preflight-');
+ const requests: Array = [];
+ const api = await listen(
+ createServer((request, response) => {
+ requests.push(`${request.method} ${request.url}`);
+ response.statusCode = status;
+ response.setHeader('Content-Type', 'application/json');
+ response.end(JSON.stringify({ success: false, errors: [{ code: 10006 }] }));
+ }),
+ );
+ const configPath = join(directory, 'wrangler.json');
+ writeFileSync(
+ join(directory, 'index.js'),
+ 'export default { fetch() { return new Response("ok") } };',
+ );
+ writeFileSync(
+ configPath,
+ JSON.stringify({
+ name: 'test-worker',
+ account_id: 'test-account',
+ compatibility_date: '2026-09-29',
+ main: 'index.js',
+ no_bundle: true,
+ r2_buckets: [{ binding: 'ASSETS', bucket_name: 'missing-bucket' }],
+ }),
+ );
+ const output = await runOperation(
+ directory,
+ { type: 'versions.upload', configPath },
+ unproxiedEnv(api),
+ );
+ expect(output.status).toBe(1);
+ expect(output.stderr).toContain('refusing automatic provisioning');
+ expect(output.stderr).toContain(`HTTP ${status}`);
+ expect(requests).toEqual(['GET /client/v4/accounts/test-account/r2/buckets/missing-bucket']);
+ },
+ 30_000,
+);
+
+it.each(['ordinary', 'versions.upload', 'worker.deploy'] as const)(
+ 'allows a prebuilt %s upload and scopes installation attribution to the cf child',
+ async (uploadType) => {
+ const directory = temporaryDirectory('void-cf-platform-resource-preflight-');
+ const requests: Array = [];
+ const jurisdictions: Array = [];
+ const api = await listen(
+ createServer((request, response) => {
+ const path = request.url ?? '';
+ requests.push(`${request.method} ${path}`);
+ if (path.includes('/r2/buckets/')) {
+ jurisdictions.push(request.headers['cf-r2-jurisdiction'] as string | undefined);
+ }
+ response.setHeader('Content-Type', 'application/json');
+ response.end(
+ JSON.stringify({
+ success: true,
+ result:
+ path.endsWith('/queues') || path.includes('/queues?page=')
+ ? [{ queue_id: 'queue-id', queue_name: 'existing-queue' }]
+ : {},
+ ...(path.includes('/queues?page=') ? { result_info: { page: 1, total_pages: 1 } } : {}),
+ }),
+ );
+ }),
+ );
+ const configPath = join(directory, 'wrangler.json');
+ writeFileSync(
+ join(directory, 'index.js'),
+ 'export default { fetch() { return new Response("ok") } };',
+ );
+ writeFileSync(
+ configPath,
+ JSON.stringify({
+ name: 'test-worker',
+ account_id: 'test-account',
+ compatibility_date: '2026-09-29',
+ main: 'index.js',
+ no_bundle: true,
+ r2_buckets: [{ binding: 'ASSETS', bucket_name: 'existing-bucket', jurisdiction: 'eu' }],
+ queues: { producers: [{ binding: 'JOBS', queue: 'existing-queue' }] },
+ dispatch_namespaces: [{ binding: 'DISPATCH', namespace: 'existing-namespace' }],
+ ...(uploadType === 'ordinary'
+ ? {}
+ : {
+ vars: {
+ PLATFORM_VERSION: '0.27.0',
+ PLATFORM_OWNERSHIP_MARKER: JSON.stringify({
+ schemaVersion: 1,
+ accountId: 'test-account',
+ installationId: 'installation-one',
+ ownershipNonce: 'private-ownership-proof',
+ resourceId: 'test-worker',
+ resourceName: 'test-worker',
+ resourceKey: 'api-worker',
+ resourceKind: 'worker',
+ }),
+ },
+ }),
+ }),
+ );
+ const preload = join(directory, 'mock-version-upload.mjs');
+ writeFileSync(
+ preload,
+ `import child from 'node:child_process';
+import { writeFileSync } from 'node:fs';
+import { syncBuiltinESMExports } from 'node:module';
+const actualSpawnSync=child.spawnSync;
+child.spawnSync = (binary, args, options) => {
+ if(args.slice(1,4).join(' ') !== 'workers versions create' && args[1] !== 'deploy') return actualSpawnSync(binary,args,options);
+ writeFileSync(${JSON.stringify(join(directory, 'upload-environment.json'))}, JSON.stringify({version:options.env.CLI_VERSION,telemetry:options.env.CF_SEND_TELEMETRY}));
+ return ${
+ uploadType === 'worker.deploy'
+ ? // cf 1.0.0-beta.21 and later print the uploaded version on stderr.
+ "{ status:0, stdout:'', stderr:'│ Current Version ID: 11111111-1111-4111-8111-111111111111\\n' }"
+ : "{ status:0, stdout:JSON.stringify({id:'11111111-1111-4111-8111-111111111111'}), stderr:'' }"
+ };
+};
+syncBuiltinESMExports();`,
+ );
+ const output = await runOperation(
+ directory,
+ { type: uploadType === 'ordinary' ? 'versions.upload' : uploadType, configPath },
+ unproxiedEnv(api),
+ preload,
+ );
+ expect(output.status, output.stderr).toBe(0);
+ expect(JSON.parse(output.stdout).data).toEqual({
+ versionId: '11111111-1111-4111-8111-111111111111',
+ });
+ expect(requests).toEqual([
+ 'GET /client/v4/accounts/test-account/r2/buckets/existing-bucket',
+ 'GET /client/v4/accounts/test-account/workers/dispatch/namespaces/existing-namespace',
+ 'GET /client/v4/accounts/test-account/queues?page=1',
+ ]);
+ expect(jurisdictions).toEqual(['eu']);
+ const uploadEnvironment = JSON.parse(
+ readFileSync(join(directory, 'upload-environment.json'), 'utf8'),
+ );
+ expect(uploadEnvironment).toEqual({
+ version:
+ cfVersion +
+ ' void/' +
+ voidVersion +
+ (uploadType === 'ordinary'
+ ? ''
+ : ' void-platform-install/0.27.0 void-role/api-worker void-installation/installation-one'),
+ telemetry: 'false',
+ });
+ expect(JSON.stringify(uploadEnvironment)).not.toContain('private-ownership-proof');
+ },
+ 30_000,
+);
+
+it.each([
+ { label: 'uppercase proxy variables', lowercase: false, bypass: false, authenticated: false },
+ { label: 'lowercase proxy variables', lowercase: true, bypass: false, authenticated: false },
+ { label: 'NO_PROXY bypass', lowercase: false, bypass: true, authenticated: false },
+ { label: 'no_proxy bypass', lowercase: true, bypass: true, authenticated: false },
+ { label: 'authenticated proxy', lowercase: false, bypass: false, authenticated: true },
+])(
+ 'inspects existing Worker versions with $label',
+ async ({ lowercase, bypass, authenticated }) => {
+ const directory = temporaryDirectory('void-cf-proxy-contract-');
+ const versionId = '11111111-1111-4111-8111-111111111111';
+ let proxied = 0;
+ let inspected = 0;
+ const proxyAuthorizations: Array = [];
+ // Node passes only one case variant of each environment key on Windows.
+ // Clear inherited variants so the lowercase case does not lose to an empty uppercase value.
+ const proxyEnvironment = Object.fromEntries(
+ Object.entries(process.env).filter(
+ ([key]) =>
+ !['HTTP_PROXY', 'HTTPS_PROXY', 'NO_PROXY', 'NODE_USE_ENV_PROXY'].includes(
+ key.toUpperCase(),
+ ),
+ ),
+ );
+ const api = await listen(
+ createServer((request, response) => {
+ inspected++;
+ expect(request.headers.authorization).toBe('Bearer synthetic-token');
+ expect(request.headers['proxy-authorization']).toBeUndefined();
+ expect(request.url).toBe(
+ `/client/v4/accounts/test-account/workers/scripts/test-worker/versions/${versionId}`,
+ );
+ response.setHeader('Content-Type', 'application/json');
+ response.end(
+ JSON.stringify({
+ success: true,
+ result: {
+ resources: { bindings: [], script: { handlers: ['fetch'] }, script_runtime: {} },
+ },
+ }),
+ );
+ }),
+ );
+ const proxy = createServer((request, response) => {
+ proxied++;
+ proxyAuthorizations.push(request.headers['proxy-authorization']);
+ const { 'proxy-authorization': _proxyAuthorization, ...headers } = request.headers;
+ const upstream = httpRequest(
+ new URL(request.url!),
+ { method: request.method, headers },
+ (upstreamResponse) => {
+ response.writeHead(upstreamResponse.statusCode ?? 502, upstreamResponse.headers);
+ upstreamResponse.pipe(response);
+ },
+ );
+ upstream.on('error', () => response.destroy());
+ request.pipe(upstream);
+ });
+ proxy.on('connect', (request, socket, head) => {
+ proxied++;
+ proxyAuthorizations.push(request.headers['proxy-authorization']);
+ const [host, port] = request.url!.split(':');
+ const upstream = connect(Number(port), host!, () => {
+ socket.write('HTTP/1.1 200 Connection Established\r\n\r\n');
+ if (head.length) {
+ upstream.write(head);
+ }
+ socket.pipe(upstream).pipe(socket);
+ });
+ upstream.on('error', () => socket.destroy());
+ });
+ const proxyOrigin = await listen(proxy);
+ const proxyUrl = authenticated
+ ? proxyOrigin.replace('http://', 'http://proxy-user:proxy-pass@')
+ : proxyOrigin;
+ const configPath = join(directory, 'wrangler.json');
+ const preload = join(directory, 'mock-cf.mjs');
+ writeFileSync(configPath, JSON.stringify({ name: 'test-worker', account_id: 'test-account' }));
+ writeFileSync(
+ preload,
+ `import child from 'node:child_process';
+import { syncBuiltinESMExports } from 'node:module';
+child.spawnSync = () => ({ status: 0, stdout: JSON.stringify({ id: '${versionId}', bindings: [] }), stderr: '' });
+syncBuiltinESMExports();
+`,
+ );
+ const output = await runOperation(
+ directory,
+ { type: 'versions.view', versionId, configPath },
+ {
+ ...proxyEnvironment,
+ CLOUDFLARE_ACCOUNT_ID: 'test-account',
+ CLOUDFLARE_API_TOKEN: 'synthetic-token',
+ CLOUDFLARE_API_BASE_URL: `${api}/client/v4`,
+ [lowercase ? 'http_proxy' : 'HTTP_PROXY']: proxyUrl,
+ [lowercase ? 'no_proxy' : 'NO_PROXY']: bypass ? '127.0.0.1' : '',
+ NODE_USE_ENV_PROXY: '',
+ },
+ preload,
+ );
+ expect(output.status, output.stderr).toBe(0);
+ expect(JSON.parse(output.stdout).data.resources.bindings).toEqual([]);
+ expect(proxied).toBe(bypass ? 0 : 1);
+ expect(proxyAuthorizations).toEqual(
+ bypass
+ ? []
+ : [
+ authenticated
+ ? `Basic ${Buffer.from('proxy-user:proxy-pass').toString('base64')}`
+ : undefined,
+ ],
+ );
+ expect(inspected).toBe(1);
+ },
+ 30_000,
+);
+
+it.each([
+ {
+ operation: { type: 'email.routing.settings' as const, domain: 'acme.com' },
+ commands: [
+ {
+ command: ['email-routing', 'settings', 'get', '--zone', 'acme.com'],
+ data: {
+ name: 'acme.com',
+ enabled: true,
+ status: 'ready',
+ tag: '11111111111111111111111111111111',
+ },
+ },
+ ],
+ expected: {
+ name: 'acme.com',
+ enabled: true,
+ status: 'ready',
+ tag: '11111111111111111111111111111111',
+ },
+ },
+ {
+ operation: { type: 'email.sending.settings' as const, domain: 'mail.acme.com' },
+ commands: [
+ {
+ command: ['email-routing', 'settings', 'get', '--zone', 'mail.acme.com'],
+ status: 1,
+ stderr: 'Zone not found: mail.acme.com',
+ },
+ {
+ command: ['email-routing', 'settings', 'get', '--zone', 'acme.com'],
+ data: {
+ name: 'acme.com',
+ enabled: true,
+ status: 'ready',
+ tag: '11111111111111111111111111111111',
+ },
+ },
+ {
+ command: ['email-sending', 'subdomains', 'list', '--zone', 'acme.com'],
+ data: [{ name: 'mail.acme.com', enabled: true, id: '22222222222222222222222222222222' }],
+ },
+ ],
+ expected: { name: 'mail.acme.com', enabled: true, id: '22222222222222222222222222222222' },
+ },
+ {
+ operation: { type: 'email.routing.rules.list' as const, domain: 'acme.com' },
+ commands: [
+ {
+ command: [
+ 'email-routing',
+ 'rules',
+ 'list-account',
+ '--page',
+ '1',
+ '--per-page',
+ '100',
+ '--zone',
+ 'acme.com',
+ ],
+ data: Array.from({ length: 100 }, (_, index) => ({
+ id: `rule-${index}`,
+ name: 'support',
+ enabled: index % 2 === 0,
+ matchers: [{ type: 'literal', field: 'to', value: `support-${index}@acme.com` }],
+ actions: [{ type: 'worker', value: ['my-worker'] }],
+ })),
+ },
+ {
+ command: [
+ 'email-routing',
+ 'rules',
+ 'list-account',
+ '--page',
+ '2',
+ '--per-page',
+ '100',
+ '--zone',
+ 'acme.com',
+ ],
+ data: [{ enabled: false, matchers: [{ type: 'all' }], actions: [{ type: 'drop' }] }],
+ },
+ ],
+ },
+])('returns structured email data for $operation', async ({ operation, commands, ...example }) => {
+ const directory = temporaryDirectory('void-cf-email-json-');
+ const preload = join(directory, 'mock-cf.mjs');
+ const callsPath = join(directory, 'calls.json');
+ writeFileSync(
+ preload,
+ `import child from 'node:child_process';
+import { syncBuiltinESMExports } from 'node:module';
+import { writeFileSync } from 'node:fs';
+const commands = ${JSON.stringify(commands)};
+const calls = [];
+child.spawnSync = (_executable, args) => {
+ const command = args.slice(1);
+ calls.push(command);
+ writeFileSync(${JSON.stringify(callsPath)}, JSON.stringify(calls));
+ const response = commands[calls.length - 1];
+ if (JSON.stringify(command) !== JSON.stringify(response?.command)) {
+ return { status: 1, stdout: '', stderr: 'Unexpected email transport command' };
+ }
+ return { status: response.status ?? 0, stdout: response.data === undefined ? '' : JSON.stringify(response.data), stderr: response.stderr ?? '' };
+};
+syncBuiltinESMExports();
+`,
+ );
+ const output = await runOperation(
+ directory,
+ operation,
+ { ...systemEnv, CI: 'true', CLOUDFLARE_AUTH_USE_KEYRING: 'false' },
+ preload,
+ );
+ expect(output.status, output.stderr).toBe(0);
+ expect(JSON.parse(output.stdout).data).toEqual(
+ 'expected' in example
+ ? example.expected
+ : commands.flatMap((command) => command.data ?? []),
+ );
+ expect(JSON.parse(readFileSync(callsPath, 'utf8'))).toEqual(
+ commands.map((command) => command.command),
+ );
+});
+
it.each([
{ label: 'malformed JSON', request: '{', extra: [] },
{ label: 'null request', request: 'null', extra: [] },
@@ -616,6 +1626,85 @@ it('renders binary and text frames from a real Node WebSocket in order and remov
});
}, 30_000);
+it.each([false, true])(
+ 'attaches cf to the terminal only for an interactive platform upload (interactive: %s)',
+ async (interactive) => {
+ const directory = temporaryDirectory('void-cf-interactive-upload-');
+ const requests: Array = [];
+ const api = await listen(
+ createServer((request, response) => {
+ requests.push(`${request.method} ${request.url}`);
+ response.statusCode = 500;
+ response.end();
+ }),
+ );
+ const configPath = join(directory, 'wrangler.json');
+ writeFileSync(
+ join(directory, 'index.js'),
+ 'export default { fetch() { return new Response("ok") } };',
+ );
+ writeFileSync(
+ configPath,
+ JSON.stringify({
+ name: 'test-worker',
+ account_id: 'test-account',
+ compatibility_date: '2026-09-29',
+ main: 'index.js',
+ no_bundle: true,
+ }),
+ );
+ const record = join(directory, 'cf-stdio.json');
+ const preload = join(directory, 'mock-interactive-upload.mjs');
+ writeFileSync(
+ preload,
+ `import child from 'node:child_process';
+import { writeFileSync } from 'node:fs';
+import { syncBuiltinESMExports } from 'node:module';
+const actualSpawnSync=child.spawnSync;
+child.spawnSync = (binary, args, options) => {
+ if(args.slice(1,4).join(' ') !== 'workers versions create') return actualSpawnSync(binary,args,options);
+ writeFileSync(${JSON.stringify(record)}, JSON.stringify({stdio:options.stdio,args:args.slice(1)}));
+ return options.stdio === 'inherit'
+ ? { status:0, stdout:null, stderr:null }
+ : { status:0, stdout:JSON.stringify({id:'11111111-1111-4111-8111-111111111111'}), stderr:'' };
+};
+syncBuiltinESMExports();`,
+ );
+ const output = await runOperation(
+ directory,
+ {
+ type: 'versions.upload',
+ configPath,
+ message: '-review',
+ ...(interactive ? { interactive } : {}),
+ },
+ unproxiedEnv(api),
+ preload,
+ );
+ expect(output.status, output.stderr).toBe(0);
+ const called = JSON.parse(readFileSync(record, 'utf8'));
+ expect(called.args).toEqual([
+ 'workers',
+ 'versions',
+ 'create',
+ '--prebuilt',
+ '--message=-review',
+ ]);
+ if (interactive) {
+ expect(called.stdio).toBe('inherit');
+ // The terminal shows cf's own output; no result envelope follows it.
+ expect(output.stdout).toBe('');
+ } else {
+ expect(called.stdio).toEqual(['ignore', 'pipe', 'pipe']);
+ expect(JSON.parse(output.stdout).data).toEqual({
+ versionId: '11111111-1111-4111-8111-111111111111',
+ });
+ }
+ expect(requests).toEqual([]);
+ },
+ 30_000,
+);
+
it.each(['canonical', 'alias', 'bearer'] as const)(
'reads the account workers.dev subdomain with %s credentials',
async (credentials) => {
diff --git a/packages/void/test/unit/test-fixture-inputs.test.ts b/packages/void/test/unit/test-fixture-inputs.test.ts
deleted file mode 100644
index cc728c89a..000000000
--- a/packages/void/test/unit/test-fixture-inputs.test.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
-import { tmpdir } from 'node:os';
-import { join } from 'node:path';
-import { afterEach, beforeEach, expect, it } from 'vite-plus/test';
-import { prepareFixture, type FixtureApp } from '../../../../test/fixture-app.ts';
-
-let root: string;
-const fixture: FixtureApp = {
- framework: 'react',
- name: 'inputs',
- files: { 'pages/old.island.tsx': 'export default function Page() { return Old
; }' },
-};
-
-beforeEach(() => {
- root = mkdtempSync(join(tmpdir(), 'void-fixture-inputs-'));
-});
-afterEach(() => {
- rmSync(root, { recursive: true, force: true, maxRetries: 20, retryDelay: 50 });
-});
-
-it('does not replace an existing directory it does not own', () => {
- writeFileSync(join(root, 'keep.txt'), 'existing application');
- expect(() => prepareFixture(fixture, root)).toThrow('unowned fixture directory');
- expect(readFileSync(join(root, 'keep.txt'), 'utf8')).toBe('existing application');
-});
-
-it('does not give a different fixture ownership of the same directory', () => {
- prepareFixture(fixture, root);
- expect(() => prepareFixture({ ...fixture, name: 'different' }, root)).toThrow(
- 'different application',
- );
- expect(existsSync(join(root, 'pages/old.island.tsx'))).toBe(true);
-});
-
-it('replaces the complete source tree while leaving build outputs to their owning task', () => {
- prepareFixture(fixture, root);
- mkdirSync(join(root, 'dist/client'), { recursive: true });
- writeFileSync(join(root, 'dist/client/index.html'), 'previous build');
- prepareFixture(
- {
- ...fixture,
- files: { 'pages/new.island.tsx': 'export default function Page() { return New
; }' },
- },
- root,
- );
- expect(existsSync(join(root, 'pages/old.island.tsx'))).toBe(false);
- expect(readFileSync(join(root, 'pages/new.island.tsx'), 'utf8')).toContain('New');
- expect(readFileSync(join(root, 'dist/client/index.html'), 'utf8')).toBe('previous build');
- expect(existsSync(join(root, 'node_modules/@void/react/package.json'))).toBe(true);
-});
diff --git a/packages/void/vite.config.ts b/packages/void/vite.config.ts
index 2abb77ba1..faab5bdce 100644
--- a/packages/void/vite.config.ts
+++ b/packages/void/vite.config.ts
@@ -58,14 +58,6 @@ function injectWorkersTypesReferencePlugin() {
}
export default defineConfig({
- run: {
- tasks: {
- build: {
- command: 'node scripts/sync-docs.mjs && vp pack',
- dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
- },
- },
- },
pack: {
entry: [
'src/index.ts',
diff --git a/packages/vue/package.json b/packages/vue/package.json
index 6e7114be9..b34ae1379 100644
--- a/packages/vue/package.json
+++ b/packages/vue/package.json
@@ -38,6 +38,7 @@
"access": "public"
},
"scripts": {
+ "build": "vp pack",
"dev": "vp pack --watch",
"typecheck": "tsc --noEmit --rootDir ../.."
},
diff --git a/packages/vue/test/integration/island-css-build.test.ts b/packages/vue/test/integration/island-css-build.test.ts
index faa465156..717819f6d 100644
--- a/packages/vue/test/integration/island-css-build.test.ts
+++ b/packages/vue/test/integration/island-css-build.test.ts
@@ -1,13 +1,33 @@
-import { afterAll, expect } from 'vite-plus/test';
-import { buildFixture, type BuiltFixture } from '../../../../test/fixture-app.ts';
-import { islands } from '../../../../test/fixtures/vue.ts';
+import { join } from 'node:path';
+import { expect } from 'vite-plus/test';
import { defineIslandCssBuildTest } from '../../../../test/island-css-build.ts';
-let built: BuiltFixture | undefined;
-afterAll(() => built?.cleanup());
-
defineIslandCssBuildTest({
- build: () => (built ??= buildFixture(islands)),
+ packageDir: join(import.meta.dirname, '../..'),
+ pluginName: 'voidVue',
+ files: {
+ 'src/shell.css': '.shell { outline-offset: 7px; }',
+ 'src/Badge.vue': `Badge
+`,
+ 'src/Shell.vue': `
+Note
Card
+
+
+`,
+ 'pages/layout.vue': `
+`,
+ 'pages/index.island.vue': 'Home
',
+ // The layout renders Badge without hydrating it; this page hydrates it.
+ 'pages/badge.island.vue': `
+`,
+ },
expectedCss: [
'.shell{outline-offset:7px}',
'main{outline-width:9px}',
diff --git a/packages/vue/test/integration/page-errors.test.ts b/packages/vue/test/integration/page-errors.test.ts
deleted file mode 100644
index 6569f6a70..000000000
--- a/packages/vue/test/integration/page-errors.test.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import { definePageErrorsTests } from '../../../void/test/integration/page-errors.cases.ts';
-
-definePageErrorsTests('vue');
diff --git a/packages/vue/test/integration/vue-pages-client.test.ts b/packages/vue/test/integration/vue-pages-client.test.ts
index 64750b08d..19461b4f9 100644
--- a/packages/vue/test/integration/vue-pages-client.test.ts
+++ b/packages/vue/test/integration/vue-pages-client.test.ts
@@ -1,11 +1,10 @@
-import { type ChildProcess } from 'node:child_process';
-import { readFileSync, writeFileSync } from 'node:fs';
+import { execSync, type ChildProcess } from 'node:child_process';
+import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { type Browser, type Page } from 'playwright';
import { describe, expect, it, beforeAll, afterAll } from 'vite-plus/test';
import { collectBrowserDiagnostics } from '../../../../test/browser-helpers.ts';
import {
- buildPlayground,
killChild,
spawnPlaygroundServer,
startServer,
@@ -343,7 +342,12 @@ describe('vue-pages client (preview)', { retry: 2 }, () => {
let child: ChildProcess | undefined;
beforeAll(async () => {
- buildPlayground(ROOT, 'vue-pages');
+ if (!existsSync(join(ROOT, 'playground/vue-pages/dist'))) {
+ execSync('vp run --filter ./playground/vue-pages build', {
+ cwd: ROOT,
+ stdio: 'pipe',
+ });
+ }
const server = await startServer(
(port) => (child = spawnPlaygroundServer(ROOT, 'vue-pages', 'preview', port)),
diff --git a/packages/vue/vite.config.ts b/packages/vue/vite.config.ts
index af630a259..47a8e0c01 100644
--- a/packages/vue/vite.config.ts
+++ b/packages/vue/vite.config.ts
@@ -1,23 +1,6 @@
import { defineConfig } from 'vite-plus';
export default defineConfig({
- run: {
- tasks: {
- 'prepare:test:islands': {
- command: 'node ../../test/prepare-fixture.ts vue islands',
- dependsOn: ['build', '@void/md#build'],
- cache: false,
- },
- 'build:test:islands': {
- command: 'node ../../playground-local/.build-fixtures/vue-islands/build.mjs',
- dependsOn: ['prepare:test:islands'],
- },
- build: {
- command: 'vp pack',
- dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
- },
- },
- },
pack: {
entry: [
'src/runtime/PageErrorBoundary.ts',
diff --git a/platform/packages/api/test/integration/global-setup.ts b/platform/packages/api/test/integration/global-setup.ts
index ee5a9f4d6..c585eefb7 100644
--- a/platform/packages/api/test/integration/global-setup.ts
+++ b/platform/packages/api/test/integration/global-setup.ts
@@ -1,5 +1,5 @@
+import { ensurePGliteTemplateBundlePath } from './db-template.ts';
+
export default async function setup(): Promise {
- // The public package setup runs first; defer imports that use those exports until then.
- const { ensurePGliteTemplateBundlePath } = await import('./db-template.ts');
await ensurePGliteTemplateBundlePath();
}
diff --git a/platform/packages/dashboard/package.json b/platform/packages/dashboard/package.json
index b029fbbca..b49629eed 100644
--- a/platform/packages/dashboard/package.json
+++ b/platform/packages/dashboard/package.json
@@ -4,6 +4,7 @@
"private": true,
"type": "module",
"scripts": {
+ "build": "vp build",
"deploy": "node ../../scripts/wrangler-deploy.ts --build",
"deploy:staging": "node ../../scripts/wrangler-deploy.ts --build --env staging",
"dev": "node scripts/refresh-access-token.mjs && vp dev",
diff --git a/platform/packages/dashboard/vite.config.ts b/platform/packages/dashboard/vite.config.ts
index 5c0c329de..bbdbea930 100644
--- a/platform/packages/dashboard/vite.config.ts
+++ b/platform/packages/dashboard/vite.config.ts
@@ -4,14 +4,6 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
- run: {
- tasks: {
- build: {
- command: 'vp build',
- dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
- },
- },
- },
plugins: [
voidPlugin({
persistTo: resolve(__dirname, '../api/.wrangler/state'),
diff --git a/playground/analog/package.json b/playground/analog/package.json
index a4d02a362..b96a311a7 100644
--- a/playground/analog/package.json
+++ b/playground/analog/package.json
@@ -3,6 +3,7 @@
"private": true,
"type": "module",
"scripts": {
+ "build": "vp build",
"dev": "vp dev"
},
"dependencies": {
diff --git a/playground/analog/vite.config.ts b/playground/analog/vite.config.ts
index d4aa249d9..06931bcdc 100644
--- a/playground/analog/vite.config.ts
+++ b/playground/analog/vite.config.ts
@@ -4,14 +4,6 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
- run: {
- tasks: {
- build: {
- command: 'vp build',
- dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
- },
- },
- },
resolve: {
mainFields: ['module'],
},
diff --git a/playground/astro/package.json b/playground/astro/package.json
index ce16c9626..b42b4fc0c 100644
--- a/playground/astro/package.json
+++ b/playground/astro/package.json
@@ -3,6 +3,7 @@
"private": true,
"type": "module",
"scripts": {
+ "build": "astro build",
"dev": "astro dev"
},
"dependencies": {
diff --git a/playground/astro/vite.config.ts b/playground/astro/vite.config.ts
deleted file mode 100644
index e3bb87232..000000000
--- a/playground/astro/vite.config.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-import { defineConfig } from 'vite-plus';
-
-export default defineConfig({
- run: {
- tasks: {
- build: {
- command: 'astro build',
- dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
- },
- },
- },
-});
diff --git a/playground/http-errors/package.json b/playground/http-errors/package.json
index 271ee84d2..a0471f52f 100644
--- a/playground/http-errors/package.json
+++ b/playground/http-errors/package.json
@@ -3,6 +3,7 @@
"private": true,
"type": "module",
"scripts": {
+ "build": "vp build",
"dev": "vp dev",
"typecheck": "tsc --noEmit"
},
diff --git a/playground/http-errors/vite.config.ts b/playground/http-errors/vite.config.ts
index d2d2b9647..48c1c0d91 100644
--- a/playground/http-errors/vite.config.ts
+++ b/playground/http-errors/vite.config.ts
@@ -3,14 +3,6 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
- run: {
- tasks: {
- build: {
- command: 'vp build',
- dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
- },
- },
- },
define: {
__HTTP_ERRORS_SOURCE_ROOT__: JSON.stringify(new URL('./', import.meta.url).href),
},
diff --git a/playground/kitchen-sink/package.json b/playground/kitchen-sink/package.json
index e62aa3e2a..b4db24f78 100644
--- a/playground/kitchen-sink/package.json
+++ b/playground/kitchen-sink/package.json
@@ -3,6 +3,7 @@
"private": true,
"type": "module",
"scripts": {
+ "build": "vp build",
"dev": "vp dev",
"preview": "vp preview",
"remote": "VOID_REMOTE=1 vp dev",
diff --git a/playground/kitchen-sink/vite.config.ts b/playground/kitchen-sink/vite.config.ts
index 1fda86b89..82eaf98e6 100644
--- a/playground/kitchen-sink/vite.config.ts
+++ b/playground/kitchen-sink/vite.config.ts
@@ -3,13 +3,5 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
- run: {
- tasks: {
- build: {
- command: 'vp build',
- dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
- },
- },
- },
plugins: [voidPlugin(), voidVue()],
});
diff --git a/playground/markdown-blog/package.json b/playground/markdown-blog/package.json
index 806409a50..070b464d2 100644
--- a/playground/markdown-blog/package.json
+++ b/playground/markdown-blog/package.json
@@ -3,6 +3,7 @@
"private": true,
"type": "module",
"scripts": {
+ "build": "vp build",
"dev": "vp dev",
"preview": "vp preview",
"typecheck": "tsc --noEmit"
diff --git a/playground/markdown-blog/vite.config.ts b/playground/markdown-blog/vite.config.ts
index 62dffb6d6..06823dabb 100644
--- a/playground/markdown-blog/vite.config.ts
+++ b/playground/markdown-blog/vite.config.ts
@@ -4,13 +4,5 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
- run: {
- tasks: {
- build: {
- command: 'vp build',
- dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
- },
- },
- },
plugins: [voidPlugin(), voidVue(), voidMarkdown()],
});
diff --git a/playground/mysql-test/package.json b/playground/mysql-test/package.json
index ddb5f57bd..6f8f11eb9 100644
--- a/playground/mysql-test/package.json
+++ b/playground/mysql-test/package.json
@@ -3,6 +3,7 @@
"private": true,
"type": "module",
"scripts": {
+ "build": "vp build",
"dev": "vp dev",
"preview": "vp preview",
"typecheck": "tsc --noEmit"
diff --git a/playground/mysql-test/vite.config.ts b/playground/mysql-test/vite.config.ts
index d36b4a924..2bae9de06 100644
--- a/playground/mysql-test/vite.config.ts
+++ b/playground/mysql-test/vite.config.ts
@@ -2,13 +2,5 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
- run: {
- tasks: {
- build: {
- command: 'vp build',
- dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
- },
- },
- },
plugins: [voidPlugin()],
});
diff --git a/playground/named-layouts/package.json b/playground/named-layouts/package.json
index 7f06d4d56..eb44da10e 100644
--- a/playground/named-layouts/package.json
+++ b/playground/named-layouts/package.json
@@ -3,6 +3,7 @@
"private": true,
"type": "module",
"scripts": {
+ "build": "vp build",
"dev": "vp dev",
"preview": "vp preview"
},
diff --git a/playground/named-layouts/vite.config.ts b/playground/named-layouts/vite.config.ts
index cfddac695..f2669c611 100644
--- a/playground/named-layouts/vite.config.ts
+++ b/playground/named-layouts/vite.config.ts
@@ -4,13 +4,5 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
- run: {
- tasks: {
- build: {
- command: 'vp build',
- dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
- },
- },
- },
plugins: [voidPlugin(), voidReact(), voidMarkdown()],
});
diff --git a/playground/node-app/package.json b/playground/node-app/package.json
index bce36f268..a86261853 100644
--- a/playground/node-app/package.json
+++ b/playground/node-app/package.json
@@ -3,6 +3,7 @@
"private": true,
"type": "module",
"scripts": {
+ "build": "vp build",
"dev": "vp dev",
"preview": "vp preview",
"start": "node dist/ssr/index.js"
diff --git a/playground/node-app/vite.config.ts b/playground/node-app/vite.config.ts
index 0a3c9ad47..7dcd4c641 100644
--- a/playground/node-app/vite.config.ts
+++ b/playground/node-app/vite.config.ts
@@ -3,13 +3,5 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
- run: {
- tasks: {
- build: {
- command: 'vp build',
- dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
- },
- },
- },
plugins: [voidPlugin(), voidReact()],
});
diff --git a/playground/node-static-md/package.json b/playground/node-static-md/package.json
index 109e7a962..1a355ebac 100644
--- a/playground/node-static-md/package.json
+++ b/playground/node-static-md/package.json
@@ -3,6 +3,7 @@
"private": true,
"type": "module",
"scripts": {
+ "build": "vp build",
"dev": "vp dev",
"preview": "vp preview"
},
diff --git a/playground/node-static-md/vite.config.ts b/playground/node-static-md/vite.config.ts
index f9a6a354d..0a7703ecd 100644
--- a/playground/node-static-md/vite.config.ts
+++ b/playground/node-static-md/vite.config.ts
@@ -5,13 +5,5 @@ import { voidPlugin } from 'void';
// Markdown-only: every page is an implicit island with no client-side JS.
export default defineConfig({
- run: {
- tasks: {
- build: {
- command: 'vp build',
- dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
- },
- },
- },
plugins: [voidPlugin(), voidReact(), voidMarkdown()],
});
diff --git a/playground/node-static/package.json b/playground/node-static/package.json
index daf3b86a9..276f0b14b 100644
--- a/playground/node-static/package.json
+++ b/playground/node-static/package.json
@@ -3,6 +3,7 @@
"private": true,
"type": "module",
"scripts": {
+ "build": "vp build",
"dev": "vp dev",
"preview": "vp preview",
"serve:static": "node scripts/serve-static.mjs"
diff --git a/playground/node-static/vite.config.ts b/playground/node-static/vite.config.ts
index 0a3c9ad47..7dcd4c641 100644
--- a/playground/node-static/vite.config.ts
+++ b/playground/node-static/vite.config.ts
@@ -3,13 +3,5 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
- run: {
- tasks: {
- build: {
- command: 'vp build',
- dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
- },
- },
- },
plugins: [voidPlugin(), voidReact()],
});
diff --git a/playground/nuxt/package.json b/playground/nuxt/package.json
index dc112493c..8fad54eed 100644
--- a/playground/nuxt/package.json
+++ b/playground/nuxt/package.json
@@ -3,6 +3,7 @@
"private": true,
"type": "module",
"scripts": {
+ "build": "nuxt build",
"dev": "nuxt dev"
},
"dependencies": {
diff --git a/playground/nuxt/vite.config.ts b/playground/nuxt/vite.config.ts
deleted file mode 100644
index e9021c53b..000000000
--- a/playground/nuxt/vite.config.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-import { defineConfig } from 'vite-plus';
-
-export default defineConfig({
- run: {
- tasks: {
- build: {
- command: 'nuxt build',
- dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
- },
- },
- },
-});
diff --git a/playground/pg-api-test/package.json b/playground/pg-api-test/package.json
index 99291ddf8..b844c5b08 100644
--- a/playground/pg-api-test/package.json
+++ b/playground/pg-api-test/package.json
@@ -3,6 +3,7 @@
"private": true,
"type": "module",
"scripts": {
+ "build": "vp build",
"dev": "vp dev",
"preview": "vp preview",
"typecheck": "tsc --noEmit"
diff --git a/playground/pg-api-test/vite.config.ts b/playground/pg-api-test/vite.config.ts
index d36b4a924..2bae9de06 100644
--- a/playground/pg-api-test/vite.config.ts
+++ b/playground/pg-api-test/vite.config.ts
@@ -2,13 +2,5 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
- run: {
- tasks: {
- build: {
- command: 'vp build',
- dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
- },
- },
- },
plugins: [voidPlugin()],
});
diff --git a/playground/pg-test/package.json b/playground/pg-test/package.json
index 67d0d4e30..3d94d77f7 100644
--- a/playground/pg-test/package.json
+++ b/playground/pg-test/package.json
@@ -3,6 +3,7 @@
"private": true,
"type": "module",
"scripts": {
+ "build": "vp build",
"dev": "vp dev",
"typecheck": "tsc --noEmit"
},
diff --git a/playground/pg-test/vite.config.ts b/playground/pg-test/vite.config.ts
index 0a3c9ad47..7dcd4c641 100644
--- a/playground/pg-test/vite.config.ts
+++ b/playground/pg-test/vite.config.ts
@@ -3,13 +3,5 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
- run: {
- tasks: {
- build: {
- command: 'vp build',
- dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
- },
- },
- },
plugins: [voidPlugin(), voidReact()],
});
diff --git a/playground/react-pages/package.json b/playground/react-pages/package.json
index b76f0932c..fec075a96 100644
--- a/playground/react-pages/package.json
+++ b/playground/react-pages/package.json
@@ -3,6 +3,7 @@
"private": true,
"type": "module",
"scripts": {
+ "build": "vp build",
"dev": "vp dev",
"preview": "vp preview",
"typecheck": "tsc --noEmit"
diff --git a/playground/react-pages/vite.config.ts b/playground/react-pages/vite.config.ts
index c5d5a2e8d..de06ddc1e 100644
--- a/playground/react-pages/vite.config.ts
+++ b/playground/react-pages/vite.config.ts
@@ -3,14 +3,6 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
- run: {
- tasks: {
- build: {
- command: 'vp build',
- dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
- },
- },
- },
plugins: [voidPlugin(), voidReact()],
// stabilize dev server start for tests
optimizeDeps: { include: ['valibot', 'react-dom', 'react/jsx-dev-runtime'] },
diff --git a/playground/react-router/build.mjs b/playground/react-router/build.mjs
deleted file mode 100644
index aef483f33..000000000
--- a/playground/react-router/build.mjs
+++ /dev/null
@@ -1,22 +0,0 @@
-import { spawnSync } from 'node:child_process';
-import { readFileSync } from 'node:fs';
-import { fileURLToPath } from 'node:url';
-
-const manifest = new URL(import.meta.resolve('@react-router/dev/package.json'));
-const { bin } = JSON.parse(readFileSync(manifest, 'utf8'));
-const reactRouter = fileURLToPath(new URL(bin['react-router'], manifest));
-
-// Type generation and the build both write framework configuration. Cache their final output
-// as one task so restoring the earlier stage cannot overwrite the completed build's files.
-for (const args of [
- [reactRouter, 'typegen'],
- [reactRouter, 'build', ...process.argv.slice(2)],
-]) {
- const result = spawnSync(process.execPath, args, { stdio: 'inherit' });
- if (result.error) {
- throw result.error;
- }
- if (result.status !== 0) {
- process.exit(result.status ?? 1);
- }
-}
diff --git a/playground/react-router/package.json b/playground/react-router/package.json
index 815b426d0..03be98ec4 100644
--- a/playground/react-router/package.json
+++ b/playground/react-router/package.json
@@ -3,6 +3,7 @@
"private": true,
"type": "module",
"scripts": {
+ "build": "react-router typegen && vp build",
"dev": "vp dev"
},
"dependencies": {
diff --git a/playground/react-router/vite.config.ts b/playground/react-router/vite.config.ts
index c068d402a..81961d6c3 100644
--- a/playground/react-router/vite.config.ts
+++ b/playground/react-router/vite.config.ts
@@ -3,13 +3,5 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
- run: {
- tasks: {
- build: {
- command: 'node build.mjs',
- dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
- },
- },
- },
plugins: [voidPlugin(), reactRouter()],
});
diff --git a/playground/server-auth-errors/package.json b/playground/server-auth-errors/package.json
index 134c9c511..44c3376b8 100644
--- a/playground/server-auth-errors/package.json
+++ b/playground/server-auth-errors/package.json
@@ -3,6 +3,7 @@
"private": true,
"type": "module",
"scripts": {
+ "build": "vp build",
"dev": "vp dev",
"typecheck": "tsc --noEmit"
},
diff --git a/playground/server-auth-errors/vite.config.ts b/playground/server-auth-errors/vite.config.ts
index 1b7bd521f..4a594243f 100644
--- a/playground/server-auth-errors/vite.config.ts
+++ b/playground/server-auth-errors/vite.config.ts
@@ -3,14 +3,6 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
- run: {
- tasks: {
- build: {
- command: 'vp build',
- dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
- },
- },
- },
define: {
__SERVER_AUTH_ERRORS_SOURCE_ROOT__: JSON.stringify(new URL('./', import.meta.url).href),
},
diff --git a/playground/solid-pages/package.json b/playground/solid-pages/package.json
index 66a8364ba..fc5b1bab6 100644
--- a/playground/solid-pages/package.json
+++ b/playground/solid-pages/package.json
@@ -3,6 +3,7 @@
"private": true,
"type": "module",
"scripts": {
+ "build": "vp build",
"dev": "vp dev",
"preview": "vp preview",
"typecheck": "tsc --noEmit"
diff --git a/playground/solid-pages/vite.config.ts b/playground/solid-pages/vite.config.ts
index 16709a5b3..bd458d256 100644
--- a/playground/solid-pages/vite.config.ts
+++ b/playground/solid-pages/vite.config.ts
@@ -3,14 +3,6 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
- run: {
- tasks: {
- build: {
- command: 'vp build',
- dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
- },
- },
- },
plugins: [voidPlugin(), voidSolid()],
// stabilize dev server start for tests
optimizeDeps: { include: ['valibot'] },
diff --git a/playground/spa/package.json b/playground/spa/package.json
index 1556f1d14..1baddb974 100644
--- a/playground/spa/package.json
+++ b/playground/spa/package.json
@@ -3,6 +3,7 @@
"private": true,
"type": "module",
"scripts": {
+ "build": "vp build",
"dev": "vp dev",
"preview": "vp preview",
"typecheck": "tsc --noEmit"
diff --git a/playground/spa/vite.config.ts b/playground/spa/vite.config.ts
index 10301a857..36a2318f7 100644
--- a/playground/spa/vite.config.ts
+++ b/playground/spa/vite.config.ts
@@ -3,13 +3,5 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
- run: {
- tasks: {
- build: {
- command: 'vp build',
- dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
- },
- },
- },
plugins: [react(), voidPlugin()],
});
diff --git a/playground/ssr/package.json b/playground/ssr/package.json
index cb17db0cd..6a3b611f6 100644
--- a/playground/ssr/package.json
+++ b/playground/ssr/package.json
@@ -3,6 +3,7 @@
"private": true,
"type": "module",
"scripts": {
+ "build": "vp build",
"dev": "vp dev",
"preview": "vp preview"
},
diff --git a/playground/ssr/vite.config.ts b/playground/ssr/vite.config.ts
index 10301a857..36a2318f7 100644
--- a/playground/ssr/vite.config.ts
+++ b/playground/ssr/vite.config.ts
@@ -3,13 +3,5 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
- run: {
- tasks: {
- build: {
- command: 'vp build',
- dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
- },
- },
- },
plugins: [react(), voidPlugin()],
});
diff --git a/playground/static-pages/package.json b/playground/static-pages/package.json
index 7e22a9d95..a2fe6a8a6 100644
--- a/playground/static-pages/package.json
+++ b/playground/static-pages/package.json
@@ -3,6 +3,7 @@
"private": true,
"type": "module",
"scripts": {
+ "build": "vp build",
"dev": "vp dev",
"preview": "vp preview"
},
diff --git a/playground/static-pages/vite.config.ts b/playground/static-pages/vite.config.ts
index e3c800624..b95685391 100644
--- a/playground/static-pages/vite.config.ts
+++ b/playground/static-pages/vite.config.ts
@@ -22,13 +22,5 @@ function virtualTagsPlugin(): Plugin {
}
export default defineConfig({
- run: {
- tasks: {
- build: {
- command: 'vp build',
- dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
- },
- },
- },
plugins: [voidPlugin(), voidVue(), virtualTagsPlugin()],
});
diff --git a/playground/svelte-pages/package.json b/playground/svelte-pages/package.json
index 08fde873b..94f507bd9 100644
--- a/playground/svelte-pages/package.json
+++ b/playground/svelte-pages/package.json
@@ -3,6 +3,7 @@
"private": true,
"type": "module",
"scripts": {
+ "build": "vp build",
"dev": "vp dev",
"preview": "vp preview",
"typecheck": "tsc --noEmit"
diff --git a/playground/svelte-pages/vite.config.ts b/playground/svelte-pages/vite.config.ts
index 8d8ea628c..c197a8f47 100644
--- a/playground/svelte-pages/vite.config.ts
+++ b/playground/svelte-pages/vite.config.ts
@@ -3,14 +3,6 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
- run: {
- tasks: {
- build: {
- command: 'vp build',
- dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
- },
- },
- },
plugins: [voidPlugin(), voidSvelte()],
// stabilize dev server start for tests
optimizeDeps: { include: ['valibot'] },
diff --git a/playground/sveltekit/package.json b/playground/sveltekit/package.json
index 48318bb9b..e83f29c3e 100644
--- a/playground/sveltekit/package.json
+++ b/playground/sveltekit/package.json
@@ -3,6 +3,7 @@
"private": true,
"type": "module",
"scripts": {
+ "build": "vp build",
"dev": "vp dev",
"typecheck": "void prepare && svelte-kit sync && tsc --noEmit"
},
diff --git a/playground/sveltekit/vite.config.ts b/playground/sveltekit/vite.config.ts
index 803921b6f..a14191db7 100644
--- a/playground/sveltekit/vite.config.ts
+++ b/playground/sveltekit/vite.config.ts
@@ -3,14 +3,6 @@ import { sveltekit } from '@sveltejs/kit/vite';
import { voidPlugin } from 'void';
export default {
- run: {
- tasks: {
- build: {
- command: 'vp build',
- dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
- },
- },
- },
plugins: [
voidPlugin(),
sveltekit({
diff --git a/playground/tanstack-start/package.json b/playground/tanstack-start/package.json
index 7eadbeff9..4440c8761 100644
--- a/playground/tanstack-start/package.json
+++ b/playground/tanstack-start/package.json
@@ -3,6 +3,7 @@
"private": true,
"type": "module",
"scripts": {
+ "build": "vp build",
"dev": "vp dev"
},
"dependencies": {
diff --git a/playground/tanstack-start/vite.config.ts b/playground/tanstack-start/vite.config.ts
index 1bb14dcd2..22e73ec90 100644
--- a/playground/tanstack-start/vite.config.ts
+++ b/playground/tanstack-start/vite.config.ts
@@ -4,14 +4,6 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
- run: {
- tasks: {
- build: {
- command: 'vp build',
- dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
- },
- },
- },
plugins: [
// voidPlugin wraps @cloudflare/vite-plugin — must come before tanstackStart
voidPlugin(),
diff --git a/playground/vinext-app/package.json b/playground/vinext-app/package.json
index 9c0494d90..be4b4811a 100644
--- a/playground/vinext-app/package.json
+++ b/playground/vinext-app/package.json
@@ -3,6 +3,7 @@
"private": true,
"type": "module",
"scripts": {
+ "build": "vp build",
"dev": "vp dev"
},
"dependencies": {
diff --git a/playground/vinext-app/vite.config.ts b/playground/vinext-app/vite.config.ts
index 0b403cfcb..fa671ebd7 100644
--- a/playground/vinext-app/vite.config.ts
+++ b/playground/vinext-app/vite.config.ts
@@ -3,13 +3,5 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
- run: {
- tasks: {
- build: {
- command: 'vp build',
- dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
- },
- },
- },
plugins: [voidPlugin(), vinext()],
});
diff --git a/playground/vinext-pages/package.json b/playground/vinext-pages/package.json
index df1d556a7..7c1ee82fd 100644
--- a/playground/vinext-pages/package.json
+++ b/playground/vinext-pages/package.json
@@ -3,6 +3,7 @@
"private": true,
"type": "module",
"scripts": {
+ "build": "vp build",
"dev": "vp dev"
},
"dependencies": {
diff --git a/playground/vinext-pages/vite.config.ts b/playground/vinext-pages/vite.config.ts
index 0b403cfcb..fa671ebd7 100644
--- a/playground/vinext-pages/vite.config.ts
+++ b/playground/vinext-pages/vite.config.ts
@@ -3,13 +3,5 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
- run: {
- tasks: {
- build: {
- command: 'vp build',
- dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
- },
- },
- },
plugins: [voidPlugin(), vinext()],
});
diff --git a/playground/vue-pages/package.json b/playground/vue-pages/package.json
index 1cc7001ed..86e3a3856 100644
--- a/playground/vue-pages/package.json
+++ b/playground/vue-pages/package.json
@@ -3,6 +3,7 @@
"private": true,
"type": "module",
"scripts": {
+ "build": "vp build",
"dev": "vp dev",
"preview": "vp preview",
"typecheck": "tsc --noEmit"
diff --git a/playground/vue-pages/vite.config.ts b/playground/vue-pages/vite.config.ts
index cfe5350e6..39ec3e1ab 100644
--- a/playground/vue-pages/vite.config.ts
+++ b/playground/vue-pages/vite.config.ts
@@ -3,14 +3,6 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
- run: {
- tasks: {
- build: {
- command: 'vp build',
- dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
- },
- },
- },
plugins: [voidPlugin(), voidVue()],
// stabilize dev server start for tests
optimizeDeps: { include: ['valibot'] },
diff --git a/playground/websockets/package.json b/playground/websockets/package.json
index 5eb55e887..3f804b43f 100644
--- a/playground/websockets/package.json
+++ b/playground/websockets/package.json
@@ -3,6 +3,7 @@
"private": true,
"type": "module",
"scripts": {
+ "build": "vp build",
"dev": "vp dev",
"preview": "vp preview",
"typecheck": "tsc --noEmit"
diff --git a/playground/websockets/vite.config.ts b/playground/websockets/vite.config.ts
index da39a5f2a..d77f451a3 100644
--- a/playground/websockets/vite.config.ts
+++ b/playground/websockets/vite.config.ts
@@ -3,14 +3,6 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
- run: {
- tasks: {
- build: {
- command: 'vp build',
- dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
- },
- },
- },
plugins: [voidPlugin(), voidReact()],
optimizeDeps: { include: ['valibot'] },
});
diff --git a/playground/zero-js/package.json b/playground/zero-js/package.json
index 16b64816e..86d01659e 100644
--- a/playground/zero-js/package.json
+++ b/playground/zero-js/package.json
@@ -3,6 +3,7 @@
"private": true,
"type": "module",
"scripts": {
+ "build": "vp build",
"dev": "vp dev",
"preview": "vp preview"
},
diff --git a/playground/zero-js/vite.config.ts b/playground/zero-js/vite.config.ts
index 62dffb6d6..06823dabb 100644
--- a/playground/zero-js/vite.config.ts
+++ b/playground/zero-js/vite.config.ts
@@ -4,13 +4,5 @@ import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
- run: {
- tasks: {
- build: {
- command: 'vp build',
- dependsOn: [{ task: 'build', from: ['dependencies', 'devDependencies'] }],
- },
- },
- },
plugins: [voidPlugin(), voidVue(), voidMarkdown()],
});
diff --git a/test/affected.mjs b/test/affected.mjs
index f6aaa7285..d0759d5cb 100644
--- a/test/affected.mjs
+++ b/test/affected.mjs
@@ -1,15 +1,15 @@
+import { spawnSync } from 'node:child_process';
import { globSync, readFileSync, realpathSync } from 'node:fs';
import { join, relative } from 'node:path';
import { fileURLToPath } from 'node:url';
import { parseArgs } from 'node:util';
import { deletedFiles, planAffectedTests } from './affected-tests.ts';
import { createAffectedVcsProvider } from './affected-vcs.ts';
-import { preparePublicPackages } from './build-setup.ts';
async function runAffected(root, values) {
root = realpathSync(root);
if (values.help) {
- console.log('vp run test [--base [] [--list] [--unit] [--report ]');
+ console.log('vp run test [--base ][] [--list] [--unit]');
console.log(
'Defaults to staged, unstaged, and untracked changes. --base includes branch changes.',
);
@@ -37,10 +37,19 @@ async function runAffected(root, values) {
console.log('Documentation-only changes: no runtime tests selected. Verify docs separately.');
return;
}
- let publicBuildMilliseconds;
if (initial.build && !values.list) {
console.log('Refreshing public package builds before testing their installed exports.');
- publicBuildMilliseconds = await preparePublicPackages(root);
+ const build = spawnSync('vp', ['run', 'build'], {
+ cwd: root,
+ stdio: 'inherit',
+ shell: process.platform === 'win32',
+ });
+ if (build.error) {
+ throw build.error;
+ }
+ if (build.status !== 0) {
+ throw new Error(`Public package build failed (${build.status ?? build.signal}).`);
+ }
}
console.log('Initializing Vitest and discovering test files...');
const { createVitest } = await import('vite-plus/test/node');
@@ -49,22 +58,10 @@ async function runAffected(root, values) {
watch: false,
changed: initial.full ? false : changed,
experimental: { vcsProvider },
- ...(values.report
- ? {
- reporters: [
- 'default',
- fileURLToPath(new URL('./performance-reporter.ts', import.meta.url)),
- ],
- outputFile: values.report,
- }
- : {}),
...(values.unit
? { project: ['unit', 'unit-pglite', 'cli-unit', 'platform-unit', 'platform-unit-pglite'] }
: {}),
});
- if (publicBuildMilliseconds !== undefined) {
- vitest.provide('publicBuildMilliseconds', publicBuildMilliseconds);
- }
try {
const all = await vitest.globTestSpecifications();
if (!all.length) {
@@ -139,7 +136,6 @@ try {
base: { type: 'string' },
list: { type: 'boolean' },
unit: { type: 'boolean' },
- report: { type: 'string' },
help: { type: 'boolean', short: 'h' },
},
});
diff --git a/test/build-setup.ts b/test/build-setup.ts
deleted file mode 100644
index 08afd8dd6..000000000
--- a/test/build-setup.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-import spawn from 'cross-spawn';
-import type { TestProject } from 'vite-plus/test/node';
-
-declare module 'vite-plus/test' {
- export interface ProvidedContext {
- publicBuildMilliseconds: number;
- }
-}
-
-export async function preparePublicPackages(root: string): Promise {
- const started = performance.now();
- await new Promise((resolve, reject) => {
- const child = spawn('vp', ['run', 'build'], {
- cwd: root,
- // Clear Vitest's mode so build tools use their production defaults and the same cache
- // fingerprint as a normal `vp run build` outside the test runner.
- env: { ...process.env, NODE_ENV: undefined },
- stdio: ['ignore', 'pipe', 'pipe'],
- });
- let output = '';
- const collect = (chunk: Buffer) => {
- output = (output + chunk.toString()).slice(-200_000);
- };
- child.stdout?.on('data', collect);
- child.stderr?.on('data', collect);
- child.once('error', reject);
- child.once('close', (code) => {
- if (code === 0) {
- resolve();
- } else {
- reject(new Error(`Public package preparation failed (${code}).\n${output}`));
- }
- });
- });
- return performance.now() - started;
-}
-
-/** Restore/build public exports before any integration worker imports them. */
-export default async function setup(project: TestProject): Promise {
- const vitest = project.vitest;
- if (vitest.getProvidedContext().publicBuildMilliseconds !== undefined) {
- return;
- }
- const build = async () => {
- vitest.provide('publicBuildMilliseconds', await preparePublicPackages(vitest.config.root));
- };
- await build();
- vitest.onTestsRerun(build);
-}
diff --git a/test/fixture-app.ts b/test/fixture-app.ts
deleted file mode 100644
index 5e328b5e2..000000000
--- a/test/fixture-app.ts
+++ /dev/null
@@ -1,194 +0,0 @@
-import {
- cpSync,
- existsSync,
- mkdirSync,
- mkdtempSync,
- readFileSync,
- readdirSync,
- realpathSync,
- rmSync,
- writeFileSync,
-} from 'node:fs';
-import { dirname, join } from 'node:path';
-import { fileURLToPath } from 'node:url';
-import spawn from 'cross-spawn';
-import { fixtureBuildCacheArgs, linkFixtureDependencies } from './integration-helpers.ts';
-
-export type FixtureFramework = 'react' | 'vue' | 'svelte' | 'solid';
-export type FixtureApp = {
- framework: FixtureFramework;
- name: string;
- files: Readonly>;
-};
-
-const repository = fileURLToPath(new URL('../', import.meta.url));
-const plugins = {
- react: 'voidReact',
- vue: 'voidVue',
- svelte: 'voidSvelte',
- solid: 'voidSolid',
-} as const;
-const ownershipFile = '.void-test-fixture.json';
-const generated = new Set([
- ownershipFile,
- 'node_modules',
- 'dist',
- '.cloudflare',
- '.void',
- '.wrangler',
- '.vite',
-]);
-
-export function fixtureBuildRoot(fixture: FixtureApp): string {
- return join(
- repository,
- 'playground-local',
- '.build-fixtures',
- `${fixture.framework}-${fixture.name}`,
- );
-}
-
-/** Materialize inputs before Vite Task checks the build cache. No build results are cached here. */
-export function prepareFixture(
- fixture: FixtureApp,
- root: string = fixtureBuildRoot(fixture),
-): void {
- mkdirSync(root, { recursive: true });
- root = realpathSync.native(root);
- const ownership = JSON.stringify({ framework: fixture.framework, name: fixture.name });
- const marker = join(root, ownershipFile);
- if (existsSync(marker)) {
- if (readFileSync(marker, 'utf8') !== ownership) {
- throw new Error(`Fixture directory belongs to a different application: ${root}`);
- }
- } else {
- if (readdirSync(root).length) {
- throw new Error(`Refusing to replace files in an unowned fixture directory: ${root}`);
- }
- writeFileSync(marker, ownership, { flag: 'wx' });
- }
- // This directory belongs to the fixture. Preserve outputs so Vite Task can validate/restore
- // them, but replace the complete authored input tree, including deleted routes.
- for (const entry of readdirSync(root)) {
- if (!generated.has(entry)) {
- rmSync(join(root, entry), { recursive: true, force: true });
- }
- }
- const packageRoot = join(repository, 'packages', fixture.framework);
- linkFixtureDependencies(packageRoot, root, {
- void: join(repository, 'packages/void'),
- [`@void/${fixture.framework}`]: packageRoot,
- '@void/md': join(repository, 'packages/md'),
- });
- const plugin = plugins[fixture.framework];
- const files = {
- 'package.json': JSON.stringify({
- name: `void-test-${fixture.framework}-${fixture.name}`,
- private: true,
- type: 'module',
- dependencies: {
- void: 'workspace:*',
- [`@void/${fixture.framework}`]: 'workspace:*',
- '@void/md': 'workspace:*',
- },
- }),
- 'vite.config.mjs': `import { voidPlugin } from 'void';
-import { ${plugin} } from '@void/${fixture.framework}/plugin';
-import { voidMarkdown } from '@void/md/plugin';
-export default { plugins: [voidPlugin(), ${plugin}(), voidMarkdown()] };
-`,
- 'void.config.ts': `import { defineConfig } from 'void/config';
-export default defineConfig({ output: 'static', worker: { compatibility_date: '2026-02-24' } });
-`,
- // Use the fixture's installed Vite instance and its public builder API. Running another
- // task-runner CLI here would make workspace discovery part of this build's inputs.
- 'build.mjs': `import { realpathSync } from 'node:fs';
-process.env.NODE_ENV = 'production';
-process.chdir(realpathSync.native(import.meta.dirname));
-const { createBuilder } = await import('vite');
-const builder = await createBuilder({ configLoader: 'native' });
-await builder.buildApp();
-`,
- 'pages/about.md': '---\ntitle: About\n---\n\n# About\n',
- ...fixture.files,
- };
- for (const [file, contents] of Object.entries(files)) {
- const path = join(root, file);
- mkdirSync(dirname(path), { recursive: true });
- writeFileSync(path, contents);
- }
-}
-
-export type BuiltFixture = {
- root: string;
- page(file: string): { html: string; css: string };
- output(dir: 'client' | 'ssr'): Map;
- cleanup(): void;
-};
-
-/** One immutable cached build can supply separate writable runtime copies. */
-export function buildFixture(fixture: FixtureApp): BuiltFixture {
- prepareFixture(fixture);
- const result = spawn.sync(
- 'vp',
- [
- 'run',
- '--ignore-depends-on',
- ...fixtureBuildCacheArgs(),
- `@void/${fixture.framework}#build:test:${fixture.name}`,
- ],
- {
- cwd: repository,
- env: { ...process.env, NODE_ENV: undefined },
- encoding: 'utf8',
- maxBuffer: 10 * 1024 * 1024,
- },
- );
- if (result.error || result.status !== 0) {
- throw new Error(`Fixture build failed.\n${result.stdout ?? ''}${result.stderr ?? ''}`, {
- cause: result.error,
- });
- }
- const runs = join(repository, 'playground-local', '.test-fixtures');
- mkdirSync(runs, { recursive: true });
- const root = mkdtempSync(join(runs, `${fixture.framework}-${fixture.name}-`));
- try {
- prepareFixture(fixture, root);
- const built = fixtureBuildRoot(fixture);
- for (const directory of ['dist', '.cloudflare']) {
- if (existsSync(join(built, directory))) {
- cpSync(join(built, directory), join(root, directory), { recursive: true });
- }
- }
- } catch (error) {
- rmSync(root, { recursive: true, force: true });
- throw error;
- }
- const client = join(root, 'dist/client');
- return {
- root,
- page(file) {
- const html = readFileSync(join(client, file), 'utf8');
- const css = html
- .split(' readFileSync(join(client, href), 'utf8'))
- .join('\n');
- return { html, css };
- },
- output(dir) {
- const output = join(root, 'dist', dir);
- const files = new Map();
- for (const file of readdirSync(output, { recursive: true, encoding: 'utf8' })) {
- if (/\.(js|css|html)$/.test(file)) {
- files.set(file, readFileSync(join(output, file), 'utf8'));
- }
- }
- return files;
- },
- cleanup() {
- rmSync(root, { recursive: true, force: true, maxRetries: 20, retryDelay: 50 });
- },
- };
-}
diff --git a/test/fixtures/markdown-scripts.ts b/test/fixtures/markdown-scripts.ts
deleted file mode 100644
index b5e38b2de..000000000
--- a/test/fixtures/markdown-scripts.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-import type { FixtureApp } from '../fixture-app.ts';
-
-export const markdownScripts: FixtureApp = {
- framework: 'react',
- name: 'markdown-scripts',
- files: {
- 'tsconfig.json': JSON.stringify({ compilerOptions: { jsx: 'react-jsx' } }),
- 'components/Counter.island.tsx': `import { useState } from 'react';
-export default function Counter() {
- const [count, setCount] = useState(0);
- return ;
-}`,
- 'pages/script.md': `
-
-# Script
-
-unset
-`,
- 'pages/mixed.md': `
-
-# Mixed
-
-unset
-
-
-`,
- },
-};
diff --git a/test/fixtures/private-pages.ts b/test/fixtures/private-pages.ts
deleted file mode 100644
index 0a0d8bd5c..000000000
--- a/test/fixtures/private-pages.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-/** Shared application input, not a model of the adapter's implementation. */
-export function privatePages(
- framework: 'react' | 'solid',
- counter: string,
-): Record {
- const attribute = framework === 'react' ? 'className' : 'class';
- return {
- 'pages/_ui/frame.tsx': `import './frame.css';
-export function Frame(props) {
- return {props.children};
-}`,
- 'pages/_ui/frame.css': '.private-frame { outline-offset: 11px; }',
- 'pages/_ui/counter.tsx': counter,
- 'pages/_layouts/docs.tsx': `import './docs.css';
-export default function Docs(props) {
- return ;
-}`,
- 'pages/_layouts/docs.css': '.private-layout { word-spacing: 3px; }',
- 'pages/private.island.tsx': `import { Frame } from './_ui/frame';
-import Counter from './_ui/counter' with { island: 'load' };
-export const layout = 'docs';
-export default function Private() { return ; }`,
- };
-}
diff --git a/test/fixtures/react.ts b/test/fixtures/react.ts
deleted file mode 100644
index 93dd8a852..000000000
--- a/test/fixtures/react.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-import type { FixtureApp } from '../fixture-app.ts';
-import { markdownScripts } from './markdown-scripts.ts';
-import { privatePages } from './private-pages.ts';
-
-const tsconfig = JSON.stringify({ compilerOptions: { jsx: 'react-jsx' } });
-
-export const islands: FixtureApp = {
- framework: 'react',
- name: 'islands',
- files: {
- 'tsconfig.json': tsconfig,
- 'src/shell.css': '.shell { outline-offset: 7px; }',
- 'src/card.module.css': '.card { text-indent: 9px; }',
- 'src/badge.css': '.badge { word-spacing: 5px; }',
- 'src/Badge.tsx': `import './badge.css';
-export default function Badge() { return Badge; }`,
- 'src/Shell.tsx': `import './shell.css';
-import styles from './card.module.css';
-import Badge from './Badge';
-export default function Shell({ children }) {
- return {children};
-}`,
- 'pages/layout.tsx': `import Shell from '../src/Shell';
-export default function Layout({ children }) { return {children}; }`,
- 'pages/index.island.tsx': 'export default function Home() { return ]Home
; }',
- 'pages/badge.island.tsx': `import Badge from '../src/Badge' with { island: 'load' };
-export default function BadgePage() { return ; }`,
- ...privatePages(
- 'react',
- `import { useState } from 'react';
-export default function Counter() {
- const [count, setCount] = useState(0);
- return ;
-}`,
- ),
- },
-};
-
-export const bare: FixtureApp = {
- framework: 'react',
- name: 'bare',
- files: {
- 'tsconfig.json': tsconfig,
- 'pages/layout.tsx':
- 'export default function Layout({ children }) { return {children}; }',
- 'pages/index.island.tsx': 'export default function Home() { return Home
; }',
- },
-};
-
-export const fixtures: Readonly> = {
- islands,
- bare,
- 'markdown-scripts': markdownScripts,
-};
diff --git a/test/fixtures/solid-hydration.ts b/test/fixtures/solid-hydration.ts
deleted file mode 100644
index 6e2de1ca1..000000000
--- a/test/fixtures/solid-hydration.ts
+++ /dev/null
@@ -1,76 +0,0 @@
-import type { FixtureApp } from '../fixture-app.ts';
-
-const counter = `import { createSignal, createUniqueId, useContext } from 'solid-js';
-import { FrontmatterContext } from '@void/solid';
-export default function Counter(props) {
- const [count, setCount] = createSignal(props.initial);
- const id = createUniqueId();
- return ;
-}`;
-
-const capture = `window.__ssrCounters = Object.fromEntries(
- Array.from(document.querySelectorAll('[data-counter]')).map(host => {
- const input = host.querySelector('input');
- input.value = 'draft-' + host.dataset.counter;
- return [host.dataset.counter, { button: host.querySelector('button'), input }];
- })
-);`;
-
-const files = {
- 'components/Counter.tsx': counter,
- 'components/AsyncCounter.tsx': `
-import { createResource, Suspense } from 'solid-js';
-import Counter from './Counter';
-export default function AsyncCounter() {
- const [name] = createResource(async () => {
- await new Promise(resolve => setTimeout(resolve, 10));
- return 'async';
- });
- return Loading}>
-
- ;
-}`,
- 'pages/layout.island.tsx': `
-import Counter from '../components/Counter' with { island: 'load' };
-export default function Layout(props) {
- return {props.children}
;
-}`,
- 'pages/index.island.tsx': `
-import Counter from '../components/Counter' with { island: 'load' };
-import VisibleCounter from '../components/Counter' with { island: 'visible' };
-import AsyncCounter from '../components/AsyncCounter' with { island: 'load' };
-export const frontmatter = { title: 'Island metadata' };
-export default function Page() {
- return
-
-
-
-
-
-
-
- ;
-}`,
- 'pages/plain.island.tsx': `
-import Counter from '../components/Counter' with { island: 'load' };
-export default function Plain() {
- return
-
-
- ;
-}`,
-};
-
-export const hydration: FixtureApp = {
- framework: 'solid',
- name: 'hydration',
- files: {
- 'tsconfig.json': JSON.stringify({
- compilerOptions: { jsx: 'preserve', jsxImportSource: 'solid-js' },
- }),
- ...files,
- },
-};
diff --git a/test/fixtures/solid.ts b/test/fixtures/solid.ts
deleted file mode 100644
index 40d3ca877..000000000
--- a/test/fixtures/solid.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-import type { FixtureApp } from '../fixture-app.ts';
-import { privatePages } from './private-pages.ts';
-import { hydration } from './solid-hydration.ts';
-
-const cssFiles = {
- 'tsconfig.json': JSON.stringify({
- compilerOptions: { jsx: 'preserve', jsxImportSource: 'solid-js' },
- }),
- 'src/shell.css': '.shell { outline-offset: 7px; }',
- 'src/card.module.css': '.card { text-indent: 9px; }',
- 'src/badge.css': '.badge { word-spacing: 5px; }',
- 'src/Badge.tsx': `import './badge.css';
-export default function Badge() { return Badge; }`,
- 'src/Shell.tsx': `import './shell.css';
-import styles from './card.module.css';
-import Badge from './Badge';
-export default function Shell(props) {
- return {props.children};
-}`,
- 'pages/layout.tsx': `import Shell from '../src/Shell';
-export default function Layout(props) { return {props.children}; }`,
- 'pages/index.island.tsx': 'export default function Home() { return Home
; }',
- // The layout renders Badge without hydrating it; this page hydrates it.
- 'pages/badge.island.tsx': `import Badge from '../src/Badge' with { island: 'load' };
-export default function BadgePage() { return ; }`,
-};
-
-export const islands: FixtureApp = {
- framework: 'solid',
- name: 'islands',
- files: {
- ...cssFiles,
- ...privatePages(
- 'solid',
- `import { createSignal } from 'solid-js';
-export default function Counter() {
- const [count, setCount] = createSignal(0);
- return ;
-}`,
- ),
- },
-};
-export const fixtures: Readonly> = { islands, hydration };
diff --git a/test/fixtures/svelte.ts b/test/fixtures/svelte.ts
deleted file mode 100644
index e1b57d97c..000000000
--- a/test/fixtures/svelte.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import type { FixtureApp } from '../fixture-app.ts';
-
-const files = {
- 'src/shell.css': '.shell { outline-offset: 7px; }',
- 'src/card.module.css': '.card { text-indent: 9px; }',
- 'src/Badge.svelte': 'Badge\n',
- 'src/Shell.svelte': `
-{@render children()}
-`,
- 'pages/layout.svelte': `
-{@render children()}`,
- 'pages/index.island.svelte': 'Home
',
- // The layout renders Badge without hydrating it; this page hydrates it.
- 'pages/badge.island.svelte': `
-`,
-};
-
-export const islands: FixtureApp = { framework: 'svelte', name: 'islands', files };
-export const mixed: FixtureApp = {
- framework: 'svelte',
- name: 'mixed',
- files: { ...files, 'pages/regular.svelte': 'Regular
' },
-};
-export const fixtures: Readonly> = { islands, mixed };
diff --git a/test/fixtures/vue.ts b/test/fixtures/vue.ts
deleted file mode 100644
index 46bc0cb58..000000000
--- a/test/fixtures/vue.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-import type { FixtureApp } from '../fixture-app.ts';
-
-export const islands: FixtureApp = {
- framework: 'vue',
- name: 'islands',
- files: {
- 'src/shell.css': '.shell { outline-offset: 7px; }',
- 'src/Badge.vue': `Badge
-`,
- 'src/Shell.vue': `
-Note
Card
-
-
-`,
- 'pages/layout.vue': `
-`,
- 'pages/index.island.vue': 'Home
',
- 'pages/badge.island.vue': `
-`,
- },
-};
-
-export const fixtures: Readonly> = { islands };
diff --git a/test/integration-helpers.ts b/test/integration-helpers.ts
index 99802e8d4..8cbf4c539 100644
--- a/test/integration-helpers.ts
+++ b/test/integration-helpers.ts
@@ -13,7 +13,7 @@ import {
writeFileSync,
} from 'node:fs';
import { createServer, type AddressInfo } from 'node:net';
-import { basename, dirname, join, relative } from 'node:path/posix';
+import { basename, join, relative } from 'node:path/posix';
import { setTimeout as delay } from 'node:timers/promises';
import { stripVTControlCharacters } from 'node:util';
import crossSpawn from 'cross-spawn';
@@ -50,40 +50,6 @@ export type IsolatedPlayground = {
cleanup: () => void;
};
-export function fixtureBuildCacheArgs(): Array {
- return process.env.VOID_TEST_FRESH_BUILDS === '1' ? ['--no-cache'] : [];
-}
-
-/**
- * Validate/restore a playground build without rewriting SDK artifacts while workers use them.
- * The shared global setup prepares those prerequisites before any test file is imported.
- */
-export function buildPlayground(workspaceRoot: string, playground: string): void {
- const result = crossSpawn.sync(
- 'vp',
- [
- 'run',
- '--ignore-depends-on',
- ...fixtureBuildCacheArgs(),
- '--filter',
- `./playground/${playground}`,
- 'build',
- ],
- {
- cwd: workspaceRoot,
- encoding: 'utf8',
- env: { ...process.env, NODE_ENV: undefined },
- maxBuffer: 10 * 1024 * 1024,
- },
- );
- if (result.error || result.status !== 0) {
- throw new Error(
- `Could not prepare playground/${playground}.\n${result.stdout ?? ''}${result.stderr ?? ''}`,
- { cause: result.error },
- );
- }
-}
-
function shouldCopyPlaygroundPath(sourceRoot: string, path: string): boolean {
const normalizedSourceRoot = sourceRoot.replaceAll('\\', '/');
const normalizedPath = path.replaceAll('\\', '/');
@@ -116,67 +82,16 @@ export function createIsolatedPlayground(
},
});
- linkFixtureDependencies(sourceRoot, root);
-
- // Avoid duplicate workspace package names when multiple copies exist concurrently.
- const packagePath = join(root, 'package.json');
- const packageJson = JSON.parse(readFileSync(packagePath, 'utf-8')) as { name?: string };
- packageJson.name = `${packageJson.name ?? basename(sourceWorkspacePath)}-${basename(root)}`;
- writeFileSync(packagePath, `${JSON.stringify(packageJson, null, 2)}\n`);
-
- return {
- root,
- workspacePath: relative(workspaceRoot, root),
- cleanup() {
- rmSync(root, { recursive: true, force: true, maxRetries: 20, retryDelay: 50 });
- },
- };
-}
-
-/** Restore immutable production output, then give the server its own source and storage root. */
-export function createBuiltPlayground(
- workspaceRoot: string,
- playground: string,
-): IsolatedPlayground {
- buildPlayground(workspaceRoot, playground);
- const source = join(workspaceRoot, 'playground', playground);
- const fixture = createIsolatedPlayground(workspaceRoot, `playground/${playground}`);
- try {
- for (const directory of ['dist', '.cloudflare']) {
- if (existsSync(join(source, directory))) {
- cpSync(join(source, directory), join(fixture.root, directory), { recursive: true });
- }
- }
- return fixture;
- } catch (error) {
- fixture.cleanup();
- throw error;
- }
-}
-
-/** Link installed dependencies into a fixture without archiving or copying node_modules. */
-export function linkFixtureDependencies(
- sourceRoot: string,
- root: string,
- additionalPackages: Record = {},
-): void {
- const fixtureNodeModules = join(root, 'node_modules');
- mkdirSync(fixtureNodeModules, { recursive: true });
- const linkDependency = (source: string, destination: string) => {
- const target = realpathSync.native(source);
- try {
- if (realpathSync.native(destination) === target) {
- return;
- }
- } catch {
- // A fresh fixture has no links yet.
- }
- rmSync(destination, { recursive: true, force: true });
- mkdirSync(dirname(destination), { recursive: true });
- symlinkSync(target, destination, process.platform === 'win32' ? 'junction' : 'dir');
- };
const sourceNodeModules = join(sourceRoot, 'node_modules');
if (existsSync(sourceNodeModules)) {
+ const fixtureNodeModules = join(root, 'node_modules');
+ mkdirSync(fixtureNodeModules);
+ const linkDependency = (source: string, destination: string) =>
+ symlinkSync(
+ realpathSync(source),
+ destination,
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
// Linking the whole directory leaves pnpm's relative package links behind
// a Windows junction at a different depth. Pin each package's real target.
for (const entry of readdirSync(sourceNodeModules, { withFileTypes: true })) {
@@ -193,7 +108,7 @@ export function linkFixtureDependencies(
const source = join(sourceNodeModules, entry.name);
const destination = join(fixtureNodeModules, entry.name);
if (entry.name.startsWith('@')) {
- mkdirSync(destination, { recursive: true });
+ mkdirSync(destination);
for (const name of readdirSync(source)) {
linkDependency(join(source, name), join(destination, name));
}
@@ -202,9 +117,20 @@ export function linkFixtureDependencies(
}
}
}
- for (const [name, directory] of Object.entries(additionalPackages)) {
- linkDependency(directory, join(fixtureNodeModules, name));
- }
+
+ // Avoid duplicate workspace package names when multiple copies exist concurrently.
+ const packagePath = join(root, 'package.json');
+ const packageJson = JSON.parse(readFileSync(packagePath, 'utf-8')) as { name?: string };
+ packageJson.name = `${packageJson.name ?? basename(sourceWorkspacePath)}-${basename(root)}`;
+ writeFileSync(packagePath, `${JSON.stringify(packageJson, null, 2)}\n`);
+
+ return {
+ root,
+ workspacePath: relative(workspaceRoot, root),
+ cleanup() {
+ rmSync(root, { recursive: true, force: true, maxRetries: 20, retryDelay: 50 });
+ },
+ };
}
/** Returns a port that is free right now. Another process can still take it before use. */
diff --git a/test/integration-timings.ts b/test/integration-timings.ts
index 2aec101e9..ef386ccae 100644
--- a/test/integration-timings.ts
+++ b/test/integration-timings.ts
@@ -1,105 +1,52 @@
-// Windows file durations measured in https://github.com/voidzero-dev/void/actions/runs/44090756592.
-// These estimates schedule shards only; every discovered test still executes.
+// Windows file durations measured in https://github.com/voidzero-dev/void/actions/runs/36572350995.
+// Edited suites use conservative estimates adjusted for removed browser cases and duplicate builds.
+// These values schedule shards only; every discovered test is still included.
export const integrationTimings: Readonly> = {
- 'packages/md/test/integration/client-script-build.test.ts': 5489,
- 'packages/md/test/integration/invalid-frontmatter.test.ts': 3753,
- 'packages/md/test/integration/markdown-blog.test.ts': 22991,
- 'packages/md/test/integration/theme-layout.test.ts': 793,
- 'packages/react/test/integration/island-css-build.test.ts': 6438,
- 'packages/react/test/integration/md-layout-frontmatter.test.ts': 3546,
- 'packages/react/test/integration/page-errors.test.ts': 15372,
- 'packages/react/test/integration/react-island-hydration.test.ts': 759,
- 'packages/react/test/integration/react-pages-client.test.ts': 40368,
- 'packages/react/test/integration/react-pages-navigation-fallback.test.ts': 5025,
- 'packages/solid/test/integration/island-css-build.test.ts': 6898,
- 'packages/solid/test/integration/island-hydration.test.ts': 7095,
- 'packages/solid/test/integration/md-layout-frontmatter.test.ts': 1722,
- 'packages/solid/test/integration/page-errors.test.ts': 15222,
- 'packages/solid/test/integration/solid-pages-playground.test.ts': 42237,
- 'packages/solid/test/integration/use-params-navigation.test.ts': 863,
- 'packages/svelte/test/integration/island-css-build.test.ts': 13293,
- 'packages/svelte/test/integration/md-layout-frontmatter.test.ts': 1722,
- 'packages/svelte/test/integration/page-errors.test.ts': 9922,
- 'packages/svelte/test/integration/svelte-pages-client.test.ts': 37306,
- 'packages/svelte/test/integration/use-params-navigation.test.ts': 1445,
- 'packages/void/test/e2e/cloudflare-deploy-live.test.ts': 8,
- 'packages/void/test/integration/analog.test.ts': 19141,
- 'packages/void/test/integration/astro.test.ts': 44718,
- 'packages/void/test/integration/auth-client-optimizer.test.ts': 487,
- 'packages/void/test/integration/auth-forwarded-cookies.test.ts': 11553,
- 'packages/void/test/integration/auth-isr-cache-policy.test.ts': 1767,
- 'packages/void/test/integration/auth-rate-limit.test.ts': 460,
- 'packages/void/test/integration/auth-schema-startup.test.ts': 7563,
- 'packages/void/test/integration/auth-types-typecheck.test.ts': 2088,
- 'packages/void/test/integration/cli-help.test.ts': 2336,
- 'packages/void/test/integration/cli-runtime-check.test.ts': 171,
- 'packages/void/test/integration/cloudflare-deploy-build.test.ts': 6625,
- 'packages/void/test/integration/cloudflare-durable-build.test.ts': 27281,
- 'packages/void/test/integration/cloudflare-isr-policy.test.ts': 10572,
- 'packages/void/test/integration/dev-trigger-secret-guard.test.ts': 84,
- 'packages/void/test/integration/durable-state-rpc.test.ts': 913,
- 'packages/void/test/integration/env-cli.test.ts': 3124,
- 'packages/void/test/integration/env-server-build.test.ts': 445,
- 'packages/void/test/integration/env-types-typecheck.test.ts': 601,
- 'packages/void/test/integration/error-pages.test.ts': 1494,
- 'packages/void/test/integration/full-deploy-manifest.test.ts': 3324,
- 'packages/void/test/integration/http-errors-dev.test.ts': 26387,
- 'packages/void/test/integration/http-errors-production.test.ts': 21419,
- 'packages/void/test/integration/info-cli.test.ts': 455,
- 'packages/void/test/integration/init-install.test.ts': 1599,
- 'packages/void/test/integration/init-vite-plus-registry.test.ts': 704,
- 'packages/void/test/integration/jsx-websocket.test.ts': 6947,
- 'packages/void/test/integration/kitchen-sink-build.test.ts': 6824,
- 'packages/void/test/integration/kitchen-sink.test.ts': 17024,
- 'packages/void/test/integration/mysql-test.test.ts': 8394,
- 'packages/void/test/integration/named-layouts.test.ts': 3557,
- 'packages/void/test/integration/native-asset-cache-policy.test.ts': 1981,
- 'packages/void/test/integration/nitro-worker.test.ts': 44105,
- 'packages/void/test/integration/node-static-md.test.ts': 1538,
- 'packages/void/test/integration/node-static.test.ts': 13652,
- 'packages/void/test/integration/node-target.test.ts': 5545,
- 'packages/void/test/integration/nuxt.test.ts': 19697,
- 'packages/void/test/integration/operator-cli.test.ts': 1879,
- 'packages/void/test/integration/page-action-types-typecheck.test.ts': 2282,
- 'packages/void/test/integration/pages-target-assets.test.ts': 5558,
- 'packages/void/test/integration/pg-api-test.test.ts': 14826,
- 'packages/void/test/integration/pg-test.test.ts': 10932,
- 'packages/void/test/integration/plugin-better-auth-dev.test.ts': 3568,
- 'packages/void/test/integration/plugin-cloudflare-v2.test.ts': 14399,
- 'packages/void/test/integration/plugin-env-schema.test.ts': 589,
- 'packages/void/test/integration/plugin-vite-environment.test.ts': 6870,
- 'packages/void/test/integration/prepare-cli.test.ts': 2038,
- 'packages/void/test/integration/queue-dispatch.test.ts': 98,
- 'packages/void/test/integration/react-router.test.ts': 19143,
- 'packages/void/test/integration/resource-name-migration.test.ts': 8627,
- 'packages/void/test/integration/room-action-types-typecheck.test.ts': 689,
- 'packages/void/test/integration/route-response-types-typecheck.test.ts': 658,
- 'packages/void/test/integration/route-url-builder.test.ts': 7482,
- 'packages/void/test/integration/sandbox-managed-rpc.test.ts': 383,
- 'packages/void/test/integration/sandbox-native-websocket.test.ts': 500,
- 'packages/void/test/integration/secret-cli.test.ts': 726,
- 'packages/void/test/integration/server-auth-errors-session.test.ts': 21251,
- 'packages/void/test/integration/server-auth-errors-signed-in.test.ts': 24123,
- 'packages/void/test/integration/server-auth-errors-signed-out.test.ts': 40327,
- 'packages/void/test/integration/spa-middleware-auth.test.ts': 10397,
- 'packages/void/test/integration/ssr-playground.test.ts': 7365,
- 'packages/void/test/integration/static-pages.test.ts': 14397,
- 'packages/void/test/integration/sveltekit.test.ts': 25670,
- 'packages/void/test/integration/tanstack-start.test.ts': 10353,
- 'packages/void/test/integration/terminal-links.test.ts': 631,
- 'packages/void/test/integration/test-build-cache.test.ts': 28586,
- 'packages/void/test/integration/trailing-slash.test.ts': 21974,
- 'packages/void/test/integration/trigger-auth.test.ts': 329,
- 'packages/void/test/integration/tsx-server.test.ts': 6105,
- 'packages/void/test/integration/typed-routing-runtime.test.ts': 4014,
- 'packages/void/test/integration/vinext-app.test.ts': 21807,
- 'packages/void/test/integration/vinext-pages.test.ts': 5439,
- 'packages/void/test/integration/vitest-app.test.ts': 5046,
- 'packages/void/test/integration/websocket-middleware.test.ts': 1122,
- 'packages/void/test/integration/websocket-room-actions.test.ts': 13883,
- 'packages/void/test/integration/websockets-playground.test.ts': 13084,
- 'packages/vue/test/integration/island-css-build.test.ts': 3555,
- 'packages/vue/test/integration/md-island-frontmatter.test.ts': 1932,
- 'packages/vue/test/integration/page-errors.test.ts': 8565,
- 'packages/vue/test/integration/vue-pages-client.test.ts': 26065,
+ 'packages/md/test/integration/markdown-blog.test.ts': 42014,
+ 'packages/react/test/integration/react-pages-client.test.ts': 43000,
+ 'packages/react/test/integration/react-pages-navigation-fallback.test.ts': 6920,
+ 'packages/solid/test/integration/solid-pages-playground.test.ts': 39000,
+ 'packages/svelte/test/integration/svelte-pages-client.test.ts': 30000,
+ 'packages/void/test/e2e/cloudflare-deploy-live.test.ts': 6,
+ 'packages/void/test/integration/analog.test.ts': 38000,
+ 'packages/void/test/integration/astro.test.ts': 26000,
+ 'packages/void/test/integration/cli-help.test.ts': 1718,
+ 'packages/void/test/integration/cli-runtime-check.test.ts': 900,
+ 'packages/void/test/integration/cloudflare-durable-build.test.ts': 15000,
+ 'packages/void/test/integration/cloudflare-deploy-build.test.ts': 6700,
+ 'packages/void/test/integration/cloudflare-isr-policy.test.ts': 15391,
+ 'packages/void/test/integration/durable-state-rpc.test.ts': 1160,
+ 'packages/void/test/integration/env-cli.test.ts': 2970,
+ 'packages/void/test/integration/env-server-build.test.ts': 873,
+ 'packages/void/test/integration/env-types-typecheck.test.ts': 1395,
+ 'packages/void/test/integration/full-deploy-manifest.test.ts': 6370,
+ 'packages/void/test/integration/kitchen-sink-build.test.ts': 7365,
+ 'packages/void/test/integration/kitchen-sink.test.ts': 20887,
+ 'packages/void/test/integration/mysql-test.test.ts': 11000,
+ 'packages/void/test/integration/named-layouts.test.ts': 9939,
+ 'packages/void/test/integration/nitro-worker.test.ts': 30000,
+ 'packages/void/test/integration/node-static-md.test.ts': 2000,
+ 'packages/void/test/integration/node-static.test.ts': 13667,
+ 'packages/void/test/integration/node-target.test.ts': 10833,
+ 'packages/void/test/integration/nuxt.test.ts': 43000,
+ 'packages/void/test/integration/operator-cli.test.ts': 4910,
+ 'packages/void/test/integration/pages-target-assets.test.ts': 10966,
+ 'packages/void/test/integration/pg-api-test.test.ts': 11000,
+ 'packages/void/test/integration/pg-test.test.ts': 16237,
+ 'packages/void/test/integration/plugin-env-schema.test.ts': 236,
+ 'packages/void/test/integration/prepare-cli.test.ts': 1957,
+ 'packages/void/test/integration/queue-dispatch.test.ts': 208,
+ 'packages/void/test/integration/react-router.test.ts': 21000,
+ 'packages/void/test/integration/sandbox-managed-rpc.test.ts': 722,
+ 'packages/void/test/integration/spa-middleware-auth.test.ts': 26264,
+ 'packages/void/test/integration/ssr-playground.test.ts': 13008,
+ 'packages/void/test/integration/static-pages.test.ts': 7034,
+ 'packages/void/test/integration/sveltekit.test.ts': 32000,
+ 'packages/void/test/integration/tanstack-start.test.ts': 12000,
+ 'packages/void/test/integration/trigger-auth.test.ts': 400,
+ 'packages/void/test/integration/vinext-app.test.ts': 12000,
+ 'packages/void/test/integration/vinext-pages.test.ts': 9000,
+ 'packages/void/test/integration/websocket-middleware.test.ts': 11188,
+ 'packages/void/test/integration/websockets-playground.test.ts': 16783,
+ 'packages/vue/test/integration/vue-pages-client.test.ts': 34000,
};
diff --git a/test/island-css-build.ts b/test/island-css-build.ts
index 20bb4d3bd..b2c4fdd70 100644
--- a/test/island-css-build.ts
+++ b/test/island-css-build.ts
@@ -1,37 +1,130 @@
+import { execSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { pathToFileURL } from 'node:url';
import { expect, it } from 'vite-plus/test';
-import type { BuiltFixture } from './fixture-app.ts';
-type IslandCssContract = {
- build: () => BuiltFixture;
+const MD_PLUGIN = join(import.meta.dirname, '../packages/md/dist/plugin.mjs');
+
+type IslandCssApp = {
+ /** The adapter package directory, e.g. `packages/react`. */
+ packageDir: string;
+ /** The adapter's plugin export in `dist/plugin.mjs`, e.g. `voidReact`. */
+ pluginName: string;
+ /** App files by path. `index` and `about` must ship no JavaScript. */
+ files: Record;
+ /** Rules (as minified CSS) every page must link, found once in the client build. */
expectedCss: Array;
+ /** Extra assertions for each page. */
check?: (page: { file: string; html: string; css: string }) => void;
- checkBuild?: (build: BuiltFixture) => void;
+ /** Extra assertions against this same production build. */
+ checkBuild?: (build: ReturnType) => void;
};
+/** The stylesheet links of a page, without a regular expression. */
+function stylesheetHrefs(html: string): Array {
+ const marker = '` resolves to the adapter package itself.
+ */
+export function buildIslandApp(app: Omit): {
+ root: string;
+ page(file: string): { html: string; css: string };
+ /** The text of every built file under `dist/`, by path. */
+ output(dir: 'client' | 'ssr'): Map;
+ cleanup(): void;
+} {
+ const root = mkdtempSync(join(app.packageDir, 'test/integration/__tmp_island_css_'));
+ try {
+ const plugin = pathToFileURL(join(app.packageDir, 'dist/plugin.mjs')).href;
+ const files: Record = {
+ 'vite.config.mjs': `import { voidPlugin } from 'void';
+import { ${app.pluginName} } from ${JSON.stringify(plugin)};
+import { voidMarkdown } from ${JSON.stringify(pathToFileURL(MD_PLUGIN).href)};
+export default { plugins: [voidPlugin(), ${app.pluginName}(), voidMarkdown()] };
+`,
+ 'void.config.ts': `import { defineConfig } from 'void/config';
+export default defineConfig({ output: 'static', worker: { compatibility_date: '2026-02-24' } });
+`,
+ 'pages/about.md': '---\ntitle: About\n---\n\n# About\n',
+ ...app.files,
+ };
+ for (const [file, content] of Object.entries(files)) {
+ mkdirSync(dirname(join(root, file)), { recursive: true });
+ writeFileSync(join(root, file), content);
+ }
+ // The native loader keeps the config's imports in the adapter package scope.
+ execSync('vp build --configLoader native', { cwd: root, stdio: 'pipe' });
+ } catch (error) {
+ rmSync(root, { recursive: true, force: true });
+ throw error;
+ }
+ const client = join(root, 'dist/client');
+ return {
+ root,
+ page(file) {
+ const html = readFileSync(join(client, file), 'utf-8');
+ const css = stylesheetHrefs(html)
+ .map((href) => readFileSync(join(client, href), 'utf-8'))
+ .join('\n');
+ return { html, css };
+ },
+ output(dir) {
+ const out = join(root, 'dist', dir);
+ const files = new Map();
+ for (const file of readdirSync(out, { recursive: true, encoding: 'utf-8' })) {
+ if (file.endsWith('.js') || file.endsWith('.css') || file.endsWith('.html')) {
+ files.set(file, readFileSync(join(out, file), 'utf-8'));
+ }
+ }
+ return files;
+ },
+ cleanup() {
+ rmSync(root, { recursive: true, force: true });
+ },
+ };
+}
+
+/** How many times `text` contains `part`. */
export function countOf(text: string, part: string): number {
return text.split(part).length - 1;
}
-/** The caller owns the immutable build's runtime copy and releases it after its contracts. */
-export function defineIslandCssBuildTest(app: IslandCssContract): void {
+/**
+ * Shared by the four adapters: a layout renders a component that imports CSS.
+ * Production must link that CSS on island and Markdown pages, as dev does,
+ * even though the pages ship no JavaScript.
+ */
+export function defineIslandCssBuildTest(app: IslandCssApp): void {
it('links the CSS that a layout component imports on island and Markdown pages', () => {
- const build = app.build();
- for (const file of ['index.html', 'about.html']) {
- const { html, css } = build.page(file);
+ const build = buildIslandApp(app);
+ try {
+ for (const file of ['index.html', 'about.html']) {
+ const { html, css } = build.page(file);
+ for (const rule of app.expectedCss) {
+ expect(countOf(css, rule), `${file}: ${rule}`).toBe(1);
+ }
+ expect(html, file).not.toContain('