Files
tech-log-frontend/tests/unit/build-environment-bundle.test.ts
T
DongHyeonka 9e20d471b0 fix(build): 부팅 실패 화면이 앱 그래프 청크 없이 그려진다
앱 모듈 하나가 평가 중에 예외를 던지면 main.tsx는 부팅 실패 화면
(render-boot-failure.tsx)을 그린다. 그런데 그 청크가 route-not-found
청크에서 값 둘을 import하고, route-not-found에는 React, i18n 카탈로그,
installed-feature-messages.ts가 같이 들어 있다. 그래서 예외를 던진
청크에 실패 화면도 같이 걸려 그리지 못하고, 정적 「불러오는 중」
화면이 계속 남는다(boot-module-failure e2e, 세 엔진 모두).

원인은 vite.config.ts의 manualChunks다. Rolldown은 manualChunks를
includeDependenciesRecursively가 기본값(true)인 group으로 바꾼다. 그래서
route-not-found로 지정한 Public not-found 화면이 자기 정적 의존을 전부
그 청크로 끌고 간다. PR #6 전(27e342d) 빌드도 같은 import가 있었다.

템플릿과 같은 output.codeSplitting.groups 형식으로 바꾼다. react-dom과
route 화면 group은 includeDependenciesRecursively: false로 둬서, 화면
모듈만 그 이름의 청크에 들어가게 한다. 공유 모듈은 Rolldown이 쓰는
쪽에 따라 나눈다. preload-helper·react-dom·route 청크 이름은 그대로다.

검증:
- build-environment-bundle.test.ts에 시험 하나를 더했다. 실패 화면
  청크에서 정적 import로 닿는 청크 가운데 installed-feature-messages의
  오류 문구가 든 것이 없어야 한다. 고치기 전에는
  route-not-found-*.js가 잡혀 실패했고, 고친 뒤 통과한다.
- vite-route-chunks, bundle-*, chunk-recovery*, performance-budgets 단위
  시험(29건) 통과.
- e2e: boot-module-failure, old-tab-chunk-recovery,
  service-worker-update·recovery, production-csp가 chromium·firefox·
  webkit에서 통과한다.
2026-11-12 18:38:30 +09:00

138 lines
5.7 KiB
TypeScript

import { spawnSync } from "node:child_process";
import { mkdtemp, 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<Record<string, string>>) {
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);
// The design system, found by what it holds rather than by name: this
// product's route chunk split (vite.config.ts) names chunks after route
// modules, and upstream's `design-system-*` does not exist here.
// (The previous check looked at `render-boot-failure-*`, which holds the
// build id on purpose and can never keep its name.)
const designSystem = ({ contents }: Awaited<ReturnType<typeof build>>) =>
contents
.filter(({ file, text }) =>
file.endsWith(".js") && text.includes("ui-button--pending"),
)
.map(({ file }) => path.basename(file));
const firstChunks = designSystem(first);
expect(firstChunks).toHaveLength(1);
expect(designSystem(second)).toEqual(firstChunks);
// Template 1103/15-06. react-dom sat in the boot-failure chunk with the
// build id, so every release renamed it and returning visitors downloaded
// it again. Its own chunk keeps the name while only the build id changes.
const reactDom = ({ contents }: Awaited<ReturnType<typeof build>>) =>
contents
.filter(({ file, text }) => file.endsWith(".js") && text.includes("__reactContainer$"))
.map(({ file }) => path.basename(file));
expect(reactDom(first)).toHaveLength(1);
expect(reactDom(first)[0]).not.toMatch(/render-boot-failure/u);
expect(reactDom(second)).toEqual(reactDom(first));
}, 120_000);
// 09-03. main.tsx imports the boot-failure screen when the application
// graph throws while its modules evaluate, so that screen must not import a
// chunk holding that graph. installed-feature-messages.ts (the module the
// boot-module-failure e2e makes throw) is found by its error text.
it("draws the boot-failure screen without the application graph", async () => {
const { run, contents } = await build({ VITE_BUILD_ID: "build-probe-boot" });
expect(run.status).toBe(0);
const chunks = new Map(
contents
.filter(({ file }) => file.endsWith(".js"))
.map(({ file, text }) => [path.basename(file), text]),
);
const staticImports = (text: string) =>
[...text.matchAll(/(?:from|import)\s*"\.\/([\w.-]+\.js)"/gu)].map(
([, name]) => name!,
);
const entry = [...chunks.keys()].find((name) =>
name.startsWith("render-boot-failure-"),
);
expect(entry).toBeDefined();
const reached = new Set<string>();
const pending = [entry!];
while (pending.length > 0) {
const name = pending.pop()!;
if (reached.has(name)) continue;
reached.add(name);
pending.push(...staticImports(chunks.get(name) ?? ""));
}
expect(
[...reached].filter((name) => chunks.get(name)?.includes("message key: ")),
).toEqual([]);
}, 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);
});