40 lines
1.3 KiB
JavaScript
40 lines
1.3 KiB
JavaScript
const CACHE_NAME = 'mykindlebox-shell-v1'
|
|
const SHELL_URLS = ['/', '/favicon.svg', '/icon-192.png', '/manifest.json']
|
|
|
|
self.addEventListener('install', (event) => {
|
|
event.waitUntil(caches.open(CACHE_NAME).then((cache) => cache.addAll(SHELL_URLS)))
|
|
})
|
|
|
|
self.addEventListener('activate', (event) => {
|
|
event.waitUntil(
|
|
caches
|
|
.keys()
|
|
.then((keys) => Promise.all(keys.filter((key) => key !== CACHE_NAME).map((key) => caches.delete(key))))
|
|
.then(() => self.clients.claim()),
|
|
)
|
|
})
|
|
|
|
// Network-first with a cache fallback for the app shell (HTML/JS/CSS/static
|
|
// assets), so a previously-visited bundle still loads offline. API requests
|
|
// are left alone — they should fail fast so the UI can show its own inline
|
|
// "offline" state instead of serving stale data silently.
|
|
self.addEventListener('fetch', (event) => {
|
|
const { request } = event
|
|
if (request.method !== 'GET') return
|
|
|
|
const url = new URL(request.url)
|
|
if (url.pathname.startsWith('/api/') || url.pathname.startsWith('/uploads/')) return
|
|
|
|
event.respondWith(
|
|
fetch(request)
|
|
.then((response) => {
|
|
if (response.ok) {
|
|
const copy = response.clone()
|
|
caches.open(CACHE_NAME).then((cache) => cache.put(request, copy))
|
|
}
|
|
return response
|
|
})
|
|
.catch(() => caches.match(request).then((cached) => cached ?? caches.match('/'))),
|
|
)
|
|
})
|