Files
clean-architecture-frontend…/scripts/lib/performance-budgets.ts
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

198 lines
6.3 KiB
TypeScript

import { SERVICE_WORKER_SCRIPT_PATH } from "../../src/contracts/service-worker.ts";
export type BundleMeasurements = Readonly<{
initialJsGzipBytes: number;
initialJsFiles: number;
lazyChunks: readonly Readonly<{ path: string; gzipBytes: number }>[];
/** `null` when the build ships no Service Worker script (REV-FE-0010). */
serviceWorkerGzipBytes: number | null;
}>;
/**
* 1103/15-05. `initialJsFiles` bounds the number of initial JavaScript files
* (entry included). The entry preloads them in parallel, which costs no round
* trip over HTTP/2 and queues them six at a time over HTTP/1.1
* (docs/operations/performance-evidence.md, "초기 청크 수와 HTTP/1.1").
*/
export type BundleThresholds = Readonly<{
initialJsGzipBytes: number;
initialJsFiles: number;
lazyChunkGzipBytes: number;
serviceWorkerGzipBytes: number;
}>;
export function evaluateBundleBudget(
measurements: BundleMeasurements,
thresholds: BundleThresholds,
) {
const initialPassed =
measurements.initialJsGzipBytes <= thresholds.initialJsGzipBytes;
const initialFilesPassed = measurements.initialJsFiles <= thresholds.initialJsFiles;
const lazyResults = measurements.lazyChunks.map((chunk) => ({
...chunk,
threshold: thresholds.lazyChunkGzipBytes,
passed: chunk.gzipBytes <= thresholds.lazyChunkGzipBytes,
}));
const serviceWorkerPassed =
measurements.serviceWorkerGzipBytes === null ||
measurements.serviceWorkerGzipBytes <= thresholds.serviceWorkerGzipBytes;
return Object.freeze({
initialPassed,
initialFilesPassed,
lazyResults: Object.freeze(lazyResults),
serviceWorkerPassed,
passed:
initialPassed &&
initialFilesPassed &&
serviceWorkerPassed &&
lazyResults.every((chunk) => chunk.passed),
});
}
/**
* 1103/15-03. One line per exceeded limit with the measured value, the limit
* and the excess, so a failed check:bundle says what to cut without opening
* artifacts/performance/bundle.json.
*/
export function describeBundleBudgetFailures(
measurements: BundleMeasurements,
thresholds: BundleThresholds,
): string[] {
const over = (label: string, measured: number, limit: number, unit = " gzip bytes") =>
`${label} ${measured}${unit} > budget ${limit} (over by ${measured - limit})`;
const lines: string[] = [];
if (measurements.initialJsGzipBytes > thresholds.initialJsGzipBytes) {
lines.push(over("initial JavaScript", measurements.initialJsGzipBytes, thresholds.initialJsGzipBytes));
}
if (measurements.initialJsFiles > thresholds.initialJsFiles) {
lines.push(over("initial JavaScript files", measurements.initialJsFiles, thresholds.initialJsFiles, ""));
}
for (const chunk of measurements.lazyChunks) {
if (chunk.gzipBytes > thresholds.lazyChunkGzipBytes) {
lines.push(over(`lazy chunk ${chunk.path}`, chunk.gzipBytes, thresholds.lazyChunkGzipBytes));
}
}
const worker = measurements.serviceWorkerGzipBytes;
if (worker !== null && worker > thresholds.serviceWorkerGzipBytes) {
lines.push(
over(`service worker ${SERVICE_WORKER_SCRIPT_PATH}`, worker, thresholds.serviceWorkerGzipBytes),
);
}
return lines;
}
/**
* 1105/15-01. `targetDeepLinkCls` is the CLS of a direct visit to the lab's
* target route, judged against the same `cls` threshold. The click run
* cannot see a shift the target makes while it fills in: one within 500 ms
* of the click is input-driven by definition.
*/
export type LabMetrics = Readonly<{
lcpMs: number;
cls: number;
namedInteractionMs: number;
targetDeepLinkCls: number;
/**
* 1105/15-04. Click to heading on the first public navigation route an
* installed feature owns (`labFeatureRoute`). `null` when there is none:
* nothing to judge.
*/
featureRouteInteractionMs: number | null;
}>;
export type LabThresholds = Readonly<{
lcpMs: number;
cls: number;
namedInteractionMs: number;
featureRouteInteractionMs: number;
}>;
export function evaluateLabBudget(
report: Readonly<{
context?: Readonly<Record<string, unknown>>;
metrics: LabMetrics;
}>,
thresholds: LabThresholds,
) {
const requiredContext = [
"runner",
"browser",
"viewport",
"network",
"cpu",
"cache",
"build",
];
const missingContext = requiredContext.filter(
(field) => report.context?.[field] === undefined,
);
const results = {
lcp: report.metrics.lcpMs <= thresholds.lcpMs,
cls: report.metrics.cls <= thresholds.cls,
namedInteraction:
report.metrics.namedInteractionMs <= thresholds.namedInteractionMs,
targetDeepLinkCls: report.metrics.targetDeepLinkCls <= thresholds.cls,
featureRouteInteraction:
report.metrics.featureRouteInteractionMs === null ||
report.metrics.featureRouteInteractionMs <= thresholds.featureRouteInteractionMs,
};
return Object.freeze({
missingContext: Object.freeze(missingContext),
results: Object.freeze(results),
passed: missingContext.length === 0 && Object.values(results).every(Boolean),
});
}
export function percentile75(values: readonly number[]): number | null {
if (values.length === 0) return null;
const sorted = [...values].sort((left, right) => left - right);
return sorted[Math.ceil(sorted.length * 0.75) - 1];
}
export type FieldMetrics = Readonly<{
p75LcpMs: number | null;
p75Cls: number | null;
p75InpMs: number | null;
}>;
export type FieldThresholds = Readonly<{
p75LcpMs: number;
p75Cls: number;
p75InpMs: number;
minimumEligibleSamples: number | null;
}>;
export type FieldBudgetResult = Readonly<{
status: "PASS" | "FAIL_THRESHOLD" | "FAIL_UNVERIFIED";
passed: boolean;
}>;
export function evaluateFieldBudget(
report: Readonly<{ metrics: FieldMetrics; eligibleSamples: number }>,
thresholds: FieldThresholds,
): FieldBudgetResult {
if (
thresholds.minimumEligibleSamples === null ||
report.eligibleSamples < thresholds.minimumEligibleSamples ||
Object.values(report.metrics).some((value) => value === null)
) {
return Object.freeze({
status: "FAIL_UNVERIFIED",
passed: false,
});
}
const metrics = report.metrics as Readonly<{
p75LcpMs: number;
p75Cls: number;
p75InpMs: number;
}>;
const passed =
metrics.p75LcpMs <= thresholds.p75LcpMs &&
metrics.p75Cls <= thresholds.p75Cls &&
metrics.p75InpMs <= thresholds.p75InpMs;
return Object.freeze({
status: passed ? "PASS" : "FAIL_THRESHOLD",
passed,
});
}