// Bumped from v1: the v1 networkFirst fallback returned OFFLINE_PAGE_URL // (index.html) for failed script requests, causing "module script MIME text/html" // errors when the server was down or served a different asset hash. The v2 // activate handler deletes v1, flushing any poisoned cached entries. const CACHE_NAME = 'nomifun-webui-v2'; const NON_CACHEABLE_PATHS = new Set(['/qr-login']); const OFFLINE_PAGE_URL = new URL('./index.html', self.location.href).toString(); const PRECACHE_URLS = [ new URL('./', self.location.href).toString(), OFFLINE_PAGE_URL, new URL('./manifest.webmanifest', self.location.href).toString(), new URL('./pwa/icon-192.png', self.location.href).toString(), new URL('./pwa/icon-512.png', self.location.href).toString(), ]; self.addEventListener('install', (event) => { event.waitUntil( caches .open(CACHE_NAME) .then((cache) => cache.addAll(PRECACHE_URLS)) .then(() => self.skipWaiting()) ); }); self.addEventListener('activate', (event) => { event.waitUntil( caches .keys() .then((keys) => Promise.all( keys.map((key) => { if (key === CACHE_NAME) { return Promise.resolve(); } return caches.delete(key); }) ) ) .then(() => self.clients.claim()) // After claim, tell any open WebUI tabs running under the previous SW // to reload so they pick up the fixed fetch handler immediately. // Without this, an already-open tab keeps serving from the old v1 SW // until the user manually refreshes. .then(() => self.clients.matchAll({ type: 'window' }).then((clients) => { for (const client of clients) { client.navigate(client.url).catch(() => undefined); } }) ) ); }); function shouldHandleRequest(request) { if (request.method !== 'GET') { return false; } const url = new URL(request.url); if (url.origin !== self.location.origin) { return false; } return !url.pathname.startsWith('/api/') && !NON_CACHEABLE_PATHS.has(url.pathname); } async function networkFirst(request) { const cache = await caches.open(CACHE_NAME); try { const response = await fetch(request); if (response.ok) { cache.put(request, response.clone()); } return response; } catch { // Only fall back to the offline index.html for navigation requests. // Returning index.html for a `