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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions packages/void/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,10 @@ export function voidPlugin(options?: {
detected || isNodeTarget(config.target)
? undefined
: { root, scan: () => getNativeWorkerSourceFiles(application) },
() => ({
authContext: authEnabled || bindings.needsLive === true || application.websockets.length > 0,
database: application.needsDatabase,
}),
);
// Scan queues/websocket routes early so both framework-mode and default-mode
// branches can safely close over these bindings.
Expand Down
19 changes: 12 additions & 7 deletions packages/void/src/pages/plugin.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { existsSync } from 'node:fs';
import { dirname, isAbsolute, join } from 'pathslash';
import { loadEnv, normalizePath } from 'vite';
import { loadEnv, mergeConfig, normalizePath } from 'vite';
import type { Plugin, ResolvedConfig, UserConfig } from 'vite';
import { computePagesBuildId, endPagesBuild } from './build-id-source.ts';
import type { PagesBuildInputs } from './build-id-source.ts';
Expand All @@ -15,6 +15,13 @@ import type { PageScanResult } from './types.ts';
const RENDERER_ID = 'virtual:void-pages-renderer';
const CLIENT_ENTRY_ID = 'virtual:void-pages-client';

// The generated client entry reaches void/pages-client, which imports devalue, through a virtual
// module and the adapter package, so the client scan does not find it. A linked void is served as
// source, and the first page load would find devalue and run the optimizer again.
const DEV_CLIENT_CONFIG: UserConfig = {
environments: { client: { optimizeDeps: { include: ['void > devalue'] } } },
};

type PagesPluginContext = {
isDev: boolean;
scan: () => Promise<PageScanResult | null>;
Expand Down Expand Up @@ -263,12 +270,10 @@ export function createPagesPlugin(pagesDir: string, options: CreatePagesPluginOp
// The dev server serves a single build, so a tab never outlives the chunks
// it imported, and an app without a client entry has no tab to recover.
// Leaving the id undefined keeps every build check a no-op there.
if (
dev ||
resolved === null ||
resolved === undefined ||
options.deployRecovery === false
) {
if (dev) {
return mergeConfig(resolved ?? {}, DEV_CLIENT_CONFIG);
}
if (resolved === null || resolved === undefined || options.deployRecovery === false) {
return resolved;
}
// An explicit app define pins the id, for a fixture or for one that
Expand Down
41 changes: 36 additions & 5 deletions packages/void/src/plugin-worker-environment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,33 @@ const DATABASE_DRIVER_DEPS: Record<DatabaseDialect, Array<string>> = {
mysql: ['void > mysql2'],
};

// The generated entry loads Void's routing runtime, which imports these for itself and for the
// generated routes.
const ROUTING_RUNTIME_DEPS = [
'void > devalue',
'void > hono',
'void > hono/route',
'void > hono/utils/url',
];

// Void's request auth context, which void/auth, void/live and WebSocket routes load.
const AUTH_CONTEXT_DEPS = ['void > hono/http-exception'];

// void/schema-* re-exports the dialect's Drizzle schema builders. App schemas and the generated
// auth schema import it.
const DATABASE_SCHEMA_DEPS: Record<DatabaseDialect, Array<string>> = {
sqlite: ['void > drizzle-orm/sqlite-core'],
postgresql: ['void > drizzle-orm/pg-core'],
mysql: ['void > drizzle-orm/mysql-core'],
};

/** The parts of Void's runtime that an app loads beyond the routing runtime. */
export type WorkerRuntimeFeatures = {
/** Auth, void/live or a WebSocket route. */
authContext: boolean;
database: boolean;
};

const NODE_BUILTIN = new RegExp(`^(?:node:)?(?:${builtinModules.join('|')})$`);
const NODE_BUILTIN_REQUIRE_PREFIX = '\0void:node-require:';

Expand Down Expand Up @@ -255,6 +282,7 @@ export function createServerRuntimeOptimizerPlugin(
readCompat: () => WranglerCompat,
ssrEntry: string | null = null,
nativeWorker?: { root: string; scan: () => Promise<Array<string>> },
readFeatures: () => WorkerRuntimeFeatures = () => ({ authContext: false, database: false }),
): Plugin {
let workerdNodeBuiltins: Promise<Set<string>> | undefined;
let scanNativeWorker = false;
Expand Down Expand Up @@ -299,6 +327,7 @@ export function createServerRuntimeOptimizerPlugin(
entries.push(...(await nativeWorker.scan()));
}
}
const features = readFeatures();
return {
optimizeDeps: {
// `better-auth` keeps OAuth request state on a module-local ref. Prebundling an app
Expand All @@ -313,14 +342,16 @@ export function createServerRuntimeOptimizerPlugin(
// Excluding void also skips converting its CommonJS dependencies, which workerd cannot
// evaluate: an installed void/email fails with "exports is not defined".
//
// Void's routing runtime imports Hono for itself and for the generated routes. Naming
// it here prebundles it before the Worker starts, not on its first request.
// The Worker reaches Void's runtime through generated modules and this excluded
// package, so the scan never sees the runtime's own imports. Naming them here
// prebundles them before the Worker starts. Each one found during a request instead
// reloads the Worker.
include: [
'void > devalue',
'void > email-validator',
'void > hono',
'void > hono/route',
...ROUTING_RUNTIME_DEPS,
...(features.authContext ? AUTH_CONTEXT_DEPS : []),
...DATABASE_DRIVER_DEPS[dialect],
...(features.database ? DATABASE_SCHEMA_DEPS[dialect] : []),
],
},
};
Expand Down
29 changes: 29 additions & 0 deletions packages/void/test/integration/plugin-vite-environment.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,35 @@ export default defineDurableState({ initialState: { count }, methods: { get(c) {
expect(config.environments.ssr.optimizeDeps.exclude ?? []).not.toContain('better-auth');
});

it('prebundles the runtime modules an app loads in the worker environment', async () => {
const plain = createProjectRoot();
vi.spyOn(process, 'cwd').mockReturnValue(plain);
const plainConfig = await resolveConfig(
{ root: plain, configFile: false, plugins: [voidPlugin()] },
'serve',
'development',
);
const plainIncludes = plainConfig.environments.void_worker.optimizeDeps.include;
expect(plainIncludes).toContain('void > hono/utils/url');
expect(plainIncludes).not.toContain('void > hono/http-exception');
expect(plainIncludes).not.toContain('void > drizzle-orm/sqlite-core');

const withAuth = createProjectRoot();
vi.spyOn(process, 'cwd').mockReturnValue(withAuth);
writeFileSync(
join(withAuth, 'auth.ts'),
"import { defineAuth } from 'void/auth'; export default defineAuth({});",
);
const authConfig = await resolveConfig(
{ root: withAuth, configFile: false, plugins: [voidPlugin()] },
'serve',
'development',
);
expect(authConfig.environments.void_worker.optimizeDeps.include).toEqual(
expect.arrayContaining(['void > hono/http-exception', 'void > drizzle-orm/sqlite-core']),
);
});

it.each(['before', 'after'])(
'prebundles them in an adapter-owned workerd environment with Void listed %s it',
async (order) => {
Expand Down
2 changes: 1 addition & 1 deletion packages/void/test/unit/pages-build-id.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -476,7 +476,7 @@ describe('createPagesPlugin build id', () => {
it('defines nothing in the dev server, which serves one build', async () => {
const config = createConfigHook();

expect(await config({}, { command: 'serve' })).toEqual({});
expect(await config({}, { command: 'serve' })).not.toHaveProperty('define');
});

it('leaves an id the app defines to Vite, without hashing the tree', async () => {
Expand Down
47 changes: 47 additions & 0 deletions packages/void/test/unit/pages-plugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,53 @@ describe('shared Pages plugin scan lifecycle', () => {
});
});

describe('shared Pages plugin dev dependencies', () => {
let root: string;

beforeEach(() => {
root = normalizePath(mkdtempSync(join(tmpdir(), 'void-pages-plugin-')));
mkdirSync(join(root, 'pages'));
});

afterEach(() => {
rmSync(root, { recursive: true, force: true });
});

function setup(adapterConfig: () => import('vite').UserConfig | void) {
return createPagesPlugin(join(root, 'pages'), {
name: 'test:pages',
generateRenderer: () => '',
generateClient: () => '',
config: adapterConfig,
}) as unknown as PagesPluginHooks;
}

it("prebundles the pages client's devalue import with the adapter's dev config", () => {
const plugin = setup(() => ({
optimizeDeps: { include: ['react'] },
environments: { client: { optimizeDeps: { include: ['react-dom/client'] } } },
}));

expect(plugin.config({}, { command: 'serve' })).toEqual({
optimizeDeps: { include: ['react'] },
environments: {
client: { optimizeDeps: { include: ['react-dom/client', 'void > devalue'] } },
},
});
expect(setup(() => {}).config({}, { command: 'serve' })).toEqual({
environments: { client: { optimizeDeps: { include: ['void > devalue'] } } },
});
});

it('leaves build config to the adapter', () => {
const plugin = setup(() => ({ optimizeDeps: { include: ['react'] } }));

expect(plugin.config({}, { command: 'build' })).toEqual(
expect.not.objectContaining({ environments: expect.anything() }),
);
});
});

describe('resolvePrefetchConfig', () => {
it('leaves Links without a prefetch prop off by default', () => {
expect(resolvePrefetchConfig(undefined)).toEqual({
Expand Down
17 changes: 9 additions & 8 deletions packages/void/test/unit/plugin-dev-asset-routing.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,13 @@ describe('voidPlugin dev asset routing', () => {
// The Cloudflare plugin gives each environment it runs in workerd these conditions.
const workerd = { resolve: { conditions: ['workerd', 'worker', 'module', 'browser'] } };
const node = { resolve: { conditions: ['module', 'node'] } };
const workerdIncludes = [
'void > email-validator',
'void > devalue',
'void > hono',
'void > hono/route',
'void > hono/utils/url',
];

async function resolveRuntimeOptimizerConfig(
root: string,
Expand All @@ -254,7 +261,7 @@ describe('voidPlugin dev asset routing', () => {
const workerdOptimizer = {
optimizeDeps: {
exclude: ['void', 'better-auth'],
include: ['void > devalue', 'void > email-validator', 'void > hono', 'void > hono/route'],
include: workerdIncludes,
},
};
const nodeOptimizer = { optimizeDeps: { exclude: ['void'] } };
Expand Down Expand Up @@ -295,13 +302,7 @@ describe('voidPlugin dev asset routing', () => {
optimizeDeps: drivers
? {
exclude: ['void', 'better-auth'],
include: [
'void > devalue',
'void > email-validator',
'void > hono',
'void > hono/route',
...drivers,
],
include: [...workerdIncludes, ...drivers],
}
: { exclude: ['void'] },
});
Expand Down
123 changes: 123 additions & 0 deletions packages/void/test/unit/worker-runtime-optimizer.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
import { existsSync, readFileSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import type { UserConfig } from 'vite';
import { parseSync } from 'vite';
import { describe, expect, it } from 'vite-plus/test';
import type { DatabaseDialect } from '../../src/config.ts';
import { createServerRuntimeOptimizerPlugin } from '../../src/plugin-worker-environment.ts';
import type { WorkerRuntimeFeatures } from '../../src/plugin-worker-environment.ts';
import { staticModuleReferences } from '../../src/shared/module-references.ts';
import { getHookHandler } from '../helpers/vite-hooks.ts';

const runtimeDir = fileURLToPath(new URL('../../src/runtime/', import.meta.url));

async function workerIncludes(
features: WorkerRuntimeFeatures,
dialect: DatabaseDialect = 'sqlite',
): Promise<Array<string>> {
const plugin = createServerRuntimeOptimizerPlugin(
dialect,
() => ({ compatibilityDate: '2026-02-24' }),
null,
undefined,
() => features,
);
const configEnvironment = getHookHandler(plugin.configEnvironment);
const config = (await configEnvironment.call(
{} as ThisParameterType<typeof configEnvironment>,
'void_worker',
{ resolve: { conditions: ['workerd'] } },
{ command: 'serve', mode: 'development' },
)) as UserConfig;
return config.optimizeDeps?.include ?? [];
}

function resolveSource(specifier: string, importer: string): string {
const base = resolve(dirname(importer), specifier);
const file = [base, base.replace(/\.js$/, '.ts'), `${base}.ts`, join(base, 'index.ts')].find(
(candidate) => candidate.endsWith('.ts') && existsSync(candidate),
);
if (!file) {
throw new Error(`Cannot resolve ${specifier} from ${importer}`);
}
return file;
}

/** The packages that these runtime modules and the modules they import load at runtime. */
function runtimeImports(modules: Array<string>): Set<string> {
const packages = new Set<string>();
const pending = modules.map((module) => join(runtimeDir, module));
const seen = new Set<string>();
for (let file = pending.pop(); file !== undefined; file = pending.pop()) {
if (seen.has(file)) {
continue;
}
seen.add(file);
const code = readFileSync(file, 'utf8');
const parsed = parseSync(file, code);
const specifiers = staticModuleReferences(parsed, code).map(({ source }) => source);
for (const { moduleRequest } of parsed.module.dynamicImports) {
const literal = /^(["'])([^"'`]+)\1$/.exec(
code.slice(moduleRequest.start, moduleRequest.end),
);
if (literal) {
specifiers.push(literal[2]);
}
}
for (const specifier of specifiers) {
if (specifier.startsWith('.')) {
// Queried imports such as `?raw` load assets, not modules.
if (!specifier.includes('?')) {
pending.push(resolveSource(specifier, file));
}
} else if (!/^(?:node:|cloudflare:|#)/.test(specifier)) {
packages.add(specifier);
}
}
}
return packages;
}

// Void's own packages are linked in a workspace and installed beside void otherwise, so Vite
// serves them as source. The Worker loads void's copy of better-auth from source on purpose.
const NOT_PREBUNDLED = /^(?:@void\/|better-auth$)/;

function expectPrebundled(modules: Array<string>, includes: Array<string>): void {
const missing = [...runtimeImports(modules)].filter(
(specifier) => !NOT_PREBUNDLED.test(specifier) && !includes.includes(`void > ${specifier}`),
);
expect(missing).toEqual([]);
}

describe('Worker runtime dependency optimizer', () => {
it('prebundles what the routing runtime imports in every Worker', async () => {
const includes = await workerIncludes({ authContext: false, database: false });

expectPrebundled(['routing/index.ts', 'env/runtime.ts'], includes);
expect(includes).not.toContain('void > hono/http-exception');
expect(includes.filter((include) => include.startsWith('void > drizzle-orm'))).toEqual([]);
});

it("prebundles the auth context's imports for auth, void/live and WebSocket routes", async () => {
const includes = await workerIncludes({ authContext: true, database: false });

expectPrebundled(
['auth/index.ts', 'live/index.ts', 'live/server.ts', 'ws/room.ts', 'ws/server.ts'],
includes,
);
});

it.each([
['sqlite', 'schema/d1.ts'],
['postgresql', 'schema/postgres.ts'],
['mysql', 'schema/mysql.ts'],
] as const)(
'prebundles the %s schema builders for an app with a database',
async (dialect, schema) => {
const includes = await workerIncludes({ authContext: false, database: true }, dialect);

expectPrebundled([`db/${schema}`], includes);
},
);
});