Files
clean-architecture-frontend…/scripts/lib/classify-vite-bundle.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

118 lines
3.9 KiB
TypeScript

import path from "node:path";
import {
BUILD_ASSET_DIRECTORY,
HASHED_STATIC_ASSET_NAME,
SERVICE_WORKER_SCRIPT_PATH,
} from "../../src/contracts/service-worker.ts";
type ViteManifestEntry = Readonly<{
file: string;
isEntry?: boolean;
imports?: readonly string[];
dynamicImports?: readonly string[];
}>;
/**
* Static imports of an entry are part of initial JavaScript, and so are the
* chunks the entry itself imports dynamically: main.tsx only imports the
* application graph that way so it can report a graph that fails to evaluate
* (09-03). Every remaining JavaScript file of the manifest is governed by
* the lazy-chunk budget.
*/
export function classifyViteJavascript(
manifest: Readonly<Record<string, ViteManifestEntry>>,
) {
const initialFiles = new Set<string>();
const visitedKeys = new Set<string>();
const pendingKeys = Object.entries(manifest)
.filter(([, entry]) => entry.isEntry)
.map(([key]) => key);
const missingImports: string[] = [];
while (pendingKeys.length > 0) {
const key = pendingKeys.pop();
if (key === undefined) break;
if (visitedKeys.has(key)) continue;
visitedKeys.add(key);
const entry = manifest[key];
if (!entry) {
missingImports.push(key);
continue;
}
if (entry.file.endsWith(".js")) initialFiles.add(entry.file);
pendingKeys.push(...(entry.imports ?? []));
if (entry.isEntry) pendingKeys.push(...(entry.dynamicImports ?? []));
}
const allJavaScript = new Set(
Object.values(manifest)
.map((entry) => entry.file)
.filter((file) => file.endsWith(".js")),
);
const lazyFiles = [...allJavaScript].filter(
(file) => !initialFiles.has(file),
);
return Object.freeze({
initialFiles: Object.freeze([...initialFiles].sort()),
lazyFiles: Object.freeze(lazyFiles.sort()),
missingImports: Object.freeze(missingImports.sort()),
});
}
const JAVASCRIPT_FILE = /\.[cm]?js$/iu;
/**
* REV-FE-0010. Vite emits a Web Worker as a content-hashed file under its
* assets directory and gives it no manifest row. It loads on demand, so each
* such file is a lazy chunk. A file Vite copied from public/ is no build
* output: a name like `vendor-analytics.js` only looks hashed, and a page can
* load it before anything else, so it is listed apart and has no budget.
*/
export function addUnlistedBuildChunks(
classification: ReturnType<typeof classifyViteJavascript>,
outputFiles: Iterable<string>,
isPublicFile: (file: string) => boolean,
) {
const listed = new Set([...classification.initialFiles, ...classification.lazyFiles]);
const javascript = [...outputFiles].filter((file) => JAVASCRIPT_FILE.test(file));
const publicFiles = javascript.filter(isPublicFile).sort();
const unlisted = javascript.filter(
(file) =>
!listed.has(file) &&
!publicFiles.includes(file) &&
file.startsWith(BUILD_ASSET_DIRECTORY) &&
HASHED_STATIC_ASSET_NAME.test(path.posix.basename(file)),
);
return Object.freeze({
...classification,
lazyFiles: Object.freeze([...classification.lazyFiles, ...unlisted].sort()),
publicFiles: Object.freeze(publicFiles),
});
}
/**
* REV-FE-0010. The Service Worker is a second build without a manifest
* (vite.service-worker.config.ts) and has a budget of its own. No budget covers
* any other JavaScript output the classification does not list, nor a copy
* of a public/ file, one named service-worker.js included.
*/
export function findUnbudgetedJavascript(
outputFiles: Iterable<string>,
classification: Readonly<{
initialFiles: readonly string[];
lazyFiles: readonly string[];
publicFiles: readonly string[];
}>,
): string[] {
const budgeted = new Set([
...classification.initialFiles,
...classification.lazyFiles,
SERVICE_WORKER_SCRIPT_PATH,
]);
for (const file of classification.publicFiles) budgeted.delete(file);
return [...outputFiles]
.filter((file) => JAVASCRIPT_FILE.test(file) && !budgeted.has(file))
.sort();
}