const STATIC_CACHE = "construction-delivery-static-v1"; const RUNTIME_CACHE = "construction-delivery-runtime-v1"; const APP_SHELL_URLS = ["/", "/index.html", "/manifest.webmanifest", "/icons/icon-192.svg", "/icons/icon-512.svg"]; self.addEventListener("install", (event) => { event.waitUntil( caches.open(STATIC_CACHE).then((cache) => cache.addAll(APP_SHELL_URLS)).then(() => self.skipWaiting()), ); }); self.addEventListener("activate", (event) => { event.waitUntil( caches .keys() .then((keys) => Promise.all( keys .filter((key) => ![STATIC_CACHE, RUNTIME_CACHE].includes(key)) .map((key) => caches.delete(key)), ), ) .then(() => self.clients.claim()) .then(async () => { const clients = await self.clients.matchAll({ includeUncontrolled: true }); clients.forEach((client) => client.postMessage({ type: "PWA_OFFLINE_READY" })); }), ); }); self.addEventListener("fetch", (event) => { if (event.request.method !== "GET") { return; } const requestUrl = new URL(event.request.url); const isSameOrigin = requestUrl.origin === self.location.origin; if (event.request.mode === "navigate") { event.respondWith( fetch(event.request) .then((response) => { const responseClone = response.clone(); caches.open(RUNTIME_CACHE).then((cache) => cache.put(event.request, responseClone)); return response; }) .catch(async () => { const cachedPage = await caches.match(event.request); return cachedPage || caches.match("/index.html"); }), ); return; } if (!isSameOrigin) { return; } event.respondWith( caches.match(event.request).then((cachedResponse) => { if (cachedResponse) { return cachedResponse; } return fetch(event.request).then((response) => { if (!response || response.status !== 200) { return response; } const responseClone = response.clone(); caches.open(RUNTIME_CACHE).then((cache) => cache.put(event.request, responseClone)); return response; }); }), ); });