Files
DataStack/public/sw.js
T

72 lines
1.8 KiB
JavaScript
Raw Normal View History

const CACHE_NAME = 'datastack-cache-v2';
const STATIC_ASSETS = [
'/',
'/manifest.json',
'/icon.svg',
'/icon-192.png',
'/icon-512.png',
'/icon-maskable-512.png',
'/apple-touch-icon.png',
];
2026-10-23 11:43:49 -05:00
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => {
return cache.addAll(STATIC_ASSETS).catch(() => {});
})
);
self.skipWaiting();
});
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys().then((keys) => {
return Promise.all(
keys.filter((key) => key !== CACHE_NAME).map((key) => caches.delete(key))
);
})
);
self.clients.claim();
});
self.addEventListener('fetch', (event) => {
const { request } = event;
if (request.method !== 'GET') return;
let url;
try {
url = new URL(request.url);
} catch {
2026-10-23 11:43:49 -05:00
return;
}
// Only handle same-origin GET requests; never intercept WebSocket, HMR, or API routes
if (url.origin !== self.location.origin) return;
if (
url.pathname.startsWith('/socket.io/') ||
url.pathname.startsWith('/api/') ||
url.pathname.startsWith('/_next/webpack-hmr')
) {
return;
}
2026-10-23 11:43:49 -05:00
event.respondWith(
fetch(request)
.then((response) => {
if (response && response.ok && response.type === 'basic') {
const clone = response.clone();
caches.open(CACHE_NAME).then((cache) => cache.put(request, clone)).catch(() => {});
}
return response;
})
.catch(async () => {
const cached = await caches.match(request);
if (cached) return cached;
return new Response('Offline — network unavailable.', {
status: 503,
statusText: 'Service Unavailable',
headers: { 'Content-Type': 'text/plain; charset=utf-8' },
});
})
2026-10-23 11:43:49 -05:00
);
});