Files
clean-architecture-frontend…/scripts/generate-service-worker-assets.ts
T
DongHyeonka 37e5f9d682 test(e2e): SW spec이 이미 켠 worker와 생성된 사전 캐시 목록을 쓴다 (0929/11-03)
SW e2e는 템플릿의 `= null;` 줄만 바꿔 worker를 켰다. 제품이 이미 ACTIVE로
켠 트리에서는 2건이 실패하고 4건이 실행되지 않았다. 사전 캐시 목록도
템플릿 기준으로 고정돼 있어 해시 파일을 더하면 2건이 실패했다.

선택을 지금 값과 상관없이 고치되, 이미 ACTIVE면 제품의 handler를 그대로
두는 `turnOnServiceWorker` 하나로 모았다. 빌드가 만든 사전 캐시 목록을
`precached`로 돌려주고 spec이 그 목록과 비교한다. 같은 문제를 고친
0929/06-04(`96a4f68`)의 `selectActiveServiceWorker`는 ACTIVE 선택을
템플릿 값으로 덮어써 제품 handler가 빠지므로 이 함수로 바꿨고, 실패한
준비 단계에서 임시 복사본을 지우는 처리는 유지했다(두 브랜치 병합 때
오케스트레이터가 충돌을 풀었다).

위험: 테스트 도우미만 바뀐다. 0929/06-04 단위 테스트의 기대값이 "ACTIVE
선택도 템플릿 값으로 덮어쓴다"에서 "ACTIVE 선택은 그대로 둔다"로 바뀐다.
검증: ACTIVE 선택과 해시 파일 추가 트리 모두 6 passed(에이전트).
병합 뒤 service-worker-build-output 단위 테스트 5/5, SW e2e chromium·webkit
12/12, tsc(test), eslint 통과.
2026-11-01 23:20:28 +09:00

168 lines
5.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 {
HASHED_STATIC_ASSET_NAME,
SERVICE_WORKER_BOUNDS,
SERVICE_WORKER_SCRIPT_PATH,
type StaticAssetManifestV1,
} from "../src/contracts/service-worker.ts";
/**
* §17.2.2 step 4. Scans the completed app `dist` and emits the exact hashed
* asset list 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). */
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; only those may be treated as immutable. */
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 = "/",
): Promise<StaticAssetManifestV1> {
const files = await walk(distDirectory, distDirectory);
const assets: StaticAssetManifestV1["assets"][number][] = [];
for (const relative of files.sort()) {
const base = path.basename(relative);
if (EXCLUDED_FILES.has(base) || relative.startsWith(".vite/")) continue;
const contentType = CACHEABLE_EXTENSIONS[path.extname(base).toLowerCase()];
if (!contentType || !HASHED_NAME.test(base)) continue;
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,
});
}
if (assets.length > SERVICE_WORKER_BOUNDS.assets) {
throw new Error("Static asset count exceeds its bound.");
}
const totalBytes = assets.reduce((sum, asset) => sum + asset.bytes, 0);
if (totalBytes > SERVICE_WORKER_BOUNDS.assetSetBytes) {
throw new Error("Static asset set exceeds its byte bound.");
}
// 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;
}
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] ?? "dist";
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 "../../src/contracts/service-worker.ts";',
"",
`export const SERVICE_WORKER_ASSETS: StaticAssetManifestV1 = ${JSON.stringify(
manifest,
null,
2,
)} as const;`,
"",
].join("\n");
await mkdir(path.dirname(SERVICE_WORKER_ASSETS_OUTPUT), { recursive: true });
await writeFile(SERVICE_WORKER_ASSETS_OUTPUT, source, "utf8");
process.stdout.write(
`service worker assets: ${manifest.assets.length} file(s) ${manifest.setDigest}\n`,
);
}
if (process.argv[1]?.endsWith("generate-service-worker-assets.ts")) {
await main();
}