Files
tidefront/apps/web/public/sw.js
T

85 lines
2.8 KiB
JavaScript

// Einfacher Service Worker: App-Shell cachen, Navigation zuerst aus dem Netz, API nie cachen; Push-Benachrichtigungen.
const CACHE = "tidefront-v2";
const SHELL = ["/", "/index.html", "/manifest.webmanifest", "/icon.svg"];
self.addEventListener("install", (e) => {
e.waitUntil(caches.open(CACHE).then((c) => c.addAll(SHELL)).then(() => self.skipWaiting()));
});
self.addEventListener("activate", (e) => {
e.waitUntil(
caches.keys().then((keys) => Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k)))).then(() => self.clients.claim()),
);
});
self.addEventListener("fetch", (e) => {
const url = new URL(e.request.url);
if (e.request.method !== "GET" || url.origin !== location.origin) return;
if (url.pathname.startsWith("/trpc") || url.pathname.startsWith("/ws") || url.pathname.startsWith("/healthz") || url.pathname.startsWith("/api/")) return;
if (e.request.mode === "navigate") {
e.respondWith(
fetch(e.request)
.then((res) => {
const copy = res.clone();
caches.open(CACHE).then((c) => c.put("/index.html", copy));
return res;
})
.catch(() => caches.match("/index.html")),
);
return;
}
if (url.pathname.startsWith("/assets/") || SHELL.includes(url.pathname) || url.pathname.endsWith(".png")) {
e.respondWith(
caches.match(e.request).then(
(hit) =>
hit ??
fetch(e.request).then((res) => {
if (res.ok) {
const copy = res.clone();
caches.open(CACHE).then((c) => c.put(e.request, copy));
}
return res;
}),
),
);
}
});
// Push: Nutzlast { title, body, url, tag, kind } vom Server.
self.addEventListener("push", (e) => {
let data = {};
try {
data = e.data ? e.data.json() : {};
} catch {
data = { body: e.data ? e.data.text() : "" };
}
const title = data.title || "TIDEFRONT";
e.waitUntil(
self.registration.showNotification(title, {
body: data.body || "",
tag: data.tag || undefined,
renotify: !!data.tag,
icon: "/icon-192.png",
badge: "/badge-96.png",
data: { url: data.url || "/" },
requireInteraction: data.kind === "attack",
}),
);
});
// Tippen auf die Benachrichtigung: offene App fokussieren und dorthin wechseln, sonst neu öffnen.
self.addEventListener("notificationclick", (e) => {
e.notification.close();
const target = new URL((e.notification.data && e.notification.data.url) || "/", self.location.origin).href;
e.waitUntil(
self.clients.matchAll({ type: "window", includeUncontrolled: true }).then((list) => {
const own = list.find((c) => new URL(c.url).origin === self.location.origin);
if (own) {
own.postMessage({ type: "open", url: target });
return own.focus();
}
return self.clients.openWindow(target);
}),
);
});