Files
DongHyeonka 81447354cd fix(bundle): check:bundle이 Service Worker와 manifest 밖 JS를 잰다
check:bundle은 Vite manifest의 chunk만 잰다. Service Worker를 켠 제품의
worker와 public·Web Worker 출력은 크기가 얼마든 FE-GATE-012를 통과한다.

빌드가 만든 Service Worker는 새 key `bundle.serviceWorkerGzipBytes`로,
assets/에 빌드가 만든 hash 이름 파일은 파일마다 lazy 예산으로 잰다.
public/ 사본은 이름이 hash처럼 보이거나 service-worker.js여도 빌드
출력이 아니므로, 그 밖의 예산 없는 JS와 함께 경로를 대고 실패한다.
이름만 보는 안은 HTML이 바로 읽는 public JS 221,678 B가 통과해 버렸다.
새 key가 없으면 파일과 key를 대고 실패한다.

예산 값은 자산 목록을 상한까지(채운 이름은 줄기 16자 무작위) 채우고
build·release id를 128자로 준 worker(Mmax)를 1 KiB 단위로 올림한
값이다(review 판정 2026-11-23, 소유자 결정 아님). 100 B 단위 올림은
기능을 더한 제품이 코드 변경 없이 막히고, 긴 이름에 맞춰 올리거나
id를 512자로 재는 안은 worker 코드 증가를 더 숨긴다. 목록과 코드를
나눠 재는 안은 빌드 구조를 바꿔서 버렸다.

위험: 자산 목록이 상한에 가까우면 이름이 길고 다양하거나 id가 길 때
예산을 넘을 수 있다. 기본 id로도 넘는 조합을 쟀다. 자산이 적은
빌드에서는 목록 몫만큼 worker 코드 증가를 못 잡는다. 기본 선택이
null이라 템플릿 CI는 worker 값을 재지 않는다.

검증: 고치기 전 코드에 이 커밋의 시험을 얹으면 세 파일 47개 가운데
25개가 실패하고 이 트리에서 통과한다. 보호 규칙 변이 15개가 실패한다.
노트북 check:types, lint, check:architecture, test:unit, test:contract,
test:runtime-schema, verify:documentation 통과. desktop에서 worker
입력이 같은 트리의 Mmax 23404 B, 자산 길이 다섯 자리 23442 B, handler
둘 23424 B가 예산 안이고 zod를 넣은 worker는 실패했다. merge 단계와
FE-GATE-029·030은 커밋 때 돌리지 않았다.

Refs: REV-FE-0010
2026-11-23 06:00:49 +09:00

209 lines
6.5 KiB
TypeScript

