Skip to content
Merged
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
2 changes: 2 additions & 0 deletions docs/guide/env-vars.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ Declare your environment variables in `env.ts`, then read them through `env` fro

Create `env.ts` at the project root:

For a package with `"type": "commonjs"` in `package.json`, use `env.mts`.

```ts
import { defineEnv, number, string, url } from 'void/env';

Expand Down
2 changes: 1 addition & 1 deletion docs/reference/cli/setup.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ void init [--tsconfig] [--github] [--git | --no-git]
[--toolchain <name>] [--framework <name>] [--starter <name>] [--deploy <target>]
```

Set up a new or existing Void project. In an empty directory, choose Vite+ or Vite, a framework, and a D1, PostgreSQL, MySQL, or Static Pages starter. The new app's `void.config.ts` turns on [`routing.typedRoutes`](../config.md#routing-typedroutes).
Set up a new or existing Void project. In an empty directory, choose Vite+ or Vite, a framework, and a D1, PostgreSQL, MySQL, or Static Pages starter. For a package with `"type": "commonjs"`, starters use `vite.config.mts` and inferred env schemas use `env.mts`. The new app's `void.config.ts` turns on [`routing.typedRoutes`](../config.md#routing-typedroutes).

Pass your choices as flags to scaffold from a script or coding agent:

Expand Down
37 changes: 19 additions & 18 deletions packages/void/src/cli/env-scaffold.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
/**
* `void init` hook — when the project has no `env.ts` but has dotenv files
* on disk, scaffold an `env.ts` whose keys mirror what the user already
* has. Inference is intentionally permissive: we only upgrade from the
* default `string()` helper when the value is unambiguously a boolean,
* During `void init`, scaffold an environment schema for the keys in a
* project's existing `.env`. Use the default `string()` helper unless the value is a boolean,
* URL, or small integer. Everything else stays a string and carries a
* one-line banner nudging the user to tighten the schema.
*
* This is a best-effort DX sweetener, not a correctness boundary — a
* wrong guess only costs the user a single-line edit.
*/
import { existsSync, writeFileSync } from 'node:fs';
import { join } from 'pathslash';
import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
import { basename, join } from 'pathslash';
import { readProjectPaths } from '../project-paths.ts';
import { parseDotenvFile } from '../shared/dotenv.ts';
import { readPackageJson } from '../shared/package-json.ts';

export type InferredHelper = 'string' | 'number' | 'boolean' | 'url';

Expand Down Expand Up @@ -61,7 +61,7 @@ export function collectInferredEntries(root: string): Array<InferredEntry> {
}

