/* Service Worker:静态资源持久缓存(Pyodide 运行时 + 构建产物) * 首次访问从网络拉取并写入 Cache API;此后(包括刷新/离线)全部本地命中, * Pyodide 引擎启动从 ~60s 降到 ~2-3s。 * 缓存策略: * - "/pyodide/...":带版本(v0.26.4),内容不可变 → cache-first,永不淘汰 * - "/assets/...":文件名带内容 hash → cache-first * - "/py/..."(算法核心 py 文件):no-store 语义 → network-only(SW 不缓存) * - 根路径与 index.html:network-first(SW 更新后立即生效) */ const CACHE = "fdets-static-v1"; const IMMUTABLE = [ /\/pyodide\//, // 自托管 Pyodide 运行时(版本化,immutable) /\/assets\/.+-[A-Za-z0-9_]{8}\.[a-z]+$/, // vite 内容 hash 产物 ]; self.addEventListener("install", (e) => { self.skipWaiting(); e.waitUntil(caches.open(CACHE)); }); self.addEventListener("activate", (e) => { e.waitUntil((async () => { // 清理旧版本缓存 const keys = await caches.keys(); await Promise.all(keys.filter(k => k.startsWith("fdets-static-") && k !== CACHE).map(k => caches.delete(k))); await self.clients.claim(); })()); }); self.addEventListener("fetch", (e) => { const url = new URL(e.request.url); if (url.origin !== location.origin) return; // 只管同源 if (e.request.method !== "GET") return; // 不可变静态资源:cache-first if (IMMUTABLE.some((re) => re.test(url.pathname))) { e.respondWith((async () => { const cached = await caches.match(e.request); if (cached) return cached; const resp = await fetch(e.request); if (resp.ok) { const cache = await caches.open(CACHE); cache.put(e.request, resp.clone()); } return resp; })()); return; } // HTML 入口:network-first(保证新版本部署后立即生效) if (url.pathname === "/" || url.pathname.endsWith(".html")) { e.respondWith((async () => { try { const resp = await fetch(e.request, { cache: "no-store" }); return resp; } catch { const cached = await caches.match(e.request); if (cached) return cached; throw new Error("offline"); } })()); } // 其余(py 算法核心等):默认行为,不拦截 });