/** * TRXTD service worker – makes the game installable as an app (PWA) and * keeps it playable offline. * * Strategy: network-first with runtime caching. The deployed build uses * hashed asset names, so index.html must always come from the network to * pick up new deploys; the cache is only a fallback when offline. * API calls and WebSocket upgrades are never intercepted. */ const CACHE = 'trxtd-v1' self.addEventListener('install', () => { self.skipWaiting() }) self.addEventListener('activate', (event) => { event.waitUntil( caches .keys() .then((keys) => Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k)))) .then(() => self.clients.claim()), ) }) self.addEventListener('fetch', (event) => { const req = event.request if (req.method !== 'GET') return const url = new URL(req.url) if (url.origin !== self.location.origin) return // CDN/external resources if (url.pathname.startsWith('/api/')) return // auth & game API: network only if (url.pathname.startsWith('/ws')) return event.respondWith( fetch(req) .then((res) => { if (res && res.status === 200 && res.type === 'basic') { const copy = res.clone() caches.open(CACHE).then((c) => c.put(req, copy)).catch(() => {}) } return res }) .catch(() => caches.match(req).then((hit) => hit || caches.match('/')), ), ) })