Files
clean-architecture-frontend…/tests/e2e/service-worker-update.spec.ts
T
DongHyeonka 2963c6f42c fix(features): 선택 런타임(SW 등) 선택을 제품 소유 파일로 옮긴다 (1103/09-05)
문제
Service Worker를 켜는 유일한 방법은 src/features/installed-runtime-capabilities.ts의
SERVICE_WORKER 상수를 바꾸는 것이었다. 그 파일에는 "Product-owned." 표시가
없고, 매뉴얼 03 D절은 src/features/installed-*.ts를 고치지 말라고 한다.
매뉴얼대로 하면 SW를 켤 수 없고, 켜면 동기화마다 템플릿 파일을 손으로
병합한다. 템플릿 상태 설명과 제품 선택 상수가 한 블록에 섞여 있었다(1101/09-05).

고른 방법
리뷰의 최소 방향을 따른다.
- 선택 상수 넷(REALTIME, WEB_WORKERS, SERVICE_WORKER, OFFLINE_COMMANDS)을 제품
  소유 src/features/product-capabilities.ts의
  PRODUCT_RUNTIME_CAPABILITY_SELECTION으로 옮긴다. 09-02에서 만든 같은 새 제품
  소유 파일이다. product-contracts.ts에 넣지 않은 이유: 계약 층(src/contracts)이
  아니라 기능 카탈로그 옆의 선택이고, 템플릿은 복사 뒤 기존 제품 소유 파일에
  칸을 더하지 않는다.
- installed-runtime-capabilities.ts는 템플릿 소유로 남고 그 선택을 검사
  (validateRealtimeContributions, validateWebWorkerContributions)하고 투영만
  한다. §3.5 설명과 템플릿 상태 설명은 여기에 남는다.
- 매뉴얼 03 C절에 "SW 켜기"를 넣었다. 조립 거절 메시지, e2e SW 빌드 도우미의
  편집 대상(premise 1), 레시피·운영 문서, dependency-cruiser 주석의 경로를
  새 파일로 바꿨다.
- 09-02 typecheck 테스트는 이제 출하된 product-capabilities.ts에 타입만 채우고
  (선택은 유지), 복사 목록은 REMOVAL_FIXTURE_COPY_TARGETS 하나를 쓴다.

위험·한계
- 리뷰가 함께 제안한 composeProduct의 SW 연결 칸(blockers, observe)은 만들지
  않았다. 그 연결은 여전히 템플릿 파일 create-runtime-composition.ts를 고쳐야
  한다. 매뉴얼 "SW 켜기"에 적었다.
- 템플릿 안의 선택을 이미 바꾼 다운스트림은 값을 새 파일로 옮겨야 한다.

검증
- RED: tests/unit/product-runtime-capability-selection.test.ts 3건(선택이 제품
  소유 파일에만 있음, 제품 SW 선택 투영, 잘못된 선택은 여전히 검사)이 수정 전
  실패.
- 그 테스트, service-worker-build-output, optional-runtime-host,
  runtime-composition-service-worker-telemetry, product-features,
  product-extension-typecheck, runtime-adapters 통과.
- check:types, check:architecture, eslint, verify:documentation PASS_SCOPED.

Refs: docs/reviews/2026-11-03-maturity-review/09-app-core.md 09-05
2026-11-04 20:35:11 +09:00

281 lines
10 KiB
TypeScript

