diff --git a/eslint.config.ts b/eslint.config.ts index 2505f4b5..bb445e91 100644 --- a/eslint.config.ts +++ b/eslint.config.ts @@ -865,4 +865,50 @@ export default [ ], }, }, + { + // 13-06. Vite inlines every loaded VITE_* value into the bundle wherever + // code references the whole `import.meta.env` object, including values no + // code reads. Keyed reads are replaced one by one. + files: [`src/**/*.${sourceExtensions}`], + plugins: { + "build-env": { + rules: { + "no-whole-import-meta-env": { + meta: { + type: "problem", + schema: [], + messages: { + whole: + "Read build variables by key (import.meta.env.VITE_NAME). Referencing import.meta or import.meta.env as a whole bundles every VITE_* value (13-06).", + }, + }, + create(context: any) { + const isMember = (node: any) => + node?.type === "MemberExpression" || + node?.type === "OptionalMemberExpression"; + return { + MetaProperty(node: any) { + if (node.meta?.name !== "import") return; + const member = node.parent; + if (!isMember(member) || member.object !== node || member.computed) { + context.report({ node, messageId: "whole" }); + return; + } + if (member.property?.name !== "env") return; + const read = member.parent; + if (isMember(read) && read.object === member && !read.computed) { + return; + } + context.report({ node: member, messageId: "whole" }); + }, + }; + }, + }, + }, + }, + }, + rules: { + "build-env/no-whole-import-meta-env": "error", + }, + }, ]; diff --git a/src/contracts/env.ts b/src/contracts/env.ts index 916be599..3b756399 100644 --- a/src/contracts/env.ts +++ b/src/contracts/env.ts @@ -120,8 +120,18 @@ export type BuildEnvironment = Readonly<{ VITE_RUNTIME_CONFIG_URL?: string; }>; +/** + * 13-06. Each variable is read by key so Vite replaces it on its own. Passing + * `import.meta.env` whole made Vite inline every loaded VITE_* value, read or + * not, into this module's chunk. + */ export function getBuildConfig( - environment: BuildEnvironment = import.meta.env as BuildEnvironment, + environment: BuildEnvironment = { + VITE_BUILD_ID: import.meta.env.VITE_BUILD_ID, + VITE_COMMIT_SHA: import.meta.env.VITE_COMMIT_SHA, + VITE_ROUTER_BASE_PATH: import.meta.env.VITE_ROUTER_BASE_PATH, + VITE_RUNTIME_CONFIG_URL: import.meta.env.VITE_RUNTIME_CONFIG_URL, + }, ) { const buildId = environment.VITE_BUILD_ID || "local-build"; const commitSha = environment.VITE_COMMIT_SHA || "local"; diff --git a/tests/unit/build-environment-bundle.test.ts b/tests/unit/build-environment-bundle.test.ts new file mode 100644 index 00000000..78490be8 --- /dev/null +++ b/tests/unit/build-environment-bundle.test.ts @@ -0,0 +1,86 @@ +import { spawnSync } from "node:child_process"; +import { mkdtemp, readdir, readFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +import { afterAll, describe, expect, it } from "vitest"; + +import { filesBelow } from "../../scripts/lib/removal-fixture.ts"; + +/** + * 13-06. Which VITE_* values reach the bundle. The declared values the app + * reads must still be there (build id, commit, runtime config URL, base path); + * a declared value nothing reads and an undeclared one must not be, and the + * design-system chunk must not change with the build id. + */ +const roots: string[] = []; + +afterAll(async () => { + await Promise.all(roots.map((root) => rm(root, { recursive: true, force: true }))); +}); + +function inheritedEnvironment(): NodeJS.ProcessEnv { + return Object.fromEntries( + Object.entries(process.env).filter(([name]) => !name.startsWith("VITE_")), + ); +} + +async function build(variables: Readonly>) { + const outDir = await mkdtemp(path.join(tmpdir(), "build-environment-")); + roots.push(outDir); + const run = spawnSync( + path.resolve("node_modules/.bin/vite"), + ["build", "--outDir", outDir, "--emptyOutDir", "--logLevel", "error"], + { encoding: "utf8", env: { ...inheritedEnvironment(), ...variables } }, + ); + const contents = run.status === 0 + ? await Promise.all( + (await filesBelow(outDir)) + .filter((file) => /\.(?:js|html)$/u.test(file)) + .map(async (file) => ({ file, text: await readFile(file, "utf8") })), + ) + : []; + return { run, outDir, contents }; +} + +const DECLARED = Object.freeze({ + VITE_COMMIT_SHA: "commit-probe-13", + VITE_ROUTER_BASE_PATH: "/base-probe/", + VITE_RUNTIME_CONFIG_URL: "/base-probe/runtime-probe.json", + // Declared, but applied by the index generator; the bundle never reads it. + VITE_PRODUCT_FEATURES: "unreferenced-probe-13", +}); + +describe("build variables in the bundle (13-06)", () => { + it("keeps the values the app reads and nothing else", async () => { + const first = await build({ ...DECLARED, VITE_BUILD_ID: "build-probe-1" }); + expect(first.run.stderr).toBe(""); + expect(first.run.status).toBe(0); + const bundled = (value: string) => + first.contents.some(({ text }) => text.includes(value)); + expect(bundled("build-probe-1")).toBe(true); + expect(bundled("commit-probe-13")).toBe(true); + expect(bundled("/base-probe/runtime-probe.json")).toBe(true); + const html = first.contents.find(({ file }) => file.endsWith("index.html")); + expect(html?.text).toContain('src="/base-probe/assets/'); + expect(bundled("unreferenced-probe-13")).toBe(false); + + const second = await build({ ...DECLARED, VITE_BUILD_ID: "build-probe-2" }); + expect(second.run.status).toBe(0); + const designSystem = async (outDir: string) => + (await readdir(path.join(outDir, "assets"))).filter((name) => + name.startsWith("design-system-"), + ); + const firstChunks = await designSystem(first.outDir); + expect(firstChunks).toHaveLength(1); + expect(await designSystem(second.outDir)).toEqual(firstChunks); + }, 120_000); + + it("refuses a VITE_* variable the build does not declare", async () => { + const refused = await build({ VITE_PAYMENT_KEY: "sk_live_probe" }); + expect(refused.run.status).not.toBe(0); + expect(refused.run.stderr + refused.run.stdout).toMatch( + /Undeclared VITE_\* build variables: VITE_PAYMENT_KEY/u, + ); + }, 120_000); +}); diff --git a/tests/unit/product-feature-selection-build.test.ts b/tests/unit/product-feature-selection-build.test.ts index 9eb4341f..966f8e5e 100644 --- a/tests/unit/product-feature-selection-build.test.ts +++ b/tests/unit/product-feature-selection-build.test.ts @@ -22,6 +22,7 @@ const BUILD_INPUTS = [ "src", "public", "index.html", + "package.json", "vite.config.ts", "tsconfig.base.json", "tsconfig.app.json", diff --git a/vite.config.ts b/vite.config.ts index 7fc05d4a..ffd866ea 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -1,8 +1,27 @@ -import { defineConfig } from "vite"; +import { defineConfig, loadEnv } from "vite"; import react from "@vitejs/plugin-react"; import tailwindcss from "@tailwindcss/vite"; import { viteModuleInventoryPlugin } from "./scripts/lib/vite-module-inventory.ts"; +import { ENV_REGISTRY } from "./src/contracts/env.ts"; + +/** + * 13-06. Every VITE_* value Vite loads (shell or `.env*`) is public once + * something bundles it, so a value the build does not declare is refused + * rather than carried along. + */ +function assertDeclaredBuildVariables(mode: string): void { + const undeclared = Object.keys(loadEnv(mode, process.cwd(), "VITE_")) + .filter((name) => !Object.hasOwn(ENV_REGISTRY, name)) + .sort(); + if (undeclared.length > 0) { + throw new Error( + `Undeclared VITE_* build variables: ${undeclared.join(", ")}. ` + + "Declare them in ENV_REGISTRY (src/contracts/env.ts) or unset them; " + + "VITE_ values are published to the browser.", + ); + } +} /** * ยง6.1. One sub-path, declared once. @@ -24,11 +43,14 @@ function routerBasePath(environment: NodeJS.ProcessEnv): string { return declared; } -export default defineConfig({ - base: routerBasePath(process.env), - plugins: [react(), tailwindcss(), viteModuleInventoryPlugin()], - build: { - manifest: true, - sourcemap: false, - }, +export default defineConfig(({ mode }) => { + assertDeclaredBuildVariables(mode); + return { + base: routerBasePath(process.env), + plugins: [react(), tailwindcss(), viteModuleInventoryPlugin()], + build: { + manifest: true, + sourcemap: false, + }, + }; });