/**
* Render the scaffolded `env.ts` body. The imports are pulled in lazily
* Render the scaffolded schema. The imports are pulled in lazily
* so only helpers we reference appear in the import statement.
*/
export function renderEnvTs(entries: Array<InferredEntry>): string {
Expand Down Expand Up @@ -108,26 +108,27 @@ export type ScaffoldResult = {
};

/**
* If the project has no `env.ts`, scaffold one based on the local `.env`
* user already has. Safe to call unconditionally during `void init` — it
* no-ops when `env.ts` is present. Never overwrites an existing file.
* Scaffold a schema from `.env` when the project does not already have one.
*/
export function maybeScaffoldEnvTs(root: string): ScaffoldResult {
// Respect `env.*` at the root or under `src/`, whichever the user already uses.
for (const dir of ['', 'src/']) {
for (const ext of ['ts', 'mts', 'js', 'mjs']) {
if (existsSync(join(root, `${dir}env.${ext}`))) {
return { written: null, skipReason: 'env-ts-exists', entries: [] };
}
}
const commonJs = readPackageJson(root)?.type === 'commonjs';
const { sourceDir, sourceRoot, envFileCandidates } = readProjectPaths(root);
const hasSchema = envFileCandidates.some(
(file) => existsSync(file) || (sourceDir !== '' && existsSync(join(root, basename(file)))),
);
if (hasSchema) {
return { written: null, skipReason: 'env-ts-exists', entries: [] };
}

if (!existsSync(join(root, '.env'))) {
return { written: null, skipReason: 'no-dotenv-files', entries: [] };
}

const entries = collectInferredEntries(root);
const target = join(root, 'env.ts');
const target = join(sourceRoot, commonJs ? 'env.mts' : 'env.ts');
if (sourceDir) {
mkdirSync(sourceRoot, { recursive: true });
}
writeFileSync(target, renderEnvTs(entries));
return { written: target, entries };
}
38 changes: 21 additions & 17 deletions packages/void/src/cli/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ import type { DeploymentPlatform } from './project.ts';
import {
createPagesStarterTemplate,
detectScaffoldFrameworkFromDependencies,
getGeneratedViteConfigPath,
getScaffoldTsconfigCompilerOptions,
SCAFFOLD_BASE_DEV_DEPENDENCIES,
SCAFFOLD_FRAMEWORKS,
Expand Down Expand Up @@ -2022,17 +2023,6 @@ function scaffoldPagesApp(
): boolean {
const packageJsonPath = join(root, 'package.json');
const packageJsonExisted = existsSync(packageJsonPath);
const template = createPagesStarterTemplate({
framework,
starterMode,
toolchain,
voidPackageSpec: resolveScaffoldDependencySpec(root, 'void', getOwnVersion()),
adapterPackageSpec: resolveScaffoldDependencySpec(
root,
SCAFFOLD_FRAMEWORKS[framework].adapterPackage,
getOwnVersion(),
),
});
let pkg: JsonObject = {};

if (packageJsonExisted) {
Expand All @@ -2054,6 +2044,19 @@ function scaffoldPagesApp(
pkg.type = 'module';
}

const template = createPagesStarterTemplate({
framework,
starterMode,
toolchain,
packageType: pkg.type,
voidPackageSpec: resolveScaffoldDependencySpec(root, 'void', getOwnVersion()),
adapterPackageSpec: resolveScaffoldDependencySpec(
root,
SCAFFOLD_FRAMEWORKS[framework].adapterPackage,
getOwnVersion(),
),
});

const scripts = asRecord(pkg.scripts) ?? {};
pkg.scripts = scripts;
for (const [name, command] of Object.entries(template.scripts)) {
Expand Down Expand Up @@ -2259,11 +2262,6 @@ export default defineConfig({
`;
}

function getGeneratedViteConfigPath(root: string): 'vite.config.ts' | 'vite.config.mts' {
const pkg = readPackageJson(root);
return pkg?.type === 'module' ? 'vite.config.ts' : 'vite.config.mts';
}

function noteManualViteConfigSetup(configPath?: string): void {
const target = configPath ?? 'your framework Vite config';
note(
Expand Down Expand Up @@ -2352,7 +2350,13 @@ function ensureExistingProjectViteConfig(

const configPath = findViteConfig(root);
if (!configPath) {
writeFileIfMissing(root, getGeneratedViteConfigPath(root), getBasicVoidViteConfig(), report);
const packageType = readPackageJson(root)?.type;
writeFileIfMissing(
root,
getGeneratedViteConfigPath(packageType),
getBasicVoidViteConfig(),
report,
);
return;
}

Expand Down
10 changes: 9 additions & 1 deletion packages/void/src/cli/template.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,17 +181,25 @@ export function getScaffoldTsconfigCompilerOptions(
return framework ? { ...SCAFFOLD_FRAMEWORKS[framework].tsconfigCompilerOptions } : {};
}

export function getGeneratedViteConfigPath(
packageType: unknown,
): 'vite.config.ts' | 'vite.config.mts' {
return packageType === 'module' ? 'vite.config.ts' : 'vite.config.mts';
}

export function createPagesStarterTemplate(options: {
framework: ScaffoldFramework;
starterMode: ScaffoldStarterMode;
toolchain?: ScaffoldToolchain;
packageType?: unknown;
voidPackageSpec: string;
adapterPackageSpec: string;
}): PagesStarterTemplate {
const {
framework,
starterMode,
toolchain = 'vite',
packageType = 'module',
voidPackageSpec,
adapterPackageSpec,
} = options;
Expand All @@ -203,7 +211,7 @@ export function createPagesStarterTemplate(options: {
{ routing: { typedRoutes: true } },
'// Generated by void init.',
),
'vite.config.ts': getViteConfig(framework, config, toolchain),
[getGeneratedViteConfigPath(packageType)]: getViteConfig(framework, config, toolchain),
[`pages/index.${config.pageExtension}`]: getIndexPage(framework, starterMode),
'pages/style.css': starterStyles,
'pages/vite-env.d.ts': '/// <reference types="vite/client" />\n',
Expand Down
2 changes: 0 additions & 2 deletions packages/void/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ import { cloudflare } from './plugin-cloudflare.ts';
import type { WorkerConfig, AuxiliaryWorkerConfig } from './plugin-cloudflare.ts';
import {
afterServerReady,
warnIfPackageJsonIsNotEsm,
isViteBuildOrPreview,
getOrCreateDevTriggerToken,
devTriggerSecretGuardPlugin,
Expand Down Expand Up @@ -108,7 +107,6 @@ export function voidPlugin(options?: {
// needs it, because build prerendering can open a remote session too.
selectVoidCloudflareLogin();
}
warnIfPackageJsonIsNotEsm(root);
// Token only matters in serve — the dispatch module that uses it is
// DCE'd from production worker bundles. In build/preview we still need
// *some* string (the wrapper embeds it for completeness), but we skip
Expand Down
36 changes: 0 additions & 36 deletions packages/void/src/plugin-dev-config.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import {
chmodSync,
closeSync,
existsSync,
mkdirSync,
openSync,
readFileSync,
Expand All @@ -10,7 +9,6 @@ import {
} from 'node:fs';
import { join } from 'pathslash';
import type { Plugin, PluginOption, ViteDevServer } from 'vite';
import { voidWarn } from './log.ts';

/**
* Whether Vite is resolving the server that Vitest creates to run tests, whatever its `--mode`.
Expand Down Expand Up @@ -215,37 +213,3 @@ export function devTriggerSecretGuardPlugin(): Plugin {
},
};
}

/**
* Warn when the project's `package.json` does not declare `"type": "module"`.
*
* Vite's default `configLoader: "bundle"` bundles `vite.config.ts`,
* externalizes deps, and then loads the bundle. When `package.json` is non-ESM
* the bundle is written as `.js` and loaded via CJS `require()`, which throws
* `ERR_REQUIRE_ASYNC_MODULE` if any externalized dep's ESM graph contains
* top-level await. `@cloudflare/vite-plugin` (which voidPlugin pulls in) has
* exactly such a TLA, so non-ESM consumers hit this on every Vite invocation.
*
* Runs once per Vite process (factory time), single sync read.
*/
export function warnIfPackageJsonIsNotEsm(root: string): void {
const pkgPath = join(root, 'package.json');
if (!existsSync(pkgPath)) {
return;
}
let pkg: { type?: unknown };
try {
pkg = JSON.parse(readFileSync(pkgPath, 'utf8')) as { type?: unknown };
} catch {
return;
}
if (pkg.type === 'module') {
return;
}
voidWarn(
'package.json is missing `"type": "module"`. Vite\'s default config loader ' +
'will fail with ERR_REQUIRE_ASYNC_MODULE on transitive top-level await ' +
'(e.g. @cloudflare/vite-plugin). Add `"type": "module"` to package.json, ' +
'or run vite build with `--configLoader runner`.',
);
}
73 changes: 72 additions & 1 deletion packages/void/test/integration/prepare-cli.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
import { spawnSync } from 'node:child_process';
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import {
existsSync,
mkdirSync,
mkdtempSync,
readFileSync,
rmSync,
symlinkSync,
writeFileSync,
} from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { pathToFileURL } from 'node:url';
Expand Down Expand Up @@ -45,10 +53,12 @@ function createProject(options: { withSources?: boolean; sourceDir?: string } =
function runVoid(
root: string,
args: Array<string>,
input?: string,
): { stdout: string; stderr: string; status: number } {
const res = spawnSync(process.execPath, [CLI_ENTRY, ...args], {
cwd: root,
encoding: 'utf8',
input,
env: {
PATH: process.env.PATH,
HOME: root,
Expand All @@ -69,6 +79,67 @@ afterEach(() => {
}
});

it.each([
['commonjs', 'env.mts'],
['module', 'env.ts'],
])('builds a %s app with a sourceDir env schema after init', (type, schemaFile) => {
const root = createProject();
const vite = join(PACKAGE_ROOT, 'node_modules', 'vite');
mkdirSync(join(root, 'node_modules'));
symlinkSync(PACKAGE_ROOT, join(root, 'node_modules', 'void'), 'junction');
symlinkSync(vite, join(root, 'node_modules', 'vite'), 'junction');
writeFileSync(
join(root, 'package.json'),
JSON.stringify({
name: 'source-dir-app',
type,
devDependencies: { typescript: '*', vite: '*', void: '*' },
}),
);
writeFileSync(join(root, 'void.config.ts'), "export default { sourceDir: 'app' };\n");
writeFileSync(
join(root, type === 'commonjs' ? 'vite.config.mts' : 'vite.config.ts'),
"import { voidPlugin } from 'void';\nexport default { plugins: [voidPlugin()] };\n",
);
writeFileSync(join(root, 'index.html'), '<!doctype html><main>Source directory app</main>\n');
writeFileSync(join(root, '.env'), 'TEST_GREETING=hello\n');
mkdirSync(join(root, 'app', 'routes'), { recursive: true });
writeFileSync(
join(root, 'app', 'routes', 'hello.ts'),
"export const GET = () => new Response('ok');\n",
);
const envFile = join(root, 'app', schemaFile);
const schema =
"import { defineEnv, string } from 'void/env';\nexport default defineEnv({ TEST_GREETING: string() });\n";
if (type === 'commonjs') {
writeFileSync(envFile, schema);
}

// Select "No Database Yet" for this existing project.
const init = runVoid(root, ['init', '--deploy', 'none', '--no-git'], '\u001b[B'.repeat(3) + '\r');
expect(init.status, init.stdout + init.stderr).toBe(0);
const envTypes = join(root, '.void', 'env.d.ts');
rmSync(envTypes, { force: true });
const buildSource = `import { createBuilder } from 'vite';
const builder = await createBuilder({});
await builder.buildApp();`;
const build = spawnSync(process.execPath, ['--input-type=module', '--eval', buildSource], {
cwd: root,
encoding: 'utf8',
timeout: 30_000,
});
expect(build.status, build.stderr).toBe(0);
const schemaSource = readFileSync(envFile, 'utf8');
if (type === 'commonjs') {
expect(schemaSource).toBe(schema);
} else {
expect(schemaSource).toContain('TEST_GREETING: string(),');
}
expect(readFileSync(envTypes, 'utf8')).toContain(`typeof import("../app/${schemaFile}")`);
expect(existsSync(join(root, 'env.ts'))).toBe(false);
expect(existsSync(join(root, 'env.mts'))).toBe(false);
});

describe('void prepare (subprocess)', () => {
it('generates custom binding types and removes them when switching targets', () => {
const root = createProject();
Expand Down
Loading