Add service worker implementation and tests for PWA caching strategy

- Implemented a service worker (sw.js) that handles installation, activation, and fetch events.
- Added caching logic for public assets and a fallback for offline navigation.
- Created unit tests (sw.test.ts) to validate service worker behavior, including asset caching, navigation handling, and activation logic.
- Ensured that private API routes and third-party requests are excluded from caching.
This commit is contained in:
syntaxbullet
2026-09-08 17:19:12 +02:00
parent e081e9acbf
commit ccd998ab04
29 changed files with 795 additions and 13 deletions

View File

@@ -18,6 +18,8 @@ export function createApi(db: AppDatabase, config: AuthConfig, request?: FetchDi
app.use("*", async (c, next) => {
const requestId = crypto.randomUUID();
c.set("requestId", requestId); c.header("X-Request-ID", requestId);
// Accounts, calendars, exports and OAuth responses must never enter HTTP caches.
c.header("Cache-Control", "no-store");
await next();
});
const auth = createAuth(db, config, request, now);

View File

@@ -11,6 +11,7 @@ const authErrors: Record<string, string> = {
};
function signIn() {
if (navigator.onLine === false) return;
let timezone = "UTC";
try { timezone = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC"; } catch { /* Use UTC fallback. */ }
window.location.assign(`/api/auth/discord?${new URLSearchParams({ timezone })}`);
@@ -21,6 +22,7 @@ type AuthState = {
loading: boolean;
busy: boolean;
accountError: string;
connectionError: boolean;
error: string;
signIn: () => void;
signOut: () => Promise<void>;
@@ -34,6 +36,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
const [loading, setLoading] = useState(true);
const [busy, setBusy] = useState(false);
const [accountError, setAccountError] = useState("");
const [connectionError, setConnectionError] = useState(false);
const [actionError, setActionError] = useState("");
const [attempt, setAttempt] = useState(0);
const { search } = useLocation();
@@ -42,15 +45,22 @@ export function AuthProvider({ children }: { children: ReactNode }) {
useEffect(() => {
const controller = new AbortController();
async function loadUser() {
let reachedServer = false;
try {
const response = await fetch("/api/me", { signal: controller.signal });
setAccountError("");
setConnectionError(false);
const response = await fetch("/api/me", { signal: AbortSignal.any([controller.signal, AbortSignal.timeout(10_000)]) });
reachedServer = true;
if (controller.signal.aborted) return;
if (response.status === 401) { setUser(null); return; }
if (!response.ok) throw new Error("Could not load your account. Please try again.");
const account: PublicUser = await response.json();
if (!controller.signal.aborted) setUser(account);
} catch (error) {
if (!controller.signal.aborted) setAccountError(error instanceof Error ? error.message : "Could not load your account.");
if (!controller.signal.aborted) {
setConnectionError(!reachedServer);
setAccountError(!reachedServer ? "Could not connect to Mina Habits. Check your connection and try again." : error instanceof Error ? error.message : "Could not load your account.");
}
} finally {
if (!controller.signal.aborted) setLoading(false);
}
@@ -59,6 +69,15 @@ export function AuthProvider({ children }: { children: ReactNode }) {
return () => controller.abort();
}, [attempt]);
useEffect(() => {
const reconnect = () => { if (accountError) retry(); };
const check = () => { if (connectionError && navigator.onLine !== false && document.visibilityState === "visible") retry(); };
const timer = window.setInterval(check, 15_000);
window.addEventListener("online", reconnect);
window.addEventListener("focus", check);
return () => { window.clearInterval(timer); window.removeEventListener("online", reconnect); window.removeEventListener("focus", check); };
}, [accountError, connectionError]);
function retry() {
setAccountError("");
setLoading(true);
@@ -69,6 +88,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
setBusy(true);
setActionError("");
try {
if (navigator.onLine === false) throw new Error("Reconnect to sign out.");
const response = await fetch("/api/auth/logout", { method: "POST" });
if (!response.ok) throw new Error("Could not sign out. Please try again.");
setUser(null);
@@ -78,7 +98,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
}
return (
<AuthContext.Provider value={{ user, loading, busy, accountError, error: accountError || actionError || signInError || "", signIn, signOut, retry }}>
<AuthContext.Provider value={{ user, loading, busy, accountError, connectionError, error: accountError || actionError || signInError || "", signIn, signOut, retry }}>
{children}
</AuthContext.Provider>
);

View File

@@ -0,0 +1,43 @@
import { useState } from "react";
import { applyUpdate, installApp, useOnline, usePwa } from "../pwa/client";
import { Button } from "./design-system/primitives";
import { Modal } from "./design-system/Modal";
export function InstallApp() {
const { enabled, installed, installPrompt } = usePwa();
const [help, setHelp] = useState(false);
if (!enabled || installed) return null;
return <>
<Button variant="text" onClick={() => { if (installPrompt) void installApp(); else setHelp(true); }}>Install app</Button>
{help && <Modal id="install-app" size="compact" title="Keep Mina Habits close." onClose={() => setHelp(false)}>
<div className="ds-form-stack">
<p>Open Mina Habits from your home screen or dock.</p>
<p><strong>iPhone or iPad:</strong> open the Share menu, then choose Add to Home Screen.</p>
<p><strong>Mac Safari:</strong> choose File → Add to Dock.</p>
<p><strong>Chrome or Edge:</strong> use the install icon in the address bar, or Install app in the browser menu.</p>
<p className="ds-supporting-copy">Installation options depend on your browser. Your habits still need a connection to load and save.</p>
<div className="ds-actions"><Button onClick={() => setHelp(false)}>Got it</Button></div>
</div>
</Modal>}
</>;
}
export function PwaStatus() {
const online = useOnline();
const { updateReady, error } = usePwa();
const [confirmUpdate, setConfirmUpdate] = useState(false);
return <>
{!online && <div className="ds-form-feedback" role="status">You’re offline. Reconnect to load or save your habits. Changes are not queued.</div>}
{error && <div className="ds-form-feedback" role="status">{error}</div>}
{updateReady && <div className="ds-action-row" role="status">
<span>A new version of Mina Habits is ready.</span>
<Button variant="secondary" onClick={() => setConfirmUpdate(true)}>Update app</Button>
</div>}
{confirmUpdate && <Modal id="update-app" size="compact" title="Ready to update?" onClose={() => setConfirmUpdate(false)}>
<div className="ds-form-stack">
<p>This window will reload. Save any unfinished changes first.</p>
<div className="ds-actions"><Button onClick={applyUpdate}>Reload and update</Button><Button variant="text" onClick={() => setConfirmUpdate(false)}>Later</Button></div>
</div>
</Modal>}
</>;
}

View File

@@ -13,6 +13,7 @@ export function ThemeProvider({ children }: { children: ReactNode }) {
document.documentElement.dataset.theme = theme;
document.documentElement.classList.toggle("dark", theme === "dark");
document.documentElement.style.colorScheme = theme;
document.querySelector('meta[name="theme-color"]')?.setAttribute("content", theme === "dark" ? "#191e1b" : "#ffffff");
}, [theme]);
useEffect(() => {
const media = window.matchMedia?.("(prefers-color-scheme: dark)");

View File

@@ -2,6 +2,7 @@ import type { ReactNode } from "react";
import { Link } from "react-router";
import { ThemeControl } from "../ThemeProvider";
import { Button } from "./primitives";
import { InstallApp, PwaStatus } from "../PwaControls";
/** The existing design-system page shell, shared without page-specific styling. */
export function PageLayout({
@@ -34,10 +35,12 @@ export function PageLayout({
<div className="ds-header-actions">{header}<ThemeControl /></div>
</header>
<main id={mainId} className="ds-main" tabIndex={-1}>
<PwaStatus />
{children}
<footer className="ds-footer">
<span className="ds-wordmark">Mina Habits.</span>
<span>A little, every day.</span>
<InstallApp />
<Button
variant="text"
onClick={() => window.scrollTo({ top: 0, behavior: "instant" })}

View File

@@ -3,6 +3,9 @@ import { createRoot } from "react-dom/client";
import { BrowserRouter } from "react-router";
import { App } from "./App";
import "../styles/globals.css";
import { startPwa } from "./pwa/client";
if (process.env.NODE_ENV === "production") startPwa();
const container = document.getElementById("root")!;
const root = import.meta.hot

View File

@@ -2,7 +2,14 @@
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<base href="/" />
<link rel="manifest" href="./pwa/manifest.webmanifest" />
<meta name="theme-color" content="#ffffff" />
<meta name="mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-title" content="Mina Habits" />
<meta name="apple-mobile-web-app-status-bar-style" content="default" />
<link rel="icon" type="image/png" sizes="32x32" href="./assets/favicon.png" />
<link rel="apple-touch-icon" sizes="180x180" href="./assets/apple-touch-icon.png" />
<title>Mina Habits</title>
@@ -11,5 +18,6 @@
</head>
<body>
<div id="root"></div>
<noscript>Mina Habits needs JavaScript to display your habits. Enable JavaScript and reload this page.</noscript>
</body>
</html>

View File

@@ -1,4 +1,5 @@
import { browserFont } from "./browser-fonts";
import { pwaAsset } from "./pwa/assets";
import { startReminders } from "./reminders/worker";
import { backupConfig, startBackups } from "./ops/backups";
import { databasePath } from "./db/config";
@@ -30,6 +31,9 @@ const server = Bun.serve({
hostname: process.env.HOST ?? "127.0.0.1",
port: Number(process.env.PORT ?? 3000),
routes: {
"/manifest.webmanifest": pwaAsset,
"/sw.js": pwaAsset,
"/pwa/*": pwaAsset,
"/fonts/browser/*": browserFont,
"/api": req => app.fetch(req),
"/api/*": req => app.fetch(req),

View File

@@ -14,6 +14,8 @@ export async function habitRequest<T>(
path: string,
options?: RequestInit,
): Promise<T> {
if (typeof navigator !== "undefined" && navigator.onLine === false)
throw new Error("You’re offline. Reconnect and try again. Changes have not been saved or queued.");
const response = await fetch(`/api${path}`, options);
if (!response.ok) {
if (response.status === 401)

View File

@@ -1,4 +1,5 @@
import { deferred } from "../components/design-system/deferred";
import { useOnline } from "../pwa/client";
import { CalendarCacheProvider } from "../components/CalendarCache";
import { Archive, Plus, Settings2 } from "lucide-react";
const ArchivedHabits = deferred(() => import("../components/ArchivedHabits").then(module => module.ArchivedHabits));
@@ -30,22 +31,24 @@ import type { Schedule } from "../habits/contracts";
const ShareProgress = deferred(() => import("../components/ShareProgress").then(module => module.ShareProgress));
export function Home() {
const { user, loading, busy, error, accountError, signIn, signOut, retry } = useAuth();
const online = useOnline();
const { user, loading, busy, error, accountError, connectionError, signIn, signOut, retry } = useAuth();
const disconnected = !online || connectionError;
return (
<PageLayout
header={
loading ? (
<span className="ds-library-label">Loading account…</span>
) : user ? (
<Button variant="text" disabled={busy} onClick={() => void signOut()}>
<Button variant="text" disabled={busy || !online} onClick={() => void signOut()}>
{busy ? "Signing out…" : "Sign out"}
</Button>
) : (
!accountError && <DiscordSignInButton variant="secondary" onClick={signIn} />
!accountError && <DiscordSignInButton disabled={!online} variant="secondary" onClick={signIn} />
)
}
>
{error && (
{error && !disconnected && (
<div className="ds-form-feedback" role="alert">
{error}
</div>
@@ -56,9 +59,9 @@ export function Home() {
</section>
) : accountError ? (
<section className="ds-section">
<h1 className="type-section">Let’s try that again.</h1>
<Card headingLevel={2} heading="Account unavailable">
<p>Your account couldn’t be loaded.</p>
<h1 className="type-section">{disconnected ? "A moment to reconnect." : "Let’s try that again."}</h1>
<Card headingLevel={2} heading={disconnected ? "Your habits will be here." : "Account unavailable"}>
<p>{disconnected ? "We can’t connect to Mina Habits. Check your internet connection to load your account and check in. We’ll try again automatically." : "Your account couldn’t be loaded."}</p>
<div className="ds-actions">
<Button onClick={retry}>Try again</Button>
</div>
@@ -74,6 +77,7 @@ export function Home() {
}
function Welcome({ onSignIn }: { onSignIn: () => void }) {
const online = useOnline();
const [water, setWater] = useState(3);
const [read, setRead] = useState(false);
return (
@@ -93,7 +97,7 @@ function Welcome({ onSignIn }: { onSignIn: () => void }) {
day at a time.
</p>
<div className="ds-actions">
<DiscordSignInButton onClick={onSignIn} />
<DiscordSignInButton disabled={!online} onClick={onSignIn} />
<ButtonLink href="#try-it">Try it below ↓</ButtonLink>
</div>
<p className="type-small">Sign in with your Discord account to save your habits.</p>
@@ -230,14 +234,16 @@ function Dashboard({ user, onExpired }: { user: PublicUser; onExpired: () => voi
// Refresh after returning to the page and across the account's local midnight.
useEffect(() => {
const refresh = () => {
if (!saving.current && progressSaves.current.size === 0 && document.visibilityState === "visible")
if (navigator.onLine !== false && !saving.current && progressSaves.current.size === 0 && document.visibilityState === "visible")
setAttempt((value) => value + 1);
};
const timer = window.setInterval(refresh, 60_000);
window.addEventListener("focus", refresh);
window.addEventListener("online", refresh);
return () => {
window.clearInterval(timer);
window.removeEventListener("focus", refresh);
window.removeEventListener("online", refresh);
};
}, []);

26
src/pwa/assets.ts Normal file
View File

@@ -0,0 +1,26 @@
import path from "node:path";
import { manifest } from "./manifest";
/** Serve only public PWA files. Never expose the server bundle or source maps. */
export function pwaAsset(request: Request): Response {
const pathname = new URL(request.url).pathname;
const headers = { "Cache-Control": "no-cache", "X-Content-Type-Options": "nosniff" };
if (!["GET", "HEAD"].includes(request.method)) return new Response(null, { status: 405, headers: { ...headers, Allow: "GET, HEAD" } });
if (pathname === "/manifest.webmanifest") {
return new Response(request.method === "HEAD" ? null : JSON.stringify(manifest), { headers: { ...headers, "Content-Type": "application/manifest+json" } });
}
const production = process.env.NODE_ENV === "production";
const filename = pathname.slice("/pwa/".length);
const icon = /^icon-(192|512|maskable-512)\.png$/.test(filename);
const shell = production && /^shell-[a-f0-9]{16}\.html$/.test(filename);
if (pathname !== "/sw.js" && !icon && !shell) return new Response(null, { status: 404, headers });
if (pathname === "/sw.js" && !production) return new Response(null, { status: 404, headers });
const file = Bun.file(path.resolve(production ? "pwa" : "src/pwa/public", pathname === "/sw.js" ? "sw.js" : filename));
if (!file.size) return new Response(null, { status: 404, headers });
return new Response(request.method === "HEAD" ? null : file, { headers: {
...headers,
"Content-Type": icon ? "image/png" : shell ? "text/html; charset=utf-8" : "text/javascript; charset=utf-8",
...(pathname === "/sw.js" ? { "Service-Worker-Allowed": "/" } : {}),
...(shell ? { "Cache-Control": "public, max-age=31536000, immutable" } : {}),
} });
}

90
src/pwa/client.ts Normal file
View File

@@ -0,0 +1,90 @@
import { useSyncExternalStore } from "react";
type InstallPrompt = Event & {
prompt: () => Promise<void>;
userChoice: Promise<{ outcome: "accepted" | "dismissed" }>;
};
type PwaState = { enabled: boolean; installed: boolean; installPrompt: InstallPrompt | null; updateReady: boolean; error: string };
let state: PwaState = { enabled: false, installed: false, installPrompt: null, updateReady: false, error: "" };
const listeners = new Set<() => void>();
let registration: ServiceWorkerRegistration | undefined;
let reloading = false;
let started = false;
const publish = (change: Partial<PwaState>) => {
state = { ...state, ...change };
listeners.forEach(listener => listener());
};
const subscribe = (listener: () => void) => { listeners.add(listener); return () => { listeners.delete(listener); }; };
export const usePwa = () => useSyncExternalStore(subscribe, () => state, () => state);
const subscribeOnline = (listener: () => void) => {
window.addEventListener("online", listener);
window.addEventListener("offline", listener);
return () => { window.removeEventListener("online", listener); window.removeEventListener("offline", listener); };
};
export const useOnline = () => useSyncExternalStore(subscribeOnline, () => navigator.onLine !== false, () => true);
/** Called once before React renders so early install events cannot be missed. */
export function startPwa() {
if (started || !window.isSecureContext || !("serviceWorker" in navigator)) return;
started = true;
const standalone = window.matchMedia("(display-mode: standalone)");
const installed = () => standalone.matches || (navigator as Navigator & { standalone?: boolean }).standalone === true;
publish({ enabled: true, installed: installed() });
standalone.addEventListener("change", () => publish({ installed: installed() }));
window.addEventListener("beforeinstallprompt", event => {
event.preventDefault();
publish({ installPrompt: event as InstallPrompt });
});
window.addEventListener("appinstalled", () => publish({ installed: true, installPrompt: null }));
let controller = navigator.serviceWorker.controller;
navigator.serviceWorker.addEventListener("controllerchange", () => {
if (reloading) window.location.reload();
else if (controller) publish({ updateReady: true });
controller = navigator.serviceWorker.controller;
});
const register = async () => {
try {
registration = await navigator.serviceWorker.register("/sw.js", { scope: "/", updateViaCache: "none" });
publish({ updateReady: Boolean(registration.waiting) });
const observeInstall = () => {
const worker = registration?.installing;
worker?.addEventListener("statechange", () => {
if (worker.state === "installed") publish({ updateReady: Boolean(navigator.serviceWorker.controller), error: "" });
if (worker.state === "redundant" && !navigator.serviceWorker.controller)
publish({ error: "Offline setup didn’t finish. Reconnect and reload to try again." });
});
};
registration.addEventListener("updatefound", observeInstall);
observeInstall();
const check = () => {
if (navigator.onLine && document.visibilityState === "visible") void registration?.update().catch(() => {});
};
document.addEventListener("visibilitychange", check);
window.addEventListener("online", check);
window.setInterval(check, 60 * 60 * 1000);
} catch {
publish({ error: "Offline setup is unavailable. Reconnect and reload to try again." });
}
};
if (document.readyState === "complete") void register();
else window.addEventListener("load", () => { void register(); }, { once: true });
}
export async function installApp(): Promise<boolean> {
const prompt = state.installPrompt;
if (!prompt) return false;
publish({ installPrompt: null });
try {
await prompt.prompt();
await prompt.userChoice;
} catch { publish({ error: "Could not open installation. Try your browser’s install menu." }); }
return true;
}
export function applyUpdate() {
if (!state.updateReady) return;
if (registration?.waiting) {
reloading = true;
registration.waiting.postMessage({ type: "ACTIVATE_UPDATE" });
} else window.location.reload();
}

9
src/pwa/manifest.ts Normal file
View File

@@ -0,0 +1,9 @@
import source from "./manifest.webmanifest" with { type: "text" };
export const manifest = JSON.parse(source) as {
id: string; name: string; short_name: string; description: string;
lang: string; dir: string; start_url: string; scope: string; display: string;
background_color: string; theme_color: string; categories: string[];
prefer_related_applications: boolean;
icons: { src: string; sizes: string; type: string; purpose: string }[];
};

View File

@@ -0,0 +1,38 @@
{
"id": "/",
"name": "Mina Habits",
"short_name": "Mina Habits",
"description": "A quiet place to track your habits and see your progress.",
"lang": "en",
"dir": "ltr",
"start_url": "/",
"scope": "/",
"display": "standalone",
"background_color": "#ffffff",
"theme_color": "#ffffff",
"categories": [
"productivity",
"lifestyle"
],
"prefer_related_applications": false,
"icons": [
{
"src": "/pwa/icon-192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "any"
},
{
"src": "/pwa/icon-512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "any"
},
{
"src": "/pwa/icon-maskable-512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "maskable"
}
]
}

BIN
src/pwa/public/icon-192.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

BIN
src/pwa/public/icon-512.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 103 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 59 KiB

66
src/pwa/sw.js Normal file
View File

@@ -0,0 +1,66 @@
/* Build injects a content-derived version and an explicit public-asset allowlist. */
const CONFIG = JSON.parse("__PWA_CONFIG__");
const PREFIX = "mina-habits-static-";
const CACHE = PREFIX + CONFIG.version;
const ASSETS = new Set(CONFIG.assets);
self.addEventListener("install", event => {
event.waitUntil((async () => {
const cache = await caches.open(CACHE);
// addAll is atomic: a failed download cannot activate a partial release.
await cache.addAll(CONFIG.assets.map(url => new Request(url, { cache: "reload", credentials: "omit" })));
})());
});
self.addEventListener("activate", event => {
event.waitUntil((async () => {
// A user can accept an update while other windows still hold older code.
// Preserve their lazy chunks until a later activation with no open windows.
const windows = await self.clients.matchAll({ type: "window", includeUncontrolled: true });
if (windows.length === 0) {
await Promise.all((await caches.keys()).filter(key => key.startsWith(PREFIX) && key !== CACHE).map(key => caches.delete(key)));
}
await self.clients.claim();
})());
});
self.addEventListener("message", event => {
if (event.data?.type === "ACTIVATE_UPDATE") event.waitUntil(self.skipWaiting());
});
async function cachedAsset(request) {
const current = await caches.open(CACHE);
const cached = await current.match(request);
if (cached) return cached;
// Old windows can still request fingerprinted chunks after an accepted update.
for (const key of await caches.keys()) {
if (key.startsWith(PREFIX) && key !== CACHE) {
const response = await (await caches.open(key)).match(request);
if (response) return response;
}
}
return fetch(request);
}
async function navigate(request) {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 4000);
try {
const response = await fetch(request, { signal: controller.signal });
if (response.ok) return response;
} catch { /* Unreachable server or offline: use the public shell. */ }
finally { clearTimeout(timeout); }
return (await (await caches.open(CACHE)).match(CONFIG.shell)) || Response.error();
}
self.addEventListener("fetch", event => {
const request = event.request;
const url = new URL(request.url);
// In particular: no account data, OAuth callbacks, exports, writes or third-party responses.
if (request.method !== "GET" || url.origin !== self.location.origin || /^\/api(?:\/|$)/.test(url.pathname)) return;
if (request.mode === "navigate") {
event.respondWith(navigate(request));
} else if (ASSETS.has(url.pathname) || /^\/chunk-[\w-]+\.js$/.test(url.pathname)) {
event.respondWith(cachedAsset(request));
}
});

99
src/pwa/sw.test.ts Normal file
View File

@@ -0,0 +1,99 @@
import { expect, test } from "bun:test";
import { runInNewContext } from "node:vm";
const template = await Bun.file(new URL("./sw.js", import.meta.url)).text();
const origin = "https://mina.example";
const cacheName = "mina-habits-static-test";
function worker({ offline = false, windows = 0, failInstall = false } = {}) {
const events = new Map<string, (event: any) => void>();
const stores = new Map<string, Map<string, Response>>([
[cacheName, new Map([[`${origin}/pwa/shell-test.html`, new Response("offline shell")]])],
["mina-habits-static-old", new Map([[`${origin}/chunk-old.js`, new Response("old chunk")]])],
["unrelated-cache", new Map()],
]);
const deleted: string[] = [];
const fetched: string[] = [];
let skipped = false;
let claimed = false;
let installed: Request[] = [];
const requestOptions: RequestInit[] = [];
const url = (input: Request | string) => new URL(typeof input === "string" ? input : input.url, origin).href;
const config = { version: "test", shell: "/pwa/shell-test.html", assets: ["/chunk-new.js", "/pwa/shell-test.html"] };
runInNewContext(template.replace('"__PWA_CONFIG__"', JSON.stringify(JSON.stringify(config))), {
self: {
location: { origin }, addEventListener: (type: string, handler: (event: any) => void) => events.set(type, handler),
skipWaiting: async () => { skipped = true; },
clients: { matchAll: async () => Array.from({ length: windows }, () => ({})), claim: async () => { claimed = true; } },
},
caches: {
open: async (name: string) => ({
match: async (request: Request | string) => stores.get(name)?.get(url(request))?.clone(),
addAll: async (requests: Request[]) => { if (failInstall) throw new Error("download failed"); installed = requests; },
}),
keys: async () => [...stores.keys()],
delete: async (name: string) => { deleted.push(name); return stores.delete(name); },
},
fetch: async (request: Request) => { fetched.push(request.url); if (offline) throw new TypeError("offline"); return new Response("network"); },
Request: class extends Request { constructor(input: string, init?: RequestInit) { super(url(input), init); requestOptions.push(init ?? {}); } },
Response, Set, URL, AbortController, setTimeout, clearTimeout,
});
async function lifecycle(type: string, data?: unknown) {
let promise: Promise<unknown> | undefined;
events.get(type)!({ data, waitUntil: (value: Promise<unknown>) => { promise = value; } });
await promise;
}
function request(pathname: string, method = "GET", mode = "cors") {
let response: Promise<Response> | undefined;
events.get("fetch")!({ request: { url: new URL(pathname, origin).href, method, mode }, respondWith: (value: Promise<Response>) => { response = value; } });
return response;
}
return { request, lifecycle, deleted, fetched, requestOptions, get skipped() { return skipped; }, get claimed() { return claimed; }, get installed() { return installed; } };
}
test("service worker excludes private API and OAuth navigations, writes and other origins", () => {
const sw = worker();
for (const route of ["/api", "/api/me", "/api/account/export", "/api/auth/discord/callback?code=private"]) {
expect(sw.request(route, "GET", "navigate")).toBeUndefined();
}
expect(sw.request("/chunk-new.js", "POST")).toBeUndefined();
expect(sw.request("https://discord.com/api/me")).toBeUndefined();
expect(sw.request("/private.json")).toBeUndefined();
expect(sw.request("/index.js")).toBeUndefined();
expect(sw.request("/chunk-new.js.map")).toBeUndefined();
});
test("network navigation is fresh while offline navigation uses only the public shell", async () => {
expect(await (await worker().request("/", "GET", "navigate"))!.text()).toBe("network");
const sw = worker({ offline: true });
expect(await (await sw.request("/a/deep/link", "GET", "navigate"))!.text()).toBe("offline shell");
});
test("older windows can load their cached lazy chunks after an update", async () => {
const sw = worker({ offline: true });
expect(await (await sw.request("/chunk-old.js"))!.text()).toBe("old chunk");
expect(sw.fetched).toEqual([]);
});
test("install excludes credentials and waits for every public asset without forcing activation", async () => {
const sw = worker();
await sw.lifecycle("install");
expect(sw.installed).toHaveLength(2);
expect(sw.requestOptions.every(options => options.credentials === "omit" && options.cache === "reload")).toBe(true);
expect(sw.skipped).toBe(false);
await expect(worker({ failInstall: true }).lifecycle("install")).rejects.toThrow("download failed");
});
test("activation preserves old windows and cleans only its own obsolete caches when windows close", async () => {
const occupied = worker({ windows: 2 });
await occupied.lifecycle("activate");
expect(occupied.deleted).toEqual([]);
expect(occupied.claimed).toBe(true);
const empty = worker();
await empty.lifecycle("activate");
expect(empty.deleted).toEqual(["mina-habits-static-old"]);
await empty.lifecycle("message", { type: "unrelated" });
expect(empty.skipped).toBe(false);
await empty.lifecycle("message", { type: "ACTIVATE_UPDATE" });
expect(empty.skipped).toBe(true);
});