From 78d2fe20ef0d9deb988237253b3c8b914d153f33 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Wed, 17 Jun 2026 16:41:32 -0400 Subject: [PATCH] feat: add service worker precaching with app shell and runtime cache strategies --- frontend/index.html | 1 + frontend/plugins/sw-precache-manifest.ts | 75 ++++++++++++ frontend/src/App.tsx | 2 + .../components/ui/route-error-boundary.tsx | 109 ++++++++++++++++++ frontend/src/lib/serviceWorker.ts | 6 +- frontend/src/sw.ts | 97 +++++++++++++--- frontend/tsconfig.node.json | 2 +- frontend/vite.config.ts | 2 + 8 files changed, 277 insertions(+), 17 deletions(-) create mode 100644 frontend/plugins/sw-precache-manifest.ts create mode 100644 frontend/src/components/ui/route-error-boundary.tsx diff --git a/frontend/index.html b/frontend/index.html index fe67e71d..90991b2a 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -3,6 +3,7 @@ + diff --git a/frontend/plugins/sw-precache-manifest.ts b/frontend/plugins/sw-precache-manifest.ts new file mode 100644 index 00000000..31cac5ff --- /dev/null +++ b/frontend/plugins/sw-precache-manifest.ts @@ -0,0 +1,75 @@ +import { createHash } from "node:crypto"; +import { readdir, readFile, writeFile } from "node:fs/promises"; +import path from "node:path"; +import type { Plugin } from "vite"; + +const SW_FILENAME = "sw.js"; +const PRECACHE_DIR_PREFIXES = ["assets/"]; +const PRECACHE_ROOT_FILES = ["index.html", "manifest.json", "favicon.svg"]; + +async function collectFiles(dir: string, base = dir): Promise { + const entries = await readdir(dir, { withFileTypes: true }); + const files = await Promise.all( + entries.map(async (entry) => { + const absolute = path.join(dir, entry.name); + if (entry.isDirectory()) return collectFiles(absolute, base); + return [path.relative(base, absolute)]; + }) + ); + return files.flat(); +} + +function toUrl(relativePath: string): string { + return "/" + relativePath.split(path.sep).join("/"); +} + +function isPrecacheTarget(relativePath: string): boolean { + const url = toUrl(relativePath); + if (url === `/${SW_FILENAME}` || url.endsWith(".map")) return false; + if (PRECACHE_ROOT_FILES.includes(relativePath)) return true; + return PRECACHE_DIR_PREFIXES.some((prefix) => url.startsWith(`/${prefix}`)); +} + +export function swPrecacheManifest(): Plugin { + let outDir = ""; + + return { + name: "sw-precache-manifest", + apply: "build", + configResolved(config) { + outDir = path.resolve(config.root, config.build.outDir); + }, + async closeBundle() { + const swPath = path.join(outDir, SW_FILENAME); + let swSource: string; + try { + swSource = await readFile(swPath, "utf-8"); + } catch { + throw new Error(`[sw-precache-manifest] ${SW_FILENAME} not found in ${outDir}`); + } + + const relativePaths = (await collectFiles(outDir)).filter(isPrecacheTarget).sort(); + + const hash = createHash("sha256"); + const urls: string[] = []; + for (const relativePath of relativePaths) { + const content = await readFile(path.join(outDir, relativePath)); + const url = toUrl(relativePath); + urls.push(url); + hash.update(url); + hash.update(content); + } + + if (!urls.includes("/index.html")) { + throw new Error("[sw-precache-manifest] index.html missing from build output"); + } + + const buildHash = hash.digest("hex").slice(0, 16); + const header = + `self.__SW_BUILD_HASH__=${JSON.stringify(buildHash)};` + + `self.__SW_PRECACHE__=${JSON.stringify(urls)};\n`; + + await writeFile(swPath, header + swSource); + }, + }; +} diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 145b7b47..f4570521 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -17,6 +17,7 @@ import { VersionNotifier } from './components/VersionNotifier' import { PwaUpdatePrompt } from '@/components/PwaUpdatePrompt' import { MobileTabBar } from '@/components/navigation/MobileTabBar' import { MobileSheetHost } from '@/components/navigation/MobileSheetHost' +import { RouteErrorBoundary } from '@/components/ui/route-error-boundary' import { DesktopSidebar } from '@/components/navigation/DesktopSidebar' import { useTheme } from './hooks/useTheme' import { useRightEdgeSwipe, useSwipeBack } from './hooks/useMobile' @@ -185,6 +186,7 @@ function AppShell() { const router = createBrowserRouter([ { element: , + errorElement: , children: [ { path: '/login', diff --git a/frontend/src/components/ui/route-error-boundary.tsx b/frontend/src/components/ui/route-error-boundary.tsx new file mode 100644 index 00000000..521b2e42 --- /dev/null +++ b/frontend/src/components/ui/route-error-boundary.tsx @@ -0,0 +1,109 @@ +import { useRouteError, isRouteErrorResponse } from 'react-router-dom' +import { AlertTriangle, RefreshCw, LogIn, WifiOff } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { parseNetworkError, parseOpenCodeError } from '@/lib/opencode-errors' +import type { OpenCodeError } from '@/lib/opencode-errors' + +function isOpenCodeError(error: unknown): error is OpenCodeError { + return typeof error === 'object' && error !== null && 'name' in error && 'data' in error +} + +function getErrorDetails(error: unknown) { + if (isRouteErrorResponse(error)) { + if (error.status === 401 || error.status === 403) { + return { + title: 'Authentication Required', + message: 'Please log in to access this page.', + isRetryable: false, + statusCode: error.status, + } + } + if (error.status === 404) { + return { + title: 'Page Not Found', + message: 'The page you are looking for does not exist.', + isRetryable: false, + statusCode: error.status, + } + } + return { + title: error.statusText || 'Error', + message: error.data?.message || error.status.toString(), + isRetryable: true, + statusCode: error.status, + } + } + + if (isOpenCodeError(error)) { + const parsed = parseOpenCodeError(error) + if (parsed) return parsed + } + + if (error instanceof Error) { + const networkParsed = parseNetworkError(error) + if (networkParsed.title === 'Connection Failed') { + return { + ...networkParsed, + title: "You're offline", + message: '', + isRetryable: false, + variant: 'offline' as const, + } + } + return networkParsed + } + + return { + title: 'Unexpected Error', + message: 'An unexpected error occurred. Please try refreshing the page.', + isRetryable: true, + } +} + +export function RouteErrorBoundary() { + const error = useRouteError() + const details = getErrorDetails(error) + const { title, message, isRetryable, statusCode } = details + + const isAuthError = statusCode === 401 || statusCode === 403 + + if ('variant' in details && details.variant === 'offline') { + return ( +
+ +
+ + {title} +
+ +
+ ) + } + + return ( +
+ +
+

{title}

+

{message}

+
+
+ {isAuthError && ( + + )} + {isRetryable && ( + + )} +
+
+ ) +} diff --git a/frontend/src/lib/serviceWorker.ts b/frontend/src/lib/serviceWorker.ts index 033a1d9b..d82ecf65 100644 --- a/frontend/src/lib/serviceWorker.ts +++ b/frontend/src/lib/serviceWorker.ts @@ -4,19 +4,23 @@ type UpdateCallback = () => void; let updateCallback: UpdateCallback | null = null; let updatePending = false; +let updateNotified = false; function notifyUpdate() { + if (updateNotified) return; if (!updateCallback) { updatePending = true; return; } + updateNotified = true; updatePending = false; updateCallback(); } export function onServiceWorkerUpdate(callback: UpdateCallback): void { updateCallback = callback; - if (updatePending) { + if (updatePending && !updateNotified) { + updateNotified = true; updatePending = false; callback(); } diff --git a/frontend/src/sw.ts b/frontend/src/sw.ts index 2384f0fc..434e7c1d 100644 --- a/frontend/src/sw.ts +++ b/frontend/src/sw.ts @@ -1,18 +1,44 @@ /// -declare const self: ServiceWorkerGlobalScope & typeof globalThis; +const worker = self as unknown as ServiceWorkerGlobalScope & typeof globalThis; -self.addEventListener("install", () => { - self.skipWaiting(); +interface SwBuildGlobals { + __SW_BUILD_HASH__?: string; + __SW_PRECACHE__?: string[]; +} + +const buildGlobals = worker as unknown as SwBuildGlobals; + +const BUILD_HASH = buildGlobals.__SW_BUILD_HASH__ ?? "dev"; +const PRECACHE_URLS = buildGlobals.__SW_PRECACHE__ ?? []; + +const APP_SHELL_CACHE = `app-shell-${BUILD_HASH}`; +const RUNTIME_CACHE = `runtime-${BUILD_HASH}`; +const APP_SHELL_URL = "/index.html"; +const MANAGED_CACHE_PREFIXES = ["app-shell-", "runtime-", "offline-assets-"]; + +worker.addEventListener("install", (event) => { + event.waitUntil(caches.open(APP_SHELL_CACHE).then((cache) => cache.addAll(PRECACHE_URLS))); + worker.skipWaiting(); }); -self.addEventListener("activate", (event) => { +worker.addEventListener("activate", (event) => { event.waitUntil( - caches.keys().then((names) => - Promise.all(names.map((name) => caches.delete(name))) - ).then(() => self.clients.claim()) - .then(() => self.clients.matchAll({ type: "window" })) - .then((clients) => { + caches.keys().then(async (names) => { + const stale = names.filter( + (name) => + MANAGED_CACHE_PREFIXES.some((prefix) => name.startsWith(prefix)) && + name !== APP_SHELL_CACHE && + name !== RUNTIME_CACHE + ); + const isUpdate = stale.length > 0; + + await Promise.all(stale.map((name) => caches.delete(name))); + await worker.clients.claim(); + + if (!isUpdate) return; + + const clients = await worker.clients.matchAll({ type: "window" }); for (const client of clients) { client.postMessage({ type: "SW_UPDATED" }); } @@ -20,6 +46,47 @@ self.addEventListener("activate", (event) => { ); }); +async function networkFirstShell(request: Request): Promise { + const cache = await caches.open(APP_SHELL_CACHE); + try { + const response = await fetch(request); + if (response.ok) cache.put(APP_SHELL_URL, response.clone()); + return response; + } catch (error) { + const cached = await cache.match(APP_SHELL_URL); + if (cached) return cached; + throw error; + } +} + +async function cacheFirstAsset(request: Request): Promise { + const cached = await caches.match(request); + if (cached) return cached; + + const response = await fetch(request); + if (response.ok && response.status === 200) { + const cache = await caches.open(RUNTIME_CACHE); + cache.put(request, response.clone()); + } + return response; +} + +worker.addEventListener("fetch", (event) => { + const { request } = event; + if (request.method !== "GET") return; + + const url = new URL(request.url); + if (url.origin !== worker.location.origin) return; + if (url.pathname.startsWith("/api/") || url.pathname === "/sw.js") return; + + if (request.mode === "navigate") { + event.respondWith(networkFirstShell(request)); + return; + } + + event.respondWith(cacheFirstAsset(request)); +}); + interface PushNotificationData { title: string; body: string; @@ -37,7 +104,7 @@ interface PushNotificationData { }; } -self.addEventListener("push", (event) => { +worker.addEventListener("push", (event) => { if (!event.data) return; let payload: PushNotificationData; @@ -60,27 +127,27 @@ self.addEventListener("push", (event) => { requireInteraction: isHighPriority(payload.data?.eventType, payload.data?.priority), }; - event.waitUntil(self.registration.showNotification(payload.title, options)); + event.waitUntil(worker.registration.showNotification(payload.title, options)); }); -self.addEventListener("notificationclick", (event) => { +worker.addEventListener("notificationclick", (event) => { event.notification.close(); const url = (event.notification.data?.url as string) ?? "/"; event.waitUntil( - self.clients + worker.clients .matchAll({ type: "window", includeUncontrolled: true }) .then((clientList) => { for (const client of clientList) { - if (new URL(client.url).origin === self.location.origin) { + if (new URL(client.url).origin === worker.location.origin) { const channel = new BroadcastChannel("notification-click"); channel.postMessage({ url }); channel.close(); return (client as WindowClient).focus(); } } - return self.clients.openWindow(url); + return worker.clients.openWindow(url); }) ); }); diff --git a/frontend/tsconfig.node.json b/frontend/tsconfig.node.json index 8a67f62f..1b01c4a8 100644 --- a/frontend/tsconfig.node.json +++ b/frontend/tsconfig.node.json @@ -22,5 +22,5 @@ "noFallthroughCasesInSwitch": true, "noUncheckedSideEffectImports": true }, - "include": ["vite.config.ts"] + "include": ["vite.config.ts", "plugins/**/*.ts"] } diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts index beb3371c..958e8cd6 100644 --- a/frontend/vite.config.ts +++ b/frontend/vite.config.ts @@ -2,6 +2,7 @@ import path from "path"; import { defineConfig, loadEnv } from "vite"; import react from "@vitejs/plugin-react"; import tailwindcss from "@tailwindcss/vite"; +import { swPrecacheManifest } from "./plugins/sw-precache-manifest"; export default defineConfig(({ mode }) => { const env = loadEnv(mode, path.resolve(__dirname, ".."), ""); @@ -12,6 +13,7 @@ export default defineConfig(({ mode }) => { plugins: [ react(), tailwindcss(), + swPrecacheManifest(), ], resolve: { alias: {