@plasius/offline-cache 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -14,6 +14,31 @@
14
14
  - **Security**
15
15
  - (placeholder)
16
16
 
17
+ ## [0.1.2] - 2026-09-13
18
+
19
+ - Honour asset-pack abort signals for pending downloads and late cache writes.
20
+ - Preserve exact immutable and denied path patterns in generated workers.
21
+
22
+ - Add optional worker consent leases, acknowledged withdrawal and protection against late cache writes (#12).
23
+
24
+ - **Added**
25
+ - (placeholder)
26
+
27
+ - **Changed**
28
+ - Bound npm publication to the exact prepared `main` commit after successful push-triggered CI.
29
+ - (placeholder)
30
+
31
+ - **Fixed**
32
+ - Added exact-commit CI dispatch and disabled package-manager cache finalization in both hosted validation jobs.
33
+ - (placeholder)
34
+
35
+ - **Security**
36
+ - Removed the npm write-token path, added a fail-closed npm 11.5.1-or-newer OIDC guard, and denied fork PR code access to reviewed CI.
37
+ - Pinned patched transitive npm dependencies to clear the current audit baseline.
38
+ - Moved reviewed CI to explicit GitHub-hosted runners while retaining the same-repository pull-request guard.
39
+ - Added fail-closed source and npm-package admission for the administrative contributor registry and pinned the CI/CD runtime to Node.js 24.18.0 LTS.
40
+ - (placeholder)
41
+
17
42
  ## [0.1.1] - 2026-07-12
18
43
 
19
44
  - Refuse storage and reuse of requests or responses carrying RFC 9111
@@ -41,3 +66,4 @@
41
66
 
42
67
  [0.1.0]: https://github.com/Plasius-LTD/offline-cache/releases/tag/v0.1.0
43
68
  [0.1.1]: https://github.com/Plasius-LTD/offline-cache/releases/tag/v0.1.1
69
+ [0.1.2]: https://github.com/Plasius-LTD/offline-cache/releases/tag/v0.1.2
package/README.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # @plasius/offline-cache
2
2
 
3
+ [![npm version](https://img.shields.io/npm/v/@plasius/offline-cache.svg)](https://www.npmjs.com/package/@plasius/offline-cache)
4
+ [![Build Status](https://img.shields.io/github/actions/workflow/status/Plasius-LTD/offline-cache/ci.yml?branch=main&label=build&style=flat)](https://github.com/Plasius-LTD/offline-cache/actions/workflows/ci.yml)
5
+ [![coverage](https://img.shields.io/codecov/c/github/Plasius-LTD/offline-cache)](https://codecov.io/gh/Plasius-LTD/offline-cache)
6
+ [![License](https://img.shields.io/github/license/Plasius-LTD/offline-cache)](./LICENSE)
7
+ [![Code of Conduct](https://img.shields.io/badge/code%20of%20conduct-yes-blue.svg)](./CODE_OF_CONDUCT.md)
8
+ [![Security Policy](https://img.shields.io/badge/security%20policy-yes-orange.svg)](./SECURITY.md)
9
+ [![Changelog](https://img.shields.io/badge/changelog-md-blue.svg)](./CHANGELOG.md)
10
+
3
11
  Browser-side offline cache helpers for Plasius progressive public sites and
4
12
  demo asset packs.
5
13
 
@@ -59,3 +67,39 @@ npm run typecheck
59
67
  npm run build
60
68
  npm run pack:check
61
69
  ```
70
+
71
+ <!-- BEGIN PLASIUS RELEASE INTEGRITY -->
72
+ ## Release integrity
73
+
74
+ CI keeps the administrative contributor registry outside Git and npm package
75
+ artifacts using exact, case-normalised path checks. CI runs on approved
76
+ GitHub-hosted runners for same-repository pull requests and `main`, with
77
+ package-manager cache finalization disabled; fork PR code is denied.
78
+ Publication uses the GitHub-hosted `production` job with Node 24 and a pinned
79
+ npm 11.6.2 client. It is token-free and proceeds only while the prepared SHA
80
+ is the exact `main` head after successful push-triggered CI. Do not dispatch CD
81
+ until the npm trusted-publisher binding is verified.
82
+ <!-- END PLASIUS RELEASE INTEGRITY -->
83
+
84
+ ## Consent-aware workers
85
+
86
+ Set `requireConsent: true` when generating a worker for optional caching. It starts
87
+ without permission and accepts only same-origin window messages of type
88
+ `plasius-offline-consent-v1` with `allowedUntil` (epoch milliseconds). Grants last
89
+ at most 60 seconds and must be renewed by a host that still has valid consent and
90
+ remote permission. A worker restart starts denied; host permission must be renewed.
91
+ Send `allowedUntil: 0` on withdrawal with a MessageChannel to receive the matching
92
+ `{ type, disabled: true }` acknowledgement after scoped cache deletion. Pending
93
+ responses cannot repopulate discarded caches. Unregister the worker afterwards.
94
+ Unregistration alone does not stop an already-controlling worker. Legacy workers
95
+ without this protocol must be replaced or detached through navigation before the
96
+ host can claim immediate revocation. Offline availability is limited to a current
97
+ permission lease; exhausted leases fail closed. Existing generation behaviour is
98
+ unchanged when `requireConsent` is omitted.
99
+
100
+ Use `immutableAssetPathPatterns` for exact content-addressed asset paths. Denied
101
+ paths always win; host and generated worker preserve regex source and flags.
102
+
103
+ `warmAssetPack` propagates its `signal` to downloads and rejects with the abort
104
+ reason before further cache access after cancellation, including late responses.
105
+ Hosts should treat consent cancellation as a normal stop, not a renderer failure.
package/dist/index.cjs CHANGED
@@ -147,6 +147,9 @@ function classifyOfflineCacheRequest(input, init, policy = DEFAULT_OFFLINE_CACHE
147
147
  )) {
148
148
  return { cacheable: false, strategy: "no-cache", reason: "denied-path-prefix" };
149
149
  }
150
+ if (policy.immutableAssetPathPatterns?.some((pattern) => new RegExp(pattern.source, pattern.flags).test(pathname))) {
151
+ return { cacheable: true, strategy: "cache-first", reason: "immutable-asset-pattern", cacheBucket: "immutable" };
152
+ }
150
153
  if (pathStartsWith(pathname, policy.publicApiPathPrefixes)) {
151
154
  return {
152
155
  cacheable: true,
@@ -255,7 +258,12 @@ async function warmAssetPack(pack, options = {}) {
255
258
  availableBytes
256
259
  };
257
260
  }
261
+ options.signal?.throwIfAborted();
258
262
  const cache = await cacheStorage.open(cacheName);
263
+ if (options.signal?.aborted) {
264
+ await cacheStorage.delete(cacheName);
265
+ options.signal.throwIfAborted();
266
+ }
259
267
  const results = [];
260
268
  for (const rawUrl of pack.urls) {
261
269
  const url = normalizeUrl(rawUrl, options);
@@ -264,9 +272,11 @@ async function warmAssetPack(pack, options = {}) {
264
272
  const request = new Request(url, {
265
273
  method: "GET",
266
274
  credentials: "same-origin",
267
- cache: "reload"
275
+ cache: "reload",
276
+ signal: options.signal
268
277
  });
269
278
  const response = await fetchImpl(request);
279
+ options.signal?.throwIfAborted();
270
280
  if (!response.ok) {
271
281
  const existing = await cache.match(url);
272
282
  results.push({
@@ -284,6 +294,7 @@ async function warmAssetPack(pack, options = {}) {
284
294
  await cache.put(url, response.clone());
285
295
  results.push({ url, cached: true });
286
296
  } catch (error) {
297
+ options.signal?.throwIfAborted();
287
298
  const existing = await cache.match(url);
288
299
  const isOffline = typeof globalThis.navigator !== "undefined" && globalThis.navigator.onLine === false;
289
300
  results.push({
@@ -408,7 +419,11 @@ function createOfflineCacheWorkerScript(options) {
408
419
  options.cachePrefix ?? DEFAULT_OFFLINE_CACHE_PREFIX
409
420
  );
410
421
  const buildId = sanitizeCacheSegment(options.buildId);
411
- const policyJson = JSON.stringify(options.policy);
422
+ const policyJson = JSON.stringify({
423
+ ...options.policy,
424
+ immutableAssetPathPatterns: options.policy.immutableAssetPathPatterns?.map((pattern) => ({ source: pattern.source, flags: pattern.flags })),
425
+ deniedPathPatterns: options.policy.deniedPathPatterns?.map((pattern) => ({ source: pattern.source, flags: pattern.flags }))
426
+ });
412
427
  const fallbackUrl = JSON.stringify(options.navigationFallbackUrl ?? "/");
413
428
  return `
414
429
  const CACHE_PREFIX = ${JSON.stringify(cachePrefix)};
@@ -417,9 +432,31 @@ const APP_CACHE = CACHE_PREFIX + "-app-" + BUILD_ID;
417
432
  const PUBLIC_CACHE = CACHE_PREFIX + "-public-" + BUILD_ID;
418
433
  const POLICY = ${policyJson};
419
434
  const NAVIGATION_FALLBACK_URL = ${fallbackUrl};
435
+ const REQUIRE_CONSENT = ${options.requireConsent === true};
436
+ let permissionUntil = REQUIRE_CONSENT ? 0 : Infinity;
437
+ let permissionGeneration = 0;
438
+ const permitted = (generation) => generation === permissionGeneration && Date.now() < permissionUntil;
439
+ async function discardCaches() {
440
+ const names = await caches.keys();
441
+ await Promise.all(names.filter(name => name.startsWith(CACHE_PREFIX + "-")).map(name => caches.delete(name)));
442
+ }
443
+ self.addEventListener("message", event => {
444
+ if (!REQUIRE_CONSENT || event.data?.type !== "plasius-offline-consent-v1") return;
445
+ try { if (new URL(event.source?.url).origin !== self.location.origin) return; } catch { return; }
446
+ const requested = event.data.allowedUntil;
447
+ permissionUntil = typeof requested === "number" && Number.isFinite(requested)
448
+ ? Math.min(requested, Date.now() + 60_000) : 0;
449
+ const disabled = permissionUntil <= Date.now();
450
+ if (disabled) permissionGeneration++;
451
+ event.waitUntil((async () => {
452
+ if (disabled) await discardCaches();
453
+ event.ports?.[0]?.postMessage({ type: "plasius-offline-consent-v1", disabled });
454
+ })());
455
+ });
420
456
 
421
457
  const startsWithAny = (pathname, prefixes = []) => prefixes.some((prefix) => pathname === prefix || pathname.startsWith(prefix));
422
- const isDenied = (pathname) => startsWithAny(pathname, POLICY.deniedPathPrefixes || []);
458
+ const matchesAny = (pathname, patterns = []) => patterns.some(pattern => new RegExp(pattern.source, pattern.flags).test(pathname));
459
+ const isDenied = (pathname) => startsWithAny(pathname, POLICY.deniedPathPrefixes || []) || matchesAny(pathname, POLICY.deniedPathPatterns);
423
460
  const hasNoStore = (headers) => (headers.get("cache-control") || "").split(",").some((directive) => directive.trim().split("=", 1)[0].toLowerCase() === "no-store");
424
461
  const classify = (request) => {
425
462
  if (request.method !== "GET" && request.method !== "HEAD") return { cacheable: false, strategy: "no-cache" };
@@ -427,6 +464,7 @@ const classify = (request) => {
427
464
  const url = new URL(request.url);
428
465
  if (POLICY.sameOriginOnly !== false && url.origin !== self.location.origin) return { cacheable: false, strategy: "no-cache" };
429
466
  if (isDenied(url.pathname)) return { cacheable: false, strategy: "no-cache" };
467
+ if (matchesAny(url.pathname, POLICY.immutableAssetPathPatterns)) return { cacheable: true, strategy: "cache-first", cacheName: PUBLIC_CACHE };
430
468
  if (startsWithAny(url.pathname, POLICY.publicApiPathPrefixes || [])) return { cacheable: true, strategy: "stale-while-revalidate", cacheName: PUBLIC_CACHE };
431
469
  if (startsWithAny(url.pathname, POLICY.publicAssetPathPrefixes || [])) return { cacheable: true, strategy: "stale-while-revalidate", cacheName: PUBLIC_CACHE };
432
470
  if (startsWithAny(url.pathname, POLICY.immutableAssetPathPrefixes || [])) return { cacheable: true, strategy: "cache-first", cacheName: APP_CACHE };
@@ -446,52 +484,75 @@ self.addEventListener("activate", (event) => {
446
484
  })());
447
485
  });
448
486
 
449
- async function cacheFirst(request, cacheName) {
487
+ async function openPermittedCache(cacheName, generation) {
488
+ if (!permitted(generation)) return null;
450
489
  const cache = await caches.open(cacheName);
490
+ if (!permitted(generation)) {
491
+ await caches.delete(cacheName);
492
+ return null;
493
+ }
494
+ return cache;
495
+ }
496
+
497
+ async function cacheFirst(request, cacheName, generation) {
498
+ const cache = await openPermittedCache(cacheName, generation);
499
+ if (!cache) return fetch(request);
451
500
  const cached = await cache.match(request);
501
+ if (!permitted(generation)) return fetch(request);
452
502
  if (cached && !hasNoStore(cached.headers)) return cached;
453
503
  if (cached) await cache.delete(request);
454
504
  const response = await fetch(request);
505
+ if (!permitted(generation)) return response;
455
506
  if (response.ok && !hasNoStore(response.headers)) await cache.put(request, response.clone());
456
507
  if (hasNoStore(response.headers)) await cache.delete(request);
457
508
  return response;
458
509
  }
459
510
 
460
- async function staleWhileRevalidate(request, cacheName) {
461
- const cache = await caches.open(cacheName);
511
+ async function staleWhileRevalidate(request, cacheName, generation) {
512
+ const cache = await openPermittedCache(cacheName, generation);
513
+ if (!cache) return fetch(request);
462
514
  const candidate = await cache.match(request);
515
+ if (!permitted(generation)) return fetch(request);
463
516
  const cached = candidate && !hasNoStore(candidate.headers) ? candidate : undefined;
464
517
  if (candidate && !cached) await cache.delete(request);
465
- const refresh = fetch(request).then((response) => {
466
- if (response.ok && !hasNoStore(response.headers)) cache.put(request, response.clone());
467
- if (hasNoStore(response.headers)) cache.delete(request);
518
+ const refresh = fetch(request).then(async response => {
519
+ if (!permitted(generation)) return response;
520
+ if (response.ok && !hasNoStore(response.headers)) await cache.put(request, response.clone());
521
+ if (hasNoStore(response.headers)) await cache.delete(request);
468
522
  return response;
469
523
  });
524
+ if (cached) void refresh.catch(() => undefined);
470
525
  return cached || refresh;
471
526
  }
472
527
 
473
- async function networkFirst(request, cacheName) {
474
- const cache = await caches.open(cacheName);
528
+ async function networkFirst(request, cacheName, generation) {
529
+ const cache = await openPermittedCache(cacheName, generation);
530
+ if (!cache) return fetch(request);
475
531
  try {
476
532
  const response = await fetch(request);
533
+ if (!permitted(generation)) return response;
477
534
  if (response.ok && !hasNoStore(response.headers)) await cache.put(request, response.clone());
478
535
  if (hasNoStore(response.headers)) await cache.delete(request);
479
536
  return response;
480
- } catch (error) {
537
+ } catch {
538
+ if (!permitted(generation)) return Response.error();
481
539
  const cached = await cache.match(request);
540
+ if (!permitted(generation)) return Response.error();
482
541
  if (cached && !hasNoStore(cached.headers)) return cached;
483
542
  if (cached) await cache.delete(request);
484
543
  const fallback = await cache.match(NAVIGATION_FALLBACK_URL);
485
- return fallback && !hasNoStore(fallback.headers) ? fallback : Response.error();
544
+ return permitted(generation) && fallback && !hasNoStore(fallback.headers) ? fallback : Response.error();
486
545
  }
487
546
  }
488
547
 
489
548
  self.addEventListener("fetch", (event) => {
549
+ const generation = permissionGeneration;
550
+ if (!permitted(generation)) return;
490
551
  const decision = classify(event.request);
491
552
  if (!decision.cacheable) return;
492
- if (decision.strategy === "cache-first") event.respondWith(cacheFirst(event.request, decision.cacheName));
493
- if (decision.strategy === "stale-while-revalidate") event.respondWith(staleWhileRevalidate(event.request, decision.cacheName));
494
- if (decision.strategy === "network-first") event.respondWith(networkFirst(event.request, decision.cacheName));
553
+ if (decision.strategy === "cache-first") event.respondWith(cacheFirst(event.request, decision.cacheName, generation));
554
+ if (decision.strategy === "stale-while-revalidate") event.respondWith(staleWhileRevalidate(event.request, decision.cacheName, generation));
555
+ if (decision.strategy === "network-first") event.respondWith(networkFirst(event.request, decision.cacheName, generation));
495
556
  });
496
557
  `.trimStart();
497
558
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["export type OfflineCacheStatus =\n | \"unsupported\"\n | \"idle\"\n | \"warming\"\n | \"ready\"\n | \"partial\"\n | \"quota-risk\"\n | \"offline\"\n | \"error\";\n\nexport type OfflineCacheStrategy =\n | \"cache-first\"\n | \"stale-while-revalidate\"\n | \"network-first\"\n | \"no-cache\";\n\nexport interface OfflineCacheLogger {\n debug?: (...args: unknown[]) => void;\n info?: (...args: unknown[]) => void;\n warn?: (...args: unknown[]) => void;\n error?: (...args: unknown[]) => void;\n}\n\nexport interface OfflineCacheAssetPack {\n readonly id: string;\n readonly revision: string;\n readonly urls: readonly string[];\n readonly estimatedBytes?: number;\n}\n\nexport interface OfflineCacheUrlResult {\n readonly url: string;\n readonly cached: boolean;\n readonly error?: string;\n}\n\nexport interface OfflineCacheAssetPackResult {\n readonly id: string;\n readonly revision: string;\n readonly status: OfflineCacheStatus;\n readonly cacheName?: string;\n readonly cachedUrls: number;\n readonly totalUrls: number;\n readonly results: OfflineCacheUrlResult[];\n readonly estimatedBytes?: number;\n readonly availableBytes?: number;\n readonly error?: string;\n}\n\nexport interface OfflineCacheRequestPolicy {\n readonly sameOriginOnly?: boolean;\n readonly publicNavigationPaths?: readonly string[];\n readonly immutableAssetPathPrefixes?: readonly string[];\n readonly publicAssetPathPrefixes?: readonly string[];\n readonly publicApiPathPrefixes?: readonly string[];\n readonly deniedPathPrefixes?: readonly string[];\n readonly deniedPathPatterns?: readonly RegExp[];\n}\n\nexport interface OfflineCacheRequestDecision {\n readonly cacheable: boolean;\n readonly strategy: OfflineCacheStrategy;\n readonly reason: string;\n readonly cacheBucket?: \"navigation\" | \"immutable\" | \"public-asset\" | \"public-api\";\n}\n\nexport interface RegisterOfflineCacheWorkerOptions {\n readonly workerUrl?: string;\n readonly scope?: string;\n readonly buildId?: string;\n readonly enabled?: boolean;\n readonly logger?: OfflineCacheLogger;\n readonly serviceWorkerContainer?: ServiceWorkerContainer;\n}\n\nexport interface RegisterOfflineCacheWorkerResult {\n readonly status: \"registered\" | \"unsupported\" | \"disabled\" | \"error\";\n readonly registration?: ServiceWorkerRegistration;\n readonly error?: unknown;\n}\n\nexport interface OfflineCacheRuntime {\n readonly caches?: CacheStorage;\n readonly fetch?: typeof fetch;\n readonly location?: Pick<Location, \"origin\">;\n readonly navigatorStorage?: StorageManager;\n}\n\nexport interface OfflineCacheOperationOptions extends OfflineCacheRuntime {\n readonly cachePrefix?: string;\n readonly logger?: OfflineCacheLogger;\n readonly quotaRiskRatio?: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface OfflineCacheWorkerScriptOptions {\n readonly cachePrefix?: string;\n readonly buildId: string;\n readonly policy: OfflineCacheRequestPolicy;\n readonly navigationFallbackUrl?: string;\n}\n\nexport const DEFAULT_OFFLINE_CACHE_PREFIX = \"plasius-offline\";\n\nexport const DEFAULT_OFFLINE_CACHE_POLICY: Required<\n Pick<\n OfflineCacheRequestPolicy,\n | \"sameOriginOnly\"\n | \"publicNavigationPaths\"\n | \"immutableAssetPathPrefixes\"\n | \"publicAssetPathPrefixes\"\n | \"publicApiPathPrefixes\"\n | \"deniedPathPrefixes\"\n >\n> & Pick<OfflineCacheRequestPolicy, \"deniedPathPatterns\"> = Object.freeze({\n sameOriginOnly: true,\n publicNavigationPaths: Object.freeze([\"/\"]),\n immutableAssetPathPrefixes: Object.freeze([\"/assets/\", \"/favicon\", \"/manifest.json\"]),\n publicAssetPathPrefixes: Object.freeze([]),\n publicApiPathPrefixes: Object.freeze([]),\n deniedPathPrefixes: Object.freeze([\n \"/api/admin\",\n \"/api/ai\",\n \"/api/analytics\",\n \"/api/auth\",\n \"/api/game\",\n \"/api/oauth\",\n \"/api/player-system\",\n \"/api/profile\",\n \"/api/users\",\n \"/api/voice\",\n \"/admin\",\n \"/oauth\",\n \"/profile\",\n \"/player-system\",\n ]),\n deniedPathPatterns: Object.freeze([]),\n});\n\nconst SAFE_CACHE_SEGMENT_PATTERN = /[^a-z0-9._-]+/giu;\nconst DEFAULT_QUOTA_RISK_RATIO = 0.9;\n\nfunction sanitizeCacheSegment(value: string): string {\n const sanitized = value\n .trim()\n .toLowerCase()\n .replace(SAFE_CACHE_SEGMENT_PATTERN, \"-\")\n .replace(/^-+|-+$/gu, \"\");\n return sanitized || \"default\";\n}\n\nfunction resolveCacheStorage(runtime?: OfflineCacheRuntime): CacheStorage | undefined {\n return runtime?.caches ?? globalThis.caches;\n}\n\nfunction resolveFetch(runtime?: OfflineCacheRuntime): typeof fetch | undefined {\n return runtime?.fetch ?? globalThis.fetch;\n}\n\nfunction resolveNavigatorStorage(\n runtime?: OfflineCacheRuntime,\n): StorageManager | undefined {\n return runtime?.navigatorStorage ?? globalThis.navigator?.storage;\n}\n\nfunction resolveBaseOrigin(runtime?: OfflineCacheRuntime): string {\n return runtime?.location?.origin ?? globalThis.location?.origin ?? \"https://plasius.co.uk\";\n}\n\nfunction normalizeUrl(value: string, runtime?: OfflineCacheRuntime): string {\n return new URL(value, resolveBaseOrigin(runtime)).toString();\n}\n\nfunction toUrl(input: RequestInfo | URL, runtime?: OfflineCacheRuntime): URL | null {\n try {\n if (typeof input === \"string\") {\n return new URL(input, resolveBaseOrigin(runtime));\n }\n\n if (input instanceof URL) {\n return input;\n }\n\n const requestUrl = (input as Request).url;\n return typeof requestUrl === \"string\"\n ? new URL(requestUrl, resolveBaseOrigin(runtime))\n : null;\n } catch {\n return null;\n }\n}\n\nfunction getRequestMethod(input: RequestInfo | URL, init?: RequestInit): string {\n return (init?.method ?? (typeof input === \"object\" && \"method\" in input ? input.method : \"GET\"))\n .toString()\n .toUpperCase();\n}\n\nfunction hasNoStore(headers: Headers): boolean {\n return (headers.get(\"cache-control\") ?? \"\")\n .split(\",\")\n .some(directive => directive.trim().split(\"=\", 1)[0]?.toLowerCase() === \"no-store\");\n}\n\nfunction getRequestHeaders(input: RequestInfo | URL, init?: RequestInit): Headers {\n if (init?.headers) return new Headers(init.headers);\n return typeof input === \"object\" && \"headers\" in input ? new Headers(input.headers) : new Headers();\n}\n\nfunction pathStartsWith(pathname: string, prefixes: readonly string[] = []): boolean {\n return prefixes.some(prefix => pathname === prefix || pathname.startsWith(prefix));\n}\n\nfunction isNavigationRequest(input: RequestInfo | URL, init?: RequestInit): boolean {\n if (init?.headers) {\n const headers = new Headers(init.headers);\n if (headers.get(\"accept\")?.includes(\"text/html\")) {\n return true;\n }\n }\n\n return typeof input === \"object\" && \"mode\" in input && input.mode === \"navigate\";\n}\n\nexport function buildOfflineAssetCacheName(\n pack: Pick<OfflineCacheAssetPack, \"id\" | \"revision\">,\n cachePrefix = DEFAULT_OFFLINE_CACHE_PREFIX,\n): string {\n return [\n sanitizeCacheSegment(cachePrefix),\n \"asset-pack\",\n sanitizeCacheSegment(pack.id),\n sanitizeCacheSegment(pack.revision),\n ].join(\"-\");\n}\n\nexport function classifyOfflineCacheRequest(\n input: RequestInfo | URL,\n init?: RequestInit,\n policy: OfflineCacheRequestPolicy = DEFAULT_OFFLINE_CACHE_POLICY,\n runtime?: OfflineCacheRuntime,\n): OfflineCacheRequestDecision {\n const method = getRequestMethod(input, init);\n if (method !== \"GET\" && method !== \"HEAD\") {\n return { cacheable: false, strategy: \"no-cache\", reason: \"non-get-request\" };\n }\n if (hasNoStore(getRequestHeaders(input, init))) {\n return { cacheable: false, strategy: \"no-cache\", reason: \"request-cache-control-no-store\" };\n }\n\n const url = toUrl(input, runtime);\n if (!url) {\n return { cacheable: false, strategy: \"no-cache\", reason: \"invalid-url\" };\n }\n\n const sameOriginOnly = policy.sameOriginOnly ?? DEFAULT_OFFLINE_CACHE_POLICY.sameOriginOnly;\n if (sameOriginOnly && url.origin !== resolveBaseOrigin(runtime)) {\n return { cacheable: false, strategy: \"no-cache\", reason: \"cross-origin\" };\n }\n\n const pathname = url.pathname;\n if ((policy.deniedPathPatterns ?? []).some(pattern => pattern.test(pathname))) {\n return { cacheable: false, strategy: \"no-cache\", reason: \"denied-path-pattern\" };\n }\n\n if (\n pathStartsWith(\n pathname,\n policy.deniedPathPrefixes ?? DEFAULT_OFFLINE_CACHE_POLICY.deniedPathPrefixes,\n )\n ) {\n return { cacheable: false, strategy: \"no-cache\", reason: \"denied-path-prefix\" };\n }\n\n if (pathStartsWith(pathname, policy.publicApiPathPrefixes)) {\n return {\n cacheable: true,\n strategy: \"stale-while-revalidate\",\n reason: \"public-api\",\n cacheBucket: \"public-api\",\n };\n }\n\n if (pathStartsWith(pathname, policy.publicAssetPathPrefixes)) {\n return {\n cacheable: true,\n strategy: \"stale-while-revalidate\",\n reason: \"public-asset\",\n cacheBucket: \"public-asset\",\n };\n }\n\n if (\n pathStartsWith(\n pathname,\n policy.immutableAssetPathPrefixes\n ?? DEFAULT_OFFLINE_CACHE_POLICY.immutableAssetPathPrefixes,\n )\n ) {\n return {\n cacheable: true,\n strategy: \"cache-first\",\n reason: \"immutable-asset\",\n cacheBucket: \"immutable\",\n };\n }\n\n if (\n isNavigationRequest(input, init)\n && (policy.publicNavigationPaths ?? DEFAULT_OFFLINE_CACHE_POLICY.publicNavigationPaths)\n .includes(pathname)\n ) {\n return {\n cacheable: true,\n strategy: \"network-first\",\n reason: \"public-navigation\",\n cacheBucket: \"navigation\",\n };\n }\n\n return { cacheable: false, strategy: \"no-cache\", reason: \"unmatched\" };\n}\n\nasync function resolveAvailableBytes(\n pack: OfflineCacheAssetPack,\n options: OfflineCacheOperationOptions,\n): Promise<number | undefined> {\n if (typeof pack.estimatedBytes !== \"number\" || pack.estimatedBytes <= 0) {\n return undefined;\n }\n\n try {\n const estimate = await resolveNavigatorStorage(options)?.estimate?.();\n if (\n typeof estimate?.quota !== \"number\"\n || typeof estimate.usage !== \"number\"\n || estimate.quota <= estimate.usage\n ) {\n return undefined;\n }\n\n return estimate.quota - estimate.usage;\n } catch (error) {\n options.logger?.debug?.(\"offline cache quota estimate unavailable\", { error });\n return undefined;\n }\n}\n\nfunction resultStatus(results: readonly OfflineCacheUrlResult[]): OfflineCacheStatus {\n const cachedCount = results.filter(result => result.cached).length;\n if (cachedCount === results.length) {\n return \"ready\";\n }\n if (cachedCount > 0) {\n return \"partial\";\n }\n if (results.some(result => result.error === \"offline\")) {\n return \"offline\";\n }\n return \"error\";\n}\n\nexport async function warmAssetPack(\n pack: OfflineCacheAssetPack,\n options: OfflineCacheOperationOptions = {},\n): Promise<OfflineCacheAssetPackResult> {\n const cacheStorage = resolveCacheStorage(options);\n const fetchImpl = resolveFetch(options);\n const totalUrls = pack.urls.length;\n const cacheName = buildOfflineAssetCacheName(pack, options.cachePrefix);\n\n if (!cacheStorage || typeof fetchImpl !== \"function\") {\n return {\n id: pack.id,\n revision: pack.revision,\n status: \"unsupported\",\n cachedUrls: 0,\n totalUrls,\n results: [],\n estimatedBytes: pack.estimatedBytes,\n };\n }\n\n if (totalUrls === 0) {\n return {\n id: pack.id,\n revision: pack.revision,\n status: \"idle\",\n cacheName,\n cachedUrls: 0,\n totalUrls,\n results: [],\n estimatedBytes: pack.estimatedBytes,\n };\n }\n\n const availableBytes = await resolveAvailableBytes(pack, options);\n const riskRatio = options.quotaRiskRatio ?? DEFAULT_QUOTA_RISK_RATIO;\n if (\n typeof availableBytes === \"number\"\n && typeof pack.estimatedBytes === \"number\"\n && pack.estimatedBytes > availableBytes * riskRatio\n ) {\n return {\n id: pack.id,\n revision: pack.revision,\n status: \"quota-risk\",\n cacheName,\n cachedUrls: 0,\n totalUrls,\n results: [],\n estimatedBytes: pack.estimatedBytes,\n availableBytes,\n };\n }\n\n const cache = await cacheStorage.open(cacheName);\n const results: OfflineCacheUrlResult[] = [];\n\n for (const rawUrl of pack.urls) {\n const url = normalizeUrl(rawUrl, options);\n try {\n options.signal?.throwIfAborted();\n const request = new Request(url, {\n method: \"GET\",\n credentials: \"same-origin\",\n cache: \"reload\",\n });\n const response = await fetchImpl(request);\n if (!response.ok) {\n const existing = await cache.match(url);\n results.push({\n url,\n cached: Boolean(existing),\n error: existing ? undefined : `http-${response.status}`,\n });\n continue;\n }\n\n if (hasNoStore(response.headers)) {\n await cache.delete(url);\n results.push({ url, cached: false, error: \"cache-control-no-store\" });\n continue;\n }\n\n await cache.put(url, response.clone());\n results.push({ url, cached: true });\n } catch (error) {\n const existing = await cache.match(url);\n const isOffline =\n typeof globalThis.navigator !== \"undefined\" && globalThis.navigator.onLine === false;\n results.push({\n url,\n cached: Boolean(existing),\n error: existing ? undefined : isOffline ? \"offline\" : String(error),\n });\n }\n }\n\n return {\n id: pack.id,\n revision: pack.revision,\n status: resultStatus(results),\n cacheName,\n cachedUrls: results.filter(result => result.cached).length,\n totalUrls,\n results,\n estimatedBytes: pack.estimatedBytes,\n availableBytes,\n };\n}\n\nexport async function getAssetPackStatus(\n pack: OfflineCacheAssetPack,\n options: OfflineCacheOperationOptions = {},\n): Promise<OfflineCacheAssetPackResult> {\n const cacheStorage = resolveCacheStorage(options);\n const totalUrls = pack.urls.length;\n const cacheName = buildOfflineAssetCacheName(pack, options.cachePrefix);\n\n if (!cacheStorage) {\n return {\n id: pack.id,\n revision: pack.revision,\n status: \"unsupported\",\n cachedUrls: 0,\n totalUrls,\n results: [],\n estimatedBytes: pack.estimatedBytes,\n };\n }\n\n if (totalUrls === 0) {\n return {\n id: pack.id,\n revision: pack.revision,\n status: \"idle\",\n cacheName,\n cachedUrls: 0,\n totalUrls,\n results: [],\n estimatedBytes: pack.estimatedBytes,\n };\n }\n\n const cache = await cacheStorage.open(cacheName);\n const results = await Promise.all(\n pack.urls.map(async rawUrl => {\n const url = normalizeUrl(rawUrl, options);\n return {\n url,\n cached: Boolean(await cache.match(url)),\n };\n }),\n );\n\n return {\n id: pack.id,\n revision: pack.revision,\n status: resultStatus(results),\n cacheName,\n cachedUrls: results.filter(result => result.cached).length,\n totalUrls,\n results,\n estimatedBytes: pack.estimatedBytes,\n };\n}\n\nexport async function clearOfflineCaches(options: {\n readonly cachePrefix?: string;\n readonly caches?: CacheStorage;\n} = {}): Promise<string[]> {\n const cacheStorage = options.caches ?? globalThis.caches;\n if (!cacheStorage) {\n return [];\n }\n\n const prefix = sanitizeCacheSegment(options.cachePrefix ?? DEFAULT_OFFLINE_CACHE_PREFIX);\n const cacheNames = await cacheStorage.keys();\n const deleted: string[] = [];\n for (const cacheName of cacheNames) {\n if (cacheName.startsWith(prefix) && await cacheStorage.delete(cacheName)) {\n deleted.push(cacheName);\n }\n }\n return deleted;\n}\n\nexport async function registerOfflineCacheWorker(\n options: RegisterOfflineCacheWorkerOptions = {},\n): Promise<RegisterOfflineCacheWorkerResult> {\n if (options.enabled === false) {\n return { status: \"disabled\" };\n }\n\n const serviceWorkerContainer =\n options.serviceWorkerContainer ?? globalThis.navigator?.serviceWorker;\n if (!serviceWorkerContainer) {\n return { status: \"unsupported\" };\n }\n\n const workerUrl = new URL(\n options.workerUrl ?? \"/offline-cache-worker.js\",\n globalThis.location?.origin ?? \"https://plasius.co.uk\",\n );\n if (options.buildId) {\n workerUrl.searchParams.set(\"build\", options.buildId);\n }\n\n try {\n const registration = await serviceWorkerContainer.register(workerUrl.toString(), {\n scope: options.scope ?? \"/\",\n });\n options.logger?.info?.(\"offline cache worker registered\", {\n workerUrl: workerUrl.pathname,\n scope: registration.scope,\n });\n return {\n status: \"registered\",\n registration,\n };\n } catch (error) {\n options.logger?.warn?.(\"offline cache worker registration failed\", { error });\n return {\n status: \"error\",\n error,\n };\n }\n}\n\nexport function createOfflineCacheWorkerScript(\n options: OfflineCacheWorkerScriptOptions,\n): string {\n const cachePrefix = sanitizeCacheSegment(\n options.cachePrefix ?? DEFAULT_OFFLINE_CACHE_PREFIX,\n );\n const buildId = sanitizeCacheSegment(options.buildId);\n const policyJson = JSON.stringify(options.policy);\n const fallbackUrl = JSON.stringify(options.navigationFallbackUrl ?? \"/\");\n\n return `\nconst CACHE_PREFIX = ${JSON.stringify(cachePrefix)};\nconst BUILD_ID = ${JSON.stringify(buildId)};\nconst APP_CACHE = CACHE_PREFIX + \"-app-\" + BUILD_ID;\nconst PUBLIC_CACHE = CACHE_PREFIX + \"-public-\" + BUILD_ID;\nconst POLICY = ${policyJson};\nconst NAVIGATION_FALLBACK_URL = ${fallbackUrl};\n\nconst startsWithAny = (pathname, prefixes = []) => prefixes.some((prefix) => pathname === prefix || pathname.startsWith(prefix));\nconst isDenied = (pathname) => startsWithAny(pathname, POLICY.deniedPathPrefixes || []);\nconst hasNoStore = (headers) => (headers.get(\"cache-control\") || \"\").split(\",\").some((directive) => directive.trim().split(\"=\", 1)[0].toLowerCase() === \"no-store\");\nconst classify = (request) => {\n if (request.method !== \"GET\" && request.method !== \"HEAD\") return { cacheable: false, strategy: \"no-cache\" };\n if (hasNoStore(request.headers)) return { cacheable: false, strategy: \"no-cache\", reason: \"request-cache-control-no-store\" };\n const url = new URL(request.url);\n if (POLICY.sameOriginOnly !== false && url.origin !== self.location.origin) return { cacheable: false, strategy: \"no-cache\" };\n if (isDenied(url.pathname)) return { cacheable: false, strategy: \"no-cache\" };\n if (startsWithAny(url.pathname, POLICY.publicApiPathPrefixes || [])) return { cacheable: true, strategy: \"stale-while-revalidate\", cacheName: PUBLIC_CACHE };\n if (startsWithAny(url.pathname, POLICY.publicAssetPathPrefixes || [])) return { cacheable: true, strategy: \"stale-while-revalidate\", cacheName: PUBLIC_CACHE };\n if (startsWithAny(url.pathname, POLICY.immutableAssetPathPrefixes || [])) return { cacheable: true, strategy: \"cache-first\", cacheName: APP_CACHE };\n if (request.mode === \"navigate\" && (POLICY.publicNavigationPaths || []).includes(url.pathname)) return { cacheable: true, strategy: \"network-first\", cacheName: APP_CACHE };\n return { cacheable: false, strategy: \"no-cache\" };\n};\n\nself.addEventListener(\"install\", (event) => {\n event.waitUntil(self.skipWaiting());\n});\n\nself.addEventListener(\"activate\", (event) => {\n event.waitUntil((async () => {\n const names = await caches.keys();\n await Promise.all(names.filter((name) => name.startsWith(CACHE_PREFIX + \"-\") && !name.endsWith(\"-\" + BUILD_ID) && !name.includes(\"-asset-pack-\")).map((name) => caches.delete(name)));\n await self.clients.claim();\n })());\n});\n\nasync function cacheFirst(request, cacheName) {\n const cache = await caches.open(cacheName);\n const cached = await cache.match(request);\n if (cached && !hasNoStore(cached.headers)) return cached;\n if (cached) await cache.delete(request);\n const response = await fetch(request);\n if (response.ok && !hasNoStore(response.headers)) await cache.put(request, response.clone());\n if (hasNoStore(response.headers)) await cache.delete(request);\n return response;\n}\n\nasync function staleWhileRevalidate(request, cacheName) {\n const cache = await caches.open(cacheName);\n const candidate = await cache.match(request);\n const cached = candidate && !hasNoStore(candidate.headers) ? candidate : undefined;\n if (candidate && !cached) await cache.delete(request);\n const refresh = fetch(request).then((response) => {\n if (response.ok && !hasNoStore(response.headers)) cache.put(request, response.clone());\n if (hasNoStore(response.headers)) cache.delete(request);\n return response;\n });\n return cached || refresh;\n}\n\nasync function networkFirst(request, cacheName) {\n const cache = await caches.open(cacheName);\n try {\n const response = await fetch(request);\n if (response.ok && !hasNoStore(response.headers)) await cache.put(request, response.clone());\n if (hasNoStore(response.headers)) await cache.delete(request);\n return response;\n } catch (error) {\n const cached = await cache.match(request);\n if (cached && !hasNoStore(cached.headers)) return cached;\n if (cached) await cache.delete(request);\n const fallback = await cache.match(NAVIGATION_FALLBACK_URL);\n return fallback && !hasNoStore(fallback.headers) ? fallback : Response.error();\n }\n}\n\nself.addEventListener(\"fetch\", (event) => {\n const decision = classify(event.request);\n if (!decision.cacheable) return;\n if (decision.strategy === \"cache-first\") event.respondWith(cacheFirst(event.request, decision.cacheName));\n if (decision.strategy === \"stale-while-revalidate\") event.respondWith(staleWhileRevalidate(event.request, decision.cacheName));\n if (decision.strategy === \"network-first\") event.respondWith(networkFirst(event.request, decision.cacheName));\n});\n`.trimStart();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAsGO,IAAM,+BAA+B;AAErC,IAAM,+BAU+C,OAAO,OAAO;AAAA,EACxE,gBAAgB;AAAA,EAChB,uBAAuB,OAAO,OAAO,CAAC,GAAG,CAAC;AAAA,EAC1C,4BAA4B,OAAO,OAAO,CAAC,YAAY,YAAY,gBAAgB,CAAC;AAAA,EACpF,yBA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A;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA6E3C,UAAU;AACZ;","names":[]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["export type OfflineCacheStatus =\n | \"unsupported\"\n | \"idle\"\n | \"warming\"\n | \"ready\"\n | \"partial\"\n | \"quota-risk\"\n | \"offline\"\n | \"error\";\n\nexport type OfflineCacheStrategy =\n | \"cache-first\"\n | \"stale-while-revalidate\"\n | \"network-first\"\n | \"no-cache\";\n\nexport interface OfflineCacheLogger {\n debug?: (...args: unknown[]) => void;\n info?: (...args: unknown[]) => void;\n warn?: (...args: unknown[]) => void;\n error?: (...args: unknown[]) => void;\n}\n\nexport interface OfflineCacheAssetPack {\n readonly id: string;\n readonly revision: string;\n readonly urls: readonly string[];\n readonly estimatedBytes?: number;\n}\n\nexport interface OfflineCacheUrlResult {\n readonly url: string;\n readonly cached: boolean;\n readonly error?: string;\n}\n\nexport interface OfflineCacheAssetPackResult {\n readonly id: string;\n readonly revision: string;\n readonly status: OfflineCacheStatus;\n readonly cacheName?: string;\n readonly cachedUrls: number;\n readonly totalUrls: number;\n readonly results: OfflineCacheUrlResult[];\n readonly estimatedBytes?: number;\n readonly availableBytes?: number;\n readonly error?: string;\n}\n\nexport interface OfflineCacheRequestPolicy {\n readonly sameOriginOnly?: boolean;\n readonly publicNavigationPaths?: readonly string[];\n readonly immutableAssetPathPrefixes?: readonly string[];\n readonly immutableAssetPathPatterns?: readonly RegExp[];\n readonly publicAssetPathPrefixes?: readonly string[];\n readonly publicApiPathPrefixes?: readonly string[];\n readonly deniedPathPrefixes?: readonly string[];\n readonly deniedPathPatterns?: readonly RegExp[];\n}\n\nexport interface OfflineCacheRequestDecision {\n readonly cacheable: boolean;\n readonly strategy: OfflineCacheStrategy;\n readonly reason: string;\n readonly cacheBucket?: \"navigation\" | \"immutable\" | \"public-asset\" | \"public-api\";\n}\n\nexport interface RegisterOfflineCacheWorkerOptions {\n readonly workerUrl?: string;\n readonly scope?: string;\n readonly buildId?: string;\n readonly enabled?: boolean;\n readonly logger?: OfflineCacheLogger;\n readonly serviceWorkerContainer?: ServiceWorkerContainer;\n}\n\nexport interface RegisterOfflineCacheWorkerResult {\n readonly status: \"registered\" | \"unsupported\" | \"disabled\" | \"error\";\n readonly registration?: ServiceWorkerRegistration;\n readonly error?: unknown;\n}\n\nexport interface OfflineCacheRuntime {\n readonly caches?: CacheStorage;\n readonly fetch?: typeof fetch;\n readonly location?: Pick<Location, \"origin\">;\n readonly navigatorStorage?: StorageManager;\n}\n\nexport interface OfflineCacheOperationOptions extends OfflineCacheRuntime {\n readonly cachePrefix?: string;\n readonly logger?: OfflineCacheLogger;\n readonly quotaRiskRatio?: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface OfflineCacheWorkerScriptOptions {\n /** Require renewed host permission before any worker cache access (maximum 60 seconds). */\n readonly requireConsent?: boolean;\n readonly cachePrefix?: string;\n readonly buildId: string;\n readonly policy: OfflineCacheRequestPolicy;\n readonly navigationFallbackUrl?: string;\n}\n\nexport const DEFAULT_OFFLINE_CACHE_PREFIX = \"plasius-offline\";\n\nexport const DEFAULT_OFFLINE_CACHE_POLICY: Required<\n Pick<\n OfflineCacheRequestPolicy,\n | \"sameOriginOnly\"\n | \"publicNavigationPaths\"\n | \"immutableAssetPathPrefixes\"\n | \"publicAssetPathPrefixes\"\n | \"publicApiPathPrefixes\"\n | \"deniedPathPrefixes\"\n >\n> & Pick<OfflineCacheRequestPolicy, \"deniedPathPatterns\"> = Object.freeze({\n sameOriginOnly: true,\n publicNavigationPaths: Object.freeze([\"/\"]),\n immutableAssetPathPrefixes: Object.freeze([\"/assets/\", \"/favicon\", \"/manifest.json\"]),\n publicAssetPathPrefixes: Object.freeze([]),\n publicApiPathPrefixes: Object.freeze([]),\n deniedPathPrefixes: Object.freeze([\n \"/api/admin\",\n \"/api/ai\",\n \"/api/analytics\",\n \"/api/auth\",\n \"/api/game\",\n \"/api/oauth\",\n \"/api/player-system\",\n \"/api/profile\",\n \"/api/users\",\n \"/api/voice\",\n \"/admin\",\n \"/oauth\",\n \"/profile\",\n \"/player-system\",\n ]),\n deniedPathPatterns: Object.freeze([]),\n});\n\nconst SAFE_CACHE_SEGMENT_PATTERN = /[^a-z0-9._-]+/giu;\nconst DEFAULT_QUOTA_RISK_RATIO = 0.9;\n\nfunction sanitizeCacheSegment(value: string): string {\n const sanitized = value\n .trim()\n .toLowerCase()\n .replace(SAFE_CACHE_SEGMENT_PATTERN, \"-\")\n .replace(/^-+|-+$/gu, \"\");\n return sanitized || \"default\";\n}\n\nfunction resolveCacheStorage(runtime?: OfflineCacheRuntime): CacheStorage | undefined {\n return runtime?.caches ?? globalThis.caches;\n}\n\nfunction resolveFetch(runtime?: OfflineCacheRuntime): typeof fetch | undefined {\n return runtime?.fetch ?? globalThis.fetch;\n}\n\nfunction resolveNavigatorStorage(\n runtime?: OfflineCacheRuntime,\n): StorageManager | undefined {\n return runtime?.navigatorStorage ?? globalThis.navigator?.storage;\n}\n\nfunction resolveBaseOrigin(runtime?: OfflineCacheRuntime): string {\n return runtime?.location?.origin ?? globalThis.location?.origin ?? \"https://plasius.co.uk\";\n}\n\nfunction normalizeUrl(value: string, runtime?: OfflineCacheRuntime): string {\n return new URL(value, resolveBaseOrigin(runtime)).toString();\n}\n\nfunction toUrl(input: RequestInfo | URL, runtime?: OfflineCacheRuntime): URL | null {\n try {\n if (typeof input === \"string\") {\n return new URL(input, resolveBaseOrigin(runtime));\n }\n\n if (input instanceof URL) {\n return input;\n }\n\n const requestUrl = (input as Request).url;\n return typeof requestUrl === \"string\"\n ? new URL(requestUrl, resolveBaseOrigin(runtime))\n : null;\n } catch {\n return null;\n }\n}\n\nfunction getRequestMethod(input: RequestInfo | URL, init?: RequestInit): string {\n return (init?.method ?? (typeof input === \"object\" && \"method\" in input ? input.method : \"GET\"))\n .toString()\n .toUpperCase();\n}\n\nfunction hasNoStore(headers: Headers): boolean {\n return (headers.get(\"cache-control\") ?? \"\")\n .split(\",\")\n .some(directive => directive.trim().split(\"=\", 1)[0]?.toLowerCase() === \"no-store\");\n}\n\nfunction getRequestHeaders(input: RequestInfo | URL, init?: RequestInit): Headers {\n if (init?.headers) return new Headers(init.headers);\n return typeof input === \"object\" && \"headers\" in input ? new Headers(input.headers) : new Headers();\n}\n\nfunction pathStartsWith(pathname: string, prefixes: readonly string[] = []): boolean {\n return prefixes.some(prefix => pathname === prefix || pathname.startsWith(prefix));\n}\n\nfunction isNavigationRequest(input: RequestInfo | URL, init?: RequestInit): boolean {\n if (init?.headers) {\n const headers = new Headers(init.headers);\n if (headers.get(\"accept\")?.includes(\"text/html\")) {\n return true;\n }\n }\n\n return typeof input === \"object\" && \"mode\" in input && input.mode === \"navigate\";\n}\n\nexport function buildOfflineAssetCacheName(\n pack: Pick<OfflineCacheAssetPack, \"id\" | \"revision\">,\n cachePrefix = DEFAULT_OFFLINE_CACHE_PREFIX,\n): string {\n return [\n sanitizeCacheSegment(cachePrefix),\n \"asset-pack\",\n sanitizeCacheSegment(pack.id),\n sanitizeCacheSegment(pack.revision),\n ].join(\"-\");\n}\n\nexport function classifyOfflineCacheRequest(\n input: RequestInfo | URL,\n init?: RequestInit,\n policy: OfflineCacheRequestPolicy = DEFAULT_OFFLINE_CACHE_POLICY,\n runtime?: OfflineCacheRuntime,\n): OfflineCacheRequestDecision {\n const method = getRequestMethod(input, init);\n if (method !== \"GET\" && method !== \"HEAD\") {\n return { cacheable: false, strategy: \"no-cache\", reason: \"non-get-request\" };\n }\n if (hasNoStore(getRequestHeaders(input, init))) {\n return { cacheable: false, strategy: \"no-cache\", reason: \"request-cache-control-no-store\" };\n }\n\n const url = toUrl(input, runtime);\n if (!url) {\n return { cacheable: false, strategy: \"no-cache\", reason: \"invalid-url\" };\n }\n\n const sameOriginOnly = policy.sameOriginOnly ?? DEFAULT_OFFLINE_CACHE_POLICY.sameOriginOnly;\n if (sameOriginOnly && url.origin !== resolveBaseOrigin(runtime)) {\n return { cacheable: false, strategy: \"no-cache\", reason: \"cross-origin\" };\n }\n\n const pathname = url.pathname;\n if ((policy.deniedPathPatterns ?? []).some(pattern => pattern.test(pathname))) {\n return { cacheable: false, strategy: \"no-cache\", reason: \"denied-path-pattern\" };\n }\n\n if (\n pathStartsWith(\n pathname,\n policy.deniedPathPrefixes ?? DEFAULT_OFFLINE_CACHE_POLICY.deniedPathPrefixes,\n )\n ) {\n return { cacheable: false, strategy: \"no-cache\", reason: \"denied-path-prefix\" };\n }\n\n if (policy.immutableAssetPathPatterns?.some(pattern => new RegExp(pattern.source, pattern.flags).test(pathname))) {\n return { cacheable: true, strategy: \"cache-first\", reason: \"immutable-asset-pattern\", cacheBucket: \"immutable\" };\n }\n\n if (pathStartsWith(pathname, policy.publicApiPathPrefixes)) {\n return {\n cacheable: true,\n strategy: \"stale-while-revalidate\",\n reason: \"public-api\",\n cacheBucket: \"public-api\",\n };\n }\n\n if (pathStartsWith(pathname, policy.publicAssetPathPrefixes)) {\n return {\n cacheable: true,\n strategy: \"stale-while-revalidate\",\n reason: \"public-asset\",\n cacheBucket: \"public-asset\",\n };\n }\n\n if (\n pathStartsWith(\n pathname,\n policy.immutableAssetPathPrefixes\n ?? DEFAULT_OFFLINE_CACHE_POLICY.immutableAssetPathPrefixes,\n )\n ) {\n return {\n cacheable: true,\n strategy: \"cache-first\",\n reason: \"immutable-asset\",\n cacheBucket: \"immutable\",\n };\n }\n\n if (\n isNavigationRequest(input, init)\n && (policy.publicNavigationPaths ?? DEFAULT_OFFLINE_CACHE_POLICY.publicNavigationPaths)\n .includes(pathname)\n ) {\n return {\n cacheable: true,\n strategy: \"network-first\",\n reason: \"public-navigation\",\n cacheBucket: \"navigation\",\n };\n }\n\n return { cacheable: false, strategy: \"no-cache\", reason: \"unmatched\" };\n}\n\nasync function resolveAvailableBytes(\n pack: OfflineCacheAssetPack,\n options: OfflineCacheOperationOptions,\n): Promise<number | undefined> {\n if (typeof pack.estimatedBytes !== \"number\" || pack.estimatedBytes <= 0) {\n return undefined;\n }\n\n try {\n const estimate = await resolveNavigatorStorage(options)?.estimate?.();\n if (\n typeof estimate?.quota !== \"number\"\n || typeof estimate.usage !== \"number\"\n || estimate.quota <= estimate.usage\n ) {\n return undefined;\n }\n\n return estimate.quota - estimate.usage;\n } catch (error) {\n options.logger?.debug?.(\"offline cache quota estimate unavailable\", { error });\n return undefined;\n }\n}\n\nfunction resultStatus(results: readonly OfflineCacheUrlResult[]): OfflineCacheStatus {\n const cachedCount = results.filter(result => result.cached).length;\n if (cachedCount === results.length) {\n return \"ready\";\n }\n if (cachedCount > 0) {\n return \"partial\";\n }\n if (results.some(result => result.error === \"offline\")) {\n return \"offline\";\n }\n return \"error\";\n}\n\nexport async function warmAssetPack(\n pack: OfflineCacheAssetPack,\n options: OfflineCacheOperationOptions = {},\n): Promise<OfflineCacheAssetPackResult> {\n const cacheStorage = resolveCacheStorage(options);\n const fetchImpl = resolveFetch(options);\n const totalUrls = pack.urls.length;\n const cacheName = buildOfflineAssetCacheName(pack, options.cachePrefix);\n\n if (!cacheStorage || typeof fetchImpl !== \"function\") {\n return {\n id: pack.id,\n revision: pack.revision,\n status: \"unsupported\",\n cachedUrls: 0,\n totalUrls,\n results: [],\n estimatedBytes: pack.estimatedBytes,\n };\n }\n\n if (totalUrls === 0) {\n return {\n id: pack.id,\n revision: pack.revision,\n status: \"idle\",\n cacheName,\n cachedUrls: 0,\n totalUrls,\n results: [],\n estimatedBytes: pack.estimatedBytes,\n };\n }\n\n const availableBytes = await resolveAvailableBytes(pack, options);\n const riskRatio = options.quotaRiskRatio ?? DEFAULT_QUOTA_RISK_RATIO;\n if (\n typeof availableBytes === \"number\"\n && typeof pack.estimatedBytes === \"number\"\n && pack.estimatedBytes > availableBytes * riskRatio\n ) {\n return {\n id: pack.id,\n revision: pack.revision,\n status: \"quota-risk\",\n cacheName,\n cachedUrls: 0,\n totalUrls,\n results: [],\n estimatedBytes: pack.estimatedBytes,\n availableBytes,\n };\n }\n\n options.signal?.throwIfAborted();\n const cache = await cacheStorage.open(cacheName);\n if (options.signal?.aborted) {\n await cacheStorage.delete(cacheName);\n options.signal.throwIfAborted();\n }\n const results: OfflineCacheUrlResult[] = [];\n\n for (const rawUrl of pack.urls) {\n const url = normalizeUrl(rawUrl, options);\n try {\n options.signal?.throwIfAborted();\n const request = new Request(url, {\n method: \"GET\",\n credentials: \"same-origin\",\n cache: \"reload\",\n signal: options.signal,\n });\n const response = await fetchImpl(request);\n options.signal?.throwIfAborted();\n if (!response.ok) {\n const existing = await cache.match(url);\n results.push({\n url,\n cached: Boolean(existing),\n error: existing ? undefined : `http-${response.status}`,\n });\n continue;\n }\n\n if (hasNoStore(response.headers)) {\n await cache.delete(url);\n results.push({ url, cached: false, error: \"cache-control-no-store\" });\n continue;\n }\n\n await cache.put(url, response.clone());\n results.push({ url, cached: true });\n } catch (error) {\n options.signal?.throwIfAborted();\n const existing = await cache.match(url);\n const isOffline =\n typeof globalThis.navigator !== \"undefined\" && globalThis.navigator.onLine === false;\n results.push({\n url,\n cached: Boolean(existing),\n error: existing ? undefined : isOffline ? \"offline\" : String(error),\n });\n }\n }\n\n return {\n id: pack.id,\n revision: pack.revision,\n status: resultStatus(results),\n cacheName,\n cachedUrls: results.filter(result => result.cached).length,\n totalUrls,\n results,\n estimatedBytes: pack.estimatedBytes,\n availableBytes,\n };\n}\n\nexport async function getAssetPackStatus(\n pack: OfflineCacheAssetPack,\n options: OfflineCacheOperationOptions = {},\n): Promise<OfflineCacheAssetPackResult> {\n const cacheStorage = resolveCacheStorage(options);\n const totalUrls = pack.urls.length;\n const cacheName = buildOfflineAssetCacheName(pack, options.cachePrefix);\n\n if (!cacheStorage) {\n return {\n id: pack.id,\n revision: pack.revision,\n status: \"unsupported\",\n cachedUrls: 0,\n totalUrls,\n results: [],\n estimatedBytes: pack.estimatedBytes,\n };\n }\n\n if (totalUrls === 0) {\n return {\n id: pack.id,\n revision: pack.revision,\n status: \"idle\",\n cacheName,\n cachedUrls: 0,\n totalUrls,\n results: [],\n estimatedBytes: pack.estimatedBytes,\n };\n }\n\n const cache = await cacheStorage.open(cacheName);\n const results = await Promise.all(\n pack.urls.map(async rawUrl => {\n const url = normalizeUrl(rawUrl, options);\n return {\n url,\n cached: Boolean(await cache.match(url)),\n };\n }),\n );\n\n return {\n id: pack.id,\n revision: pack.revision,\n status: resultStatus(results),\n cacheName,\n cachedUrls: results.filter(result => result.cached).length,\n totalUrls,\n results,\n estimatedBytes: pack.estimatedBytes,\n };\n}\n\nexport async function clearOfflineCaches(options: {\n readonly cachePrefix?: string;\n readonly caches?: CacheStorage;\n} = {}): Promise<string[]> {\n const cacheStorage = options.caches ?? globalThis.caches;\n if (!cacheStorage) {\n return [];\n }\n\n const prefix = sanitizeCacheSegment(options.cachePrefix ?? DEFAULT_OFFLINE_CACHE_PREFIX);\n const cacheNames = await cacheStorage.keys();\n const deleted: string[] = [];\n for (const cacheName of cacheNames) {\n if (cacheName.startsWith(prefix) && await cacheStorage.delete(cacheName)) {\n deleted.push(cacheName);\n }\n }\n return deleted;\n}\n\nexport async function registerOfflineCacheWorker(\n options: RegisterOfflineCacheWorkerOptions = {},\n): Promise<RegisterOfflineCacheWorkerResult> {\n if (options.enabled === false) {\n return { status: \"disabled\" };\n }\n\n const serviceWorkerContainer =\n options.serviceWorkerContainer ?? globalThis.navigator?.serviceWorker;\n if (!serviceWorkerContainer) {\n return { status: \"unsupported\" };\n }\n\n const workerUrl = new URL(\n options.workerUrl ?? \"/offline-cache-worker.js\",\n globalThis.location?.origin ?? \"https://plasius.co.uk\",\n );\n if (options.buildId) {\n workerUrl.searchParams.set(\"build\", options.buildId);\n }\n\n try {\n const registration = await serviceWorkerContainer.register(workerUrl.toString(), {\n scope: options.scope ?? \"/\",\n });\n options.logger?.info?.(\"offline cache worker registered\", {\n workerUrl: workerUrl.pathname,\n scope: registration.scope,\n });\n return {\n status: \"registered\",\n registration,\n };\n } catch (error) {\n options.logger?.warn?.(\"offline cache worker registration failed\", { error });\n return {\n status: \"error\",\n error,\n };\n }\n}\n\nexport function createOfflineCacheWorkerScript(\n options: OfflineCacheWorkerScriptOptions,\n): string {\n const cachePrefix = sanitizeCacheSegment(\n options.cachePrefix ?? DEFAULT_OFFLINE_CACHE_PREFIX,\n );\n const buildId = sanitizeCacheSegment(options.buildId);\n const policyJson = JSON.stringify({ ...options.policy,\n immutableAssetPathPatterns: options.policy.immutableAssetPathPatterns?.map(pattern => ({ source: pattern.source, flags: pattern.flags })),\n deniedPathPatterns: options.policy.deniedPathPatterns?.map(pattern => ({ source: pattern.source, flags: pattern.flags })),\n });\n const fallbackUrl = JSON.stringify(options.navigationFallbackUrl ?? \"/\");\n\n return `\nconst CACHE_PREFIX = ${JSON.stringify(cachePrefix)};\nconst BUILD_ID = ${JSON.stringify(buildId)};\nconst APP_CACHE = CACHE_PREFIX + \"-app-\" + BUILD_ID;\nconst PUBLIC_CACHE = CACHE_PREFIX + \"-public-\" + BUILD_ID;\nconst POLICY = ${policyJson};\nconst NAVIGATION_FALLBACK_URL = ${fallbackUrl};\nconst REQUIRE_CONSENT = ${options.requireConsent === true};\nlet permissionUntil = REQUIRE_CONSENT ? 0 : Infinity;\nlet permissionGeneration = 0;\nconst permitted = (generation) => generation === permissionGeneration && Date.now() < permissionUntil;\nasync function discardCaches() {\n const names = await caches.keys();\n await Promise.all(names.filter(name => name.startsWith(CACHE_PREFIX + \"-\")).map(name => caches.delete(name)));\n}\nself.addEventListener(\"message\", event => {\n if (!REQUIRE_CONSENT || event.data?.type !== \"plasius-offline-consent-v1\") return;\n try { if (new URL(event.source?.url).origin !== self.location.origin) return; } catch { return; }\n const requested = event.data.allowedUntil;\n permissionUntil = typeof requested === \"number\" && Number.isFinite(requested)\n ? Math.min(requested, Date.now() + 60_000) : 0;\n const disabled = permissionUntil <= Date.now();\n if (disabled) permissionGeneration++;\n event.waitUntil((async () => {\n if (disabled) await discardCaches();\n event.ports?.[0]?.postMessage({ type: \"plasius-offline-consent-v1\", disabled });\n })());\n});\n\nconst startsWithAny = (pathname, prefixes = []) => prefixes.some((prefix) => pathname === prefix || pathname.startsWith(prefix));\nconst matchesAny = (pathname, patterns = []) => patterns.some(pattern => new RegExp(pattern.source, pattern.flags).test(pathname));\nconst isDenied = (pathname) => startsWithAny(pathname, POLICY.deniedPathPrefixes || []) || matchesAny(pathname, POLICY.deniedPathPatterns);\nconst hasNoStore = (headers) => (headers.get(\"cache-control\") || \"\").split(\",\").some((directive) => directive.trim().split(\"=\", 1)[0].toLowerCase() === \"no-store\");\nconst classify = (request) => {\n if (request.method !== \"GET\" && request.method !== \"HEAD\") return { cacheable: false, strategy: \"no-cache\" };\n if (hasNoStore(request.headers)) return { cacheable: false, strategy: \"no-cache\", reason: \"request-cache-control-no-store\" };\n const url = new URL(request.url);\n if (POLICY.sameOriginOnly !== false && url.origin !== self.location.origin) return { cacheable: false, strategy: \"no-cache\" };\n if (isDenied(url.pathname)) return { cacheable: false, strategy: \"no-cache\" };\n if (matchesAny(url.pathname, POLICY.immutableAssetPathPatterns)) return { cacheable: true, strategy: \"cache-first\", cacheName: PUBLIC_CACHE };\n if (startsWithAny(url.pathname, POLICY.publicApiPathPrefixes || [])) return { cacheable: true, strategy: \"stale-while-revalidate\", cacheName: PUBLIC_CACHE };\n if (startsWithAny(url.pathname, POLICY.publicAssetPathPrefixes || [])) return { cacheable: true, strategy: \"stale-while-revalidate\", cacheName: PUBLIC_CACHE };\n if (startsWithAny(url.pathname, POLICY.immutableAssetPathPrefixes || [])) return { cacheable: true, strategy: \"cache-first\", cacheName: APP_CACHE };\n if (request.mode === \"navigate\" && (POLICY.publicNavigationPaths || []).includes(url.pathname)) return { cacheable: true, strategy: \"network-first\", cacheName: APP_CACHE };\n return { cacheable: false, strategy: \"no-cache\" };\n};\n\nself.addEventListener(\"install\", (event) => {\n event.waitUntil(self.skipWaiting());\n});\n\nself.addEventListener(\"activate\", (event) => {\n event.waitUntil((async () => {\n const names = await caches.keys();\n await Promise.all(names.filter((name) => name.startsWith(CACHE_PREFIX + \"-\") && !name.endsWith(\"-\" + BUILD_ID) && !name.includes(\"-asset-pack-\")).map((name) => caches.delete(name)));\n await self.clients.claim();\n })());\n});\n\nasync function openPermittedCache(cacheName, generation) {\n if (!permitted(generation)) return null;\n const cache = await caches.open(cacheName);\n if (!permitted(generation)) {\n await caches.delete(cacheName);\n return null;\n }\n return cache;\n}\n\nasync function cacheFirst(request, cacheName, generation) {\n const cache = await openPermittedCache(cacheName, generation);\n if (!cache) return fetch(request);\n const cached = await cache.match(request);\n if (!permitted(generation)) return fetch(request);\n if (cached && !hasNoStore(cached.headers)) return cached;\n if (cached) await cache.delete(request);\n const response = await fetch(request);\n if (!permitted(generation)) return response;\n if (response.ok && !hasNoStore(response.headers)) await cache.put(request, response.clone());\n if (hasNoStore(response.headers)) await cache.delete(request);\n return response;\n}\n\nasync function staleWhileRevalidate(request, cacheName, generation) {\n const cache = await openPermittedCache(cacheName, generation);\n if (!cache) return fetch(request);\n const candidate = await cache.match(request);\n if (!permitted(generation)) return fetch(request);\n const cached = candidate && !hasNoStore(candidate.headers) ? candidate : undefined;\n if (candidate && !cached) await cache.delete(request);\n const refresh = fetch(request).then(async response => {\n if (!permitted(generation)) return response;\n if (response.ok && !hasNoStore(response.headers)) await cache.put(request, response.clone());\n if (hasNoStore(response.headers)) await cache.delete(request);\n return response;\n });\n if (cached) void refresh.catch(() => undefined);\n return cached || refresh;\n}\n\nasync function networkFirst(request, cacheName, generation) {\n const cache = await openPermittedCache(cacheName, generation);\n if (!cache) return fetch(request);\n try {\n const response = await fetch(request);\n if (!permitted(generation)) return response;\n if (response.ok && !hasNoStore(response.headers)) await cache.put(request, response.clone());\n if (hasNoStore(response.headers)) await cache.delete(request);\n return response;\n } catch {\n if (!permitted(generation)) return Response.error();\n const cached = await cache.match(request);\n if (!permitted(generation)) return Response.error();\n if (cached && !hasNoStore(cached.headers)) return cached;\n if (cached) await cache.delete(request);\n const fallback = await cache.match(NAVIGATION_FALLBACK_URL);\n return permitted(generation) && fallback && !hasNoStore(fallback.headers) ? fallback : Response.error();\n }\n}\n\nself.addEventListener(\"fetch\", (event) => {\n const generation = permissionGeneration;\n if (!permitted(generation)) return;\n const decision = classify(event.request);\n if (!decision.cacheable) return;\n if (decision.strategy === \"cache-first\") event.respondWith(cacheFirst(event.request, decision.cacheName, generation));\n if (decision.strategy === \"stale-while-revalidate\") event.respondWith(staleWhileRevalidate(event.request, decision.cacheName, generation));\n if (decision.strategy === \"network-first\") event.respondWith(networkFirst(event.request, decision.cacheName, generation));\n});\n`.trimStart();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAyGO,IAAM,+BAA+B;AAErC,IAAM,+BAU+C,OAAO,OAAO;AAAA,EACxE,gBAAgB;AAAA,EAChB,uBAAuB,OAAO,OAAO,CAAC,GAAG,CAAC;AAAA,EAC1C,4BAA4B,OAAO,OAAO,CAAC,YAAY,YAAY,gBAAgB,CAAC;AAAA,EACpF,yBAAyB,OAAO,OAAO,CAAC,CAAC;AAAA,EACzC,uBAAuB,OAAO,OAAO,CAAC,CAAC;AAAA,EACvC,oBAAoB,OAAO,OAAO;AAAA,IAChC;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,CAAC;AAAA,EACD,oBAAoB,OAAO,OAAO,CAAC,CAAC;AACtC,CAAC;AAED,IAAM,6BAA6B;AACnC,IAAM,2BAA2B;AAEjC,SAAS,qBAAqB,OAAuB;AACnD,QAAM,YAAY,MACf,KAAK,EACL,YAAY,EACZ,QAAQ,4BAA4B,GAAG,EACvC,QAAQ,aAAa,EAAE;AA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A;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA0HvD,UAAU;AACZ;","names":[]}
package/dist/index.d.cts CHANGED
@@ -33,6 +33,7 @@ interface OfflineCacheRequestPolicy {
33
33
  readonly sameOriginOnly?: boolean;
34
34
  readonly publicNavigationPaths?: readonly string[];
35
35
  readonly immutableAssetPathPrefixes?: readonly string[];
36
+ readonly immutableAssetPathPatterns?: readonly RegExp[];
36
37
  readonly publicAssetPathPrefixes?: readonly string[];
37
38
  readonly publicApiPathPrefixes?: readonly string[];
38
39
  readonly deniedPathPrefixes?: readonly string[];
@@ -70,6 +71,8 @@ interface OfflineCacheOperationOptions extends OfflineCacheRuntime {
70
71
  readonly signal?: AbortSignal;
71
72
  }
72
73
  interface OfflineCacheWorkerScriptOptions {
74
+ /** Require renewed host permission before any worker cache access (maximum 60 seconds). */
75
+ readonly requireConsent?: boolean;
73
76
  readonly cachePrefix?: string;
74
77
  readonly buildId: string;
75
78
  readonly policy: OfflineCacheRequestPolicy;
package/dist/index.d.ts CHANGED
@@ -33,6 +33,7 @@ interface OfflineCacheRequestPolicy {
33
33
  readonly sameOriginOnly?: boolean;
34
34
  readonly publicNavigationPaths?: readonly string[];
35
35
  readonly immutableAssetPathPrefixes?: readonly string[];
36
+ readonly immutableAssetPathPatterns?: readonly RegExp[];
36
37
  readonly publicAssetPathPrefixes?: readonly string[];
37
38
  readonly publicApiPathPrefixes?: readonly string[];
38
39
  readonly deniedPathPrefixes?: readonly string[];
@@ -70,6 +71,8 @@ interface OfflineCacheOperationOptions extends OfflineCacheRuntime {
70
71
  readonly signal?: AbortSignal;
71
72
  }
72
73
  interface OfflineCacheWorkerScriptOptions {
74
+ /** Require renewed host permission before any worker cache access (maximum 60 seconds). */
75
+ readonly requireConsent?: boolean;
73
76
  readonly cachePrefix?: string;
74
77
  readonly buildId: string;
75
78
  readonly policy: OfflineCacheRequestPolicy;
package/dist/index.js CHANGED
@@ -115,6 +115,9 @@ function classifyOfflineCacheRequest(input, init, policy = DEFAULT_OFFLINE_CACHE
115
115
  )) {
116
116
  return { cacheable: false, strategy: "no-cache", reason: "denied-path-prefix" };
117
117
  }
118
+ if (policy.immutableAssetPathPatterns?.some((pattern) => new RegExp(pattern.source, pattern.flags).test(pathname))) {
119
+ return { cacheable: true, strategy: "cache-first", reason: "immutable-asset-pattern", cacheBucket: "immutable" };
120
+ }
118
121
  if (pathStartsWith(pathname, policy.publicApiPathPrefixes)) {
119
122
  return {
120
123
  cacheable: true,
@@ -223,7 +226,12 @@ async function warmAssetPack(pack, options = {}) {
223
226
  availableBytes
224
227
  };
225
228
  }
229
+ options.signal?.throwIfAborted();
226
230
  const cache = await cacheStorage.open(cacheName);
231
+ if (options.signal?.aborted) {
232
+ await cacheStorage.delete(cacheName);
233
+ options.signal.throwIfAborted();
234
+ }
227
235
  const results = [];
228
236
  for (const rawUrl of pack.urls) {
229
237
  const url = normalizeUrl(rawUrl, options);
@@ -232,9 +240,11 @@ async function warmAssetPack(pack, options = {}) {
232
240
  const request = new Request(url, {
233
241
  method: "GET",
234
242
  credentials: "same-origin",
235
- cache: "reload"
243
+ cache: "reload",
244
+ signal: options.signal
236
245
  });
237
246
  const response = await fetchImpl(request);
247
+ options.signal?.throwIfAborted();
238
248
  if (!response.ok) {
239
249
  const existing = await cache.match(url);
240
250
  results.push({
@@ -252,6 +262,7 @@ async function warmAssetPack(pack, options = {}) {
252
262
  await cache.put(url, response.clone());
253
263
  results.push({ url, cached: true });
254
264
  } catch (error) {
265
+ options.signal?.throwIfAborted();
255
266
  const existing = await cache.match(url);
256
267
  const isOffline = typeof globalThis.navigator !== "undefined" && globalThis.navigator.onLine === false;
257
268
  results.push({
@@ -376,7 +387,11 @@ function createOfflineCacheWorkerScript(options) {
376
387
  options.cachePrefix ?? DEFAULT_OFFLINE_CACHE_PREFIX
377
388
  );
378
389
  const buildId = sanitizeCacheSegment(options.buildId);
379
- const policyJson = JSON.stringify(options.policy);
390
+ const policyJson = JSON.stringify({
391
+ ...options.policy,
392
+ immutableAssetPathPatterns: options.policy.immutableAssetPathPatterns?.map((pattern) => ({ source: pattern.source, flags: pattern.flags })),
393
+ deniedPathPatterns: options.policy.deniedPathPatterns?.map((pattern) => ({ source: pattern.source, flags: pattern.flags }))
394
+ });
380
395
  const fallbackUrl = JSON.stringify(options.navigationFallbackUrl ?? "/");
381
396
  return `
382
397
  const CACHE_PREFIX = ${JSON.stringify(cachePrefix)};
@@ -385,9 +400,31 @@ const APP_CACHE = CACHE_PREFIX + "-app-" + BUILD_ID;
385
400
  const PUBLIC_CACHE = CACHE_PREFIX + "-public-" + BUILD_ID;
386
401
  const POLICY = ${policyJson};
387
402
  const NAVIGATION_FALLBACK_URL = ${fallbackUrl};
403
+ const REQUIRE_CONSENT = ${options.requireConsent === true};
404
+ let permissionUntil = REQUIRE_CONSENT ? 0 : Infinity;
405
+ let permissionGeneration = 0;
406
+ const permitted = (generation) => generation === permissionGeneration && Date.now() < permissionUntil;
407
+ async function discardCaches() {
408
+ const names = await caches.keys();
409
+ await Promise.all(names.filter(name => name.startsWith(CACHE_PREFIX + "-")).map(name => caches.delete(name)));
410
+ }
411
+ self.addEventListener("message", event => {
412
+ if (!REQUIRE_CONSENT || event.data?.type !== "plasius-offline-consent-v1") return;
413
+ try { if (new URL(event.source?.url).origin !== self.location.origin) return; } catch { return; }
414
+ const requested = event.data.allowedUntil;
415
+ permissionUntil = typeof requested === "number" && Number.isFinite(requested)
416
+ ? Math.min(requested, Date.now() + 60_000) : 0;
417
+ const disabled = permissionUntil <= Date.now();
418
+ if (disabled) permissionGeneration++;
419
+ event.waitUntil((async () => {
420
+ if (disabled) await discardCaches();
421
+ event.ports?.[0]?.postMessage({ type: "plasius-offline-consent-v1", disabled });
422
+ })());
423
+ });
388
424
 
389
425
  const startsWithAny = (pathname, prefixes = []) => prefixes.some((prefix) => pathname === prefix || pathname.startsWith(prefix));
390
- const isDenied = (pathname) => startsWithAny(pathname, POLICY.deniedPathPrefixes || []);
426
+ const matchesAny = (pathname, patterns = []) => patterns.some(pattern => new RegExp(pattern.source, pattern.flags).test(pathname));
427
+ const isDenied = (pathname) => startsWithAny(pathname, POLICY.deniedPathPrefixes || []) || matchesAny(pathname, POLICY.deniedPathPatterns);
391
428
  const hasNoStore = (headers) => (headers.get("cache-control") || "").split(",").some((directive) => directive.trim().split("=", 1)[0].toLowerCase() === "no-store");
392
429
  const classify = (request) => {
393
430
  if (request.method !== "GET" && request.method !== "HEAD") return { cacheable: false, strategy: "no-cache" };
@@ -395,6 +432,7 @@ const classify = (request) => {
395
432
  const url = new URL(request.url);
396
433
  if (POLICY.sameOriginOnly !== false && url.origin !== self.location.origin) return { cacheable: false, strategy: "no-cache" };
397
434
  if (isDenied(url.pathname)) return { cacheable: false, strategy: "no-cache" };
435
+ if (matchesAny(url.pathname, POLICY.immutableAssetPathPatterns)) return { cacheable: true, strategy: "cache-first", cacheName: PUBLIC_CACHE };
398
436
  if (startsWithAny(url.pathname, POLICY.publicApiPathPrefixes || [])) return { cacheable: true, strategy: "stale-while-revalidate", cacheName: PUBLIC_CACHE };
399
437
  if (startsWithAny(url.pathname, POLICY.publicAssetPathPrefixes || [])) return { cacheable: true, strategy: "stale-while-revalidate", cacheName: PUBLIC_CACHE };
400
438
  if (startsWithAny(url.pathname, POLICY.immutableAssetPathPrefixes || [])) return { cacheable: true, strategy: "cache-first", cacheName: APP_CACHE };
@@ -414,52 +452,75 @@ self.addEventListener("activate", (event) => {
414
452
  })());
415
453
  });
416
454
 
417
- async function cacheFirst(request, cacheName) {
455
+ async function openPermittedCache(cacheName, generation) {
456
+ if (!permitted(generation)) return null;
418
457
  const cache = await caches.open(cacheName);
458
+ if (!permitted(generation)) {
459
+ await caches.delete(cacheName);
460
+ return null;
461
+ }
462
+ return cache;
463
+ }
464
+
465
+ async function cacheFirst(request, cacheName, generation) {
466
+ const cache = await openPermittedCache(cacheName, generation);
467
+ if (!cache) return fetch(request);
419
468
  const cached = await cache.match(request);
469
+ if (!permitted(generation)) return fetch(request);
420
470
  if (cached && !hasNoStore(cached.headers)) return cached;
421
471
  if (cached) await cache.delete(request);
422
472
  const response = await fetch(request);
473
+ if (!permitted(generation)) return response;
423
474
  if (response.ok && !hasNoStore(response.headers)) await cache.put(request, response.clone());
424
475
  if (hasNoStore(response.headers)) await cache.delete(request);
425
476
  return response;
426
477
  }
427
478
 
428
- async function staleWhileRevalidate(request, cacheName) {
429
- const cache = await caches.open(cacheName);
479
+ async function staleWhileRevalidate(request, cacheName, generation) {
480
+ const cache = await openPermittedCache(cacheName, generation);
481
+ if (!cache) return fetch(request);
430
482
  const candidate = await cache.match(request);
483
+ if (!permitted(generation)) return fetch(request);
431
484
  const cached = candidate && !hasNoStore(candidate.headers) ? candidate : undefined;
432
485
  if (candidate && !cached) await cache.delete(request);
433
- const refresh = fetch(request).then((response) => {
434
- if (response.ok && !hasNoStore(response.headers)) cache.put(request, response.clone());
435
- if (hasNoStore(response.headers)) cache.delete(request);
486
+ const refresh = fetch(request).then(async response => {
487
+ if (!permitted(generation)) return response;
488
+ if (response.ok && !hasNoStore(response.headers)) await cache.put(request, response.clone());
489
+ if (hasNoStore(response.headers)) await cache.delete(request);
436
490
  return response;
437
491
  });
492
+ if (cached) void refresh.catch(() => undefined);
438
493
  return cached || refresh;
439
494
  }
440
495
 
441
- async function networkFirst(request, cacheName) {
442
- const cache = await caches.open(cacheName);
496
+ async function networkFirst(request, cacheName, generation) {
497
+ const cache = await openPermittedCache(cacheName, generation);
498
+ if (!cache) return fetch(request);
443
499
  try {
444
500
  const response = await fetch(request);
501
+ if (!permitted(generation)) return response;
445
502
  if (response.ok && !hasNoStore(response.headers)) await cache.put(request, response.clone());
446
503
  if (hasNoStore(response.headers)) await cache.delete(request);
447
504
  return response;
448
- } catch (error) {
505
+ } catch {
506
+ if (!permitted(generation)) return Response.error();
449
507
  const cached = await cache.match(request);
508
+ if (!permitted(generation)) return Response.error();
450
509
  if (cached && !hasNoStore(cached.headers)) return cached;
451
510
  if (cached) await cache.delete(request);
452
511
  const fallback = await cache.match(NAVIGATION_FALLBACK_URL);
453
- return fallback && !hasNoStore(fallback.headers) ? fallback : Response.error();
512
+ return permitted(generation) && fallback && !hasNoStore(fallback.headers) ? fallback : Response.error();
454
513
  }
455
514
  }
456
515
 
457
516
  self.addEventListener("fetch", (event) => {
517
+ const generation = permissionGeneration;
518
+ if (!permitted(generation)) return;
458
519
  const decision = classify(event.request);
459
520
  if (!decision.cacheable) return;
460
- if (decision.strategy === "cache-first") event.respondWith(cacheFirst(event.request, decision.cacheName));
461
- if (decision.strategy === "stale-while-revalidate") event.respondWith(staleWhileRevalidate(event.request, decision.cacheName));
462
- if (decision.strategy === "network-first") event.respondWith(networkFirst(event.request, decision.cacheName));
521
+ if (decision.strategy === "cache-first") event.respondWith(cacheFirst(event.request, decision.cacheName, generation));
522
+ if (decision.strategy === "stale-while-revalidate") event.respondWith(staleWhileRevalidate(event.request, decision.cacheName, generation));
523
+ if (decision.strategy === "network-first") event.respondWith(networkFirst(event.request, decision.cacheName, generation));
463
524
  });
464
525
  `.trimStart();
465
526
  }
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["export type OfflineCacheStatus =\n | \"unsupported\"\n | \"idle\"\n | \"warming\"\n | \"ready\"\n | \"partial\"\n | \"quota-risk\"\n | \"offline\"\n | \"error\";\n\nexport type OfflineCacheStrategy =\n | \"cache-first\"\n | \"stale-while-revalidate\"\n | \"network-first\"\n | \"no-cache\";\n\nexport interface OfflineCacheLogger {\n debug?: (...args: unknown[]) => void;\n info?: (...args: unknown[]) => void;\n warn?: (...args: unknown[]) => void;\n error?: (...args: unknown[]) => void;\n}\n\nexport interface OfflineCacheAssetPack {\n readonly id: string;\n readonly revision: string;\n readonly urls: readonly string[];\n readonly estimatedBytes?: number;\n}\n\nexport interface OfflineCacheUrlResult {\n readonly url: string;\n readonly cached: boolean;\n readonly error?: string;\n}\n\nexport interface OfflineCacheAssetPackResult {\n readonly id: string;\n readonly revision: string;\n readonly status: OfflineCacheStatus;\n readonly cacheName?: string;\n readonly cachedUrls: number;\n readonly totalUrls: number;\n readonly results: OfflineCacheUrlResult[];\n readonly estimatedBytes?: number;\n readonly availableBytes?: number;\n readonly error?: string;\n}\n\nexport interface OfflineCacheRequestPolicy {\n readonly sameOriginOnly?: boolean;\n readonly publicNavigationPaths?: readonly string[];\n readonly immutableAssetPathPrefixes?: readonly string[];\n readonly publicAssetPathPrefixes?: readonly string[];\n readonly publicApiPathPrefixes?: readonly string[];\n readonly deniedPathPrefixes?: readonly string[];\n readonly deniedPathPatterns?: readonly RegExp[];\n}\n\nexport interface OfflineCacheRequestDecision {\n readonly cacheable: boolean;\n readonly strategy: OfflineCacheStrategy;\n readonly reason: string;\n readonly cacheBucket?: \"navigation\" | \"immutable\" | \"public-asset\" | \"public-api\";\n}\n\nexport interface RegisterOfflineCacheWorkerOptions {\n readonly workerUrl?: string;\n readonly scope?: string;\n readonly buildId?: string;\n readonly enabled?: boolean;\n readonly logger?: OfflineCacheLogger;\n readonly serviceWorkerContainer?: ServiceWorkerContainer;\n}\n\nexport interface RegisterOfflineCacheWorkerResult {\n readonly status: \"registered\" | \"unsupported\" | \"disabled\" | \"error\";\n readonly registration?: ServiceWorkerRegistration;\n readonly error?: unknown;\n}\n\nexport interface OfflineCacheRuntime {\n readonly caches?: CacheStorage;\n readonly fetch?: typeof fetch;\n readonly location?: Pick<Location, \"origin\">;\n readonly navigatorStorage?: StorageManager;\n}\n\nexport interface OfflineCacheOperationOptions extends OfflineCacheRuntime {\n readonly cachePrefix?: string;\n readonly logger?: OfflineCacheLogger;\n readonly quotaRiskRatio?: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface OfflineCacheWorkerScriptOptions {\n readonly cachePrefix?: string;\n readonly buildId: string;\n readonly policy: OfflineCacheRequestPolicy;\n readonly navigationFallbackUrl?: string;\n}\n\nexport const DEFAULT_OFFLINE_CACHE_PREFIX = \"plasius-offline\";\n\nexport const DEFAULT_OFFLINE_CACHE_POLICY: Required<\n Pick<\n OfflineCacheRequestPolicy,\n | \"sameOriginOnly\"\n | \"publicNavigationPaths\"\n | \"immutableAssetPathPrefixes\"\n | \"publicAssetPathPrefixes\"\n | \"publicApiPathPrefixes\"\n | \"deniedPathPrefixes\"\n >\n> & Pick<OfflineCacheRequestPolicy, \"deniedPathPatterns\"> = Object.freeze({\n sameOriginOnly: true,\n publicNavigationPaths: Object.freeze([\"/\"]),\n immutableAssetPathPrefixes: Object.freeze([\"/assets/\", \"/favicon\", \"/manifest.json\"]),\n publicAssetPathPrefixes: Object.freeze([]),\n publicApiPathPrefixes: Object.freeze([]),\n deniedPathPrefixes: Object.freeze([\n \"/api/admin\",\n \"/api/ai\",\n \"/api/analytics\",\n \"/api/auth\",\n \"/api/game\",\n \"/api/oauth\",\n \"/api/player-system\",\n \"/api/profile\",\n \"/api/users\",\n \"/api/voice\",\n \"/admin\",\n \"/oauth\",\n \"/profile\",\n \"/player-system\",\n ]),\n deniedPathPatterns: Object.freeze([]),\n});\n\nconst SAFE_CACHE_SEGMENT_PATTERN = /[^a-z0-9._-]+/giu;\nconst DEFAULT_QUOTA_RISK_RATIO = 0.9;\n\nfunction sanitizeCacheSegment(value: string): string {\n const sanitized = value\n .trim()\n .toLowerCase()\n .replace(SAFE_CACHE_SEGMENT_PATTERN, \"-\")\n .replace(/^-+|-+$/gu, \"\");\n return sanitized || \"default\";\n}\n\nfunction resolveCacheStorage(runtime?: OfflineCacheRuntime): CacheStorage | undefined {\n return runtime?.caches ?? globalThis.caches;\n}\n\nfunction resolveFetch(runtime?: OfflineCacheRuntime): typeof fetch | undefined {\n return runtime?.fetch ?? globalThis.fetch;\n}\n\nfunction resolveNavigatorStorage(\n runtime?: OfflineCacheRuntime,\n): StorageManager | undefined {\n return runtime?.navigatorStorage ?? globalThis.navigator?.storage;\n}\n\nfunction resolveBaseOrigin(runtime?: OfflineCacheRuntime): string {\n return runtime?.location?.origin ?? globalThis.location?.origin ?? \"https://plasius.co.uk\";\n}\n\nfunction normalizeUrl(value: string, runtime?: OfflineCacheRuntime): string {\n return new URL(value, resolveBaseOrigin(runtime)).toString();\n}\n\nfunction toUrl(input: RequestInfo | URL, runtime?: OfflineCacheRuntime): URL | null {\n try {\n if (typeof input === \"string\") {\n return new URL(input, resolveBaseOrigin(runtime));\n }\n\n if (input instanceof URL) {\n return input;\n }\n\n const requestUrl = (input as Request).url;\n return typeof requestUrl === \"string\"\n ? new URL(requestUrl, resolveBaseOrigin(runtime))\n : null;\n } catch {\n return null;\n }\n}\n\nfunction getRequestMethod(input: RequestInfo | URL, init?: RequestInit): string {\n return (init?.method ?? (typeof input === \"object\" && \"method\" in input ? input.method : \"GET\"))\n .toString()\n .toUpperCase();\n}\n\nfunction hasNoStore(headers: Headers): boolean {\n return (headers.get(\"cache-control\") ?? \"\")\n .split(\",\")\n .some(directive => directive.trim().split(\"=\", 1)[0]?.toLowerCase() === \"no-store\");\n}\n\nfunction getRequestHeaders(input: RequestInfo | URL, init?: RequestInit): Headers {\n if (init?.headers) return new Headers(init.headers);\n return typeof input === \"object\" && \"headers\" in input ? new Headers(input.headers) : new Headers();\n}\n\nfunction pathStartsWith(pathname: string, prefixes: readonly string[] = []): boolean {\n return prefixes.some(prefix => pathname === prefix || pathname.startsWith(prefix));\n}\n\nfunction isNavigationRequest(input: RequestInfo | URL, init?: RequestInit): boolean {\n if (init?.headers) {\n const headers = new Headers(init.headers);\n if (headers.get(\"accept\")?.includes(\"text/html\")) {\n return true;\n }\n }\n\n return typeof input === \"object\" && \"mode\" in input && input.mode === \"navigate\";\n}\n\nexport function buildOfflineAssetCacheName(\n pack: Pick<OfflineCacheAssetPack, \"id\" | \"revision\">,\n cachePrefix = DEFAULT_OFFLINE_CACHE_PREFIX,\n): string {\n return [\n sanitizeCacheSegment(cachePrefix),\n \"asset-pack\",\n sanitizeCacheSegment(pack.id),\n sanitizeCacheSegment(pack.revision),\n ].join(\"-\");\n}\n\nexport function classifyOfflineCacheRequest(\n input: RequestInfo | URL,\n init?: RequestInit,\n policy: OfflineCacheRequestPolicy = DEFAULT_OFFLINE_CACHE_POLICY,\n runtime?: OfflineCacheRuntime,\n): OfflineCacheRequestDecision {\n const method = getRequestMethod(input, init);\n if (method !== \"GET\" && method !== \"HEAD\") {\n return { cacheable: false, strategy: \"no-cache\", reason: \"non-get-request\" };\n }\n if (hasNoStore(getRequestHeaders(input, init))) {\n return { cacheable: false, strategy: \"no-cache\", reason: \"request-cache-control-no-store\" };\n }\n\n const url = toUrl(input, runtime);\n if (!url) {\n return { cacheable: false, strategy: \"no-cache\", reason: \"invalid-url\" };\n }\n\n const sameOriginOnly = policy.sameOriginOnly ?? DEFAULT_OFFLINE_CACHE_POLICY.sameOriginOnly;\n if (sameOriginOnly && url.origin !== resolveBaseOrigin(runtime)) {\n return { cacheable: false, strategy: \"no-cache\", reason: \"cross-origin\" };\n }\n\n const pathname = url.pathname;\n if ((policy.deniedPathPatterns ?? []).some(pattern => pattern.test(pathname))) {\n return { cacheable: false, strategy: \"no-cache\", reason: \"denied-path-pattern\" };\n }\n\n if (\n pathStartsWith(\n pathname,\n policy.deniedPathPrefixes ?? DEFAULT_OFFLINE_CACHE_POLICY.deniedPathPrefixes,\n )\n ) {\n return { cacheable: false, strategy: \"no-cache\", reason: \"denied-path-prefix\" };\n }\n\n if (pathStartsWith(pathname, policy.publicApiPathPrefixes)) {\n return {\n cacheable: true,\n strategy: \"stale-while-revalidate\",\n reason: \"public-api\",\n cacheBucket: \"public-api\",\n };\n }\n\n if (pathStartsWith(pathname, policy.publicAssetPathPrefixes)) {\n return {\n cacheable: true,\n strategy: \"stale-while-revalidate\",\n reason: \"public-asset\",\n cacheBucket: \"public-asset\",\n };\n }\n\n if (\n pathStartsWith(\n pathname,\n policy.immutableAssetPathPrefixes\n ?? DEFAULT_OFFLINE_CACHE_POLICY.immutableAssetPathPrefixes,\n )\n ) {\n return {\n cacheable: true,\n strategy: \"cache-first\",\n reason: \"immutable-asset\",\n cacheBucket: \"immutable\",\n };\n }\n\n if (\n isNavigationRequest(input, init)\n && (policy.publicNavigationPaths ?? DEFAULT_OFFLINE_CACHE_POLICY.publicNavigationPaths)\n .includes(pathname)\n ) {\n return {\n cacheable: true,\n strategy: \"network-first\",\n reason: \"public-navigation\",\n cacheBucket: \"navigation\",\n };\n }\n\n return { cacheable: false, strategy: \"no-cache\", reason: \"unmatched\" };\n}\n\nasync function resolveAvailableBytes(\n pack: OfflineCacheAssetPack,\n options: OfflineCacheOperationOptions,\n): Promise<number | undefined> {\n if (typeof pack.estimatedBytes !== \"number\" || pack.estimatedBytes <= 0) {\n return undefined;\n }\n\n try {\n const estimate = await resolveNavigatorStorage(options)?.estimate?.();\n if (\n typeof estimate?.quota !== \"number\"\n || typeof estimate.usage !== \"number\"\n || estimate.quota <= estimate.usage\n ) {\n return undefined;\n }\n\n return estimate.quota - estimate.usage;\n } catch (error) {\n options.logger?.debug?.(\"offline cache quota estimate unavailable\", { error });\n return undefined;\n }\n}\n\nfunction resultStatus(results: readonly OfflineCacheUrlResult[]): OfflineCacheStatus {\n const cachedCount = results.filter(result => result.cached).length;\n if (cachedCount === results.length) {\n return \"ready\";\n }\n if (cachedCount > 0) {\n return \"partial\";\n }\n if (results.some(result => result.error === \"offline\")) {\n return \"offline\";\n }\n return \"error\";\n}\n\nexport async function warmAssetPack(\n pack: OfflineCacheAssetPack,\n options: OfflineCacheOperationOptions = {},\n): Promise<OfflineCacheAssetPackResult> {\n const cacheStorage = resolveCacheStorage(options);\n const fetchImpl = resolveFetch(options);\n const totalUrls = pack.urls.length;\n const cacheName = buildOfflineAssetCacheName(pack, options.cachePrefix);\n\n if (!cacheStorage || typeof fetchImpl !== \"function\") {\n return {\n id: pack.id,\n revision: pack.revision,\n status: \"unsupported\",\n cachedUrls: 0,\n totalUrls,\n results: [],\n estimatedBytes: pack.estimatedBytes,\n };\n }\n\n if (totalUrls === 0) {\n return {\n id: pack.id,\n revision: pack.revision,\n status: \"idle\",\n cacheName,\n cachedUrls: 0,\n totalUrls,\n results: [],\n estimatedBytes: pack.estimatedBytes,\n };\n }\n\n const availableBytes = await resolveAvailableBytes(pack, options);\n const riskRatio = options.quotaRiskRatio ?? DEFAULT_QUOTA_RISK_RATIO;\n if (\n typeof availableBytes === \"number\"\n && typeof pack.estimatedBytes === \"number\"\n && pack.estimatedBytes > availableBytes * riskRatio\n ) {\n return {\n id: pack.id,\n revision: pack.revision,\n status: \"quota-risk\",\n cacheName,\n cachedUrls: 0,\n totalUrls,\n results: [],\n estimatedBytes: pack.estimatedBytes,\n availableBytes,\n };\n }\n\n const cache = await cacheStorage.open(cacheName);\n const results: OfflineCacheUrlResult[] = [];\n\n for (const rawUrl of pack.urls) {\n const url = normalizeUrl(rawUrl, options);\n try {\n options.signal?.throwIfAborted();\n const request = new Request(url, {\n method: \"GET\",\n credentials: \"same-origin\",\n cache: \"reload\",\n });\n const response = await fetchImpl(request);\n if (!response.ok) {\n const existing = await cache.match(url);\n results.push({\n url,\n cached: Boolean(existing),\n error: existing ? undefined : `http-${response.status}`,\n });\n continue;\n }\n\n if (hasNoStore(response.headers)) {\n await cache.delete(url);\n results.push({ url, cached: false, error: \"cache-control-no-store\" });\n continue;\n }\n\n await cache.put(url, response.clone());\n results.push({ url, cached: true });\n } catch (error) {\n const existing = await cache.match(url);\n const isOffline =\n typeof globalThis.navigator !== \"undefined\" && globalThis.navigator.onLine === false;\n results.push({\n url,\n cached: Boolean(existing),\n error: existing ? undefined : isOffline ? \"offline\" : String(error),\n });\n }\n }\n\n return {\n id: pack.id,\n revision: pack.revision,\n status: resultStatus(results),\n cacheName,\n cachedUrls: results.filter(result => result.cached).length,\n totalUrls,\n results,\n estimatedBytes: pack.estimatedBytes,\n availableBytes,\n };\n}\n\nexport async function getAssetPackStatus(\n pack: OfflineCacheAssetPack,\n options: OfflineCacheOperationOptions = {},\n): Promise<OfflineCacheAssetPackResult> {\n const cacheStorage = resolveCacheStorage(options);\n const totalUrls = pack.urls.length;\n const cacheName = buildOfflineAssetCacheName(pack, options.cachePrefix);\n\n if (!cacheStorage) {\n return {\n id: pack.id,\n revision: pack.revision,\n status: \"unsupported\",\n cachedUrls: 0,\n totalUrls,\n results: [],\n estimatedBytes: pack.estimatedBytes,\n };\n }\n\n if (totalUrls === 0) {\n return {\n id: pack.id,\n revision: pack.revision,\n status: \"idle\",\n cacheName,\n cachedUrls: 0,\n totalUrls,\n results: [],\n estimatedBytes: pack.estimatedBytes,\n };\n }\n\n const cache = await cacheStorage.open(cacheName);\n const results = await Promise.all(\n pack.urls.map(async rawUrl => {\n const url = normalizeUrl(rawUrl, options);\n return {\n url,\n cached: Boolean(await cache.match(url)),\n };\n }),\n );\n\n return {\n id: pack.id,\n revision: pack.revision,\n status: resultStatus(results),\n cacheName,\n cachedUrls: results.filter(result => result.cached).length,\n totalUrls,\n results,\n estimatedBytes: pack.estimatedBytes,\n };\n}\n\nexport async function clearOfflineCaches(options: {\n readonly cachePrefix?: string;\n readonly caches?: CacheStorage;\n} = {}): Promise<string[]> {\n const cacheStorage = options.caches ?? globalThis.caches;\n if (!cacheStorage) {\n return [];\n }\n\n const prefix = sanitizeCacheSegment(options.cachePrefix ?? DEFAULT_OFFLINE_CACHE_PREFIX);\n const cacheNames = await cacheStorage.keys();\n const deleted: string[] = [];\n for (const cacheName of cacheNames) {\n if (cacheName.startsWith(prefix) && await cacheStorage.delete(cacheName)) {\n deleted.push(cacheName);\n }\n }\n return deleted;\n}\n\nexport async function registerOfflineCacheWorker(\n options: RegisterOfflineCacheWorkerOptions = {},\n): Promise<RegisterOfflineCacheWorkerResult> {\n if (options.enabled === false) {\n return { status: \"disabled\" };\n }\n\n const serviceWorkerContainer =\n options.serviceWorkerContainer ?? globalThis.navigator?.serviceWorker;\n if (!serviceWorkerContainer) {\n return { status: \"unsupported\" };\n }\n\n const workerUrl = new URL(\n options.workerUrl ?? \"/offline-cache-worker.js\",\n globalThis.location?.origin ?? \"https://plasius.co.uk\",\n );\n if (options.buildId) {\n workerUrl.searchParams.set(\"build\", options.buildId);\n }\n\n try {\n const registration = await serviceWorkerContainer.register(workerUrl.toString(), {\n scope: options.scope ?? \"/\",\n });\n options.logger?.info?.(\"offline cache worker registered\", {\n workerUrl: workerUrl.pathname,\n scope: registration.scope,\n });\n return {\n status: \"registered\",\n registration,\n };\n } catch (error) {\n options.logger?.warn?.(\"offline cache worker registration failed\", { error });\n return {\n status: \"error\",\n error,\n };\n }\n}\n\nexport function createOfflineCacheWorkerScript(\n options: OfflineCacheWorkerScriptOptions,\n): string {\n const cachePrefix = sanitizeCacheSegment(\n options.cachePrefix ?? DEFAULT_OFFLINE_CACHE_PREFIX,\n );\n const buildId = sanitizeCacheSegment(options.buildId);\n const policyJson = JSON.stringify(options.policy);\n const fallbackUrl = JSON.stringify(options.navigationFallbackUrl ?? \"/\");\n\n return `\nconst CACHE_PREFIX = ${JSON.stringify(cachePrefix)};\nconst BUILD_ID = ${JSON.stringify(buildId)};\nconst APP_CACHE = CACHE_PREFIX + \"-app-\" + BUILD_ID;\nconst PUBLIC_CACHE = CACHE_PREFIX + \"-public-\" + BUILD_ID;\nconst POLICY = ${policyJson};\nconst NAVIGATION_FALLBACK_URL = ${fallbackUrl};\n\nconst startsWithAny = (pathname, prefixes = []) => prefixes.some((prefix) => pathname === prefix || pathname.startsWith(prefix));\nconst isDenied = (pathname) => startsWithAny(pathname, POLICY.deniedPathPrefixes || []);\nconst hasNoStore = (headers) => (headers.get(\"cache-control\") || \"\").split(\",\").some((directive) => directive.trim().split(\"=\", 1)[0].toLowerCase() === \"no-store\");\nconst classify = (request) => {\n if (request.method !== \"GET\" && request.method !== \"HEAD\") return { cacheable: false, strategy: \"no-cache\" };\n if (hasNoStore(request.headers)) return { cacheable: false, strategy: \"no-cache\", reason: \"request-cache-control-no-store\" };\n const url = new URL(request.url);\n if (POLICY.sameOriginOnly !== false && url.origin !== self.location.origin) return { cacheable: false, strategy: \"no-cache\" };\n if (isDenied(url.pathname)) return { cacheable: false, strategy: \"no-cache\" };\n if (startsWithAny(url.pathname, POLICY.publicApiPathPrefixes || [])) return { cacheable: true, strategy: \"stale-while-revalidate\", cacheName: PUBLIC_CACHE };\n if (startsWithAny(url.pathname, POLICY.publicAssetPathPrefixes || [])) return { cacheable: true, strategy: \"stale-while-revalidate\", cacheName: PUBLIC_CACHE };\n if (startsWithAny(url.pathname, POLICY.immutableAssetPathPrefixes || [])) return { cacheable: true, strategy: \"cache-first\", cacheName: APP_CACHE };\n if (request.mode === \"navigate\" && (POLICY.publicNavigationPaths || []).includes(url.pathname)) return { cacheable: true, strategy: \"network-first\", cacheName: APP_CACHE };\n return { cacheable: false, strategy: \"no-cache\" };\n};\n\nself.addEventListener(\"install\", (event) => {\n event.waitUntil(self.skipWaiting());\n});\n\nself.addEventListener(\"activate\", (event) => {\n event.waitUntil((async () => {\n const names = await caches.keys();\n await Promise.all(names.filter((name) => name.startsWith(CACHE_PREFIX + \"-\") && !name.endsWith(\"-\" + BUILD_ID) && !name.includes(\"-asset-pack-\")).map((name) => caches.delete(name)));\n await self.clients.claim();\n })());\n});\n\nasync function cacheFirst(request, cacheName) {\n const cache = await caches.open(cacheName);\n const cached = await cache.match(request);\n if (cached && !hasNoStore(cached.headers)) return cached;\n if (cached) await cache.delete(request);\n const response = await fetch(request);\n if (response.ok && !hasNoStore(response.headers)) await cache.put(request, response.clone());\n if (hasNoStore(response.headers)) await cache.delete(request);\n return response;\n}\n\nasync function staleWhileRevalidate(request, cacheName) {\n const cache = await caches.open(cacheName);\n const candidate = await cache.match(request);\n const cached = candidate && !hasNoStore(candidate.headers) ? candidate : undefined;\n if (candidate && !cached) await cache.delete(request);\n const refresh = fetch(request).then((response) => {\n if (response.ok && !hasNoStore(response.headers)) cache.put(request, response.clone());\n if (hasNoStore(response.headers)) cache.delete(request);\n return response;\n });\n return cached || refresh;\n}\n\nasync function networkFirst(request, cacheName) {\n const cache = await caches.open(cacheName);\n try {\n const response = await fetch(request);\n if (response.ok && !hasNoStore(response.headers)) await cache.put(request, response.clone());\n if (hasNoStore(response.headers)) await cache.delete(request);\n return response;\n } catch (error) {\n const cached = await cache.match(request);\n if (cached && !hasNoStore(cached.headers)) return cached;\n if (cached) await cache.delete(request);\n const fallback = await cache.match(NAVIGATION_FALLBACK_URL);\n return fallback && !hasNoStore(fallback.headers) ? fallback : Response.error();\n }\n}\n\nself.addEventListener(\"fetch\", (event) => {\n const decision = classify(event.request);\n if (!decision.cacheable) return;\n if (decision.strategy === \"cache-first\") event.respondWith(cacheFirst(event.request, decision.cacheName));\n if (decision.strategy === \"stale-while-revalidate\") event.respondWith(staleWhileRevalidate(event.request, decision.cacheName));\n if (decision.strategy === \"network-first\") event.respondWith(networkFirst(event.request, decision.cacheName));\n});\n`.trimStart();\n}\n"],"mappings":";AAsGO,IAAM,+BAA+B;AAErC,IAAM,+BAU+C,OAAO,OAAO;AAAA,EACxE,gBAAgB;AAAA,EAChB,uBAAuB,OAAO,OAAO,CAAC,GAAG,CAAC;AAAA,EAC1C,4BAA4B,OAAO,OAAO,CAAC,YAAY,YAAY,gBAAgB,CAAC;AAAA,EACpF,yBAAy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AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA6E3C,UAAU;AACZ;","names":[]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["export type OfflineCacheStatus =\n | \"unsupported\"\n | \"idle\"\n | \"warming\"\n | \"ready\"\n | \"partial\"\n | \"quota-risk\"\n | \"offline\"\n | \"error\";\n\nexport type OfflineCacheStrategy =\n | \"cache-first\"\n | \"stale-while-revalidate\"\n | \"network-first\"\n | \"no-cache\";\n\nexport interface OfflineCacheLogger {\n debug?: (...args: unknown[]) => void;\n info?: (...args: unknown[]) => void;\n warn?: (...args: unknown[]) => void;\n error?: (...args: unknown[]) => void;\n}\n\nexport interface OfflineCacheAssetPack {\n readonly id: string;\n readonly revision: string;\n readonly urls: readonly string[];\n readonly estimatedBytes?: number;\n}\n\nexport interface OfflineCacheUrlResult {\n readonly url: string;\n readonly cached: boolean;\n readonly error?: string;\n}\n\nexport interface OfflineCacheAssetPackResult {\n readonly id: string;\n readonly revision: string;\n readonly status: OfflineCacheStatus;\n readonly cacheName?: string;\n readonly cachedUrls: number;\n readonly totalUrls: number;\n readonly results: OfflineCacheUrlResult[];\n readonly estimatedBytes?: number;\n readonly availableBytes?: number;\n readonly error?: string;\n}\n\nexport interface OfflineCacheRequestPolicy {\n readonly sameOriginOnly?: boolean;\n readonly publicNavigationPaths?: readonly string[];\n readonly immutableAssetPathPrefixes?: readonly string[];\n readonly immutableAssetPathPatterns?: readonly RegExp[];\n readonly publicAssetPathPrefixes?: readonly string[];\n readonly publicApiPathPrefixes?: readonly string[];\n readonly deniedPathPrefixes?: readonly string[];\n readonly deniedPathPatterns?: readonly RegExp[];\n}\n\nexport interface OfflineCacheRequestDecision {\n readonly cacheable: boolean;\n readonly strategy: OfflineCacheStrategy;\n readonly reason: string;\n readonly cacheBucket?: \"navigation\" | \"immutable\" | \"public-asset\" | \"public-api\";\n}\n\nexport interface RegisterOfflineCacheWorkerOptions {\n readonly workerUrl?: string;\n readonly scope?: string;\n readonly buildId?: string;\n readonly enabled?: boolean;\n readonly logger?: OfflineCacheLogger;\n readonly serviceWorkerContainer?: ServiceWorkerContainer;\n}\n\nexport interface RegisterOfflineCacheWorkerResult {\n readonly status: \"registered\" | \"unsupported\" | \"disabled\" | \"error\";\n readonly registration?: ServiceWorkerRegistration;\n readonly error?: unknown;\n}\n\nexport interface OfflineCacheRuntime {\n readonly caches?: CacheStorage;\n readonly fetch?: typeof fetch;\n readonly location?: Pick<Location, \"origin\">;\n readonly navigatorStorage?: StorageManager;\n}\n\nexport interface OfflineCacheOperationOptions extends OfflineCacheRuntime {\n readonly cachePrefix?: string;\n readonly logger?: OfflineCacheLogger;\n readonly quotaRiskRatio?: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface OfflineCacheWorkerScriptOptions {\n /** Require renewed host permission before any worker cache access (maximum 60 seconds). */\n readonly requireConsent?: boolean;\n readonly cachePrefix?: string;\n readonly buildId: string;\n readonly policy: OfflineCacheRequestPolicy;\n readonly navigationFallbackUrl?: string;\n}\n\nexport const DEFAULT_OFFLINE_CACHE_PREFIX = \"plasius-offline\";\n\nexport const DEFAULT_OFFLINE_CACHE_POLICY: Required<\n Pick<\n OfflineCacheRequestPolicy,\n | \"sameOriginOnly\"\n | \"publicNavigationPaths\"\n | \"immutableAssetPathPrefixes\"\n | \"publicAssetPathPrefixes\"\n | \"publicApiPathPrefixes\"\n | \"deniedPathPrefixes\"\n >\n> & Pick<OfflineCacheRequestPolicy, \"deniedPathPatterns\"> = Object.freeze({\n sameOriginOnly: true,\n publicNavigationPaths: Object.freeze([\"/\"]),\n immutableAssetPathPrefixes: Object.freeze([\"/assets/\", \"/favicon\", \"/manifest.json\"]),\n publicAssetPathPrefixes: Object.freeze([]),\n publicApiPathPrefixes: Object.freeze([]),\n deniedPathPrefixes: Object.freeze([\n \"/api/admin\",\n \"/api/ai\",\n \"/api/analytics\",\n \"/api/auth\",\n \"/api/game\",\n \"/api/oauth\",\n \"/api/player-system\",\n \"/api/profile\",\n \"/api/users\",\n \"/api/voice\",\n \"/admin\",\n \"/oauth\",\n \"/profile\",\n \"/player-system\",\n ]),\n deniedPathPatterns: Object.freeze([]),\n});\n\nconst SAFE_CACHE_SEGMENT_PATTERN = /[^a-z0-9._-]+/giu;\nconst DEFAULT_QUOTA_RISK_RATIO = 0.9;\n\nfunction sanitizeCacheSegment(value: string): string {\n const sanitized = value\n .trim()\n .toLowerCase()\n .replace(SAFE_CACHE_SEGMENT_PATTERN, \"-\")\n .replace(/^-+|-+$/gu, \"\");\n return sanitized || \"default\";\n}\n\nfunction resolveCacheStorage(runtime?: OfflineCacheRuntime): CacheStorage | undefined {\n return runtime?.caches ?? globalThis.caches;\n}\n\nfunction resolveFetch(runtime?: OfflineCacheRuntime): typeof fetch | undefined {\n return runtime?.fetch ?? globalThis.fetch;\n}\n\nfunction resolveNavigatorStorage(\n runtime?: OfflineCacheRuntime,\n): StorageManager | undefined {\n return runtime?.navigatorStorage ?? globalThis.navigator?.storage;\n}\n\nfunction resolveBaseOrigin(runtime?: OfflineCacheRuntime): string {\n return runtime?.location?.origin ?? globalThis.location?.origin ?? \"https://plasius.co.uk\";\n}\n\nfunction normalizeUrl(value: string, runtime?: OfflineCacheRuntime): string {\n return new URL(value, resolveBaseOrigin(runtime)).toString();\n}\n\nfunction toUrl(input: RequestInfo | URL, runtime?: OfflineCacheRuntime): URL | null {\n try {\n if (typeof input === \"string\") {\n return new URL(input, resolveBaseOrigin(runtime));\n }\n\n if (input instanceof URL) {\n return input;\n }\n\n const requestUrl = (input as Request).url;\n return typeof requestUrl === \"string\"\n ? new URL(requestUrl, resolveBaseOrigin(runtime))\n : null;\n } catch {\n return null;\n }\n}\n\nfunction getRequestMethod(input: RequestInfo | URL, init?: RequestInit): string {\n return (init?.method ?? (typeof input === \"object\" && \"method\" in input ? input.method : \"GET\"))\n .toString()\n .toUpperCase();\n}\n\nfunction hasNoStore(headers: Headers): boolean {\n return (headers.get(\"cache-control\") ?? \"\")\n .split(\",\")\n .some(directive => directive.trim().split(\"=\", 1)[0]?.toLowerCase() === \"no-store\");\n}\n\nfunction getRequestHeaders(input: RequestInfo | URL, init?: RequestInit): Headers {\n if (init?.headers) return new Headers(init.headers);\n return typeof input === \"object\" && \"headers\" in input ? new Headers(input.headers) : new Headers();\n}\n\nfunction pathStartsWith(pathname: string, prefixes: readonly string[] = []): boolean {\n return prefixes.some(prefix => pathname === prefix || pathname.startsWith(prefix));\n}\n\nfunction isNavigationRequest(input: RequestInfo | URL, init?: RequestInit): boolean {\n if (init?.headers) {\n const headers = new Headers(init.headers);\n if (headers.get(\"accept\")?.includes(\"text/html\")) {\n return true;\n }\n }\n\n return typeof input === \"object\" && \"mode\" in input && input.mode === \"navigate\";\n}\n\nexport function buildOfflineAssetCacheName(\n pack: Pick<OfflineCacheAssetPack, \"id\" | \"revision\">,\n cachePrefix = DEFAULT_OFFLINE_CACHE_PREFIX,\n): string {\n return [\n sanitizeCacheSegment(cachePrefix),\n \"asset-pack\",\n sanitizeCacheSegment(pack.id),\n sanitizeCacheSegment(pack.revision),\n ].join(\"-\");\n}\n\nexport function classifyOfflineCacheRequest(\n input: RequestInfo | URL,\n init?: RequestInit,\n policy: OfflineCacheRequestPolicy = DEFAULT_OFFLINE_CACHE_POLICY,\n runtime?: OfflineCacheRuntime,\n): OfflineCacheRequestDecision {\n const method = getRequestMethod(input, init);\n if (method !== \"GET\" && method !== \"HEAD\") {\n return { cacheable: false, strategy: \"no-cache\", reason: \"non-get-request\" };\n }\n if (hasNoStore(getRequestHeaders(input, init))) {\n return { cacheable: false, strategy: \"no-cache\", reason: \"request-cache-control-no-store\" };\n }\n\n const url = toUrl(input, runtime);\n if (!url) {\n return { cacheable: false, strategy: \"no-cache\", reason: \"invalid-url\" };\n }\n\n const sameOriginOnly = policy.sameOriginOnly ?? DEFAULT_OFFLINE_CACHE_POLICY.sameOriginOnly;\n if (sameOriginOnly && url.origin !== resolveBaseOrigin(runtime)) {\n return { cacheable: false, strategy: \"no-cache\", reason: \"cross-origin\" };\n }\n\n const pathname = url.pathname;\n if ((policy.deniedPathPatterns ?? []).some(pattern => pattern.test(pathname))) {\n return { cacheable: false, strategy: \"no-cache\", reason: \"denied-path-pattern\" };\n }\n\n if (\n pathStartsWith(\n pathname,\n policy.deniedPathPrefixes ?? DEFAULT_OFFLINE_CACHE_POLICY.deniedPathPrefixes,\n )\n ) {\n return { cacheable: false, strategy: \"no-cache\", reason: \"denied-path-prefix\" };\n }\n\n if (policy.immutableAssetPathPatterns?.some(pattern => new RegExp(pattern.source, pattern.flags).test(pathname))) {\n return { cacheable: true, strategy: \"cache-first\", reason: \"immutable-asset-pattern\", cacheBucket: \"immutable\" };\n }\n\n if (pathStartsWith(pathname, policy.publicApiPathPrefixes)) {\n return {\n cacheable: true,\n strategy: \"stale-while-revalidate\",\n reason: \"public-api\",\n cacheBucket: \"public-api\",\n };\n }\n\n if (pathStartsWith(pathname, policy.publicAssetPathPrefixes)) {\n return {\n cacheable: true,\n strategy: \"stale-while-revalidate\",\n reason: \"public-asset\",\n cacheBucket: \"public-asset\",\n };\n }\n\n if (\n pathStartsWith(\n pathname,\n policy.immutableAssetPathPrefixes\n ?? DEFAULT_OFFLINE_CACHE_POLICY.immutableAssetPathPrefixes,\n )\n ) {\n return {\n cacheable: true,\n strategy: \"cache-first\",\n reason: \"immutable-asset\",\n cacheBucket: \"immutable\",\n };\n }\n\n if (\n isNavigationRequest(input, init)\n && (policy.publicNavigationPaths ?? DEFAULT_OFFLINE_CACHE_POLICY.publicNavigationPaths)\n .includes(pathname)\n ) {\n return {\n cacheable: true,\n strategy: \"network-first\",\n reason: \"public-navigation\",\n cacheBucket: \"navigation\",\n };\n }\n\n return { cacheable: false, strategy: \"no-cache\", reason: \"unmatched\" };\n}\n\nasync function resolveAvailableBytes(\n pack: OfflineCacheAssetPack,\n options: OfflineCacheOperationOptions,\n): Promise<number | undefined> {\n if (typeof pack.estimatedBytes !== \"number\" || pack.estimatedBytes <= 0) {\n return undefined;\n }\n\n try {\n const estimate = await resolveNavigatorStorage(options)?.estimate?.();\n if (\n typeof estimate?.quota !== \"number\"\n || typeof estimate.usage !== \"number\"\n || estimate.quota <= estimate.usage\n ) {\n return undefined;\n }\n\n return estimate.quota - estimate.usage;\n } catch (error) {\n options.logger?.debug?.(\"offline cache quota estimate unavailable\", { error });\n return undefined;\n }\n}\n\nfunction resultStatus(results: readonly OfflineCacheUrlResult[]): OfflineCacheStatus {\n const cachedCount = results.filter(result => result.cached).length;\n if (cachedCount === results.length) {\n return \"ready\";\n }\n if (cachedCount > 0) {\n return \"partial\";\n }\n if (results.some(result => result.error === \"offline\")) {\n return \"offline\";\n }\n return \"error\";\n}\n\nexport async function warmAssetPack(\n pack: OfflineCacheAssetPack,\n options: OfflineCacheOperationOptions = {},\n): Promise<OfflineCacheAssetPackResult> {\n const cacheStorage = resolveCacheStorage(options);\n const fetchImpl = resolveFetch(options);\n const totalUrls = pack.urls.length;\n const cacheName = buildOfflineAssetCacheName(pack, options.cachePrefix);\n\n if (!cacheStorage || typeof fetchImpl !== \"function\") {\n return {\n id: pack.id,\n revision: pack.revision,\n status: \"unsupported\",\n cachedUrls: 0,\n totalUrls,\n results: [],\n estimatedBytes: pack.estimatedBytes,\n };\n }\n\n if (totalUrls === 0) {\n return {\n id: pack.id,\n revision: pack.revision,\n status: \"idle\",\n cacheName,\n cachedUrls: 0,\n totalUrls,\n results: [],\n estimatedBytes: pack.estimatedBytes,\n };\n }\n\n const availableBytes = await resolveAvailableBytes(pack, options);\n const riskRatio = options.quotaRiskRatio ?? DEFAULT_QUOTA_RISK_RATIO;\n if (\n typeof availableBytes === \"number\"\n && typeof pack.estimatedBytes === \"number\"\n && pack.estimatedBytes > availableBytes * riskRatio\n ) {\n return {\n id: pack.id,\n revision: pack.revision,\n status: \"quota-risk\",\n cacheName,\n cachedUrls: 0,\n totalUrls,\n results: [],\n estimatedBytes: pack.estimatedBytes,\n availableBytes,\n };\n }\n\n options.signal?.throwIfAborted();\n const cache = await cacheStorage.open(cacheName);\n if (options.signal?.aborted) {\n await cacheStorage.delete(cacheName);\n options.signal.throwIfAborted();\n }\n const results: OfflineCacheUrlResult[] = [];\n\n for (const rawUrl of pack.urls) {\n const url = normalizeUrl(rawUrl, options);\n try {\n options.signal?.throwIfAborted();\n const request = new Request(url, {\n method: \"GET\",\n credentials: \"same-origin\",\n cache: \"reload\",\n signal: options.signal,\n });\n const response = await fetchImpl(request);\n options.signal?.throwIfAborted();\n if (!response.ok) {\n const existing = await cache.match(url);\n results.push({\n url,\n cached: Boolean(existing),\n error: existing ? undefined : `http-${response.status}`,\n });\n continue;\n }\n\n if (hasNoStore(response.headers)) {\n await cache.delete(url);\n results.push({ url, cached: false, error: \"cache-control-no-store\" });\n continue;\n }\n\n await cache.put(url, response.clone());\n results.push({ url, cached: true });\n } catch (error) {\n options.signal?.throwIfAborted();\n const existing = await cache.match(url);\n const isOffline =\n typeof globalThis.navigator !== \"undefined\" && globalThis.navigator.onLine === false;\n results.push({\n url,\n cached: Boolean(existing),\n error: existing ? undefined : isOffline ? \"offline\" : String(error),\n });\n }\n }\n\n return {\n id: pack.id,\n revision: pack.revision,\n status: resultStatus(results),\n cacheName,\n cachedUrls: results.filter(result => result.cached).length,\n totalUrls,\n results,\n estimatedBytes: pack.estimatedBytes,\n availableBytes,\n };\n}\n\nexport async function getAssetPackStatus(\n pack: OfflineCacheAssetPack,\n options: OfflineCacheOperationOptions = {},\n): Promise<OfflineCacheAssetPackResult> {\n const cacheStorage = resolveCacheStorage(options);\n const totalUrls = pack.urls.length;\n const cacheName = buildOfflineAssetCacheName(pack, options.cachePrefix);\n\n if (!cacheStorage) {\n return {\n id: pack.id,\n revision: pack.revision,\n status: \"unsupported\",\n cachedUrls: 0,\n totalUrls,\n results: [],\n estimatedBytes: pack.estimatedBytes,\n };\n }\n\n if (totalUrls === 0) {\n return {\n id: pack.id,\n revision: pack.revision,\n status: \"idle\",\n cacheName,\n cachedUrls: 0,\n totalUrls,\n results: [],\n estimatedBytes: pack.estimatedBytes,\n };\n }\n\n const cache = await cacheStorage.open(cacheName);\n const results = await Promise.all(\n pack.urls.map(async rawUrl => {\n const url = normalizeUrl(rawUrl, options);\n return {\n url,\n cached: Boolean(await cache.match(url)),\n };\n }),\n );\n\n return {\n id: pack.id,\n revision: pack.revision,\n status: resultStatus(results),\n cacheName,\n cachedUrls: results.filter(result => result.cached).length,\n totalUrls,\n results,\n estimatedBytes: pack.estimatedBytes,\n };\n}\n\nexport async function clearOfflineCaches(options: {\n readonly cachePrefix?: string;\n readonly caches?: CacheStorage;\n} = {}): Promise<string[]> {\n const cacheStorage = options.caches ?? globalThis.caches;\n if (!cacheStorage) {\n return [];\n }\n\n const prefix = sanitizeCacheSegment(options.cachePrefix ?? DEFAULT_OFFLINE_CACHE_PREFIX);\n const cacheNames = await cacheStorage.keys();\n const deleted: string[] = [];\n for (const cacheName of cacheNames) {\n if (cacheName.startsWith(prefix) && await cacheStorage.delete(cacheName)) {\n deleted.push(cacheName);\n }\n }\n return deleted;\n}\n\nexport async function registerOfflineCacheWorker(\n options: RegisterOfflineCacheWorkerOptions = {},\n): Promise<RegisterOfflineCacheWorkerResult> {\n if (options.enabled === false) {\n return { status: \"disabled\" };\n }\n\n const serviceWorkerContainer =\n options.serviceWorkerContainer ?? globalThis.navigator?.serviceWorker;\n if (!serviceWorkerContainer) {\n return { status: \"unsupported\" };\n }\n\n const workerUrl = new URL(\n options.workerUrl ?? \"/offline-cache-worker.js\",\n globalThis.location?.origin ?? \"https://plasius.co.uk\",\n );\n if (options.buildId) {\n workerUrl.searchParams.set(\"build\", options.buildId);\n }\n\n try {\n const registration = await serviceWorkerContainer.register(workerUrl.toString(), {\n scope: options.scope ?? \"/\",\n });\n options.logger?.info?.(\"offline cache worker registered\", {\n workerUrl: workerUrl.pathname,\n scope: registration.scope,\n });\n return {\n status: \"registered\",\n registration,\n };\n } catch (error) {\n options.logger?.warn?.(\"offline cache worker registration failed\", { error });\n return {\n status: \"error\",\n error,\n };\n }\n}\n\nexport function createOfflineCacheWorkerScript(\n options: OfflineCacheWorkerScriptOptions,\n): string {\n const cachePrefix = sanitizeCacheSegment(\n options.cachePrefix ?? DEFAULT_OFFLINE_CACHE_PREFIX,\n );\n const buildId = sanitizeCacheSegment(options.buildId);\n const policyJson = JSON.stringify({ ...options.policy,\n immutableAssetPathPatterns: options.policy.immutableAssetPathPatterns?.map(pattern => ({ source: pattern.source, flags: pattern.flags })),\n deniedPathPatterns: options.policy.deniedPathPatterns?.map(pattern => ({ source: pattern.source, flags: pattern.flags })),\n });\n const fallbackUrl = JSON.stringify(options.navigationFallbackUrl ?? \"/\");\n\n return `\nconst CACHE_PREFIX = ${JSON.stringify(cachePrefix)};\nconst BUILD_ID = ${JSON.stringify(buildId)};\nconst APP_CACHE = CACHE_PREFIX + \"-app-\" + BUILD_ID;\nconst PUBLIC_CACHE = CACHE_PREFIX + \"-public-\" + BUILD_ID;\nconst POLICY = ${policyJson};\nconst NAVIGATION_FALLBACK_URL = ${fallbackUrl};\nconst REQUIRE_CONSENT = ${options.requireConsent === true};\nlet permissionUntil = REQUIRE_CONSENT ? 0 : Infinity;\nlet permissionGeneration = 0;\nconst permitted = (generation) => generation === permissionGeneration && Date.now() < permissionUntil;\nasync function discardCaches() {\n const names = await caches.keys();\n await Promise.all(names.filter(name => name.startsWith(CACHE_PREFIX + \"-\")).map(name => caches.delete(name)));\n}\nself.addEventListener(\"message\", event => {\n if (!REQUIRE_CONSENT || event.data?.type !== \"plasius-offline-consent-v1\") return;\n try { if (new URL(event.source?.url).origin !== self.location.origin) return; } catch { return; }\n const requested = event.data.allowedUntil;\n permissionUntil = typeof requested === \"number\" && Number.isFinite(requested)\n ? Math.min(requested, Date.now() + 60_000) : 0;\n const disabled = permissionUntil <= Date.now();\n if (disabled) permissionGeneration++;\n event.waitUntil((async () => {\n if (disabled) await discardCaches();\n event.ports?.[0]?.postMessage({ type: \"plasius-offline-consent-v1\", disabled });\n })());\n});\n\nconst startsWithAny = (pathname, prefixes = []) => prefixes.some((prefix) => pathname === prefix || pathname.startsWith(prefix));\nconst matchesAny = (pathname, patterns = []) => patterns.some(pattern => new RegExp(pattern.source, pattern.flags).test(pathname));\nconst isDenied = (pathname) => startsWithAny(pathname, POLICY.deniedPathPrefixes || []) || matchesAny(pathname, POLICY.deniedPathPatterns);\nconst hasNoStore = (headers) => (headers.get(\"cache-control\") || \"\").split(\",\").some((directive) => directive.trim().split(\"=\", 1)[0].toLowerCase() === \"no-store\");\nconst classify = (request) => {\n if (request.method !== \"GET\" && request.method !== \"HEAD\") return { cacheable: false, strategy: \"no-cache\" };\n if (hasNoStore(request.headers)) return { cacheable: false, strategy: \"no-cache\", reason: \"request-cache-control-no-store\" };\n const url = new URL(request.url);\n if (POLICY.sameOriginOnly !== false && url.origin !== self.location.origin) return { cacheable: false, strategy: \"no-cache\" };\n if (isDenied(url.pathname)) return { cacheable: false, strategy: \"no-cache\" };\n if (matchesAny(url.pathname, POLICY.immutableAssetPathPatterns)) return { cacheable: true, strategy: \"cache-first\", cacheName: PUBLIC_CACHE };\n if (startsWithAny(url.pathname, POLICY.publicApiPathPrefixes || [])) return { cacheable: true, strategy: \"stale-while-revalidate\", cacheName: PUBLIC_CACHE };\n if (startsWithAny(url.pathname, POLICY.publicAssetPathPrefixes || [])) return { cacheable: true, strategy: \"stale-while-revalidate\", cacheName: PUBLIC_CACHE };\n if (startsWithAny(url.pathname, POLICY.immutableAssetPathPrefixes || [])) return { cacheable: true, strategy: \"cache-first\", cacheName: APP_CACHE };\n if (request.mode === \"navigate\" && (POLICY.publicNavigationPaths || []).includes(url.pathname)) return { cacheable: true, strategy: \"network-first\", cacheName: APP_CACHE };\n return { cacheable: false, strategy: \"no-cache\" };\n};\n\nself.addEventListener(\"install\", (event) => {\n event.waitUntil(self.skipWaiting());\n});\n\nself.addEventListener(\"activate\", (event) => {\n event.waitUntil((async () => {\n const names = await caches.keys();\n await Promise.all(names.filter((name) => name.startsWith(CACHE_PREFIX + \"-\") && !name.endsWith(\"-\" + BUILD_ID) && !name.includes(\"-asset-pack-\")).map((name) => caches.delete(name)));\n await self.clients.claim();\n })());\n});\n\nasync function openPermittedCache(cacheName, generation) {\n if (!permitted(generation)) return null;\n const cache = await caches.open(cacheName);\n if (!permitted(generation)) {\n await caches.delete(cacheName);\n return null;\n }\n return cache;\n}\n\nasync function cacheFirst(request, cacheName, generation) {\n const cache = await openPermittedCache(cacheName, generation);\n if (!cache) return fetch(request);\n const cached = await cache.match(request);\n if (!permitted(generation)) return fetch(request);\n if (cached && !hasNoStore(cached.headers)) return cached;\n if (cached) await cache.delete(request);\n const response = await fetch(request);\n if (!permitted(generation)) return response;\n if (response.ok && !hasNoStore(response.headers)) await cache.put(request, response.clone());\n if (hasNoStore(response.headers)) await cache.delete(request);\n return response;\n}\n\nasync function staleWhileRevalidate(request, cacheName, generation) {\n const cache = await openPermittedCache(cacheName, generation);\n if (!cache) return fetch(request);\n const candidate = await cache.match(request);\n if (!permitted(generation)) return fetch(request);\n const cached = candidate && !hasNoStore(candidate.headers) ? candidate : undefined;\n if (candidate && !cached) await cache.delete(request);\n const refresh = fetch(request).then(async response => {\n if (!permitted(generation)) return response;\n if (response.ok && !hasNoStore(response.headers)) await cache.put(request, response.clone());\n if (hasNoStore(response.headers)) await cache.delete(request);\n return response;\n });\n if (cached) void refresh.catch(() => undefined);\n return cached || refresh;\n}\n\nasync function networkFirst(request, cacheName, generation) {\n const cache = await openPermittedCache(cacheName, generation);\n if (!cache) return fetch(request);\n try {\n const response = await fetch(request);\n if (!permitted(generation)) return response;\n if (response.ok && !hasNoStore(response.headers)) await cache.put(request, response.clone());\n if (hasNoStore(response.headers)) await cache.delete(request);\n return response;\n } catch {\n if (!permitted(generation)) return Response.error();\n const cached = await cache.match(request);\n if (!permitted(generation)) return Response.error();\n if (cached && !hasNoStore(cached.headers)) return cached;\n if (cached) await cache.delete(request);\n const fallback = await cache.match(NAVIGATION_FALLBACK_URL);\n return permitted(generation) && fallback && !hasNoStore(fallback.headers) ? fallback : Response.error();\n }\n}\n\nself.addEventListener(\"fetch\", (event) => {\n const generation = permissionGeneration;\n if (!permitted(generation)) return;\n const decision = classify(event.request);\n if (!decision.cacheable) return;\n if (decision.strategy === \"cache-first\") event.respondWith(cacheFirst(event.request, decision.cacheName, generation));\n if (decision.strategy === \"stale-while-revalidate\") event.respondWith(staleWhileRevalidate(event.request, decision.cacheName, generation));\n if (decision.strategy === \"network-first\") event.respondWith(networkFirst(event.request, decision.cacheName, generation));\n});\n`.trimStart();\n}\n"],"mappings":";AAyGO,IAAM,+BAA+B;AAErC,IAAM,+BAU+C,OAAO,OAAO;AAAA,EACxE,gBAAgB;AAAA,EAChB,uBAAuB,OAAO,OAAO,CAAC,GAAG,CAAC;AAAA,EAC1C,4BAA4B,OAAO,OAAO,CAAC,YAAY,YAAY,gBAAgB,CAAC;AAAA,EACpF,yBAAyB,OAAO,OAAO,CAAC,CAAC;AAAA,EACzC,uBAAuB,OAAO,OAAO,CAAC,CAAC;AAAA,EACvC,oBAAoB,OAAO,OAAO;AAAA,IAChC;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,CAAC;AAAA,EACD,oBAAoB,OAAO,OAAO,CAAC,CAAC;AACtC,CAAC;AAED,IAAM,6BAA6B;AACnC,IAAM,2BAA2B;AAEjC,SAAS,qBAAqB,OAAuB;AACnD,QAAM,YAAY,MACf,KAAK,EACL,YAAY,EACZ,QAAQ,4BAA4B,GAAG,EACvC,QAAQ,aAAa,EAAE;AAC1B,SAAO,aAAa;AACtB;AAEA,SAAS,oBAAoB,SAAyD;AACpF,SAAO,SAAS,UAAU,WAAW;AACvC;AAEA,SAAS,aAAa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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA0HvD,UAAU;AACZ;","names":[]}
@@ -0,0 +1,28 @@
1
+ # ADR-0002: Hosted OIDC Package Publication
2
+
3
+ - Status: Accepted
4
+ - Date: 2026-08-11
5
+
6
+ ## Context
7
+
8
+ `@plasius/offline-cache` must publish without a long-lived npm write token and without
9
+ accepting CI evidence for another source snapshot.
10
+
11
+ ## Decision
12
+
13
+ Publication is phase-isolated: dependency installation, package validation, SBOM generation, and immutable tarball packing run in `validate_and_pack` without the `production` environment or OIDC permission. The final hosted `publish` job downloads only that sealed artifact, explicitly installs npm 11.6.2, runs no repository dependency code, and publishes the tarball with lifecycle scripts disabled. It re-fetches current `main` immediately before the first release mutation and again immediately before npm publication. `.npmrc` contains no registry-auth placeholder, and release preparation returns the reviewed current `main` HEAD rather than package-file history.
14
+
15
+ Publish only from the GitHub-hosted `production` job using npm trusted
16
+ publishing. Prove the prepared SHA is still the exact remote `main` head and
17
+ that push-triggered `ci.yml` succeeded for it. Require Node 24 and npm 11.5.1 or
18
+ newer, request provenance, and prohibit npm write-token fallbacks. Reviewed CI
19
+ uses explicit GitHub-hosted runners; fork PR code is denied.
20
+
21
+ ## Consequences
22
+
23
+ Missing trust configuration, moved `main`, absent CI, unsupported runtime, or
24
+ missing OIDC identity fails closed before publication.
25
+
26
+ ## Test implications
27
+
28
+ Workflow tests enforce source, CI, runtime, identity, runner, and token rules.
@@ -0,0 +1,14 @@
1
+ # ADR 0004: Optional worker storage requires current host permission
2
+
3
+ Status: Accepted
4
+
5
+ Consent-aware workers start denied and require a same-origin host permission lease
6
+ of at most 60 seconds. The host combines its versioned visitor choice with the
7
+ persisted flag `site.privacy.optional-processing.enabled`. Withdrawal invalidates
8
+ in-flight cache operations before scoped deletion and acknowledgement. Ordinary
9
+ worker generation stays compatible. No identifier or persistent consent copy is
10
+ introduced in the worker. A restart/expired lease fails closed; offline operation
11
+ is bounded by the lease, so hosts must not promise indefinite offline access.
12
+ Legacy controllers require a migration/detachment before revocation is verified.
13
+
14
+ Tracking: site Feature #2206, Story #2207; offline-cache Task #12.
@@ -1,3 +1,5 @@
1
1
  # ADR Index
2
2
 
3
3
  - [ADR 0001: Browser CacheStorage Package Boundary](./adr-0001-browser-cache-storage-package-boundary.md)
4
+ - [ADR-0002: Hosted OIDC Package Publication](./adr-0002-hosted-oidc-package-publication.md)
5
+ - [ADR 0004: Worker consent lifecycle](./adr-0004-worker-consent-lifecycle.md)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@plasius/offline-cache",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "Browser offline cache helpers for Plasius progressive public sites and demo asset packs.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -63,17 +63,17 @@
63
63
  "homepage": "https://github.com/Plasius-LTD/offline-cache#readme",
64
64
  "devDependencies": {
65
65
  "@eslint/js": "^10.0.1",
66
- "@types/node": "^25.7.0",
67
- "@typescript-eslint/eslint-plugin": "^8.59.3",
68
- "@typescript-eslint/parser": "^8.59.3",
69
- "@vitest/coverage-v8": "^4.1.6",
70
- "eslint": "^10.3.0",
66
+ "@types/node": "^25.9.5",
67
+ "@typescript-eslint/eslint-plugin": "^8.65.0",
68
+ "@typescript-eslint/parser": "^8.65.0",
69
+ "@vitest/coverage-v8": "^4.1.10",
70
+ "eslint": "^10.7.0",
71
71
  "globals": "^17.6.0",
72
72
  "rimraf": "^6.1.3",
73
73
  "tsup": "^8.5.1",
74
- "tsx": "^4.21.0",
74
+ "tsx": "^4.23.1",
75
75
  "typescript": "^6.0.3",
76
- "vitest": "^4.1.6"
76
+ "vitest": "^4.1.10"
77
77
  },
78
78
  "publishConfig": {
79
79
  "access": "public"
@@ -89,7 +89,13 @@
89
89
  }
90
90
  ],
91
91
  "overrides": {
92
- "minimatch": "^10.2.1"
92
+ "nanoid": "3.3.18",
93
+ "postcss": "8.5.26",
94
+ "brace-expansion": "5.0.9",
95
+ "minimatch": "^10.2.1",
96
+ "tsup": {
97
+ "esbuild": "0.28.1"
98
+ }
93
99
  },
94
100
  "engines": {
95
101
  "node": ">=24"
@@ -1,2 +0,0 @@
1
- type,github_handle,full_name,company,email,date,approver
2
- corporate,Zephod111r,Phillip Hounslow,Plasius LTD,zephod@plasius.co.uk,2025-09-12,Phillip Hounslow (Maintainer)