const CACHE_NAME = 'grabengasse-v1.0'; const STATIC_ASSETS = [ '/', '/index.html', '/manifest.webmanifest', '/icon-192.png', '/icon-512.png', '/apple-touch-icon.png', '/favicon.png' ]; // Install: Cache essential shell assets self.addEventListener('install', (event) => { event.waitUntil( caches.open(CACHE_NAME).then((cache) => { return cache.addAll(STATIC_ASSETS); }).then(() => self.skipWaiting()) ); }); // Activate: Clean up previous cache versions self.addEventListener('activate', (event) => { event.waitUntil( caches.keys().then((keys) => { return Promise.all( keys.filter((key) => key !== CACHE_NAME).map((key) => caches.delete(key)) ); }).then(() => self.clients.claim()) ); }); // Fetch: Network-first for API data, Stale-while-revalidate for static assets self.addEventListener('fetch', (event) => { const { request } = event; const url = new URL(request.url); // API calls: Network first with no fallback caching of stale live metrics if (url.pathname.startsWith('/api/')) { event.respondWith( fetch(request).catch(() => { return new Response(JSON.stringify({ error: 'Offline / Telemetry Link Offline' }), { status: 503, headers: { 'Content-Type': 'application/json' } }); }) ); return; } // Navigation requests: Network first, fallback to cached /index.html (SPA routing) if (request.mode === 'navigate') { event.respondWith( fetch(request).catch(() => { return caches.match('/index.html'); }) ); return; } // Static assets (CSS, JS, Fonts, Images): Cache-first with network fallback & cache update event.respondWith( caches.match(request).then((cachedResponse) => { if (cachedResponse) { // Fetch in background to update cache fetch(request).then((networkResponse) => { if (networkResponse && networkResponse.status === 200) { caches.open(CACHE_NAME).then((cache) => cache.put(request, networkResponse)); } }).catch(() => {}); return cachedResponse; } return fetch(request).then((networkResponse) => { if (!networkResponse || networkResponse.status !== 200 || networkResponse.type !== 'basic') { return networkResponse; } const responseToCache = networkResponse.clone(); caches.open(CACHE_NAME).then((cache) => { cache.put(request, responseToCache); }); return networkResponse; }); }) ); });