From b19a3e9b2fb033797e1d40534537fd8ea1a67dda Mon Sep 17 00:00:00 2001 From: "arrz.dev" <55147716+arrzdev@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:55:10 +0000 Subject: [PATCH 1/2] test(sw): pin the expiration window per cache and the 200-only cache gate --- src/sw/sw.expiration.test.ts | 185 +++++++++++++++++++++++++++++++++++ src/sw/sw.plugins.test.ts | 157 +++++++++++++++++++++++++++++ 2 files changed, 342 insertions(+) create mode 100644 src/sw/sw.expiration.test.ts create mode 100644 src/sw/sw.plugins.test.ts diff --git a/src/sw/sw.expiration.test.ts b/src/sw/sw.expiration.test.ts new file mode 100644 index 00000000..22dc4585 --- /dev/null +++ b/src/sw/sw.expiration.test.ts @@ -0,0 +1,185 @@ +/// + +import "fake-indexeddb/auto" +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" +import { executeQuotaErrorCallbacks } from "workbox-core/_private/executeQuotaErrorCallbacks.js" +import { ExpirationPlugin } from "workbox-expiration" +import { createExpirationPlugins } from "#adaptv/sw/sw.expiration" +import { createCacheFirstStrategy } from "#adaptv/sw/sw.strategies" +import type { TestServiceWorkerScope } from "#adaptv/sw/sw.test-helper" +import { + browserRequest, + installServiceWorkerScope, + ORIGIN, + TestFetchEvent, +} from "#adaptv/sw/sw.test-helper" +import type { CacheExpirationOptions } from "#adaptv/sw/sw.types" + +/* + * `createExpirationPlugins` — how long a runtime cache keeps what it stored. + * + * Workbox's ExpirationPlugin is the real one, with its IndexedDB timestamp + * store on `fake-indexeddb`; the strategy is adaptv's own cache-first. So a + * test reads the cache the way the worker would, not the options object. + */ + +let sw: TestServiceWorkerScope +let now: number + +beforeEach(() => { + sw = installServiceWorkerScope() + sw.fetch.mockImplementation(async (input) => { + const url = typeof input === "string" ? input : (input as Request).url + return new Response(`body of ${url}`, { + status: 200, + headers: { date: new Date(now).toUTCString() }, + }) + }) + //one tick per request, so "oldest" is never a tie on the same millisecond + now = Date.UTC(2026, 10, 17, 12) + vi.spyOn(Date, "now").mockImplementation(() => now) +}) + +afterEach(() => { + vi.restoreAllMocks() + vi.unstubAllGlobals() +}) + +//each test gets caches the timestamp store has never seen +let caseId = 0 +function cacheName(label: string) { + caseId += 1 + return `${label}-${caseId}` +} + +function strategyFor(name: string, expiration: CacheExpirationOptions) { + return createCacheFirstStrategy({ cacheName: name, expiration }) +} + +async function request( + strategy: ReturnType, + path: string, +) { + now += 1000 + const event = new TestFetchEvent(browserRequest(path)) + const response = await strategy.handle({ + request: event.request, + event: event as unknown as FetchEvent, + }) + await event.settled() + return response +} + +describe("createExpirationPlugins — when it adds a plugin", () => { + it("adds none for a permanent cache", () => { + expect(createExpirationPlugins(undefined)).toEqual([]) + }) + + it("adds exactly one ExpirationPlugin when a window is given", () => { + const plugins = createExpirationPlugins({ maxEntries: 10 }) + expect(plugins).toHaveLength(1) + expect(plugins[0]).toBeInstanceOf(ExpirationPlugin) + }) +}) + +describe("createExpirationPlugins — maxEntries", () => { + it("keeps the newest entries and evicts the oldest past the limit", async () => { + const name = cacheName("images") + const strategy = strategyFor(name, { maxEntries: 2 }) + await request(strategy, "/img/a.png") + await request(strategy, "/img/b.png") + await request(strategy, "/img/c.png") + expect(sw.caches.urlsIn(name).sort()).toEqual([ + `${ORIGIN}/img/b.png`, + `${ORIGIN}/img/c.png`, + ]) + }) + + it("counts a cache hit as use, so a re-read entry outlives a newer one", async () => { + const name = cacheName("images") + const strategy = strategyFor(name, { maxEntries: 2 }) + await request(strategy, "/img/a.png") + await request(strategy, "/img/b.png") + await request(strategy, "/img/a.png") //served from cache, timestamp bumped + await request(strategy, "/img/c.png") + expect(sw.caches.urlsIn(name).sort()).toEqual([ + `${ORIGIN}/img/a.png`, + `${ORIGIN}/img/c.png`, + ]) + }) + + it("applies per cache — one cache's limit never evicts from another", async () => { + const small = cacheName("thumbs") + const large = cacheName("photos") + const thumbs = strategyFor(small, { maxEntries: 1 }) + const photos = strategyFor(large, { maxEntries: 3 }) + for (const path of ["/t/1", "/t/2", "/t/3"]) { + await request(thumbs, path) + } + for (const path of ["/p/1", "/p/2", "/p/3"]) { + await request(photos, path) + } + expect(sw.caches.urlsIn(small)).toEqual([`${ORIGIN}/t/3`]) + expect(sw.caches.urlsIn(large).sort()).toEqual([ + `${ORIGIN}/p/1`, + `${ORIGIN}/p/2`, + `${ORIGIN}/p/3`, + ]) + }) +}) + +describe("createExpirationPlugins — maxAgeSeconds", () => { + it("serves a cached entry while it is younger than the limit", async () => { + const name = cacheName("feed") + const strategy = strategyFor(name, { maxAgeSeconds: 60 }) + const first = await request(strategy, "/feed.json") + sw.fetch.mockClear() + now += 30_000 + const second = await request(strategy, "/feed.json") + expect(sw.fetch).not.toHaveBeenCalled() + expect(await second.text()).toBe(await first.text()) + }) + + it("goes back to the network once the entry is older than the limit", async () => { + const name = cacheName("feed") + const strategy = strategyFor(name, { maxAgeSeconds: 60 }) + await request(strategy, "/feed.json") + sw.fetch.mockClear() + now += 120_000 + await request(strategy, "/feed.json") + expect(sw.fetch).toHaveBeenCalledTimes(1) + }) + + it("deletes expired entries from the cache, not only skips them", async () => { + const name = cacheName("feed") + const strategy = strategyFor(name, { maxAgeSeconds: 60 }) + await request(strategy, "/old.json") + now += 120_000 + await request(strategy, "/new.json") + expect(sw.caches.urlsIn(name)).toEqual([`${ORIGIN}/new.json`]) + }) +}) + +describe("createExpirationPlugins — purgeOnQuotaError", () => { + //quota callbacks are process-wide in Workbox, so earlier tests' plugins run + //too; each test only reads its own cache + it("defaults on: a quota error drops the whole cache", async () => { + const name = cacheName("big") + const strategy = strategyFor(name, { maxEntries: 10 }) + await request(strategy, "/blob/1") + expect(sw.caches.urlsIn(name)).toHaveLength(1) + await executeQuotaErrorCallbacks() + expect(await sw.caches.has(name)).toBe(false) + }) + + it("can be turned off, and then the cache survives a quota error", async () => { + const name = cacheName("keep") + const strategy = strategyFor(name, { + maxEntries: 10, + purgeOnQuotaError: false, + }) + await request(strategy, "/blob/1") + await executeQuotaErrorCallbacks() + expect(sw.caches.urlsIn(name)).toEqual([`${ORIGIN}/blob/1`]) + }) +}) diff --git a/src/sw/sw.plugins.test.ts b/src/sw/sw.plugins.test.ts new file mode 100644 index 00000000..37670898 --- /dev/null +++ b/src/sw/sw.plugins.test.ts @@ -0,0 +1,157 @@ +/// + +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" +import type { WorkboxPlugin } from "workbox-core/types" +import { createCacheOkResponsesPlugin } from "#adaptv/sw/sw.plugins" +import { createCacheFirstStrategy } from "#adaptv/sw/sw.strategies" +import type { TestServiceWorkerScope } from "#adaptv/sw/sw.test-helper" +import { + browserRequest, + installServiceWorkerScope, + ORIGIN, + TestFetchEvent, +} from "#adaptv/sw/sw.test-helper" + +/* + * `createCacheOkResponsesPlugin` — the gate every adaptv strategy puts in front + * of the cache. Only a 200 is kept: an opaque response hides its status (it may + * be a 500), a redirect or a 206 is not the resource itself, and an error body + * cached once would be served offline for as long as the entry lives. + */ + +function cacheWillUpdate(response: Response | undefined) { + const plugin = createCacheOkResponsesPlugin() + return plugin.cacheWillUpdate?.({ + request: new Request(`${ORIGIN}/data/item`), + response: response as Response, + event: new Event("fetch") as ExtendableEvent, + state: {}, + }) +} + +/** What a cross-origin `no-cors` fetch returns: status 0, body unreadable. */ +function opaqueResponse(): Response { + const response = new Response(null) + Object.defineProperty(response, "status", { value: 0 }) + Object.defineProperty(response, "type", { value: "opaque" }) + return response +} + +describe("createCacheOkResponsesPlugin — cacheWillUpdate", () => { + it("keeps a 200 as it is", async () => { + const response = new Response("ok", { status: 200 }) + expect(await cacheWillUpdate(response)).toBe(response) + }) + + it("refuses an opaque response — its status could be anything", async () => { + expect(await cacheWillUpdate(opaqueResponse())).toBeNull() + }) + + it("refuses a network error", async () => { + expect(await cacheWillUpdate(Response.error())).toBeNull() + }) + + it.each([ + [204, "no content"], + [206, "a partial body"], + [301, "a redirect"], + [304, "a revalidation with no body"], + ])( + "refuses a %i (%s) — only the full resource is kept", + async (status) => { + const body = status === 204 || status === 304 ? null : "x" + expect( + await cacheWillUpdate(new Response(body, { status })), + ).toBeNull() + }, + ) + + it.each([400, 401, 403, 404, 410, 429])( + "refuses a %i client error", + async (status) => { + expect( + await cacheWillUpdate(new Response("nope", { status })), + ).toBeNull() + }, + ) + + it.each([500, 502, 503, 504])( + "refuses a %i server error", + async (status) => { + expect( + await cacheWillUpdate(new Response("down", { status })), + ).toBeNull() + }, + ) + + it("refuses when there is no response at all", async () => { + expect(await cacheWillUpdate(undefined)).toBeNull() + }) +}) + +describe("createCacheOkResponsesPlugin — inside a real strategy", () => { + let sw: TestServiceWorkerScope + + beforeEach(() => { + sw = installServiceWorkerScope() + }) + + afterEach(() => { + vi.unstubAllGlobals() + }) + + async function fetchThrough(path: string, plugins?: WorkboxPlugin[]) { + const strategy = createCacheFirstStrategy({ + cacheName: "assets", + plugins, + }) + const event = new TestFetchEvent(browserRequest(path)) + const response = await strategy.handle({ + request: event.request, + event: event as unknown as FetchEvent, + }) + await event.settled() + return response + } + + it("caches a 200 the network returned", async () => { + sw.fetch.mockResolvedValue(new Response("logo", { status: 200 })) + const response = await fetchThrough("/img/logo.png") + expect(response.status).toBe(200) + expect(sw.caches.urlsIn("assets")).toEqual([`${ORIGIN}/img/logo.png`]) + }) + + it("still hands a 500 to the page but does not cache it", async () => { + sw.fetch.mockResolvedValue(new Response("down", { status: 500 })) + const response = await fetchThrough("/img/logo.png") + expect(response.status).toBe(500) + expect(sw.caches.urlsIn("assets")).toEqual([]) + }) + + it("still hands a 404 to the page but does not cache it", async () => { + sw.fetch.mockResolvedValue(new Response("gone", { status: 404 })) + const response = await fetchThrough("/img/missing.png") + expect(response.status).toBe(404) + expect(sw.caches.urlsIn("assets")).toEqual([]) + }) + + it("does not cache an opaque response", async () => { + sw.fetch.mockResolvedValue(opaqueResponse()) + await fetchThrough("/img/logo.png") + expect(sw.caches.urlsIn("assets")).toEqual([]) + }) + + it("runs before an app's own plugin, so that plugin never sees a 500", async () => { + //Workbox only applies its own 200-only default when NO plugin defines + //`cacheWillUpdate`; an app plugin that does would otherwise switch it off + const keepEverything = vi.fn( + async ({ response }: { response: Response }) => response, + ) + sw.fetch.mockResolvedValue(new Response("down", { status: 500 })) + await fetchThrough("/img/logo.png", [ + { cacheWillUpdate: keepEverything }, + ]) + expect(keepEverything).not.toHaveBeenCalled() + expect(sw.caches.urlsIn("assets")).toEqual([]) + }) +}) From 92e1081dfa2be7640834960b6440ae40aa592630 Mon Sep 17 00:00:00 2001 From: "arrz.dev" <55147716+arrzdev@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:55:10 +0000 Subject: [PATCH 2/2] fix(sw): precache cleanup keeps the precache of an app under a nested scope --- docs/design/rendering.md | 6 +- src/sw/sw.precache.test.ts | 207 +++++++++++++++++++++++++++++++++++++ src/sw/sw.precache.ts | 35 +++++-- 3 files changed, 241 insertions(+), 7 deletions(-) create mode 100644 src/sw/sw.precache.test.ts diff --git a/docs/design/rendering.md b/docs/design/rendering.md index 0bf2ac33..7ca8cc91 100644 --- a/docs/design/rendering.md +++ b/docs/design/rendering.md @@ -733,10 +733,14 @@ Freshness belongs to the **data layer** (consumer-wired: TanStack Query + an IDB - **Activate-time cache sweep.** Runtime buckets are named `-`, with the base in front under a subpath (`/app/static-`, because Cache Storage is per origin, not per scope); on `activate`, every cache whose name starts with a bucket adaptv **owns** under this app's base and - whose tag is not the current one is deleted. `cleanupOutdatedCaches()` does **not** do this — it only removes precaches written by *older + whose tag is not the current one is deleted. Precache cleanup does **not** do this — it only removes precaches written by *older Workbox versions* — so without the sweep every deploy mints buckets that are never freed, ending in a quota error on a frequently-deployed app. → `docs/decisions/register.md` B2 + That precache cleanup is adaptv's own (`sw.precache.ts`), not Workbox's `cleanupOutdatedCaches()`: + Workbox's matches the scope as a substring, so a worker at `/` deleted the precache of an app at + `/docs/` on the same origin. adaptv's requires the precache name to **end** with its own scope. + The owned list is exactly `static`, `pages`, `documents`, and it is an **allowlist on purpose**: a prefix rule like "delete anything that isn't the current tag" would take caches adaptv did not create — another app on the same origin, a third-party worker, Workbox's own bookkeeping. diff --git a/src/sw/sw.precache.test.ts b/src/sw/sw.precache.test.ts new file mode 100644 index 00000000..0bc785d9 --- /dev/null +++ b/src/sw/sw.precache.test.ts @@ -0,0 +1,207 @@ +/// + +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" +import type { TestServiceWorkerScope } from "#adaptv/sw/sw.test-helper" +import { + browserRequest, + installServiceWorkerScope, + ORIGIN, + TestExtendableEvent, + TestFetchEvent, +} from "#adaptv/sw/sw.test-helper" +import type { PrecacheManifestEntry } from "#adaptv/sw/sw.types" + +/* + * `setupPrecache` — the build manifest the worker installs before it takes over, + * and the sweep of what an older worker precached. + * + * Workbox's precaching is the real one, end to end: its controller, its default + * router's fetch listener and its activate-time cleanup. They are singletons + * that read the scope at import time (the precache cache name ends in + * `registration.scope`), so every test stubs the scope first and then imports + * fresh modules. + */ + +const SCOPE = `${ORIGIN}/` +const PRECACHE = `workbox-precache-v2-${SCOPE}` + +let sw: TestServiceWorkerScope + +beforeEach(() => { + vi.resetModules() + sw = installServiceWorkerScope() + vi.stubGlobal("registration", sw.scope.registration) + sw.fetch.mockImplementation(async (input) => { + const url = typeof input === "string" ? input : (input as Request).url + return new Response(`network: ${new URL(url).pathname}`, { + status: 200, + }) + }) +}) + +afterEach(() => { + vi.unstubAllGlobals() +}) + +async function setup(manifest: PrecacheManifestEntry[]) { + const { setupPrecache } = await import("#adaptv/sw/sw.precache") + setupPrecache(manifest) +} + +async function install() { + const event = sw.dispatch(new TestExtendableEvent("install")) + await event.settled() +} + +async function activate() { + const event = sw.dispatch(new TestExtendableEvent("activate")) + await event.settled() +} + +/** Dispatch a fetch the way the browser does and read what the worker answered. */ +async function navigateFetch(path: string) { + const event = new TestFetchEvent(browserRequest(path)) + let answered: Promise | undefined + Object.defineProperty(event, "respondWith", { + value: (response: Promise) => { + answered = response + }, + }) + sw.dispatch(event) + return answered && (await answered) +} + +const MANIFEST: PrecacheManifestEntry[] = [ + { url: "/index.html", revision: "rev-1" }, + { url: "/assets/app.4f2a9c.js", revision: null }, +] + +describe("setupPrecache — registration", () => { + it("listens for install, activate and fetch", async () => { + await setup(MANIFEST) + expect(sw.listenerCount("install")).toBe(1) + expect(sw.listenerCount("fetch")).toBe(1) + //one from the precache controller, one from cleanupOutdatedCaches + expect(sw.listenerCount("activate")).toBe(2) + }) + + it("does not keep a reference to the caller's manifest array", async () => { + const manifest = [...MANIFEST] + await setup(manifest) + manifest.push({ url: "/late.html", revision: "x" }) + await install() + expect(sw.caches.urlsIn(PRECACHE)).not.toContain( + expect.stringContaining("late.html"), + ) + }) +}) + +describe("setupPrecache — install", () => { + it("stores every manifest entry, keyed by its revision", async () => { + await setup(MANIFEST) + await install() + expect(sw.caches.urlsIn(PRECACHE).sort()).toEqual([ + `${ORIGIN}/assets/app.4f2a9c.js`, + `${ORIGIN}/index.html?__WB_REVISION__=rev-1`, + ]) + }) + + it("fails the install when an entry cannot be fetched", async () => { + //a worker that activated with half its shell would serve a broken app + //offline; the browser keeps the old worker instead + sw.fetch.mockImplementation(async (input) => { + const url = + typeof input === "string" ? input : (input as Request).url + return url.includes("app.4f2a9c") + ? new Response("missing", { status: 404 }) + : new Response("ok", { status: 200 }) + }) + await setup(MANIFEST) + const event = sw.dispatch(new TestExtendableEvent("install")) + const results = await Promise.allSettled(event.pending) + expect(results.some((r) => r.status === "rejected")).toBe(true) + }) +}) + +describe("setupPrecache — serving", () => { + it("answers a precached URL from the precache, without the network", async () => { + await setup(MANIFEST) + await install() + await activate() + sw.fetch.mockClear() + const response = await navigateFetch("/index.html") + expect(response?.status).toBe(200) + expect(await response?.text()).toBe("network: /index.html") + expect(sw.fetch).not.toHaveBeenCalled() + }) + + it("leaves a URL outside the manifest to the browser", async () => { + await setup(MANIFEST) + await install() + await activate() + expect(await navigateFetch("/not-precached.json")).toBeUndefined() + }) +}) + +describe("setupPrecache — cleanup", () => { + it("drops an entry whose revision changed, keeping only the new one", async () => { + sw.caches.seed( + PRECACHE, + "/index.html?__WB_REVISION__=rev-0", + new Response("old shell"), + ) + await setup(MANIFEST) + await install() + await activate() + const urls = sw.caches.urlsIn(PRECACHE) + expect(urls).toContain(`${ORIGIN}/index.html?__WB_REVISION__=rev-1`) + expect(urls).not.toContain( + `${ORIGIN}/index.html?__WB_REVISION__=rev-0`, + ) + }) + + it("drops an entry the new manifest no longer lists", async () => { + sw.caches.seed(PRECACHE, "/assets/app.0ld000.js", new Response("old")) + await setup(MANIFEST) + await install() + await activate() + expect(sw.caches.urlsIn(PRECACHE)).not.toContain( + `${ORIGIN}/assets/app.0ld000.js`, + ) + }) + + it("deletes a precache left by an older Workbox format on activate", async () => { + const v1 = `workbox-precache-${SCOPE}` + sw.caches.seed(v1, "/index.html", new Response("v1 shell")) + await setup(MANIFEST) + await install() + await activate() + expect(await sw.caches.has(v1)).toBe(false) + expect(await sw.caches.has(PRECACHE)).toBe(true) + }) + + it("leaves runtime caches alone", async () => { + const runtime = "static-myapp-2f9c1a" + sw.caches.seed(runtime, "/img/a.png", new Response("a")) + await setup(MANIFEST) + await install() + await activate() + expect(await sw.caches.has(runtime)).toBe(true) + }) + + it("leaves the precache of an app under a nested scope alone", async () => { + //Cache Storage is shared by every worker on the origin: a user site at `/` + //and a project site at `/docs/` on the same GitHub Pages host both have + //one. The root worker's scope is a substring of the nested one's precache + //name, so a substring match deletes that app's offline shell. + const nested = `workbox-precache-v2-${ORIGIN}/docs/` + const nestedV1 = `workbox-precache-${ORIGIN}/docs/` + sw.caches.seed(nested, "/docs/index.html", new Response("docs shell")) + sw.caches.seed(nestedV1, "/docs/index.html", new Response("docs v1")) + await setup(MANIFEST) + await install() + await activate() + expect(await sw.caches.has(nested)).toBe(true) + expect(await sw.caches.has(nestedV1)).toBe(true) + }) +}) diff --git a/src/sw/sw.precache.ts b/src/sw/sw.precache.ts index 4cb0ba20..1d6a016f 100644 --- a/src/sw/sw.precache.ts +++ b/src/sw/sw.precache.ts @@ -1,12 +1,35 @@ +import { cacheNames } from "workbox-core" import type { PrecacheEntry } from "workbox-precaching" -import { - cleanupOutdatedCaches, - precacheAndRoute, -} from "workbox-precaching" +import { precacheAndRoute } from "workbox-precaching" +import { serviceWorkerScope } from "#adaptv/sw/sw.scope" import type { PrecacheManifestEntry } from "#adaptv/sw/sw.types" -/** Inject {@link precacheAndRoute} + {@link cleanupOutdatedCaches} for build output. */ +/** Inject {@link precacheAndRoute} + {@link deleteOutdatedPrecaches} for build output. */ export function setupPrecache(manifest: readonly PrecacheManifestEntry[]) { precacheAndRoute([...manifest] as PrecacheEntry[]) - cleanupOutdatedCaches() + serviceWorkerScope().addEventListener("activate", (event) => { + event.waitUntil(deleteOutdatedPrecaches()) + }) +} + +/** + * Delete the precaches an older Workbox left under THIS worker's scope. + * + * Not Workbox's `cleanupOutdatedCaches()`: it deletes every `-precache-` cache + * whose name merely CONTAINS the scope, and a root scope (`https://host/`) is + * contained in a nested one's name (`workbox-precache-v2-https://host/docs/`). + * Cache Storage is shared by every worker on the origin, so a root app's + * activate deleted the offline shell of another app under a sub-path. Workbox + * names a precache `--`, so the scope must END it. + */ +async function deleteOutdatedPrecaches(): Promise { + const sw = serviceWorkerScope() + const ownScope = `-${sw.registration.scope}` + const outdated = (await sw.caches.keys()).filter( + (name) => + name.includes("-precache-") && + name.endsWith(ownScope) && + name !== cacheNames.precache, + ) + await Promise.all(outdated.map((name) => sw.caches.delete(name))) }