fix(service-worker): ship a self-unregistering worker for REMOVE_REGISTRATION (06-03)
A worker that stops the page from booting had no exit: every off switch was page code. A REMOVE_REGISTRATION release now writes a service-worker.js that skips waiting and unregisters itself (D-5), checked end to end in the browser. The runbook and rollback doc now name only paths that exist in code. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
cebfa67549
commit
9f2305a562
@@ -460,8 +460,11 @@ committed object를 sync handle로 in-place repair하지 않는다. 새 generati
|
||||
## 8. Cache Storage/Service Worker stale or poisoned release
|
||||
|
||||
public static Cache release runtime은 존재하지만 cursor/count/deadline이 있는
|
||||
bounded inspect/cleanup과 Service Worker waiting/client-drain controller는 아직
|
||||
없다. Service Worker는 제품이 PWA/offline fetch를 별도로 선택한 경우에만 아래
|
||||
bounded inspect/cleanup은 아직 없다. Service Worker의 waiting/client-drain
|
||||
활성화는 page controller의 `requestActivation()` 핸드셰이크로 구현돼 있다
|
||||
(`src/adapters/service-worker/service-worker-page-controller.ts`). 템플릿에는 이를
|
||||
부르는 화면이 없다. Service Worker는 제품이 static selection
|
||||
(`src/features/installed-runtime-capabilities.ts`)을 `ACTIVE`로 바꾼 경우에만 아래
|
||||
worker 절차를 적용한다.
|
||||
|
||||
### 신호
|
||||
@@ -506,12 +509,38 @@ static Cache-only 조합:
|
||||
invocation을 추가 budget으로 반복 실행하지 않는다. VD-15 bounded cursor
|
||||
runtime 구현 전에는 큰 namespace를 자동 sweep하지 않는다.
|
||||
|
||||
Service Worker를 별도 선택한 조합에서만 추가:
|
||||
Service Worker를 별도 선택한 조합에서만 추가. 워커의 fetch 가로채기만 끄는
|
||||
스위치는 없다. 끄는 경로는 아래 둘이다.
|
||||
|
||||
- fetch interception을 network-only kill switch로 전환
|
||||
- new worker activation 중지
|
||||
- 필요하면 unregister + 다음 navigation cleanup migration
|
||||
- old controlled client가 drain되기 전 해당 release cleanup 금지
|
||||
- 페이지가 부팅하면: runtime config에 `CAPABILITY_OVERRIDES.SERVICE_WORKER:
|
||||
"DISABLED"`를 넣는다. 재빌드는 필요 없다. 다음 부팅 때 page controller가 scope와
|
||||
script가 정확히 일치하는 등록만 unregister하고, 새 등록은 하지 않는다
|
||||
(`src/contracts/runtime-capabilities.ts` `resolveRuntimeCapabilities`,
|
||||
`service-worker-page-controller.ts` `start()`의 `disabledCleanup` 분기). 소유
|
||||
캐시는 지우지 않는다. unregister는 이미 열린 탭의 제어를 끊지 않으므로, 그 탭은
|
||||
닫히거나 다시 load될 때까지 현재 워커를 쓴다.
|
||||
- 워커 때문에 페이지가 부팅하지 못하면: static selection을
|
||||
`{ mode: "REMOVE_REGISTRATION", scriptPath: "service-worker.js" }`로 바꾼
|
||||
release를 배포한다. 이 release는 같은 URL에 자기 해제 `service-worker.js`를 낸다
|
||||
(`scripts/build-frontend.ts`, `scripts/lib/self-unregistering-service-worker.ts`).
|
||||
페이지 코드가 돌지 않아도 브라우저 update 검사(내비게이션 때, 등록은
|
||||
`updateViaCache: "none"`)가 이 파일을 받아 설치한다. 설치 즉시
|
||||
`skipWaiting()`하고, 활성화 때 `registration.unregister()`한다. fetch handler가
|
||||
없어서 그동안의 요청은 모두 네트워크로 간다. 다음 load부터는 제어받지 않는다.
|
||||
브라우저 확인: `tests/e2e/service-worker-recovery.spec.ts`.
|
||||
- 이 경로가 동작하려면 `service-worker.js`를 `Cache-Control: no-cache`로 서빙해야
|
||||
한다. `verify:hosting-headers`는 파일이 있는지만 보고 이 헤더는 보지 않는다
|
||||
(`scripts/lib/hosting-probe.ts` `checkPublicServiceWorkers`).
|
||||
- 새 워커는 install에서 `skipWaiting()`하지 않는다(`service-worker-entry.ts`).
|
||||
활성화는 페이지의 `requestActivation()`으로만 일어나므로, 새 worker 활성화를
|
||||
멈추려고 따로 할 일은 없다.
|
||||
- 제거는 `ACTIVE → REMOVE_REGISTRATION → PURGE_OWNED_RESOURCES → null` 순서로
|
||||
release를 나눈다(`src/contracts/service-worker.ts`
|
||||
`InstalledServiceWorkerSelection`). 소유 캐시는 `PURGE_OWNED_RESOURCES` release의
|
||||
page controller가 지운다(`service-worker-removal.ts` `purgeOwnedResources`).
|
||||
old controlled client가 drain되기 전에는 이 release를 배포하지 않는다. 캐시가
|
||||
사라지면 그 탭의 워커는 요청을 네트워크로 넘기고(`service-worker-entry.ts`
|
||||
fetch 리스너의 `cached ?? fetch(request)`), 서버에 없는 옛 청크는 404가 된다.
|
||||
|
||||
hosting/CDN purge는 두 branch와 분리된 provider 절차로 실행한다.
|
||||
|
||||
|
||||
@@ -45,8 +45,10 @@ The provider-independent cache defaults are:
|
||||
- runtime config and release manifest: `no-store`
|
||||
- public source maps: disabled
|
||||
- service worker/offline cache: disabled, unless the static selection in
|
||||
`src/features/installed-runtime-capabilities.ts` is `ACTIVE`; then `dist`
|
||||
holds exactly the selected `service-worker.js`
|
||||
`src/features/installed-runtime-capabilities.ts` is `ACTIVE` or
|
||||
`REMOVE_REGISTRATION`; then `dist` holds exactly the selected
|
||||
`service-worker.js`, served `no-cache` so the browser's update check sees
|
||||
each release's worker
|
||||
|
||||
HTML, JSON config/manifest, and hashed JavaScript MIME types are also compared
|
||||
to the declared allowlist; a cache-correct response with a mismatched
|
||||
@@ -73,3 +75,35 @@ request them. The minimum is the previous release while the next one is
|
||||
active (the rolling window modeled in `tests/release/release-fixture.ts`).
|
||||
Size it to the longest session the product supports; a tab older than that
|
||||
depends on the reload-once recovery (FE-RB-002).
|
||||
|
||||
## Service Worker steps (only when the static selection is not `null`)
|
||||
|
||||
The worker is part of the release tuple: `service-worker.js` comes from the
|
||||
same build as the HTML and assets it caches.
|
||||
|
||||
1. **Rollback N+1 → N.** Switching the tuple serves N's `service-worker.js`.
|
||||
The browser's update check installs it; the worker never calls
|
||||
`skipWaiting()` on install (`src/adapters/service-worker/service-worker-entry.ts`),
|
||||
so it waits until every tab of the scope closes or a page calls
|
||||
`requestActivation()`. The template has no page that calls it. The cache
|
||||
name is the asset-set digest, so if N's cache is still there as the
|
||||
retained previous cache, the install reuses it and never deletes it on
|
||||
failure (`service-worker-static-assets.ts` `installStaticAssets`). Tabs still on N+1 keep worker N+1, so N+1's assets
|
||||
stay reachable for the rolling window above.
|
||||
2. **Turn the worker off without a rebuild.** Set
|
||||
`CAPABILITY_OVERRIDES.SERVICE_WORKER: "DISABLED"` in the runtime config. The
|
||||
next boot unregisters the owned registration and registers nothing; owned
|
||||
caches stay (`src/contracts/runtime-capabilities.ts`
|
||||
`resolveRuntimeCapabilities`, `service-worker-page-controller.ts` `start()`).
|
||||
This needs a page that boots.
|
||||
3. **A worker stops the page from booting.** Deploy a release whose static
|
||||
selection is `REMOVE_REGISTRATION`. It ships a self-unregistering
|
||||
`service-worker.js` (`scripts/build-frontend.ts`,
|
||||
`scripts/lib/self-unregistering-service-worker.ts`): the update check
|
||||
installs it over the broken worker, it skips waiting, unregisters on
|
||||
activation and answers no fetch. The next load is uncontrolled
|
||||
(`tests/e2e/service-worker-recovery.spec.ts`). Runbook:
|
||||
`docs/operations/browser-file-storage-recovery.md` §8.
|
||||
4. **Removing the worker** takes three releases:
|
||||
`REMOVE_REGISTRATION` → `PURGE_OWNED_RESOURCES` (deletes owned caches) →
|
||||
`null` (`src/contracts/service-worker.ts` `InstalledServiceWorkerSelection`).
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { rm } from "node:fs/promises";
|
||||
import { rm, writeFile } from "node:fs/promises";
|
||||
import process from "node:process";
|
||||
|
||||
import { SERVICE_WORKER_SCRIPT_PATH } from "../src/contracts/service-worker.ts";
|
||||
import { INSTALLED_RUNTIME_CAPABILITIES } from "../src/features/installed-runtime-capabilities.ts";
|
||||
import { makeDistFilesPublic } from "./lib/dist-permissions.ts";
|
||||
import { SELF_UNREGISTERING_SERVICE_WORKER } from "./lib/self-unregistering-service-worker.ts";
|
||||
|
||||
/**
|
||||
* §17.2.2. Deterministic two-pass build.
|
||||
@@ -17,11 +19,14 @@ import { makeDistFilesPublic } from "./lib/dist-permissions.ts";
|
||||
* 4. materialize dist/config.json from the declared APP_PROFILE
|
||||
* 5. scan app dist and generate the static asset source
|
||||
* 6. ACTIVE only: Vite Service Worker build (emptyOutDir = false)
|
||||
* REMOVE_REGISTRATION only: write the self-unregistering worker (06-03)
|
||||
* 7. generate Release Manifest V2 and the build manifest
|
||||
* 8. make every dist file readable by other users (13-02)
|
||||
*
|
||||
* Steps 5 and 6 are skipped for `REMOVE_REGISTRATION`, `PURGE_OWNED_RESOURCES`
|
||||
* and `null`: those modes never run an active worker build.
|
||||
* `REMOVE_REGISTRATION` still ships a `service-worker.js` so the browser's
|
||||
* update check can replace a worker that stops the page from booting (D-5).
|
||||
*
|
||||
* Step 4 has to follow the Vite build. Vite copies `public/` verbatim, so
|
||||
* without it every build — including a production one — ships the local
|
||||
@@ -62,13 +67,19 @@ if (buildsActiveWorker) {
|
||||
run("node", ["scripts/generate-service-worker-assets.ts", "dist"]);
|
||||
// 6. service worker build
|
||||
run("npx", ["vite", "build", "--config", "vite.service-worker.config.ts"]);
|
||||
} else if (selection?.mode === "REMOVE_REGISTRATION") {
|
||||
// 6. self-unregistering worker in place of the active one
|
||||
await writeFile(
|
||||
`dist/${SERVICE_WORKER_SCRIPT_PATH}`,
|
||||
SELF_UNREGISTERING_SERVICE_WORKER,
|
||||
);
|
||||
} else {
|
||||
process.stdout.write(
|
||||
`service worker mode ${selection?.mode ?? "null"}: skipping worker build\n`,
|
||||
);
|
||||
}
|
||||
|
||||
// 6. release + build manifest
|
||||
// 7. release + build manifest
|
||||
run("node", ["scripts/generate-build-manifest.ts"]);
|
||||
|
||||
// 8. publishable permissions: the validated writer creates 0600 files
|
||||
|
||||
@@ -32,7 +32,8 @@ const PUBLIC_SERVICE_WORKER = /(?:^|\/)(?:service-worker|sw)(?:[.-][^/]*)?\.js$/
|
||||
|
||||
/**
|
||||
* A built `dist` may ship a worker script only when the static selection is
|
||||
* `ACTIVE`, and then only the selected script at the app root.
|
||||
* `ACTIVE` or `REMOVE_REGISTRATION` (the self-unregistering worker, 06-03), and
|
||||
* then only the selected script at the app root.
|
||||
*/
|
||||
export function checkPublicServiceWorkers(
|
||||
distFiles: readonly string[],
|
||||
@@ -40,7 +41,9 @@ export function checkPublicServiceWorkers(
|
||||
) {
|
||||
const found = distFiles.filter((file) => PUBLIC_SERVICE_WORKER.test(file));
|
||||
const allowed: string[] =
|
||||
selection?.mode === "ACTIVE" ? [selection.scriptPath] : [];
|
||||
selection?.mode === "ACTIVE" || selection?.mode === "REMOVE_REGISTRATION"
|
||||
? [selection.scriptPath]
|
||||
: [];
|
||||
const passed =
|
||||
found.length === allowed.length &&
|
||||
found.every((file) => allowed.includes(file));
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* 06-03 (D-5). The emergency exit for a worker that stops the page from
|
||||
* booting. A `REMOVE_REGISTRATION` release writes this as `service-worker.js`.
|
||||
* The browser's own update check (navigation, `updateViaCache: "none"`) then
|
||||
* installs it over any worker of this scope without a page: it skips waiting,
|
||||
* and on activation unregisters the registration. It has no fetch handler, so
|
||||
* every request goes to the network. Owned caches stay for the
|
||||
* `PURGE_OWNED_RESOURCES` release, as with the page-side removal.
|
||||
*/
|
||||
export const SELF_UNREGISTERING_SERVICE_WORKER = `// Generated by scripts/build-frontend.ts (REMOVE_REGISTRATION).
|
||||
self.addEventListener("install", (event) => {
|
||||
event.waitUntil(self.skipWaiting());
|
||||
});
|
||||
self.addEventListener("activate", (event) => {
|
||||
event.waitUntil(self.registration.unregister());
|
||||
});
|
||||
`;
|
||||
@@ -0,0 +1,151 @@
|
||||
import path from "node:path";
|
||||
|
||||
import { expect, test, type Page } from "../support/browser/strict-browser-test.ts";
|
||||
import {
|
||||
ACTIVE_SELECTION,
|
||||
prepareServiceWorkerBuilds,
|
||||
removeServiceWorkerBuilds,
|
||||
replaceOnce,
|
||||
startBuildServer,
|
||||
type ServiceWorkerBuilds,
|
||||
} from "./support/service-worker-builds.ts";
|
||||
|
||||
/**
|
||||
* 06-03 (D-5). The emergency exit for a worker that stops the page from
|
||||
* booting. Page code cannot help then: the page never runs. Build A is the
|
||||
* ACTIVE worker with its fetch handler broken (every intercepted request is a
|
||||
* network error, the entry script included). Build B is a
|
||||
* `REMOVE_REGISTRATION` release, which ships the self-unregistering
|
||||
* `service-worker.js` (`scripts/lib/self-unregistering-service-worker.ts`).
|
||||
* The browser's update check alone replaces A with it, and the next load boots
|
||||
* B from the network.
|
||||
*/
|
||||
|
||||
type Probe = typeof globalThis & {
|
||||
__caServiceWorkerTest?: { events: string[] };
|
||||
};
|
||||
|
||||
let builds: ServiceWorkerBuilds | undefined;
|
||||
|
||||
test.beforeAll(async () => {
|
||||
test.setTimeout(180_000);
|
||||
builds = await prepareServiceWorkerBuilds({
|
||||
async beforeBuild(name, root) {
|
||||
if (name === "a") {
|
||||
await replaceOnce(
|
||||
path.join(root, "src/adapters/service-worker/service-worker-entry.ts"),
|
||||
"runtime.onFetch(described).then((cached) => cached ?? fetch(request)),",
|
||||
"Promise.resolve(Response.error()),",
|
||||
);
|
||||
return;
|
||||
}
|
||||
await replaceOnce(
|
||||
path.join(root, "src/features/installed-runtime-capabilities.ts"),
|
||||
ACTIVE_SELECTION,
|
||||
`const SERVICE_WORKER: InstalledServiceWorkerSelection | null = {
|
||||
mode: "REMOVE_REGISTRATION",
|
||||
scriptPath: "service-worker.js",
|
||||
};`,
|
||||
);
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test.afterAll(async () => {
|
||||
await removeServiceWorkerBuilds(builds);
|
||||
});
|
||||
|
||||
async function startOutcome(page: Page): Promise<unknown> {
|
||||
await page.waitForFunction(
|
||||
() =>
|
||||
(globalThis as Probe).__caServiceWorkerTest?.events.some((event) =>
|
||||
event.startsWith("start:"),
|
||||
) === true,
|
||||
undefined,
|
||||
{ timeout: 60_000 },
|
||||
);
|
||||
const event = await page.evaluate(() =>
|
||||
(globalThis as Probe).__caServiceWorkerTest!.events.find((entry) =>
|
||||
entry.startsWith("start:"),
|
||||
)!,
|
||||
);
|
||||
return JSON.parse(event.slice("start:".length));
|
||||
}
|
||||
|
||||
test("a REMOVE_REGISTRATION release unregisters a worker that blocks boot", async ({
|
||||
browser,
|
||||
browserName,
|
||||
}) => {
|
||||
// Same quarantine as service-worker-update.spec.ts.
|
||||
// quarantine(owner=frontend-platform, defect=playwright-firefox-no-sw-control, expires=2027-03-31)
|
||||
test.skip(
|
||||
browserName === "firefox",
|
||||
"Playwright Firefox pages are never controlled by a service worker.",
|
||||
);
|
||||
if (!builds) throw new Error("Service Worker builds were not prepared.");
|
||||
const server = await startBuildServer(builds.dist);
|
||||
// The broken phase fails requests on purpose, so this test drives its own
|
||||
// context instead of the strict `page` fixture and checks the recovered
|
||||
// load for browser errors itself.
|
||||
const context = await browser.newContext();
|
||||
try {
|
||||
const page = await context.newPage();
|
||||
await page.goto(`${server.origin}/`);
|
||||
expect(await startOutcome(page)).toEqual({ kind: "RELOAD_TO_ENABLE" });
|
||||
await page.evaluate(async () => {
|
||||
await navigator.serviceWorker.ready;
|
||||
});
|
||||
|
||||
// Worker A controls the next load and fails the entry script.
|
||||
await page.goto(`${server.origin}/`);
|
||||
const blocked = await page.evaluate(async () => {
|
||||
const entry = document.querySelector<HTMLScriptElement>(
|
||||
'script[type="module"][src]',
|
||||
);
|
||||
if (!entry) return "no entry script";
|
||||
try {
|
||||
await fetch(entry.src);
|
||||
return "loaded";
|
||||
} catch {
|
||||
return navigator.serviceWorker.controller ? "blocked" : "uncontrolled";
|
||||
}
|
||||
});
|
||||
expect(blocked).toBe("blocked");
|
||||
|
||||
// Release B. Only the browser's update check runs; no code of B does.
|
||||
server.serve("b");
|
||||
await page.evaluate(async () => {
|
||||
await (await navigator.serviceWorker.getRegistration())?.update();
|
||||
});
|
||||
await expect
|
||||
.poll(
|
||||
() =>
|
||||
page.evaluate(
|
||||
async () =>
|
||||
(await navigator.serviceWorker.getRegistration()) === undefined,
|
||||
),
|
||||
{ timeout: 30_000 },
|
||||
)
|
||||
.toBe(true);
|
||||
|
||||
const failures: string[] = [];
|
||||
page.on("console", (message) => {
|
||||
if (["error", "warning"].includes(message.type())) {
|
||||
failures.push(`console:${message.type()}:${message.text()}`);
|
||||
}
|
||||
});
|
||||
page.on("pageerror", (error) => failures.push(`pageerror:${error.name}`));
|
||||
page.on("requestfailed", (request) =>
|
||||
failures.push(`requestfailed:${new URL(request.url()).pathname}`),
|
||||
);
|
||||
await page.goto(`${server.origin}/`);
|
||||
expect(await startOutcome(page)).toEqual({ kind: "DISABLED" });
|
||||
expect(
|
||||
await page.evaluate(() => navigator.serviceWorker.controller === null),
|
||||
).toBe(true);
|
||||
expect(failures).toEqual([]);
|
||||
} finally {
|
||||
await context.close();
|
||||
await server.close();
|
||||
}
|
||||
});
|
||||
@@ -52,7 +52,7 @@ export type ServiceWorkerBuilds = Readonly<{
|
||||
dist: Readonly<Record<BuildName, string>>;
|
||||
}>;
|
||||
|
||||
const ACTIVE_SELECTION = `const SERVICE_WORKER: InstalledServiceWorkerSelection | null = {
|
||||
export const ACTIVE_SELECTION = `const SERVICE_WORKER: InstalledServiceWorkerSelection | null = {
|
||||
mode: "ACTIVE",
|
||||
scriptPath: "service-worker.js",
|
||||
handlers: ["PWA_STATIC_ASSETS"],
|
||||
@@ -80,7 +80,7 @@ export function createServiceWorkerRuntimeHost(
|
||||
}
|
||||
`;
|
||||
|
||||
async function replaceOnce(
|
||||
export async function replaceOnce(
|
||||
file: string,
|
||||
search: string,
|
||||
replacement: string,
|
||||
@@ -105,7 +105,16 @@ function run(cwd: string, script: string, buildId: string): void {
|
||||
}
|
||||
}
|
||||
|
||||
export async function prepareServiceWorkerBuilds(): Promise<ServiceWorkerBuilds> {
|
||||
/**
|
||||
* `beforeBuild` edits the temp copy right before build `name` (06-03: a
|
||||
* broken worker A, then a `REMOVE_REGISTRATION` release B). Edits persist
|
||||
* into the later build.
|
||||
*/
|
||||
export async function prepareServiceWorkerBuilds(
|
||||
options: Readonly<{
|
||||
beforeBuild?: (name: BuildName, root: string) => Promise<void>;
|
||||
}> = {},
|
||||
): Promise<ServiceWorkerBuilds> {
|
||||
const root = await mkdtemp(path.join(tmpdir(), "ca-sw-builds-"));
|
||||
await cp(repoRoot, root, {
|
||||
recursive: true,
|
||||
@@ -128,6 +137,7 @@ export async function prepareServiceWorkerBuilds(): Promise<ServiceWorkerBuilds>
|
||||
|
||||
const dist = { a: path.join(root, "dist-a"), b: path.join(root, "dist-b") };
|
||||
for (const name of ["a", "b"] as const) {
|
||||
await options.beforeBuild?.(name, root);
|
||||
run(root, "scripts/generate-product-feature-index.ts", `sw-e2e-${name}`);
|
||||
run(root, "scripts/build-frontend.ts", `sw-e2e-${name}`);
|
||||
await rename(path.join(root, "dist"), dist[name]);
|
||||
|
||||
@@ -15,6 +15,7 @@ describe("public service worker in dist", () => {
|
||||
handlers: ["PWA_STATIC_ASSETS"],
|
||||
} as const;
|
||||
const removal = { mode: "REMOVE_REGISTRATION", scriptPath: "service-worker.js" } as const;
|
||||
const purge = { mode: "PURGE_OWNED_RESOURCES", scriptPath: "service-worker.js" } as const;
|
||||
|
||||
it("accepts the selected worker when the selection is ACTIVE", () => {
|
||||
expect(
|
||||
@@ -22,6 +23,13 @@ describe("public service worker in dist", () => {
|
||||
).toMatchObject({ expected: true, observed: true, passed: true });
|
||||
});
|
||||
|
||||
// 06-03 (D-5). REMOVE_REGISTRATION ships the self-unregistering worker.
|
||||
it("accepts the selected worker when the selection is REMOVE_REGISTRATION", () => {
|
||||
expect(
|
||||
checkPublicServiceWorkers([...app, "service-worker.js"], removal),
|
||||
).toMatchObject({ expected: true, observed: true, passed: true });
|
||||
});
|
||||
|
||||
it("accepts a worker-free dist when no worker is selected", () => {
|
||||
expect(checkPublicServiceWorkers(app, null)).toMatchObject({
|
||||
expected: false,
|
||||
@@ -31,7 +39,8 @@ describe("public service worker in dist", () => {
|
||||
|
||||
it.each([
|
||||
["no selection", [...app, "service-worker.js"], null],
|
||||
["a non-ACTIVE selection", [...app, "service-worker.js"], removal],
|
||||
["a PURGE_OWNED_RESOURCES selection", [...app, "service-worker.js"], purge],
|
||||
["REMOVE_REGISTRATION without the worker", app, removal],
|
||||
["ACTIVE without the worker", app, active],
|
||||
["ACTIVE with an extra worker", [...app, "service-worker.js", "assets/sw.js"], active],
|
||||
["ACTIVE with the worker off the root", [...app, "assets/service-worker.js"], active],
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { runInNewContext } from "node:vm";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { SELF_UNREGISTERING_SERVICE_WORKER } from "../../scripts/lib/self-unregistering-service-worker.ts";
|
||||
import { resolveServiceWorkerBuildInput } from "../../scripts/lib/service-worker-build-input.ts";
|
||||
import {
|
||||
canonicalStaticManifestBytes,
|
||||
@@ -193,3 +195,37 @@ describe("service worker build input", () => {
|
||||
).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* 06-03 (D-5). A REMOVE_REGISTRATION release ships this as
|
||||
* `service-worker.js`, so a browser update check replaces even a worker that
|
||||
* stops the page from booting. The context has no `caches` and no `fetch`: a
|
||||
* reference to either throws.
|
||||
*/
|
||||
describe("self-unregistering service worker", () => {
|
||||
it("takes over at once, unregisters itself and handles no fetch", async () => {
|
||||
const listeners = new Map<string, (event: unknown) => void>();
|
||||
const skipWaiting = vi.fn(async () => {});
|
||||
const unregister = vi.fn(async () => true);
|
||||
runInNewContext(SELF_UNREGISTERING_SERVICE_WORKER, {
|
||||
self: {
|
||||
addEventListener(type: string, listener: (event: unknown) => void) {
|
||||
listeners.set(type, listener);
|
||||
},
|
||||
skipWaiting,
|
||||
registration: { unregister },
|
||||
},
|
||||
});
|
||||
expect([...listeners.keys()].sort()).toEqual(["activate", "install"]);
|
||||
|
||||
const pending: Promise<unknown>[] = [];
|
||||
const event = { waitUntil: (task: Promise<unknown>) => pending.push(task) };
|
||||
listeners.get("install")!(event);
|
||||
expect(skipWaiting).toHaveBeenCalledOnce();
|
||||
expect(unregister).not.toHaveBeenCalled();
|
||||
listeners.get("activate")!(event);
|
||||
await Promise.all(pending);
|
||||
expect(pending).toHaveLength(2);
|
||||
expect(unregister).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user