fix: service worker network-first strategy + lint fixes

This commit is contained in:
N1C4T
2026-01-10 19:50:59 +04:00
parent 1a55696407
commit a5e82fffa6
21 changed files with 136 additions and 240 deletions

View File

@@ -1,16 +1,14 @@
// TuxMate Service Worker
// caches the entire static app for offline use - perfect for those fresh installs with spotty wifi
// caches the app for offline use - network-first so you always get fresh styles
const CACHE_NAME = 'tuxmate-v1';
const CACHE_NAME = 'tuxmate-v2';
// install: we'll cache on-demand instead of precaching
// Next.js dev mode doesn't have static files where we expect them
// install: skip waiting so updates apply immediately
self.addEventListener('install', () => {
// skipWaiting so updates apply immediately
self.skipWaiting();
});
// activate: clean up old caches when we update
// activate: clean up old caches
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys().then((cacheNames) => {
@@ -20,48 +18,34 @@ self.addEventListener('activate', (event) => {
.map((name) => caches.delete(name))
);
}).then(() => {
// take control of all clients immediately
return self.clients.claim();
})
);
});
// fetch: cache-first with network fallback
// cache everything we successfully fetch for offline use
// fetch: network-first with cache fallback (for offline support)
self.addEventListener('fetch', (event) => {
// only handle GET requests
if (event.request.method !== 'GET') return;
// skip chrome-extension, analytics, and other non-http requests
const url = new URL(event.request.url);
if (!url.protocol.startsWith('http')) return;
// skip external requests (analytics, fonts CDN, etc.) - only cache our stuff
if (url.origin !== self.location.origin) return;
event.respondWith(
caches.match(event.request).then((cachedResponse) => {
if (cachedResponse) {
// got it cached, serve it up
return cachedResponse;
}
// not cached, fetch and cache it for next time
return fetch(event.request).then((response) => {
// don't cache non-ok responses
if (!response || response.status !== 200 || response.type !== 'basic') {
return response;
fetch(event.request)
.then((response) => {
// got fresh response, cache it for offline
if (response && response.status === 200 && response.type === 'basic') {
const responseToCache = response.clone();
caches.open(CACHE_NAME).then((cache) => {
cache.put(event.request, responseToCache);
});
}
// clone because response can only be consumed once
const responseToCache = response.clone();
caches.open(CACHE_NAME).then((cache) => {
cache.put(event.request, responseToCache);
});
return response;
});
})
})
.catch(() => {
// network failed, try cache (offline mode)
return caches.match(event.request);
})
);
});