| 1 |
// License: GPL v3 Copyright: 2026, Kovid Goyal <kovid at kovidgoyal.net> |
| 2 |
// Plain-JS template; version/hash placeholders substituted at serve time. |
| 3 |
// Not compiled via RapydScript: the SW runs in a ServiceWorkerGlobalScope |
| 4 |
// where the RapydScript runtime throws during evaluation. |
| 5 |
'use strict'; |
| 6 |
|
| 7 |
const CACHE_NAME = 'calibre-server-index'; |
| 8 |
|
| 9 |
self.addEventListener('install', function(event) { |
| 10 |
event.waitUntil(self.skipWaiting()); |
| 11 |
}); |
| 12 |
|
| 13 |
self.addEventListener('activate', function(event) { |
| 14 |
event.waitUntil(self.clients.claim()); |
| 15 |
}); |
| 16 |
|
| 17 |
self.addEventListener('fetch', function(event) { |
| 18 |
if (event.request.method !== 'GET') return; |
| 19 |
const url = new URL(event.request.url); |
| 20 |
if (url.origin !== self.location.origin) return; |
| 21 |
// console.log("URL: " + event.request.url); |
| 22 |
const service_worker_root = self.location.pathname.substring(0, self.location.pathname.lastIndexOf('/') + 1); |
| 23 |
// console.log("Root: " + service_worker_root); |
| 24 |
if (!url.pathname.startsWith(service_worker_root)) return; |
| 25 |
const req_rel_path = url.pathname.replace(service_worker_root, ''); |
| 26 |
// console.log("Relpath: " + req_rel_path); |
| 27 |
if (req_rel_path !== '') return; |
| 28 |
|
| 29 |
event.respondWith( |
| 30 |
fetch(event.request) |
| 31 |
.then((response) => { |
| 32 |
if (response.ok) { |
| 33 |
// Network succeeded — update the cache and return the response |
| 34 |
const clone = response.clone(); |
| 35 |
caches.open(CACHE_NAME).then((cache) => cache.put(event.request, clone)); |
| 36 |
} |
| 37 |
return response; |
| 38 |
}) |
| 39 |
.catch((err) => { |
| 40 |
// Network failed — serve from cache |
| 41 |
const OFFLINE_RESPONSE = new Response( |
| 42 |
'Failed to contact server and no cached offline version present.' + |
| 43 |
' Error from contacting server:\n\n' + `${err}`, { |
| 44 |
status: 200, headers: { 'Content-Type': 'text/plain' }, |
| 45 |
}); |
| 46 |
return caches.match(event.request) |
| 47 |
.then((cached) => cached || OFFLINE_RESPONSE) |
| 48 |
.catch(() => OFFLINE_RESPONSE); |
| 49 |
}) |
| 50 |
); |
| 51 |
}); |