const CACHE_NAME = "checkflow-v2"; const STATIC_ASSETS = ["/manifest.json", "/icons/icon.svg"]; self.addEventListener("install", (event) => { event.waitUntil( caches.open(CACHE_NAME).then((cache) => cache.addAll(STATIC_ASSETS)).catch(() => {}) ); self.skipWaiting(); }); self.addEventListener("activate", (event) => { event.waitUntil( caches.keys().then((keys) => Promise.all(keys.filter((k) => k !== CACHE_NAME).map((k) => caches.delete(k))) ) ); self.clients.claim(); }); self.addEventListener("fetch", (event) => { const { request } = event; const url = new URL(request.url); // Only handle http/https GET requests to the same origin if (request.method !== "GET" || !url.protocol.startsWith("http") || url.origin !== self.location.origin) { return; } // Network-first for API & navigation routes to avoid stale/failed page loads if (url.pathname.startsWith("/api") || request.mode === "navigate") { event.respondWith( fetch(request).catch(() => { if (url.pathname.startsWith("/api")) { return new Response(JSON.stringify({ error: "Offline or service unavailable" }), { headers: { "Content-Type": "application/json" }, }); } return caches.match(request).then((cached) => cached || Response.error()); }) ); return; } // Cache-first for static assets with safe network fallback event.respondWith( caches.match(request).then((cached) => { if (cached) return cached; return fetch(request).then((response) => { if (response && response.status === 200 && response.type === "basic") { const clone = response.clone(); caches.open(CACHE_NAME).then((cache) => cache.put(request, clone)).catch(() => {}); } return response; }).catch(() => Response.error()); }) ); });