// Service worker for SvelteMUD Client PWA const CACHE_NAME = 'svelte-mud-v1'; const ASSETS_TO_CACHE = [ '/', '/index.html', '/manifest.json', '/favicon.ico', '/global.css', '/build/bundle.css', '/build/bundle.js' ]; // Install event - cache critical assets self.addEventListener('install', (event) => { event.waitUntil( caches.open(CACHE_NAME) .then((cache) => { return cache.addAll(ASSETS_TO_CACHE); }) .then(() => { return self.skipWaiting(); }) ); }); // Activate event - clean up old caches self.addEventListener('activate', (event) => { event.waitUntil( caches.keys().then((cacheNames) => { return Promise.all( cacheNames.map((cacheName) => { if (cacheName !== CACHE_NAME) { return caches.delete(cacheName); } }) ); }).then(() => { return self.clients.claim(); }) ); }); // Fetch event - serve from cache if available, otherwise fetch from network self.addEventListener('fetch', (event) => { // Skip cross-origin requests if (!event.request.url.startsWith(self.location.origin) || event.request.method !== 'GET') { return; } // For navigation requests (HTML pages), use a network-first strategy if (event.request.mode === 'navigate') { event.respondWith( fetch(event.request) .catch(() => { return caches.match(event.request); }) ); return; } // For all other requests, use a cache-first strategy event.respondWith( caches.match(event.request) .then((response) => { if (response) { return response; } // Clone the request because it's a one-time use stream const fetchRequest = event.request.clone(); return fetch(fetchRequest).then((response) => { // Check if valid response if (!response || response.status !== 200 || response.type !== 'basic') { return response; } // Clone the response because it's a one-time use stream const responseToCache = response.clone(); caches.open(CACHE_NAME) .then((cache) => { cache.put(event.request, responseToCache); }); return response; }); }) ); }); // Listen for messages from clients self.addEventListener('message', (event) => { if (event.data && event.data.type === 'SKIP_WAITING') { self.skipWaiting(); } });