///
// Wayfarer's service worker (P1.6). Compiled and given its asset manifest by
// scripts/build-sw.mjs, served at sw.js beside the app (/app/sw.js on the
// hosted site, W1), with the app's folder as its scope. It replaces
// @angular/service-worker, which answered failed cross-origin requests with a
// synthetic 504 (F06).
//
// Rules:
// - Cross-origin requests are never intercepted: the user's API calls go
// straight to the network, and their failures reach the app unchanged.
// - Navigations are network-first, falling back to the cached app shell, so
// the app loads offline after one visit, and after 3 s on a connection that
// is up but answers nothing. Not those under oauth/: that is the OAuth
// callback page, which is not the app.
// - Hashed same-origin assets are cache-first (their names change when their
// content does). The initial ones, the shell's static imports included, are precached at install; lazy chunks are
// cached the first time they load.
// - A new version waits until the page asks it to take over (the "Update
// available" banner), so a running page never mixes old and new chunks.
declare const WAYFARER_SW: { version: string; precache: string[] };
// A classic worker script (not a module), so `self` keeps its global type.
const sw = self as unknown as ServiceWorkerGlobalScope;
const CACHE_PREFIX = "wayfarer-";
const CACHE = `${CACHE_PREFIX}${WAYFARER_SW.version}`;
// The app's folder ("/app/"): the manifest's paths are the build's, from its root ("/" is index.html).
const SCOPE = new URL(sw.registration.scope).pathname;
const SHELL = SCOPE;
const PRECACHE = WAYFARER_SW.precache.map((path) => SCOPE + path.slice(1));
const NOT_THE_APP = `${SCOPE}oauth/`;
// The build's output hashes: main-XU6HGUMA.js, media/inter-latin-…-B6TL4M5W.woff2, and for a lazy chunk
// chunk-iAuoh2-d.js. Upper case alone left 20 of 28 lazy chunks out of the cache (F84).
const HASHED = /-[A-Za-z0-9_-]{8}\.[a-z0-9]+$/;
// How long a navigation waits for the network before the stored shell answers.
const STALLED_MS = 3000;
sw.addEventListener("install", (event) => {
event.waitUntil(
(async () => {
const cache = await caches.open(CACHE);
await cache.addAll(PRECACHE.map((path) => new Request(path, { cache: "reload" })));
// A first install takes over at once; a new build waits for the page's go-ahead.
if (!sw.registration.active) await sw.skipWaiting();
})(),
);
});
sw.addEventListener("activate", (event) => {
event.waitUntil(
(async () => {
// The cache of the build this one replaces.
for (const key of await caches.keys()) {
if (key.startsWith(CACHE_PREFIX) && key !== CACHE) await caches.delete(key);
}
await sw.clients.claim();
})(),
);
});
sw.addEventListener("message", (event) => {
if (event.data === "SKIP_WAITING") void sw.skipWaiting();
else if (Array.isArray((event.data as { loaded?: unknown } | null)?.loaded))
event.waitUntil(keep((event.data as { loaded: unknown[] }).loaded));
});
/**
* Keeps the files a page loaded before this worker controlled it (its first visit), as the fetch handler would
* have: same-origin and hashed only. They come from the browser's own cache, or from the network again.
*/
async function keep(loaded: unknown[]): Promise {
const paths = loaded.flatMap((entry) => {
const url = typeof entry === "string" && URL.canParse(entry) ? new URL(entry) : null;
return url && url.origin === sw.location.origin && HASHED.test(url.pathname) ? [url.pathname] : [];
});
await Promise.allSettled([...new Set(paths)].map((path) => cacheFirst(new Request(path))));
}
sw.addEventListener("fetch", (event) => {
const request = event.request;
const url = new URL(request.url);
if (url.origin !== sw.location.origin || request.method !== "GET") return;
// The OAuth callback page (`public/oauth/`) is a page of its own, not the
// app: it is left to the network, so it is never stored as the shell (F69)
// and the shell is never served in its place.
if (url.pathname.startsWith(NOT_THE_APP)) return;
if (request.mode === "navigate") {
event.respondWith(networkFirstShell(event));
} else if (HASHED.test(url.pathname) || PRECACHE.includes(url.pathname)) {
event.respondWith(cacheFirst(request));
}
});
async function networkFirstShell(event: FetchEvent): Promise {
const network = fetch(event.request).then(async (response) => {
// Only the SPA's index.html is the shell; a navigation to a text file
// (THIRD_PARTY_NOTICES.md, security.txt) must not replace it.
if (response.ok && isHtml(response)) await (await caches.open(CACHE)).put(SHELL, response.clone());
return response;
});
// An answer that comes after the stored shell did still refreshes it.
event.waitUntil(Promise.allSettled([network]));
// A connection that is up but answers nothing (lie-fi) hangs until the browser gives up: the stored shell
// answers first, when there is one.
const stalled = new Promise((resolve) =>
setTimeout(() => resolve(caches.match(SHELL)), STALLED_MS),
);
try {
return (await Promise.race([network, stalled])) ?? (await network);
} catch (error) {
// Offline or unreachable: serve the cached shell (every route is the SPA).
const cached = await caches.match(SHELL);
if (cached) return cached;
throw error;
}
}
async function cacheFirst(request: Request): Promise {
const cached = await caches.match(request);
if (cached) return cached;
const response = await fetch(request);
// A missing asset gets the SPA's index.html with a 200 from the host; never
// cache that under a script or font URL.
if (response.ok && !isHtml(response)) await (await caches.open(CACHE)).put(request, response.clone());
return response;
}
function isHtml(response: Response): boolean {
return response.headers.get("content-type")?.includes("text/html") ?? false;
}