Files
clean-architecture-frontend…/scripts/lib/performance-budgets.ts
T
DongHyeonka 138c195fcd fix(examples): 릴리스 신원 칸의 자리를 미리 잡고 lab이 대상 화면 직접 진입 CLS를 잰다
문제: 플랫폼 구성 화면(lab 대상)은 getReleaseSummary()가 끝날 때까지
릴리스 신원 칸을 "상태" 한 칸으로 그리고, 끝나면 hint 줄이 있는 네 칸으로
바꾼다. 제목이 보인 뒤 약 30~100 ms에 grid가 hint 한 줄만큼 커져 아래
section이 21 px 내려간다(layout shift 0.00461, 리뷰 15-platform-shift
16회). lab은 `/`에서 클릭으로만 들어가고, 클릭 뒤 500 ms 안의 shift는
hadRecentInput이라 CLS에서 빠지므로 0을 낸다. `/` 밖의 라우트 CLS는 어느
게이트도 보지 않는다.

고른 방법:
- 화면: 요약 전·실패 때도 같은 네 칸(빌드·릴리스·설정 스키마·계약 집합
  다이제스트)을 같은 hint 줄 구성으로 그린다. 값만 "확인하고 있습니다."
  / "확인하지 못했습니다." / "—"다. 상태 문장은 가장 좁은 칸(13rem)에서도
  한 줄이 되게 짧게 했다. dl에 aria-busy를 둔다. 시각 테스트는 이미
  `main [aria-busy='true']`가 0개가 될 때까지 기다리므로, dt만 보고 찍던
  대기가 값이 채워진 뒤로 유지된다.
- lab: run마다 대상 라우트를 새 context에서 직접 열고 heading 뒤 network
  idle까지의 CLS를 잰다(metrics.targetDeepLinkCls, 중앙값,
  context.sampling.targetDeepLink에 표본). evaluateLabBudget가 lab.cls
  임계값으로 판정한다. 클릭 시계(상호작용 중앙값)와 대상 라우트는 그대로다.
- 컴포넌트 테스트: 요약 전과 후의 칸 이름·hint 유무가 같다. 실패 테스트는
  빌드 칸의 값으로 본다. 단위 테스트: 직접 진입 CLS가 임계값을 넘으면
  lab 판정이 실패한다.
버린 대안: 릴리스 요약을 동기로 읽기 — getReleaseSummary()가 비동기
포트 계약이라 포트를 바꿔야 한다. 클릭 run에서 hadRecentInput을 무시 —
CLS 정의와 달라져 field 값과 비교할 수 없다.

위험·한계: lab 시간이 run마다 cold navigation 하나(lab 조건 약 2~3초)
늘어 5회면 +10~15초다. 직접 진입 CLS 예산은 0.1이라 0.0046 같은 작은
shift는 실패시키지 않고 lab.json에 값으로만 남는다. layout shift 0건은
lab 값(0)과 15-platform-shift 방법으로 확인해야 한다. 상태 문구가 바뀌어
"런타임 정보를 확인하고 있습니다." 문장은 이 화면에서 사라졌다(홈 화면
문구는 그대로). lab.json 스키마 문서(config/schemas/lab-performance.schema.json)에
새 칸을 필수로 더했다.

검증: desktop batch에서 확인.
node scripts/run-vitest.ts run tests/component/starter-platform-overview-page.test.tsx
tests/unit/performance-budgets.test.ts
corepack pnpm build && corepack pnpm test:performance -- --runs=5
(lab.json metrics.targetDeepLinkCls가 0인지)

Refs: 1105/15-01
2026-11-06 01:23:48 +09:00

169 lines
5.2 KiB
TypeScript

export type BundleMeasurements = Readonly<{
initialJsGzipBytes: number;
initialJsFiles: number;
lazyChunks: readonly Readonly<{ path: string; gzipBytes: number }>[];
}>;
/**
* 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;
}>;
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,
}));
return Object.freeze({
initialPassed,
initialFilesPassed,
lazyResults: Object.freeze(lazyResults),
passed: initialPassed && initialFilesPassed && 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));
}
}
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;
}>;
export type LabThresholds = Readonly<{
lcpMs: number;
cls: number;
namedInteractionMs: 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,
};
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,
});
}