Nick Meslovich / Products / Gravitas
// Gravitas service worker.
// Network-first for static shell (instant updates); never caches /api/* requests.
const CACHE = "gravitas-shell-v1";
const SHELL = [
"/",
"/index.html",
"/styles.css",
"/markdown.js",
"/app.js",
"/manifest.webmanifest",
"/icon.svg",
"/icon-192.png",
"/icon-512.png",
"/icon-maskable-512.png",
"/apple-touch-icon.png",
"/favicon.ico"
];
self.addEventListener("install", (event) => {
event.waitUntil(
caches.open(CACHE).then((cache) => cache.addAll(SHELL)).then(() => self.skipWaiting())
);
});
self.addEventListener("activate", (event) => {
event.waitUntil(
caches.keys().then((keys) =>
Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k)))
).then(() => self.clients.claim())
);
});
self.addEventListener("fetch", (event) => {
const req = event.request;
if (req.method !== "GET") return;
const url = new URL(req.url);
if (url.origin !== self.location.origin) return;
if (url.pathname.startsWith("/api/")) return;
event.respondWith(
fetch(req, { cache: "no-cache" })
.then((res) => {
if (res && res.ok && res.type === "basic") {
const copy = res.clone();
caches.open(CACHE).then((cache) => cache.put(req, copy)).catch(() => {});
}
return res;
})
.catch(() =>
caches.match(req).then((cached) => {
if (cached) return cached;
if (req.mode === "navigate") return caches.match("/index.html");
return new Response("Offline", { status: 503, statusText: "Offline" });
})
)
);
});