/** * Service-worker registration helper used by `root.tsx`. Kept in its own * module so it can be unit-tested without rendering a React tree. * * The function is a no-op when: * - `navigator.serviceWorker` is unavailable (SSR, older browsers). * - `window.location.protocol` is not http(s) — file:// previews would * otherwise throw SecurityError. * - `import.meta.env.DEV` is true — the dev server hot-reloads, and * a cached SW would shadow new bundles. * * Refs: docs/improvement-plan/10-compliance-polish/lighthouse.md (Step (d)). */ export type RegisterServiceWorkerOptions = { scriptUrl?: string; scope?: string; /** Inject an override container so tests can supply a fake navigator. */ navigatorRef?: Navigator; /** Inject an override container so tests can disable DEV gating. */ isDev?: boolean; }; export async function registerServiceWorker(options: RegisterServiceWorkerOptions = {}): Promise { const navigatorRef = options.navigatorRef ?? (typeof navigator === "undefined" ? undefined : navigator); if (!navigatorRef || !("serviceWorker" in navigatorRef)) { return null; } if (options.isDev) { return null; } try { return await navigatorRef.serviceWorker.register(options.scriptUrl ?? "/sw.js", { scope: options.scope ?? "/", }); } catch (err) { // Swallow but log — a failed SW must never break the app render. if (typeof console !== "undefined") { console.warn("[pwa] service worker registration failed", err); } return null; } }