const CACHE_NAME = 'hats-pwa-v1'; const PRECACHE_ASSETS = [ '/', '/offline', '/assets/logo192.png', '/assets/logo512.png', '/assets/apple-touch-icon.png', '/assets/hats-256x256.png', '/assets/illustrations/maintenance.svg', ]; self.addEventListener('install', (event) => { event.waitUntil( caches.open(CACHE_NAME).then(async (cache) => { // Attempt to precache essential assets, ignoring individual failures for (const asset of PRECACHE_ASSETS) { try { await cache.add(asset); } catch (err) { console.warn(`[PWA SW] Precache failed for ${asset}:`, err); } } }) ); self.skipWaiting(); }); self.addEventListener('activate', (event) => { event.waitUntil( caches.keys().then((keys) => { return Promise.all( keys.map((key) => { if (key !== CACHE_NAME) { return caches.delete(key); } }) ); }) ); self.clients.claim(); }); self.addEventListener('fetch', (event) => { const { request } = event; const url = new URL(request.url); // Only handle GET requests if (request.method !== 'GET') return; // Do not intercept browser extensions, HMR, or internal telemetry if (url.protocol !== 'http:' && url.protocol !== 'https:') return; if (url.pathname.includes('webpack-hmr')) return; // Do not cache API requests or authentication endpoints if ( url.pathname.startsWith('/api/') || url.hostname.includes('api') || url.pathname.startsWith('/auth') ) { return; } // Navigation requests (HTML pages) if (request.mode === 'navigate') { event.respondWith( fetch(request) .then((response) => { // Only cache successful standard responses if (response && response.status === 200 && response.type === 'basic') { const responseToCache = response.clone(); caches.open(CACHE_NAME).then((cache) => { cache.put(request, responseToCache); }); } return response; }) .catch(async () => { const cachedResponse = await caches.match(request); if (cachedResponse) { return cachedResponse; } const offlineFallback = await caches.match('/offline'); if (offlineFallback) { return offlineFallback; } return new Response( ` Offline - H.A.T.s
H.A.T.s

You are currently offline

Please check your internet connection to continue using H.A.T.s.

`, { headers: { 'Content-Type': 'text/html; charset=utf-8' } } ); }) ); return; } // Static assets (images, icons, fonts) - Cache First, Fallback to Network if ( url.pathname.startsWith('/assets/') || url.pathname.match(/\.(png|jpg|jpeg|svg|webp|gif|ico|woff|woff2|ttf|css)$/) ) { event.respondWith( caches.match(request).then((cached) => { if (cached) return cached; return fetch(request).then((response) => { if (response && response.status === 200) { const clone = response.clone(); caches.open(CACHE_NAME).then((cache) => { cache.put(request, clone); }); } return response; }); }) ); } });