/* Netwall service worker: network-first so updates always win, cache as an offline fallback (solo play offline). */ const CACHE = 'netwall-v1'; const CORE = ['./', 'index.html', 'css/style.css', 'js/sim.js', 'js/bot.js', 'js/audio.js', 'js/controllers.js', 'js/render.js', 'js/versus.js', 'js/main.js', 'manifest.webmanifest', 'icons/icon.svg', 'icons/icon-192.png', 'assets/music/tracks.json']; self.addEventListener('install', (e) => { e.waitUntil(caches.open(CACHE).then((c) => c.addAll(CORE)).then(() => self.skipWaiting()).catch(() => self.skipWaiting())); }); self.addEventListener('activate', (e) => { e.waitUntil(caches.keys().then((keys) => Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k)))).then(() => self.clients.claim())); }); // An error page from the proxy in front of the app (nginx answers 502/503/504 while the Node process restarts or is // down) is a "network failure" for our purposes: serve the cached copy instead of the proxy's error page. const GATEWAY_ERRORS = [502, 503, 504]; // The cached copy of this request; a navigation (also /?room=ABCD, which has no cache entry of its own) falls back to the // cached app shell. `res` is the proxy's error response, still better than nothing for a file that was never cached. function offline(req, res) { return caches.match(req) .then((r) => r || (req.mode === 'navigate' ? caches.match('index.html') : null)) .then((r) => r || res || Response.error()); } self.addEventListener('fetch', (e) => { const req = e.request; if (req.method !== 'GET') return; const url = new URL(req.url); if (url.origin !== self.location.origin) return; e.respondWith( fetch(req) .then((res) => { if (GATEWAY_ERRORS.includes(res.status)) return offline(req, res); // Only complete responses: a 206 (a range request for audio) is ok but is not the whole file. if (res.status === 200 && res.type === 'basic') { const copy = res.clone(); caches.open(CACHE).then((c) => c.put(req, copy)).catch(() => {}); } return res; }) .catch(() => offline(req)), ); });