/* Bike-Tinder service worker. - Precache the app shell at install; index.html + sw.js are served with Cache-Control: no-cache so updates are picked up. - /api/* : network-first; offline -> 503 JSON (the page toasts "Offline"). - /img/* : cache-first with network fill (mirrored thumbnails stay usable offline once seen). - Everything else (shell/navigation): network-first, fall back to cache. */ const VERSION = 'bike-tinder-v1'; const SHELL = [ '/', '/manifest.json', '/apple-touch-icon.png', '/icons/icon-192.png', '/icons/icon-512.png', '/icons/icon-512-maskable.png' ]; self.addEventListener('install', (e) => { e.waitUntil( caches.open(VERSION) .then((c) => c.addAll(SHELL)) .then(() => self.skipWaiting()) ); }); self.addEventListener('activate', (e) => { e.waitUntil( caches.keys() .then((keys) => Promise.all(keys.filter((k) => k !== VERSION).map((k) => caches.delete(k)))) .then(() => self.clients.claim()) ); }); self.addEventListener('fetch', (e) => { const req = e.request; if (req.method !== 'GET') return; const url = new URL(req.url); if (url.pathname.startsWith('/api/')) { e.respondWith( fetch(req).catch(() => new Response(JSON.stringify({ error: 'offline' }), { status: 503, headers: { 'Content-Type': 'application/json' } })) ); return; } if (url.pathname.startsWith('/img/')) { e.respondWith( caches.match(req).then((hit) => hit || fetch(req).then((res) => { if (res.ok) { const clone = res.clone(); caches.open(VERSION).then((c) => c.put(req, clone)); } return res; }).catch(() => new Response('', { status: 404 }))) ); return; } // shell + navigation: network first, cache fallback (offline launch) e.respondWith( fetch(req).then((res) => res).catch(() => caches.match(req).then((hit) => hit || caches.match('/')) ) ); });