diff options
Diffstat (limited to 'src/worker.ts')
| -rw-r--r-- | src/worker.ts | 184 |
1 files changed, 184 insertions, 0 deletions
diff --git a/src/worker.ts b/src/worker.ts new file mode 100644 index 0000000..44ea5b1 --- /dev/null +++ b/src/worker.ts @@ -0,0 +1,184 @@ +/// <reference lib="webworker" /> + +/** @type {ServiceWorkerGlobalScope} */ +const sw = (/** @type {any} */ (self)); + +const CACHE_PREFIX = 'epube'; + +const CACHE_VERSION = BUILD_CACHE_VERSION; +const CACHE_NAME = CACHE_PREFIX + "-" + CACHE_VERSION; +const MANIFEST_ASSETS = BUILD_MANIFEST_ASSETS; + +// Install: precache all assets from manifest +sw.addEventListener('install', (event) => { + event.waitUntil( + (async () => { + console.log('[worker] install started', CACHE_NAME); + + const cache = await caches.open(CACHE_NAME); + + try { + // 1. Fetch all assets concurrently with version parameters + const fetchPromises = MANIFEST_ASSETS.map(async (url) => { + const cleanUrl = new URL(url, location.href); + + // normalize = strip CACHE_VERSION suffix from pathname + cleanUrl.pathname = cleanUrl.pathname.replace("_" + CACHE_VERSION, ""); + + // this is our original URL from manifest (with suffix if set) + const networkUrl = new URL(url, location.href); + + const response = await fetch(networkUrl.toString(), { cache: 'reload' }); + + // Emulate cache.addAll behavior: fail if any status is not 200-299 + if (!response.ok) { + throw new Error(`Failed to fetch ${cleanUrl} (Status: ${response.status})`); + } + + return { + cleanUrlStr: cleanUrl.toString(), + response: response.clone() + }; + }); + + const results = await Promise.all(fetchPromises); + await Promise.all(results.map(({ cleanUrlStr, response }) => cache.put(cleanUrlStr, response))); + + console.log('[worker] all assets cached successfully'); + + // Only skip waiting if the entire cache was successfully built + sw.skipWaiting(); + } catch (err) { + console.error('[worker] Critical precache failed! Critical asset missing:', err); + // Do NOT call skipWaiting(). Let this installation fail so the old worker stays safe. + + // we need to tell the browser the install failed so it throws away this worker, otherwise it gets stuck in waiting + throw err; + } + })() + ); +}); + +sw.addEventListener('message', (event) => { + if (event.data && event.data.type === 'GET_CACHE_NAME') { + // Respond directly to the specific frontend window/tab that asked + event.ports[0].postMessage({ cacheName: CACHE_NAME }); + } else if (event.data && event.data.type === 'GET_CACHE_VERSION') { + // Respond directly to the specific frontend window/tab that asked + event.ports[0].postMessage({ cacheName: CACHE_VERSION }); + } +}); + +// Activate: clean up old caches and take control of all pages +sw.addEventListener('activate', (event) => { + console.log('[worker] activate'); + + // Create the async task block + const activationTask = async () => { + // await loadConfig(); + + const keyList = await caches.keys(); + for (const key of keyList) { + if (key.includes(CACHE_PREFIX) && key !== CACHE_NAME) { + /* eslint-disable no-await-in-loop */ + await caches.delete(key); + } + } + + await sw.clients.claim(); + }; + + // Hand the executed promise directly to the event + event.waitUntil(activationTask()); +}); + +// Fetch: cache-first for static assets, network-first for API +sw.addEventListener('fetch', (event) => { + const url = new URL(event.request.url); + + // console.log('[fetch]', url); + + // /assets/ belong to android app + if (url.pathname.startsWith('/assets/')) return; + + // request API endpoints from the network if possible and cache them locally + if (url.pathname.match('backend.php')) { + event.respondWith( + // @ts-ignore-next-line + (async () => { + try { + const networkResp = await fetch(event.request); + + if (networkResp.ok) { + const cache = await caches.open(CACHE_NAME); + await cache.put(networkResp.url, networkResp.clone()); + } + + return networkResp; + } catch (err) { + // Network failed, try to get the cached API response + const cachedResp = await caches.match(event.request); + if (cachedResp) return cachedResp; + } + })() + ); + return; + } + + // index & read UI: online first; if offline, map index pages to offline.html & map all read.html?* to offline read.html + if (url.pathname == "/" || url.pathname.match("index.html|offline.html|read.html")) { + event.respondWith( + // @ts-ignore-next-line + (async () => { + try { + const networkResp = await fetch(event.request); + + if (networkResp.ok) { + const cache = await caches.open(CACHE_NAME); + await cache.put(networkResp.url, networkResp.clone()); + } + + return networkResp; + } catch (err) { + // i.e. read.html?id=1234&b=1234 + if (url.pathname.includes("read.html")) { + return caches.match("read.html"); + } else { + return caches.match('/offline.html'); + } + } + })() + ); + + return; + } + + // everything else: cache-first with network fallback + event.respondWith( + (async () => { + const cache = await caches.open(CACHE_NAME); + const cached = await cache.match(event.request); + + if (cached) { + // if cached, try to update: fire background network check without waiting for it (no await) + fetch(event.request) + .then((networkResp) => { + if (networkResp.ok) cache.put(event.request, networkResp.clone()); + }) + .catch((e) => console.warn('[worker] Background update failed:', e)); + + // Return cached asset immediately + return cached; + } + + // Cache miss: fetch from network and cache it + const networkResp = await fetch(event.request); + + /* if (networkResp.ok) { -- we don't cache all responses + await cache.put(event.request, networkResp.clone()); + } */ + + return networkResp; + })() + ); +}); |
