63 lines
1.7 KiB
JavaScript
63 lines
1.7 KiB
JavaScript
const CACHE_NAME = 'inknote-v6';
|
|
|
|
// Install — don't precache, just activate immediately
|
|
self.addEventListener('install', () => {
|
|
self.skipWaiting();
|
|
});
|
|
|
|
// Activate — clean old caches, take control
|
|
self.addEventListener('activate', (e) => {
|
|
e.waitUntil(
|
|
caches.keys().then(keys =>
|
|
Promise.all(keys.filter(k => k !== CACHE_NAME).map(k => caches.delete(k)))
|
|
).then(() => self.clients.claim())
|
|
);
|
|
});
|
|
|
|
// Fetch — runtime caching strategy
|
|
self.addEventListener('fetch', (e) => {
|
|
const url = new URL(e.request.url);
|
|
|
|
// Never intercept API or WebSocket
|
|
if (url.pathname.startsWith('/api/') || url.pathname.startsWith('/ws')) return;
|
|
|
|
// Only handle GET requests
|
|
if (e.request.method !== 'GET') return;
|
|
|
|
// Navigation (HTML) — network-first with cache fallback
|
|
if (e.request.mode === 'navigate') {
|
|
e.respondWith(
|
|
fetch(e.request).then(r => {
|
|
const clone = r.clone();
|
|
caches.open(CACHE_NAME).then(c => c.put(e.request, clone));
|
|
return r;
|
|
}).catch(() => caches.match(e.request).then(r => r || caches.match('/')))
|
|
);
|
|
return;
|
|
}
|
|
|
|
// Static assets — stale-while-revalidate
|
|
e.respondWith(
|
|
caches.open(CACHE_NAME).then(cache =>
|
|
cache.match(e.request).then(cached => {
|
|
const fetchP = fetch(e.request).then(r => {
|
|
if (r.ok) cache.put(e.request, r.clone());
|
|
return r;
|
|
}).catch(() => cached);
|
|
return cached || fetchP;
|
|
})
|
|
)
|
|
);
|
|
});
|
|
|
|
// Background sync trigger
|
|
self.addEventListener('sync', (e) => {
|
|
if (e.tag === 'sync-changes') {
|
|
e.waitUntil(
|
|
self.clients.matchAll().then(clients =>
|
|
clients.forEach(c => c.postMessage({ type: 'FLUSH_QUEUE' }))
|
|
)
|
|
);
|
|
}
|
|
});
|