SPB Git

Repository Public

sw.ts 4.7 KB 99 lines typescript

1// Service worker de la coque applicative : précache versionné des fichiers du build, repli de navigation hors ligne, mise à jour sûre.2// Écrit à la main (aucune bibliothèque), compilé par le greffon `shellWorker` de vite.config.ts qui y injecte la liste des fichiers.3// RÈGLE ABSOLUE : rien de ce qui passe par /api/** n'est intercepté ni mis en cache (courrier, pièces jointes, session) — le4// courrier hors ligne vit uniquement dans le cache IndexedDB de l'application, effacé à toute perte de session. Pas de Web Push.5declare const __SHELL_VERSION__: string6declare const __SHELL_FILES__: string[]78// Types minimaux du contexte d'un service worker (la bibliothèque « webworker » de TypeScript entre en conflit avec « DOM »).9interface WaitEvent extends Event {10  waitUntil(p: Promise<unknown>): void11}12interface FetchEv extends WaitEvent {13  request: Request14  respondWith(r: Promise<Response>): void15}16interface MessageEv extends WaitEvent {17  data: unknown18  ports: readonly MessagePort[]19}20interface Scope {21  addEventListener(type: "install" | "activate", fn: (e: WaitEvent) => void): void22  addEventListener(type: "fetch", fn: (e: FetchEv) => void): void23  addEventListener(type: "message", fn: (e: MessageEv) => void): void24  skipWaiting(): Promise<void>25  clients: { claim(): Promise<void> }26  location: { origin: string }27}28const sw = self as unknown as Scope2930const PREFIX = "spmail-shell-"31const CACHE = `${PREFIX}${__SHELL_VERSION__}`32const INDEX = "/index.html"33const FILES = new Set(__SHELL_FILES__.map((f) => `/${f}`))3435/** Précache atomique : tous les fichiers de CETTE version, ou rien (un cache partiel mêlerait deux versions). */36async function precache(): Promise<void> {37  const cache = await caches.open(CACHE)38  try {39    await Promise.all(40      [...FILES].map(async (path) => {41        const r = await fetch(new Request(path, { cache: "reload", credentials: "same-origin" }))42        if (!r.ok || r.redirected) throw new Error(`precache ${path}: ${r.status}`)43        // un fichier d'actif absent ne doit jamais être remplacé par la page de repli du serveur (HTML)44        if (path !== INDEX && (r.headers.get("content-type") ?? "").includes("text/html")) throw new Error(`precache ${path}: html`)45        await cache.put(path, r)46      }),47    )48  } catch (e) {49    await caches.delete(CACHE)50    throw e51  }52}5354sw.addEventListener("install", (e) => {55  // pas de skipWaiting ici : une nouvelle version ATTEND que la personne l'accepte (« Une mise à jour est prête »)56  e.waitUntil(precache())57})5859sw.addEventListener("activate", (e) => {60  e.waitUntil(61    (async () => {62      for (const key of await caches.keys()) if (key.startsWith(PREFIX) && key !== CACHE) await caches.delete(key)63      await sw.clients.claim()64    })(),65  )66})6768/** Fichier du build : cache de cette version d'abord ; sinon le réseau, sans jamais accepter du HTML à la place d'un actif. */69async function fromShell(path: string, req: Request): Promise<Response> {70  const hit = await (await caches.open(CACHE)).match(path)71  if (hit) return hit72  const r = await fetch(req)73  if (path.startsWith("/assets/") && (r.headers.get("content-type") ?? "").includes("text/html")) return new Response("", { status: 404, statusText: "Not Found" })74  return r75}7677sw.addEventListener("fetch", (e) => {78  const req = e.request79  if (req.method !== "GET") return80  const url = new URL(req.url)81  if (url.origin !== sw.location.origin) return82  // API, téléchargements, flux d'événements, associations de domaine : réseau seul — le navigateur s'en charge, sans nous.83  if (url.pathname.startsWith("/api/") || url.pathname.startsWith("/.well-known/")) return84  if (FILES.has(url.pathname)) return e.respondWith(fromShell(url.pathname, req))85  if (url.pathname.startsWith("/assets/")) return e.respondWith(fromShell(url.pathname, req))86  // Navigation (toute adresse de l'application, sans extension de fichier) : la coque de CETTE version, même hors ligne.87  if (req.mode === "navigate" && !/\.[a-z0-9]+$/i.test(url.pathname)) e.respondWith(fromShell(INDEX, req))88})8990sw.addEventListener("message", (e) => {91  const type = (e.data as { type?: string } | null)?.type92  if (type === "SKIP_WAITING") void sw.skipWaiting()93  // après une purge (déconnexion) suivie d'une reconnexion sans rechargement : le précache est reconstruit94  else if (type === "ENSURE") e.waitUntil(caches.has(CACHE).then((has) => (has ? undefined : precache())).catch(() => undefined))95  // page chargée pendant l'activation (ou rechargée « à neuf ») : elle demande à être prise en charge96  else if (type === "CLAIM") e.waitUntil(sw.clients.claim().catch(() => undefined))97  else if (type === "VERSION") e.ports[0]?.postMessage({ version: __SHELL_VERSION__, files: FILES.size })98})99
Files main
Menu

Theme