///
///
///
///
import { build, files, version } from '$service-worker';
// This gives `self` the correct types
const sw = /** @type {ServiceWorkerGlobalScope} */ (/** @type {unknown} */ (globalThis.self));
// Create a unique cache name for this deployment
const CACHE = `cache-${version}`;
// Assets to cache immediately (app shell)
const ASSETS = [
...build, // the app itself
...files // everything in static
];
// Install: cache app shell
sw.addEventListener('install', (event) => {
async function addFilesToCache() {
const cache = await caches.open(CACHE);
// In dev mode, ASSETS is empty - skip caching
if (ASSETS.length > 0) {
await cache.addAll(ASSETS);
}
}
event.waitUntil(addFilesToCache());
});
// Activate: clean up old caches
sw.addEventListener('activate', (event) => {
async function deleteOldCaches() {
for (const key of await caches.keys()) {
if (key !== CACHE) await caches.delete(key);
}
}
event.waitUntil(deleteOldCaches());
});
// Fetch: network-first with cache fallback for pages, cache-first for assets
sw.addEventListener('fetch', (event) => {
// Only handle GET requests
if (event.request.method !== 'GET') return;
const url = new URL(event.request.url);
// Skip cross-origin requests
if (url.origin !== sw.location.origin) return;
// Skip API routes - always go to network
if (url.pathname.startsWith('/api/')) return;
async function respond() {
const cache = await caches.open(CACHE);
// For static assets (build/files), serve from cache first
if (ASSETS.includes(url.pathname)) {
const cached = await cache.match(url.pathname);
if (cached) return cached;
}
// For pages, try network first, fall back to cache
try {
const response = await fetch(event.request);
// if we're offline, fetch can return a value that is not a Response
if (!(response instanceof Response)) {
throw new Error('invalid response from fetch');
}
// Cache successful responses
if (response.status === 200) {
cache.put(event.request, response.clone());
}
return response;
} catch (err) {
// Offline: try to serve from cache
const cached = await cache.match(event.request);
if (cached) return cached;
// If no cache and it's a navigation request, show offline page
if (event.request.mode === 'navigate') {
const offlinePage = await cache.match('/');
if (offlinePage) return offlinePage;
}
throw err;
}
}
event.respondWith(respond());
});