Files
clean-architecture-frontend…/scripts/generate-service-worker-assets.ts
T
DongHyeonka 85d55e0cd3 fix(service-worker): 사전 캐시와 설정 URL이 router base path를 따른다 (0929/06-02)
문제: SW 자산 생성기(scripts/generate-service-worker-assets.ts)가 사전
캐시 URL을 `/${relative}`로 만들어 VITE_ROUTER_BASE_PATH를 무시했다.
워커는 root-relative URL을 scope 기준으로 풀지만 base가 사라지므로
/app/ 배포에서 install이 /assets/...를 요청해 404를 받고, 워커가
설치되지 않았다. 같은 빌드의 SW 설정도 runtime config URL 기본값을
"/config.json"으로 고정해, 페이지가 쓰는 /app/config.json을 워커가
network-only로 알아보지 못했다. 앱 빌드·runtime config·06-08
fallback은 이미 base를 따르는데 이 두 곳만 빠져 있었다.

고른 방법: 리뷰가 적은 최소 방향. collectStaticAssets에 basePath
인자(기본 "/")를 더하고, 생성기 main과 SW Vite 설정이 페이지와 같은
getBuildConfig(src/contracts/env.ts)로 base와 runtime config URL을
계산한다. 결과 URL은 그대로 root-relative라 isCanonicalStaticAssetUrl
검사를 통과한다. base가 "/"이면 manifest와 digest가 전과 같다.

버린 대안: 워커가 manifest URL을 scope 상대로 풀게 바꾸기. 계약 차이는
없지만 워커 코드와 manifest 계약(root-relative)을 함께 바꿔야 해서
생성기 수정보다 크다.

위험·한계:
- base마다 manifest digest가 달라진다(의도된 결과).
- VITE_RUNTIME_CONFIG_URL이 빈 문자열이면 이제 base 기본값을 쓴다.
  페이지(getBuildConfig)와 같은 규칙이다.
- 리뷰 완료 기준의 "e2e 도우미를 base 옵션으로 돌린 첫 설치가
  RELOAD_TO_ENABLE"은 하지 않았다. e2e 도우미에 base 옵션과 /app/
  서빙이 필요하고, 실제 브라우저 install은 이번에 확인하지 않았다.

검증:
- RED: collectStaticAssets 단위 테스트(basePath "/app/")가 수정 전
  `/assets/index-abcdefgh.js`를 받아 실패(1 failed | 9 passed).
  service-worker-build-output.test.ts의 새 테스트(SW ACTIVE·
  production·/app/ 실제 빌드)가 생성기만 되돌리면 URL 목록에서,
  SW 설정만 되돌리면 `Received: "/config.json"`으로 각각 실패.
- GREEN: 두 테스트 통과. `node scripts/run-vitest.ts run
  tests/unit/service-worker tests/unit/sub-path-deployment.test.ts
  tests/unit/hosting-probe.test.ts tests/unit/web-push` -> 12파일
  171건 통과(빌드 테스트는 flock 안에서).
- `npx tsc` node·test·app·service-worker -> 오류 0.
- `npx eslint <바꾼 파일 4개> --max-warnings=0` -> 통과.
- `node scripts/check-adapter-inventory.ts` -> PASS.
- 미실행: SW e2e(Playwright).

Refs: docs/reviews/2026-09-29-maturity-review/06-adapters-service-worker-push.md 06-02, docs/reviews/2026-11-01-maturity-review/06-adapters-service-worker-push.md 2.1절
2026-11-01 22:49:38 +09:00

166 lines
5.6 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).
*/
const 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(OUTPUT), { recursive: true });
await writeFile(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();
}