// Service worker: installable app shell + offline fallback. // Never caches API responses or page HTML — they carry per-user, per-page data. const VERSION = "pm-v5"; const STATIC_CACHE = `${VERSION}-static`; // Base path ("" or "/pagiva") comes from the registration scope. const BASE = new URL(self.registration.scope).pathname.replace(/\/$/, ""); const OFFLINE_URL = `${BASE}/offline.html`; self.addEventListener("install", (event) => { event.waitUntil(caches.open(STATIC_CACHE).then((c) => c.addAll([OFFLINE_URL, `${BASE}/icons/192`]))); self.skipWaiting(); }); self.addEventListener("activate", (event) => { event.waitUntil( caches.keys().then((keys) => Promise.all(keys.filter((k) => !k.startsWith(VERSION)).map((k) => caches.delete(k)))) ); self.clients.claim(); }); self.addEventListener("fetch", (event) => { const req = event.request; if (req.method !== "GET") return; const url = new URL(req.url); if (url.origin !== self.location.origin) return; // Page navigations: network only, offline page when the network is gone. if (req.mode === "navigate") { event.respondWith(fetch(req).catch(() => caches.match(OFFLINE_URL))); return; } // Build assets are content-hashed: cache-first is safe. if (url.pathname.startsWith(`${BASE}/_next/static/`) || url.pathname.startsWith(`${BASE}/icons/`)) { event.respondWith( caches.match(req).then( (hit) => hit || fetch(req).then((res) => { if (res.ok) { const copy = res.clone(); caches.open(STATIC_CACHE).then((c) => c.put(req, copy)); } return res; }) ) ); } });