about summary refs log tree commit diff stats
path: root/src/worker.ts
diff options
context:
space:
mode:
Diffstat (limited to 'src/worker.ts')
-rw-r--r--src/worker.ts218
1 files changed, 93 insertions, 125 deletions
diff --git a/src/worker.ts b/src/worker.ts
index 44ea5b1..7afde1b 100644
--- a/src/worker.ts
+++ b/src/worker.ts
@@ -11,52 +11,40 @@ 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;
-            }
-        })()
-    );
+    (event as any).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 as any).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) => {
@@ -72,11 +60,9 @@ sw.addEventListener('message', (event) => {
 // 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) {
@@ -84,101 +70,83 @@ sw.addEventListener('activate', (event) => {
                 await caches.delete(key);
             }
         }
-
+        // @ts-expect-error TS(2551): Property 'clients' does not exist on type 'Window ... Remove this comment to see the full error message
         await sw.clients.claim();
     };
-
     // Hand the executed promise directly to the event
-    event.waitUntil(activationTask());
+    (event as any).waitUntil(activationTask());
 });
 
 // Fetch: cache-first for static assets, network-first for API
 sw.addEventListener('fetch', (event) => {
-    const url = new URL(event.request.url);
-
+    const url = new URL((event as any).request.url);
     // console.log('[fetch]', url);
-
     // /assets/ belong to android app
-    if (url.pathname.startsWith('/assets/')) return;
-
+    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;
+        (event as any).respondWith((async () => {
+            try {
+                const networkResp = await fetch((event as any).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 as any).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');
-                    }
+        (event as any).respondWith((async () => {
+            try {
+                const networkResp = await fetch((event as any).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;
-        })()
-    );
+    (event as any).respondWith((async () => {
+        const cache = await caches.open(CACHE_NAME);
+        const cached = await cache.match((event as any).request);
+        if (cached) {
+            // if cached, try to update: fire background network check without waiting for it (no await)
+            fetch((event as any).request)
+                .then((networkResp) => {
+                if (networkResp.ok)
+                    cache.put((event as any).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 as any).request);
+        /* if (networkResp.ok) { -- we don't cache all responses
+            await cache.put(event.request, networkResp.clone());
+        } */
+        return networkResp;
+    })());
 });