/** * Trading Studio PWA Service Worker * 缓存应用壳,支持离线打开已访问页面;API 请求始终走网络。 */ const CACHE_NAME = "trading-studio-v1"; const SHELL = ["/", "/manifest.webmanifest"]; self.addEventListener("install", (event) => { event.waitUntil( caches.open(CACHE_NAME).then((cache) => cache.addAll(SHELL)).catch(() => {}) ); self.skipWaiting(); }); self.addEventListener("activate", (event) => { event.waitUntil( caches.keys().then((keys) => Promise.all(keys.filter((k) => k !== CACHE_NAME).map((k) => caches.delete(k))) ) ); self.clients.claim(); }); self.addEventListener("fetch", (event) => { const { request } = event; const url = new URL(request.url); // API / 文件上传 / Gradio 动态接口不走缓存 if ( request.method !== "GET" || url.pathname.startsWith("/gradio_api") || url.pathname.startsWith("/file=") || url.pathname.startsWith("/upload") || url.pathname.includes("call") ) { return; } event.respondWith( fetch(request) .then((response) => { if (response.ok && url.origin === self.location.origin) { const clone = response.clone(); caches.open(CACHE_NAME).then((cache) => cache.put(request, clone)); } return response; }) .catch(() => caches.match(request).then((r) => r || caches.match("/"))) ); });