import { existsSync } from "node:fs";
import { readFile } from "node:fs/promises";
import path from "node:path";
import {
describeBundleBudgetFailures,
evaluateBundleBudget,
} from "./lib/performance-budgets.ts";
import {
bundleOutputInventoryArtifactSchema,
bundlePerformanceArtifactSchema,
bundleThresholdsSchema,
} from "./contracts/release-artifacts.ts";
import { SERVICE_WORKER_SCRIPT_PATH } from "../src/contracts/service-worker.ts";
import {
addUnlistedBuildChunks,
classifyViteJavascript,
findUnbudgetedJavascript,
} from "./lib/classify-vite-bundle.ts";
import { checkoutBuildReadFailure } from "./lib/run-isolation.ts";
import { writeValidatedJsonArtifact } from "./lib/validated-json-artifact.ts";
type ViteManifest = Record<
string,
{ file: string; isEntry?: boolean; imports?: string[] }
>;
// 1106/12-02. This reads dist/.vite/manifest.json and the inventory
// scripts/generate-supply-chain.ts made of dist. Under RUN_OUTPUT_ROOT the
// build wrote elsewhere, and this passed a build over budget on the earlier
// one the checkout still held.
const outputRootFailure = checkoutBuildReadFailure("scripts/check-bundle.ts");
if (outputRootFailure !== undefined) {
process.stderr.write(`${outputRootFailure}\n`);
process.exit(1);
}
const report = bundleOutputInventoryArtifactSchema.parse(
JSON.parse(await readFile("artifacts/performance/bundle.json", "utf8")) as unknown,
);
const viteManifest = JSON.parse(
await readFile("dist/.vite/manifest.json", "utf8"),
) as ViteManifest;
const configuredBudgets = bundleThresholdsSchema.safeParse(
JSON.parse(await readFile("config/performance/budgets.json", "utf8")).bundle,
);
// The first failure of a project that has not added a new key, so it names
// the file and the key, not the evidence schema that would refuse it later.
if (!configuredBudgets.success) {
process.stderr.write(
`Bundle budget is invalid (config/performance/budgets.json):\n${configuredBudgets.error.issues
.map((issue) => ` ${["bundle", ...issue.path].join(".")}: ${issue.message}\n`)
.join("")}`,
);
process.exit(1);
}
const budgets = configuredBudgets.data;
const outputByPath = new Map(
report.outputs.map((output) => [output.path.replace(/^dist\//, ""), output]),
);
const classification = addUnlistedBuildChunks(
classifyViteJavascript(viteManifest),
outputByPath.keys(),
(file) => existsSync(path.join("public", file)),
);
const initialJsGzipBytes = classification.initialFiles.reduce(
(total, file) => total + (outputByPath.get(file)?.gzipBytes ?? 0),
0,
);
const lazyChunks = classification.lazyFiles.map((file) => ({
path: file,
gzipBytes: outputByPath.get(file)?.gzipBytes ?? 0,
}));
const missingOutputs = [
...classification.initialFiles,
...classification.lazyFiles,
].filter((file) => !outputByPath.has(file));
const unbudgetedOutputs = findUnbudgetedJavascript(outputByPath.keys(), classification);
const serviceWorkerGzipBytes = outputByPath.get(SERVICE_WORKER_SCRIPT_PATH)?.gzipBytes ?? null;
const measurements = {
initialJsGzipBytes,
initialJsFiles: classification.initialFiles.length,
lazyChunks,
serviceWorkerGzipBytes,
};
const result = evaluateBundleBudget(measurements, budgets);
const fixtures = [
{
name: "initial-js-over-budget",
passed:
!evaluateBundleBudget(
{
initialJsGzipBytes: budgets.initialJsGzipBytes + 1,
initialJsFiles: 0,
lazyChunks: [],
serviceWorkerGzipBytes: null,
},
budgets,
).passed,
},
{
name: "lazy-chunk-over-budget",
passed:
!evaluateBundleBudget(
{
initialJsGzipBytes: 0,
initialJsFiles: 0,
lazyChunks: [
{
path: "fixture.js",
gzipBytes: budgets.lazyChunkGzipBytes + 1,
},
],
serviceWorkerGzipBytes: null,
},
budgets,
).passed,
},
{
name: "initial-files-over-budget",
passed:
!evaluateBundleBudget(
{
initialJsGzipBytes: 0,
initialJsFiles: budgets.initialJsFiles + 1,
lazyChunks: [],
serviceWorkerGzipBytes: null,
},
budgets,
).passed,
},
{
name: "service-worker-over-budget",
passed:
!evaluateBundleBudget(
{
initialJsGzipBytes: 0,
initialJsFiles: 0,
lazyChunks: [],
serviceWorkerGzipBytes: budgets.serviceWorkerGzipBytes + 1,
},
budgets,
).passed,
},
];
const passed =
result.passed &&
fixtures.every((fixture) => fixture.passed) &&
classification.missingImports.length === 0 &&
missingOutputs.length === 0 &&
unbudgetedOutputs.length === 0;
const completedReport = {
...report,
measurements,
classification,
missingOutputs,
unbudgetedOutputs,
thresholds: budgets,
results: result,
fixtures,
passed,
};
await writeValidatedJsonArtifact({
path: "artifacts/performance/bundle.json",
schema: bundlePerformanceArtifactSchema,
value: completedReport,
});
// 1103/15-03. The budget and the manifest integrity fail for different
// reasons, so each says what failed and by how much.
if (!passed) {
const budgetFailures = describeBundleBudgetFailures(measurements, budgets);
if (budgetFailures.length > 0) {
process.stderr.write(
`Bundle budget failed (config/performance/budgets.json):\n${budgetFailures
.map((line) => ` ${line}\n`)
.join("")}`,
);
}
const integrityFailures = [
...classification.missingImports.map((key) => `manifest import without an entry: ${key}`),
...missingOutputs.map((file) => `output missing from the inventory: ${file}`),
...unbudgetedOutputs.map(
(file) =>
`JavaScript output without a budget: ${file} ` +
"(only dist/.vite/manifest.json chunks, hashed files under assets/ and the Service Worker script have one, " +
"and none of them is a file of public/)",
),
...fixtures
.filter((fixture) => !fixture.passed)
.map((fixture) => `budget self-check did not fail: ${fixture.name}`),
];
if (integrityFailures.length > 0) {
process.stderr.write(
`Bundle manifest integrity failed:\n${integrityFailures.map((line) => ` ${line}\n`).join("")}`,
);
}
process.exit(1);
}
process.stdout.write(
`Bundle budget: PASS (initial JS ${initialJsGzipBytes} / ${budgets.initialJsGzipBytes} gzip bytes, ` +
`${measurements.initialJsFiles} / ${budgets.initialJsFiles} files` +
(serviceWorkerGzipBytes === null
? ""
: `, service worker ${serviceWorkerGzipBytes} / ${budgets.serviceWorkerGzipBytes} gzip bytes`) +
")\n",
);