Skip to content

Commit 2d432af

Browse files
morinokamiclaude
andcommitted
fix(env): keep env.ts in Worker builds of apps without side effects
When an app's package.json declares "sideEffects": false, a production build dropped env.ts from the Worker. The generated entry imports env.ts only for its side effect, registering the schema, so the bundler removed that import: env read raw values, and boot validation passed anything. envSchemaPlugin now marks env.ts as having side effects in server builds. Rolldown honors the plugin's value over the package's sideEffects field. The transform filter matches the env file's path as found and as Vite resolves it, so a symlinked env.ts is covered whatever its target is named. Client builds are unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 4d51362 commit 2d432af

2 files changed

Lines changed: 112 additions & 6 deletions

File tree

‎packages/void/src/plugin-env-schema.ts‎

Lines changed: 33 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { existsSync, mkdirSync, readFileSync, realpathSync } from 'node:fs';
22
import { parseEnv } from 'node:util';
33
import { join, resolve } from 'pathslash';
4-
import { loadEnv, resolveEnvPrefix, type Plugin, type ResolvedConfig } from 'vite';
4+
import { loadEnv, normalizePath, resolveEnvPrefix, type Plugin, type ResolvedConfig } from 'vite';
55
import { findEnvFile, generateEnvTypes } from './codegen/env-types.ts';
66
import { writeFileIfChanged } from './codegen/write-if-changed.ts';
77
import { loadUserEnvFile } from './host/load-user-env.ts';
@@ -72,7 +72,7 @@ function stripLocalClientEnv(
7272
config: ResolvedConfig,
7373
before: ProcessEnvCopies | undefined,
7474
): void {
75-
if (config.envDir === false || realDir(config.envDir) !== realDir(root)) {
75+
if (config.envDir === false || realPath(config.envDir) !== realPath(root)) {
7676
return;
7777
}
7878
const file = join(root, LOCAL_ENV_FILE);
@@ -107,14 +107,24 @@ function stripLocalClientEnv(
107107
}
108108

109109
/** Match Vite's canonical paths, including Windows short names and filesystem casing. */
110-
function realDir(dir: string): string {
110+
function realPath(path: string): string {
111111
try {
112-
return realpathSync.native(dir);
112+
return realpathSync.native(path);
113113
} catch {
114-
return resolve(dir);
114+
return resolve(path);
115115
}
116116
}
117117

118+
/** Module ids that name an env file: its path as found, and as Vite resolves it. */
119+
function envFileIdsFor(envFile: string | null): Set<string> {
120+
return new Set(envFile ? [normalizePath(envFile), normalizePath(realPath(envFile))] : []);
121+
}
122+
123+
/** A hook filter pattern that matches exactly `id`. */
124+
function exactId(id: string): RegExp {
125+
return new RegExp(`^${id.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}$`);
126+
}
127+
118128
/** Patterns Vite's `define` typically uses for env-shaped constants. */
119129
const DEFINE_ENV_PATTERN =
120130
/^(?:globalThis\.)?(?:process\.env|import\.meta\.env)\.([A-Z_][A-Z0-9_]*)$/;
@@ -133,6 +143,22 @@ const DEFINE_ENV_PATTERN =
133143
export function envSchemaPlugin(root: string, options: EnvSchemaPluginOptions = {}): Plugin {
134144
const outDir = join(root, '.void');
135145
let envFile: string | null = null;
146+
// `config` finds the file again. The transform filter below keeps the ids found here: a hook
147+
// filter is fixed when the plugin is created.
148+
let envFileIds = envFileIdsFor(findEnvFile(root));
149+
// Generated server entries import env.ts only to register its schema. Keep that import when
150+
// the app's package.json declares `"sideEffects": false`, which would let the bundler drop it.
151+
// The filter matches the resolved id, which for a symlink is the target's path, whatever its
152+
// file name.
153+
const keepEnvFileImport: Plugin['transform'] = {
154+
filter: { id: [...envFileIds].map(exactId) },
155+
handler(code, id) {
156+
if (this.environment.config.consumer === 'client' || !envFileIds.has(id)) {
157+
return;
158+
}
159+
return { code, map: null, moduleSideEffects: true };
160+
},
161+
};
136162
let command: 'serve' | 'build' = 'serve';
137163
let processEnvCopiesBefore: ProcessEnvCopies | undefined;
138164
const appliedClientDefaults = new Map<string, string>();
@@ -317,6 +343,7 @@ export function envSchemaPlugin(root: string, options: EnvSchemaPluginOptions =
317343
throw new Error(reservedEnvKeysMessage('.env', reservedInDotenv));
318344
}
319345
envFile = findEnvFile(root);
346+
envFileIds = envFileIdsFor(envFile);
320347
if (!envFile) {
321348
return;
322349
}
@@ -392,5 +419,6 @@ export function envSchemaPlugin(root: string, options: EnvSchemaPluginOptions =
392419
await importUserEnv();
393420
}
394421
},
422+
...(envFileIds.size > 0 && { transform: keepEnvFileImport }),
395423
};
396424
}

‎packages/void/test/integration/plugin-env-schema.test.ts‎

Lines changed: 79 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,15 @@
1-
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
1+
import {
2+
existsSync,
3+
mkdirSync,
4+
mkdtempSync,
5+
readFileSync,
6+
rmSync,
7+
symlinkSync,
8+
writeFileSync,
9+
} from 'node:fs';
210
import { tmpdir } from 'node:os';
311
import { basename, dirname, join } from 'node:path';
12+
import { pathToFileURL } from 'node:url';
413
import { build, createBuilder, resolveConfig, type InlineConfig } from 'vite';
514
import { afterEach, describe, expect, it, vi } from 'vite-plus/test';
615
import { envClientFoldPlugin } from '../../src/plugin-env-client-fold.ts';
@@ -558,3 +567,72 @@ describe('envSchemaPlugin reserved __VOID_ names', () => {
558567
},
559568
);
560569
});
570+
571+
describe('envSchemaPlugin with "sideEffects": false', () => {
572+
const publicEnvUrl = pathToFileURL(
573+
join(import.meta.dirname, '../../src/runtime/env-public.ts'),
574+
).href;
575+
576+
/** Build an app that declares no side effects, with an entry that imports env.ts for its side effect. */
577+
async function buildEntryImportingEnv(
578+
consumer: 'server' | 'client',
579+
options: { symlinkTo?: string } = {},
580+
): Promise<string> {
581+
const root = createTempRoot();
582+
writeFileSync(
583+
join(root, 'package.json'),
584+
JSON.stringify({ type: 'module', sideEffects: false }),
585+
);
586+
const schemaFile = join(root, options.symlinkTo ?? 'env.ts');
587+
writeFileSync(
588+
schemaFile,
589+
`import { defineEnv, number } from ${JSON.stringify(publicEnvUrl)};\n` +
590+
'export default defineEnv({ SCHEMA_DEFAULT: number().default(48213) });\n',
591+
);
592+
if (options.symlinkTo) {
593+
symlinkSync(schemaFile, join(root, 'env.ts'));
594+
}
595+
writeFileSync(join(root, 'entry.js'), 'import "./env.ts";\nexport const ready = true;\n');
596+
const entry = join(root, 'entry.js');
597+
const output = await build({
598+
root,
599+
configFile: false,
600+
logLevel: 'silent',
601+
plugins: [envSchemaPlugin(root)],
602+
build: {
603+
ssr: consumer === 'server' ? entry : false,
604+
write: false,
605+
minify: false,
606+
rollupOptions: {
607+
...(consumer === 'client' && { input: entry }),
608+
external: ['cloudflare:workers'],
609+
},
610+
},
611+
});
612+
return [output]
613+
.flat()
614+
.flatMap((result) => ('output' in result ? result.output : []))
615+
.map((chunk) => ('code' in chunk ? chunk.code : ''))
616+
.join('\n');
617+
}
618+
619+
// Void's server entries import env.ts to register its schema.
620+
it('keeps env.ts in a server build', async () => {
621+
expect(await buildEntryImportingEnv('server')).toContain('48213');
622+
});
623+
624+
// Vite loads a symlinked env.ts under its target's path. Windows needs privileges for a file
625+
// symlink.
626+
it.skipIf(process.platform === 'win32')(
627+
'keeps a symlinked env.ts whose target has another name',
628+
async () => {
629+
expect(await buildEntryImportingEnv('server', { symlinkTo: 'shared-schema.ts' })).toContain(
630+
'48213',
631+
);
632+
},
633+
);
634+
635+
it('leaves client builds to the side effects that the app declares', async () => {
636+
expect(await buildEntryImportingEnv('client')).not.toContain('48213');
637+
});
638+
});

0 commit comments

Comments
 (0)