Files
clean-architecture-frontend…/tests/unit/check-bundle-output.test.ts
T
DongHyeonka 46dfe23f69 fix(bundle): 예산을 넘으면 넘은 한도와 초과량을 출력하고 초기 파일 수를 막는다
문제: 초기 JS가 예산을 넘으면 check:bundle은
"Bundle budget or manifest integrity failed: " 한 줄만 쓰고 콜론 뒤가
비어 있었다. 측정값과 한도는 artifacts/performance/bundle.json에만 있어
예산 실패인지 manifest 무결성 실패인지, 몇 바이트 넘었는지 알 수 없었다.
또 초기 JS 파일 수에는 상한이 없어 08-08처럼 파일을 16개에서 25개로
늘리는 변경도 모든 게이트를 통과했다. 템플릿은 HTTP/2를 전제로 초기
청크를 나눠 두었는데, 파일 수를 늘리는 결정이 어디에도 드러나지 않았다.

고른 방법: 예산 실패와 무결성 실패를 다른 문장으로 쓴다. 예산 실패는
넘은 한도마다 측정값·한도·초과량을 한 줄로 쓴다
(describeBundleBudgetFailures). config/performance/budgets.json에
initialJsFiles(지금 25)를 두고 check:bundle이 entry를 포함한 초기 파일
수를 센다. bundle.json 스키마는 측정값·한도·결과와 자가 검사 fixture를
하나씩 더 가진다. 두 변경은 같은 함수와 스키마를 고치므로 한 커밋에
넣었다.
버린 대안: 파일 수를 문서에만 적기. 08-08이 그 상태에서 파일을 늘렸다.

위험·한계: 초기 파일을 하나라도 늘리는 변경은 이제 budgets.json을 같이
고쳐야 통과한다. 그것이 목적이다. HTTP/2 확인 자체는 이 커밋에 없다
(13-02에서 probe에 넣는다).

검증: tests/unit/check-bundle-output.test.ts가 손으로 만든 빌드 출력에
check-bundle.ts를 돌려 통과·초기 바이트 초과·lazy 초과·파일 수 초과·
무결성 실패의 출력을 본다(고치기 전 4건 실패). bundle-artifact-contract,
performance-budgets 통과. 실제 빌드에서 check:bundle PASS(25 / 25 files).

Refs: docs/reviews/2026-11-03-maturity-review/15-performance.md 15-03, 15-05
2026-11-04 20:22:27 +09:00

129 lines
4.9 KiB
TypeScript

import { spawnSync } from "node:child_process";
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
/**
* 1103/15-03. An over-budget build printed only
* "Bundle budget or manifest integrity failed: " with nothing after the
* colon, so the first budget failure a project meets named neither the limit
* nor the excess. check-bundle runs here on a hand-made build output.
*/
const roots: string[] = [];
afterEach(async () => {
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
});
type Output = Readonly<{ path: string; gzipBytes: number }>;
async function checkBundle(
options: Readonly<{
outputs: readonly Output[];
manifest: Record<string, unknown>;
budgets: Record<string, number>;
}>,
) {
const root = await mkdtemp(path.join(tmpdir(), "check-bundle-output-"));
roots.push(root);
const write = async (file: string, value: unknown) => {
await mkdir(path.dirname(path.join(root, file)), { recursive: true });
await writeFile(path.join(root, file), `${JSON.stringify(value, null, 2)}\n`);
};
await write("config/performance/budgets.json", { schemaVersion: 1, bundle: options.budgets });
await write("dist/.vite/manifest.json", options.manifest);
await write("artifacts/performance/bundle.json", {
schemaVersion: 1,
generatedAt: "2026-11-04T00:00:00.000Z",
context: { nodeVersion: "v24.14.0", packageManager: "pnpm@11.17.0", runnerImage: "fixture" },
outputs: options.outputs.map((output) => ({
path: `dist/${output.path}`,
bytes: output.gzipBytes * 3,
gzipBytes: output.gzipBytes,
sha256: "a".repeat(64),
})),
});
const result = spawnSync(process.execPath, [path.resolve("scripts/check-bundle.ts")], {
cwd: root,
encoding: "utf8",
});
return { status: result.status, stdout: result.stdout, stderr: result.stderr };
}
const MANIFEST = {
"index.html": {
file: "assets/index-A.js",
isEntry: true,
imports: ["_boot"],
},
// The entry's own dynamic imports are initial (09-03); a route's are lazy.
_boot: { file: "assets/boot-B.js", dynamicImports: ["src/lazy.tsx"] },
"src/lazy.tsx": { file: "assets/lazy-C.js" },
};
const OUTPUTS = [
{ path: "assets/index-A.js", gzipBytes: 400 },
{ path: "assets/boot-B.js", gzipBytes: 500 },
{ path: "assets/lazy-C.js", gzipBytes: 300 },
];
const BUDGETS = { initialJsGzipBytes: 1_000, initialJsFiles: 2, lazyChunkGzipBytes: 400 };
describe("check:bundle failure output (1103/15-03)", () => {
it("passes and prints the total within budget", async () => {
const result = await checkBundle({ outputs: OUTPUTS, manifest: MANIFEST, budgets: BUDGETS });
expect(result.stderr).toBe("");
expect(result.status).toBe(0);
expect(result.stdout).toContain("initial JS 900 / 1000 gzip bytes");
});
it("names the measured initial total, the budget and the excess", async () => {
const result = await checkBundle({
outputs: OUTPUTS,
manifest: MANIFEST,
budgets: { ...BUDGETS, initialJsGzipBytes: 899 },
});
expect(result.status).toBe(1);
expect(result.stderr).toContain("Bundle budget failed (config/performance/budgets.json):");
expect(result.stderr).toContain("initial JavaScript 900 gzip bytes > budget 899 (over by 1)");
expect(result.stderr).not.toContain("manifest integrity");
});
it("names each lazy chunk over its budget", async () => {
const result = await checkBundle({
outputs: OUTPUTS,
manifest: MANIFEST,
budgets: { ...BUDGETS, lazyChunkGzipBytes: 250 },
});
expect(result.status).toBe(1);
expect(result.stderr).toContain(
"lazy chunk assets/lazy-C.js 300 gzip bytes > budget 250 (over by 50)",
);
});
// 1103/15-05. The entry preloads every initial file at once; over HTTP/1.1
// they queue for six connections. A change that adds an initial file is a
// decision recorded in the budget, not a side effect.
it("fails when the initial JavaScript has more files than the budget", async () => {
const result = await checkBundle({
outputs: OUTPUTS,
manifest: MANIFEST,
budgets: { ...BUDGETS, initialJsFiles: 1 },
});
expect(result.status).toBe(1);
expect(result.stderr).toContain("initial JavaScript files 2 > budget 1 (over by 1)");
});
it("reports a manifest integrity failure apart from the budget", async () => {
const result = await checkBundle({
outputs: OUTPUTS.filter(({ path: file }) => file !== "assets/boot-B.js"),
manifest: MANIFEST,
budgets: BUDGETS,
});
expect(result.status).toBe(1);
expect(result.stderr).toContain("Bundle manifest integrity failed:");
expect(result.stderr).toContain("output missing from the inventory: assets/boot-B.js");
expect(result.stderr).not.toContain("Bundle budget failed");
});
});