Files
clean-architecture-frontend…/scripts/generate-service-worker-assets.ts
DongHyeonka 3b3396ea07 fix(service-worker): public/ 사본을 사전 캐시와 assets 폴더에서 뺀다
Vite는 public/을 그대로 복사한다. public/assets/x는 dist assets/x가
되어 Vite의 hash 파일 옆에 자기 이름으로 놓인다. 그 이름이
HASHED_STATIC_ASSET_NAME과 맞으면 Service Worker가 immutable로 사전
캐시하고(REV-FE-0043), 호스팅 계약(config/hosting/cache-policy.json
hashedAsset)도 /assets/* 전체에 1년 immutable 헤더를 준다
(REV-FE-0044). 제품이 다음 release에서 이름은 두고 바이트만 바꾸면
worker와 브라우저·CDN이 옛 바이트를 낸다.

두 곳에서 막는다.
- 사전 캐시: 생성기가 dist 파일 가운데 public/에도 같은 경로로 있는
  파일을 뺀다. collectStaticAssets와 countPrecachedAssets가 같은 목록
  (precachedFiles)을 읽는다.
- 빌드: scripts/build-frontend.ts가 Vite 전에 public/ 아래
  BUILD_ASSET_DIRECTORY 이름의 폴더를 찾으면, 소스에서 import하거나
  public/의 다른 폴더로 옮기라는 메시지로 실패한다
  (scripts/lib/public-asset-directory.ts).
public/ 이름은 PUBLIC_DIRECTORY 한 값으로 두고, vite.config.ts의
publicDir와 같은지 시험이 본다. Mmax 측정법 2단계는 public/assets/로
채우던 것을 빌드가 import하는 소스 자산(new URL(..., ?no-inline))으로
바꾸고, 채우기 모듈이 URL 배열을 globalThis 속성 하나에 대입한다고
적는다.

시험은 두 검사를 실제 진입점으로도 부른다. 임시 프로젝트 폴더에서
scripts/build-frontend.ts가 0단계에서 거절하고 dist를 만들지 않는지,
scripts/generate-service-worker-assets.ts <dist>가 인자 없는 기본
public/로 사본을 빼는지(목록과 countPrecachedAssets 둘 다) 본다.

버린 안:
- Vite manifest(.vite/manifest.json)의 file·css·assets로 사전 캐시를
  고른다: desktop 실빌드에서 Web Worker 출력(assets/<이름>-<hash>.js)이
  manifest에 없어 빠진다.
- 호스팅 계약에 파일별 목록을 둔다: 호스팅마다 설정 방식이 달라
  템플릿이 덮지 못한다.
- 문서로만 금지한다: 지키는지 보는 곳이 없다.
- 검사를 check:bundle이나 FE-GATE-019에 둔다: 게이트 없이 pnpm
  build만 하는 배포를 막지 못하고, 019는 production 단계다.
- 카드마다 커밋 하나: 두 검사가 같은 PUBLIC_DIRECTORY를 읽는 것이
  수정의 일부라, 나누면 중간 커밋에 상수가 둘 생긴다.

위험·한계: public/assets/를 둔 파생 프로젝트는 빌드가 실패로 바뀐다
(CHANGELOG 「먼저 할 일」). publicDir를 바꾼 제품은 PUBLIC_DIRECTORY도
바꿔야 한다. scripts/check-bundle.ts는 아직 "public" 글자를 직접
쓴다(REV-FE-0010 파일, 이 커밋 밖). Mmax 측정법의 채우기 모듈 청크는
초기 JS로 세어진다(측정 트리에서 200,765 B, 예산 안). 실제 호스팅
헤더는 재지 않았다(FE-GATE-019는 production 단계).

검증(트리 fd833429):
- RED: 8bb30d2a + 사전 캐시 변경만(트리 f0b1076c)에서
  public/assets/brand-wordmark.svg를 둔 desktop 빌드가 rc=0이고 dist
  assets/brand-wordmark.svg가 같은 바이트로 생긴다. 검사를 넣은
  트리(105919e1)에서는 build refused 메시지로 rc=1, 0단계를 지운 변이는
  다시 rc=0이다.
- 사전 캐시: 고치기 전 생성기에서 시험 2 failed → 6 passed, 변이 5개
  실패(82b959ff 위). 고친 생성기 실빌드에서 사전 캐시 28 → 27이고
  빠진 것은 assets/brand-wordmark.svg 하나, Web Worker 출력은 남는다.
- 빌드 검사 단위: tests/unit/public-asset-directory.test.ts 10 passed.
  변이 6개(검사 제거, "assets" 글자 둘, public/ 자체, ENOENT 실패,
  이름 바꾸기) 모두 실패. build-frontend.ts 0단계와 import를 지운
  변이는 진입점 시험 1 failed.
- 생성기 진입점: service-worker-asset-bounds 8 passed. 기본 public
  경로를 "public-missing"으로 바꾼 변이(collectStaticAssets 쪽,
  countPrecachedAssets 쪽, 둘 다)가 각각 1·1·2 failed.
- 자식 프로세스 시한: desktop JSON reporter로 잰 가장 긴 값 527.3 ms·
  302.3 ms(unit, coverage보다 길다)를 childProcessTimeout(528)·(303)로.
- Mmax(새 채우기): 사전 캐시 256개, 23,417 B, 다섯 자리 23,441 B,
  handler 둘 23,439 B → 1 KiB 올림 23,552로 예산 그대로.
- desktop merge 단계 14개 rc=0, desktop verify:documentation rc=0.
  노트북 test:unit 4,090개, check:types, lint, check:architecture,
  verify:documentation, scripts/verify.sh docs rc=0.

Refs: REV-FE-0043, REV-FE-0044
2026-11-23 17:02:06 +09:00

254 lines
9.7 KiB
TypeScript

import { createHash } from "node:crypto";
import {
CACHEABLE_ASSET_CONTENT_TYPES,
canonicalStaticManifestBytes,
decodeStaticAssetManifest,
isCanonicalStaticAssetUrl,
} from "../src/contracts/service-worker-static-manifest.ts";
import { mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
import path from "node:path";
import { getBuildConfig } from "../src/contracts/env.ts";
import {
BUILD_ASSET_DIRECTORY,
HASHED_STATIC_ASSET_NAME,
SERVICE_WORKER_BOUNDS,
SERVICE_WORKER_SCRIPT_PATH,
type StaticAssetManifestV1,
} from "../src/contracts/service-worker.ts";
import { isEntryModule } from "./lib/entry-module.ts";
import { PUBLIC_DIRECTORY } from "./lib/public-asset-directory.ts";
import { moduleSpecifier, runOutputPath } from "./lib/run-isolation.ts";
/**
* §17.2.2 step 4. Scans the completed app `dist` and emits the exact hashed
* asset list under `BUILD_ASSET_DIRECTORY` the Service Worker will verify at
* install time.
*
* `service-worker.js` itself and `index.html` are excluded (§17.2.2), as are
* the runtime config and release manifest, which are network-only (§18.4).
*/
/**
* Read back by tests/e2e/support/service-worker-builds.ts (0929/11-03). A
* build with `RUN_OUTPUT_ROOT` writes it under that folder (1105/12-04).
*/
export const SERVICE_WORKER_ASSETS_OUTPUT =
".generated/frontend-runtime/service-worker-assets.ts";
// SW-RR-03. The generator and the shared decoder read the same table, so a
// manifest this script produces can never be one the runtime contract refuses.
const CACHEABLE_EXTENSIONS = CACHEABLE_ASSET_CONTENT_TYPES;
const EXCLUDED_FILES: ReadonlySet<string> = new Set([
"index.html",
SERVICE_WORKER_SCRIPT_PATH,
"config.json",
"release-manifest.json",
"runtime-config.schema.json",
]);
/**
* Vite emits content-hashed names under its assets directory; only those may
* be treated as immutable. A `public/` file keeps its own name even when it
* looks hashed, wherever Vite copies it: to the dist root
* (`android-chrome-192x192.png`) or, from `public/assets/`, into the assets
* directory itself (`assets/brand-wordmark.svg`). A product may change its
* bytes under that name (1105/06-01), so a dist file that `public/` also has
* is never precached (REV-FE-0043). The build refuses `public/assets/` in the
* first place (REV-FE-0044); this covers a build that skipped that check.
*
* The `public/` folder name is taken as fixed (`PUBLIC_DIRECTORY`,
* scripts/lib/public-asset-directory.ts): a product that sets `publicDir` in
* `vite.config.ts` changes that value too. collectStaticAssets and
* countPrecachedAssets also take the folder as their last argument. Vite's
* manifest cannot stand in for it: it does not name a Web Worker's output,
* which is a hashed file under `assets/`.
*/
const HASHED_NAME = HASHED_STATIC_ASSET_NAME;
/**
* `basePath` is the router base path (`VITE_ROUTER_BASE_PATH`): dist, and so
* every asset, is served under it (0929/06-02).
*/
export async function collectStaticAssets(
distDirectory: string,
buildId: string,
releaseId: string,
basePath = "/",
publicDirectory = PUBLIC_DIRECTORY,
): Promise<StaticAssetManifestV1> {
const assets: StaticAssetManifestV1["assets"][number][] = [];
for (const { relative, contentType } of await precachedFiles(distDirectory, publicDirectory)) {
const absolute = path.join(distDirectory, relative);
const bytes = await readFile(absolute);
if (bytes.byteLength > SERVICE_WORKER_BOUNDS.singleAssetBytes) {
throw new Error(`Static asset exceeds its byte bound: ${relative}`);
}
// SW-02. The URL is checked against the same predicate the runtime decoder
// applies. Emitting a path the decoder will refuse turned a correct build
// into a runtime contract failure discovered only at install time.
const url = `${basePath}${relative.split(path.sep).join("/")}`;
if (!isCanonicalStaticAssetUrl(url)) {
throw new Error(
`Static asset path is not canonical for the service worker manifest: ${relative}`,
);
}
assets.push({
url,
sha256: `sha256:${createHash("sha256").update(bytes).digest("hex")}`,
bytes: bytes.byteLength,
contentType,
});
}
// 0925/06-08. Nothing under the directory means vite.config.ts moved the
// hashed files (`build.assetsDir`) away from the one the worker reads.
if (assets.length === 0) {
throw new Error(
`No hashed static asset under ${BUILD_ASSET_DIRECTORY} in the build: vite.config.ts build.assetsDir must name the directory BUILD_ASSET_DIRECTORY (src/contracts/service-worker.ts) names.`,
);
}
// 1112/06-02. The count and the bound, so the failure says how far over
// it is. Each generated feature adds its lazy chunks here: with the Service
// Worker on, the asset bound can come before the initial JavaScript budget.
if (assets.length > SERVICE_WORKER_BOUNDS.assets) {
throw new Error(
`Static asset count ${assets.length} exceeds its bound ${SERVICE_WORKER_BOUNDS.assets} (SERVICE_WORKER_BOUNDS.assets, src/contracts/service-worker.ts): every hashed file Vite wrote under ${BUILD_ASSET_DIRECTORY} is precached.`,
);
}
const totalBytes = assets.reduce((sum, asset) => sum + asset.bytes, 0);
if (totalBytes > SERVICE_WORKER_BOUNDS.assetSetBytes) {
throw new Error(
`Static asset set ${totalBytes} bytes exceeds its byte bound ${SERVICE_WORKER_BOUNDS.assetSetBytes} (SERVICE_WORKER_BOUNDS.assetSetBytes, src/contracts/service-worker.ts).`,
);
}
// SW-05. The canonical byte serialization lives in the shared runtime-neutral
// codec so the worker can recompute the identical digest with WebCrypto.
const setDigest: `sha256:${string}` = `sha256:${createHash("sha256")
.update(canonicalStaticManifestBytes(assets))
.digest("hex")}`;
const manifest: StaticAssetManifestV1 = {
schemaVersion: 1,
buildId,
releaseId,
setDigest,
assets,
};
// SW-02. Every manifest this generator returns has already passed the exact
// decoder the runtime will apply to it, so the build stops here rather than
// at install time.
const decoded = decodeStaticAssetManifest(manifest);
if (!decoded.ok) {
throw new Error(
`Generated service worker manifest is not decodable: ${decoded.error.reason}`,
);
}
return manifest;
}
/**
* The content type of a dist file the worker precaches, or undefined: a
* content-hashed name with a cacheable type under `BUILD_ASSET_DIRECTORY`,
* not one of `EXCLUDED_FILES`.
*/
function precachedContentType(relative: string): string | undefined {
const base = path.basename(relative);
if (!relative.split(path.sep).join("/").startsWith(BUILD_ASSET_DIRECTORY)) return undefined;
if (EXCLUDED_FILES.has(base) || !HASHED_NAME.test(base)) return undefined;
return CACHEABLE_EXTENSIONS[path.extname(base).toLowerCase()];
}
/**
* The dist files the worker precaches, sorted: those precachedContentType
* accepts, less every file `publicDirectory` has at the same path (Vite's
* copy of it). collectStaticAssets and countPrecachedAssets both read it.
*/
async function precachedFiles(
distDirectory: string,
publicDirectory: string,
): Promise<{ relative: string; contentType: string }[]> {
const copied = new Set(await walkIfPresent(publicDirectory));
const files: { relative: string; contentType: string }[] = [];
for (const relative of (await walk(distDirectory, distDirectory)).sort()) {
const contentType = precachedContentType(relative);
if (contentType && !copied.has(relative)) files.push({ relative, contentType });
}
return files;
}
/**
* 1112/06-02. How many files of a dist the worker would precache, by the
* rule collectStaticAssets applies, without its bounds. The feature-shape
* measurement records it per feature.
*/
export async function countPrecachedAssets(
distDirectory: string,
publicDirectory = PUBLIC_DIRECTORY,
): Promise<number> {
return (await precachedFiles(distDirectory, publicDirectory)).length;
}
/** A project without `public/` has no copies to leave out. */
async function walkIfPresent(root: string): Promise<string[]> {
try {
return await walk(root, root);
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
throw error;
}
}
async function walk(root: string, current: string): Promise<string[]> {
const entries = await readdir(current, { withFileTypes: true });
const files: string[] = [];
for (const entry of entries) {
const absolute = path.join(current, entry.name);
if (entry.isDirectory()) {
files.push(...(await walk(root, absolute)));
} else if ((await stat(absolute)).isFile()) {
files.push(path.relative(root, absolute));
}
}
return files;
}
async function main(): Promise<void> {
const distDirectory = process.argv[2] ?? runOutputPath("dist");
const output = runOutputPath(SERVICE_WORKER_ASSETS_OUTPUT);
const buildId = process.env.VITE_BUILD_ID ?? "local-build";
const releaseId = process.env.RELEASE_ID ?? "local-release";
const manifest = await collectStaticAssets(
distDirectory,
buildId,
releaseId,
getBuildConfig(process.env).routerBasePath,
);
const source = [
"// Generated by scripts/generate-service-worker-assets.ts. Do not edit.",
"",
`import type { StaticAssetManifestV1 } from "${moduleSpecifier(output, "src/contracts/service-worker.ts")}";`,
"",
`export const SERVICE_WORKER_ASSETS: StaticAssetManifestV1 = ${JSON.stringify(
manifest,
null,
2,
)} as const;`,
"",
].join("\n");
await mkdir(path.dirname(output), { recursive: true });
await writeFile(output, source, "utf8");
process.stdout.write(
`service worker assets: ${manifest.assets.length} file(s) ${manifest.setDigest}\n`,
);
}
if (isEntryModule(import.meta)) {
await main();
}