import { appendFile, readdir, readFile } from "node:fs/promises";
import path from "node:path";
import { expect, test, type Page } from "../support/browser/strict-browser-test.ts";
import {
prepareServiceWorkerBuilds,
removeServiceWorkerBuilds,
startBuildServer,
type ServiceWorkerBuilds,
} from "./support/service-worker-builds.ts";
/**
* R3-6. Real-browser Service Worker checks, against real production builds.
*
* How the worker is enabled: the template's default build has
* `serviceWorker: null`, and the only supported switch is the static
* capability selection in `src/features/product-capabilities.ts`
* (`{ mode: "ACTIVE", scriptPath: "service-worker.js", handlers:
* ["PWA_STATIC_ASSETS"] }`); `scripts/build-frontend.ts` then adds the worker
* build. `support/service-worker-builds.ts` applies that selection in a temp
* copy of the repo, builds it twice (`VITE_BUILD_ID` sw-e2e-a / sw-e2e-b),
* and serves either dist from its own port per test. The copy also records
* the worker host's `onUpdateWaiting` / `onReloadRequired` callbacks, which
* the app itself does not subscribe to yet.
*
* The preview server of this suite is not used; each test uses absolute URLs.
*
* Premises (0929/11-03): the helper's three, listed in
* `support/service-worker-builds.ts`, plus one here: build B changes
* `CHANGED_ROUTE_SOURCE`, so a product that deletes that page points the
* constant at another route page. Run both Service Worker specs after turning
* the worker on (Service Worker checklist in
* `docs/architecture/optional-adapter-recipes.md`).
*/
type Probe = typeof globalThis & {
__caServiceWorkerTest?: {
host: { requestActivation(): Promise<unknown> };
events: string[];
};
};
let builds: ServiceWorkerBuilds | undefined;
// B changes one route chunk on purpose. Route chunks used to differ only
// because they embedded the build ID; since 09-02 they do not, so two builds
// of the same source emit the same route chunks. A dynamically imported
// module keeps all its exports, so the extra export survives the bundler.
const CHANGED_ROUTE_SOURCE =
"src/presentation/pages/not-found-page.tsx";
test.beforeAll(async () => {
test.setTimeout(180_000);
builds = await prepareServiceWorkerBuilds({
beforeBuild: async (name, root) => {
if (name !== "b") return;
await appendFile(
path.join(root, CHANGED_ROUTE_SOURCE),
'\nexport const serviceWorkerE2eBuild = "b";\n',
);
},
});
});
test.afterAll(async () => {
await removeServiceWorkerBuilds(builds);
});
function requireBuilds(): ServiceWorkerBuilds {
if (!builds) throw new Error("Service Worker builds were not prepared.");
return builds;
}
async function waitForEvent(page: Page, prefix: string): Promise<string> {
await page.waitForFunction(
(expected) =>
(globalThis as Probe).__caServiceWorkerTest?.events.some((event) =>
event.startsWith(expected),
) === true,
prefix,
{ timeout: 60_000 },
);
const events = await page.evaluate(() => [
...((globalThis as Probe).__caServiceWorkerTest?.events ?? []),
]);
return events.find((event) => event.startsWith(prefix))!;
}
async function startOutcome(page: Page): Promise<unknown> {
return JSON.parse((await waitForEvent(page, "start:")).slice("start:".length));
}
async function hashedAssets(dist: string): Promise<string[]> {
return (await readdir(path.join(dist, "assets")))
.map((file) => `/assets/${file}`)
.sort();
}
const headerCases = [
{
name: "Content-Type: application/javascript",
headers: { javascriptContentType: "application/javascript", gzip: false },
},
{
name: "Content-Encoding: gzip with the compressed Content-Length",
headers: { javascriptContentType: "text/javascript", gzip: true },
},
] as const;
for (const { name, headers } of headerCases) {
test(`installs the static asset set served with ${name}`, async ({ page }) => {
const { dist } = requireBuilds();
const server = await startBuildServer(dist, headers);
try {
await page.goto(`${server.origin}/`);
// A failed install (CONTENT_TYPE_INVALID, BYTES_MISMATCH, ...) ends as
// FAILED/INSTALL_FAILED; a first install that worked asks for a reload.
expect(await startOutcome(page)).toEqual({ kind: "RELOAD_TO_ENABLE" });
const cached = await page.evaluate(async () => {
const names = (await caches.keys()).filter((cacheName) =>
cacheName.startsWith("ca-static-v1-"),
);
const cache = await caches.open(names[0] ?? "missing");
const paths = (await cache.keys())
.map((request) => new URL(request.url))
.filter((url) => url.origin === location.origin)
.map((url) => url.pathname);
return { names, paths };
});
expect(cached.names).toHaveLength(1);
// 0929/11-03. The list A's build generated, not `dist/assets`: a product
// may precache more (or fewer) files than the template does.
expect(cached.paths.sort()).toEqual(requireBuilds().precached.a);
// The server really sent the headers under test.
const assets = server.served.filter((response) =>
response.path.startsWith("/assets/"),
);
expect(assets.length).toBeGreaterThan(0);
if (headers.gzip) {
expect(assets.every((response) => response.contentEncoding === "gzip"))
.toBe(true);
expect(
assets.some(
(response) => response.contentLength < response.decodedLength,
),
).toBe(true);
} else {
expect(
assets
.filter((response) => response.path.endsWith(".js"))
.every(
(response) => response.contentType === "application/javascript",
),
).toBe(true);
}
} finally {
await server.close();
}
});
}
type BuildServer = Awaited<ReturnType<typeof startBuildServer>>;
// Playwright's Firefox never lets a worker control a page: even a trivial
// classic worker leaves `navigator.serviceWorker.controller` null after a new
// navigation (checked by hand with Playwright 1.62). With no controlled
// client, B skips `waiting` and activates by itself (`requestActivation()` then
// returns NO_WAITING_WORKER), and the fetch handler is never reached. The
// update tests therefore run where a page can be controlled. Not a product
// defect.
// quarantine(owner=frontend-platform, defect=playwright-firefox-no-sw-control, expires=2027-03-31)
const NO_CONTROLLED_PAGES =
"Playwright Firefox pages are never controlled by a service worker.";
/**
* Loads build A twice (first install, then a normal navigation), switches the
* server to B, runs the update check and activates B through the app host.
* Returns whether the second load of A was controlled by the worker.
*/
async function updateFromAToB(
page: Page,
server: BuildServer,
): Promise<{ secondLoad: unknown; controlled: boolean }> {
await page.goto(`${server.origin}/`);
expect(await startOutcome(page)).toEqual({ kind: "RELOAD_TO_ENABLE" });
await page.evaluate(async () => {
await navigator.serviceWorker.ready;
});
// A normal navigation. (`page.reload()` would not change anything here.)
await page.goto(`${server.origin}/`);
const secondLoad = await startOutcome(page);
const controlled = await page.evaluate(
() => navigator.serviceWorker.controller !== null,
);
server.serve("b");
await page.evaluate(async () => {
await (await navigator.serviceWorker.getRegistration())?.update();
});
await waitForEvent(page, "update-waiting");
const activation = await page.evaluate(() =>
(globalThis as Probe).__caServiceWorkerTest!.host.requestActivation(),
);
expect(activation).toEqual({ kind: "ACTIVATED_RELOAD_REQUIRED" });
await waitForEvent(page, "reload-required");
return { secondLoad, controlled };
}
test("announces update-waiting and reload-required through the host when build B replaces A", async ({
page,
browserName,
}) => {
test.skip(browserName === "firefox", NO_CONTROLLED_PAGES);
const server = await startBuildServer(requireBuilds().dist);
try {
await updateFromAToB(page, server);
const registration = await page.evaluate(async () => {
const current = await navigator.serviceWorker.getRegistration();
return {
active: current?.active?.state ?? null,
waiting: current?.waiting ?? null,
};
});
expect(registration).toEqual({ active: "activated", waiting: null });
} finally {
await server.close();
}
});
test("serves A's removed chunk from the previous cache once B controls the page", async ({
page,
browserName,
}) => {
test.skip(browserName === "firefox", NO_CONTROLLED_PAGES);
const { dist } = requireBuilds();
const routeChunks = Object.values(
(
JSON.parse(
await readFile(path.join(dist.a, "release-manifest.json"), "utf8"),
) as { routeChunks: Record<string, string> }
).routeChunks,
);
const inB = new Set(await hashedAssets(dist.b));
const removedChunk = routeChunks
.map((chunk) => `/${chunk}`)
.find((chunk) => !inB.has(chunk));
if (!removedChunk) throw new Error("Build B kept every route chunk of A.");
const server = await startBuildServer(dist);
try {
const { secondLoad, controlled } = await updateFromAToB(page, server);
expect(secondLoad).toEqual({ kind: "ACTIVE", buildId: "sw-e2e-a" });
expect(controlled).toBe(true);
// B's worker now controls the page. The chunk is not in B's manifest and
// not on the server any more, so only A's retained cache can answer.
const fromWorker = await page.evaluate(async (url) => {
const response = await fetch(url);
return { status: response.status, body: await response.text() };
}, removedChunk);
expect(fromWorker).toEqual({
status: 200,
body: await readFile(path.join(dist.a, removedChunk), "utf8"),
});
expect((await page.request.get(`${server.origin}${removedChunk}`)).status())
.toBe(404);
} finally {
await server.close();
}
});
// `beforeAll` already ran `scripts/build-frontend.ts` unmodified (default
// `bundle` config loader); this pins that both builds emitted the worker.
test("builds the ACTIVE worker with the repo's unmodified build script", async () => {
const { dist } = requireBuilds();
for (const root of [dist.a, dist.b]) {
expect(await readdir(root)).toContain("service-worker.js");
}
});