/* Minimal service worker — enables installability; network-first for app/API. */ const CACHE = "dylive-shell-v2"; const PRECACHE = ["/manifest.webmanifest", "/icon-192.png", "/icon-512.png", "/apple-touch-icon.png"]; self.addEventListener("install", (event) => { event.waitUntil( (async () => { const cache = await caches.open(CACHE); // Prefer one-by-one so a single miss (e.g. auth redirect on "/") does not fail SW install. await Promise.all( PRECACHE.map((url) => cache.add(url).catch(() => undefined)), ); await 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 req = event.request; if (req.method !== "GET") return; const url = new URL(req.url); if (url.origin !== self.location.origin) return; // Never cache API / auth / SSE if (url.pathname.startsWith("/api/") || url.pathname.includes("event")) return; event.respondWith( fetch(req) .then((res) => { const copy = res.clone(); if (res.ok && (url.pathname.startsWith("/_next/static/") || PRECACHE.includes(url.pathname))) { caches.open(CACHE).then((cache) => cache.put(req, copy)).catch(() => {}); } return res; }) .catch(async () => { const hit = await caches.match(req); if (hit) return hit; if (req.mode === "navigate") { const home = await caches.match("/"); if (home) return home; } throw new Error("offline"); }), ); });