45 lines
2.7 KiB
JavaScript
45 lines
2.7 KiB
JavaScript
/* İhaleist service worker — uygulama kabuğu çevrimdışı açılır, API her zaman ağdan.
|
||
Sürüm değişince eski önbellek temizlenir (build her deploy'da yeni asset adı üretir). */
|
||
const SURUM = 'ihaleist-v3'; // v3: yalnız uygulama kabuğu ve başarılı varlık yanıtları
|
||
const KABUK = ['/', '/manifest.webmanifest', '/icons/icon-192.png', '/icons/icon-512.png'];
|
||
|
||
self.addEventListener('install', (e) => {
|
||
e.waitUntil(caches.open(SURUM).then((c) => c.addAll(KABUK)).then(() => self.skipWaiting()));
|
||
});
|
||
self.addEventListener('activate', (e) => {
|
||
e.waitUntil(caches.keys().then((ks) => Promise.all(ks.filter((k) => k.startsWith('ihaleist-') && k !== SURUM).map((k) => caches.delete(k)))).then(() => self.clients.claim()));
|
||
});
|
||
self.addEventListener('fetch', (e) => {
|
||
const url = new URL(e.request.url);
|
||
if (e.request.method !== 'GET' || url.origin !== self.location.origin) return;
|
||
// API: yalnız ağ — önbellekten eski ihale gösterme
|
||
if (url.pathname.startsWith('/api/') || e.request.headers.has('authorization')) return;
|
||
// Hash'li build varlıkları: cache-first (değişmez adlar)
|
||
if (url.pathname.startsWith('/assets/')) {
|
||
e.respondWith(caches.match(e.request).then((hit) => hit || fetch(e.request).then((r) => {
|
||
// Yalnızca sağlıklı yanıt saklanır: 404 veya JavaScript dosyasının
|
||
// yanlış MIME tipiyle (octet-stream) gelmesi önbelleğe girerse
|
||
// sunucu düzeltilse bile kullanıcı eski bozuk kopyayı görmeye devam eder.
|
||
const tip = r.headers.get('content-type') || '';
|
||
const jsMi = /\.m?js$/.test(url.pathname);
|
||
if (r.ok && !r.redirected && !/text\/html/i.test(tip) && (!jsMi || /javascript|ecmascript/i.test(tip)) && (!/\.css$/.test(url.pathname) || /text\/css/i.test(tip))) {
|
||
const kopya = r.clone(); e.waitUntil(caches.open(SURUM).then((c) => c.put(e.request, kopya)));
|
||
}
|
||
return r;
|
||
})));
|
||
return;
|
||
}
|
||
// Only known shell files and root navigation are cacheable; never cache arbitrary GETs.
|
||
const navigation = e.request.mode === 'navigate' && url.pathname === '/';
|
||
if (!navigation && !KABUK.includes(url.pathname)) return;
|
||
if (e.request.headers.has('authorization')) return;
|
||
// Kabuk / sayfa: network-first, ağ yoksa önbellekten index
|
||
e.respondWith(fetch(e.request).then((r) => {
|
||
const type = r.headers.get('content-type') || '';
|
||
if (r.ok && !r.redirected && (!navigation || /text\/html/i.test(type))) {
|
||
const kopya = r.clone(); e.waitUntil(caches.open(SURUM).then(c => c.put(navigation ? '/' : e.request, kopya)));
|
||
}
|
||
return r;
|
||
}).catch(() => caches.match(e.request).then((hit) => hit || (navigation ? caches.match('/') : Response.error()))));
|
||
});
|