/* Service worker — the piece that makes this installable as a real app. * * Deliberately minimal, and deliberately network-first for everything. * Caching the shell aggressively is the usual PWA advice, but here it would * mean shipping a stale UI against a changed API and calling it offline * support — this app cannot do anything useful without the network anyway, * since grading is a live API call. So the cache exists only as a fallback * for the app shell when the connection drops, and never for /api/. */ // Substituted server-side to the path this app is mounted under (e.g. // "/cards"), or left empty when served from the domain root — see // app.py's _static_templated. Every absolute reference below has to go // through this, since a service worker has no page URL of its own to // resolve relative paths against. const BASE = '__BASE__'; const CACHE = 'card-grader-v1'; const SHELL = [ `${BASE}/`, `${BASE}/static/app.js`, `${BASE}/static/style.css`, `${BASE}/static/icon.svg`, `${BASE}/static/manifest.json`, ]; self.addEventListener('install', (event) => { event.waitUntil( caches.open(CACHE).then((cache) => cache.addAll(SHELL)).then(() => self.skipWaiting()) ); }); self.addEventListener('activate', (event) => { event.waitUntil( caches.keys() .then((keys) => Promise.all( keys.filter((k) => k !== CACHE).map((k) => caches.delete(k)))) .then(() => self.clients.claim()) ); }); self.addEventListener('fetch', (event) => { const { request } = event; if (request.method !== 'GET') return; const url = new URL(request.url); // Never cache the API. A stale grade or a stale settings blob would be // worse than an honest failure. if (url.pathname.startsWith(`${BASE}/api/`)) return; event.respondWith( fetch(request) .then((response) => { if (response && response.ok && url.origin === self.location.origin) { const copy = response.clone(); caches.open(CACHE).then((cache) => cache.put(request, copy)); } return response; }) .catch(() => caches.match(request).then((hit) => hit || caches.match(`${BASE}/`))) ); });