///
const sw = (self as typeof globalThis) as unknown as ServiceWorkerGlobalScope;
const CACHE_PREFIX = 'epube';
const CACHE_VERSION = BUILD_CACHE_VERSION;
const CACHE_NAME = CACHE_PREFIX + "-" + CACHE_VERSION;
const MANIFEST_ASSETS = BUILD_MANIFEST_ASSETS;
function fetchWithTimeout(request: Request, timeoutMs = 2500): Promise {
return new Promise((resolve, reject) => {
// Create an abort controller to stop the native network request if the timer fires first
const controller = new AbortController();
const timeoutId = setTimeout(() => {
controller.abort();
reject(new Error("Network timeout: DNS resolution took too long."));
}, timeoutMs);
fetch(request, { signal: controller.signal })
.then((response) => {
clearTimeout(timeoutId);
resolve(response);
})
.catch((err) => {
clearTimeout(timeoutId);
reject(err);
});
});
}
// Install: precache all assets from manifest
sw.addEventListener('install', (event) => {
(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) => {
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 as any).waitUntil(activationTask());
});
// Fetch: cache-first for static assets, network-first for API
sw.addEventListener('fetch', (event) => {
const url = new URL((event as any).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 as any).respondWith((async () => {
try {
const networkResp = await fetchWithTimeout((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
note that instead of hardcoding specific URLs, we handle all user-initiated explicit page navigation requests,
everything else falls back to the next block with cache-first-online-fallback logic
@todo potentially we could rewrite this to be offline-first as all entrypoints are cached, but we need to
somehow deal with substituting index.html with offline.html if network is unavailable without flapping
the UI repeatedly between online & offline indexes
*/
if (event.request.mode === 'navigate') {
(event as any).respondWith((async () => {
try {
const networkResp = await fetchWithTimeout((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", { ignoreSearch: true });
}
else {
return caches.match('/offline.html');
}
}
})());
return;
}
// everything else: cache-first with network fallback
(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;
})());
});