Files
clean-architecture-frontend…/scripts/generate-service-worker-assets.ts
T
DongHyeonka a5e6719b18
frontend-quality-gates / merge / static checks (pull_request) Successful in 1m17s
frontend-quality-gates / merge / tests (pull_request) Successful in 11m53s
frontend-quality-gates / merge / browser tests (pull_request) Successful in 5m36s
frontend-quality-gates / FE-GATE-017 / diagram-review (pull_request) Skipped
frontend-quality-gates / main / self-tests and removal drills (pull_request) Skipped
frontend-quality-gates / FE-GATE-014 / config-compatibility (pull_request) Skipped
frontend-quality-gates / FE-GATE-028 / manual-accessibility-review (pull_request) Skipped
frontend-quality-gates / FE-GATE-026 / lab-performance (pull_request) Skipped
frontend-quality-gates / FE-GATE-015 / immutable-release-candidate (pull_request) Skipped
frontend-quality-gates / external-vulnerability-provider (pull_request) Skipped
frontend-quality-gates / external-provenance-provider (pull_request) Skipped
frontend-quality-gates / promote-verified-immutable-candidate (pull_request) Skipped
frontend-quality-gates / deploy-promoted-release (pull_request) Skipped
frontend-quality-gates / FE-GATE-019 / hosting-header (pull_request) Skipped
frontend-quality-gates / FE-GATE-021 / runbook-boot-config (pull_request) Skipped
frontend-quality-gates / FE-GATE-022 / runbook-chunk-mismatch (pull_request) Skipped
frontend-quality-gates / FE-GATE-023 / runbook-api-degradation (pull_request) Skipped
frontend-quality-gates / FE-GATE-024 / runbook-telemetry (pull_request) Skipped
frontend-quality-gates / FE-GATE-025 / runbook-release-rollback (pull_request) Skipped
frontend-quality-gates / FE-GATE-018 / field-web-vitals (pull_request) Skipped
fix(service-worker): 제품 활성화 칸을 열고 갱신 실패를 관측한다
문제: SW를 켠 제품이 새 버전 안내·reload 안내를 붙이려면 템플릿
파일을 고쳐야 한다(1103/09-05). 설치에 실패한 갱신(redundant)과 실패한
주기 검사는 아무 기록도 남기지 않는다(0925/06-05). build.assetsDir를
바꾸면 사전 캐시가 조용히 빈다(0925/06-08). 릴리스마다 바뀌지 않은
자산까지 no-store로 다시 받는다(1101/06-05). 쓰지 않는 protocol kind
셋과 reload guard 상수, void 참조, 손으로 쓴 protocol 버전 1, web-push의
fence 검사 두 벌이 남았다(1101/06-03, R1~R3).

고른 방법:
- ProductServiceWorkerWiring에 onUpdateWaiting(activate)·
  onReloadRequired()를 더한다(추가만). create-runtime-composition이 worker
  시작 전에 host 이벤트를 구독해 부르고, 던지면 버린다. page controller는
  시작 때 이미 기다리던 갱신도 onUpdateWaiting 구독자에게 알린다.
- page controller가 update_install REDUNDANT, update_check FAILED를
  observe로 낸다.
- 사전 캐시 생성기와 SW 설치가 빈 asset 목록을 거절하고, 시험이
  vite.config.ts의 build.assetsDir와 BUILD_ASSET_DIRECTORY를 대조한다
  (vite.config.ts는 그룹 C가 고치는 파일이라 건드리지 않았다).
- 설치가 이전 릴리스 캐시의 같은 URL을 digest로 다시 확인해 복사하고,
  없거나 맞지 않을 때만 받는다.
- PAGE_HELLO·WORKER_HELLO_ACK·UPDATE_READY, reloadGuard*·
  retainedPreviousCaches를 지운다. sync 알림은 createServiceWorkerMessage로
  만든다. fence 검사는 push-association-fence-store.ts 하나다.
버린 대안: 활성화 화면을 presentation 슬롯으로 열기 — 화면 문구와 흐름은
제품 것이라 조합 계약의 함수 칸이 작다.

위험·한계: 지운 kind는 보내는 곳이 없었다. 다른 빌드의 worker가 보내도
UNKNOWN_KIND로 관측만 된다. 재사용은 이전 캐시를 읽는 비용이 들고,
읽기 실패는 다운로드로 돌아간다.

검증: desktop check:types·lint·check:architecture·
check:adapter-inventory rc=0, SW 시험 묶음 통과
(/tmp/claude-gates/r9b-pr1-quick). merge 단계는 PR 본문.

Refs: 1103/09-05, 0925/06-05, 0925/06-08, 1101/06-03, 1101/06-05, 1101/R1, 1101/R2, 1101/R3
2026-11-13 19:02:07 +09:00

215 lines
7.9 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 { 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 copied to the dist root keeps its
* own name even when it looks hashed (`android-chrome-192x192.png`), and a
* product may change its bytes under that name (1105/06-01).
*/
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 contentType = precachedContentType(relative);
if (!contentType) 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,
});
}
// 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 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()];
}
/**
* 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): Promise<number> {
return (await walk(distDirectory, distDirectory)).filter(
(relative) => precachedContentType(relative) !== undefined,
).length;
}
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 (process.argv[1]?.endsWith("generate-service-worker-assets.ts")) {
await main();
}