UNPKG

@softr/sdk

Version:

The SDK for building Softr apps on TanStack Start. It lets an app interact with Softr: auth, datasources, workflows and integrations.

120 lines (113 loc) • 6.06 kB
//#region src/service-worker.ts const WORKER_PATH = "/_softr/sw.js"; /** Pages, scripts, styles and images. Its owner entry is what turns offline mode on. */ const OFFLINE_CACHE = "softr-offline-v1"; /** Answers to the app's data calls, kept apart so a long session of them never pushes out the pages. */ const OFFLINE_DATA_CACHE = "softr-offline-data-v1"; /** Whose copies the offline cache holds: the user id, or empty for a signed-out visitor. */ const OFFLINE_OWNER_KEY = "/_softr/offline-owner"; /** Between the worker and the page: whether the worker answers with saved copies. */ const OFFLINE_MESSAGE = "softr-offline"; /** * Names the signed-in user on each answer from the app's server, or is empty * for a signed-out visitor. The worker deletes copies kept for someone else. */ const OFFLINE_USER_HEADER = "x-softr-offline-user"; /** Marks a request `useOfflineMode()` saves itself, so the worker leaves it alone. */ const OFFLINE_SAVE_HEADER = "x-softr-offline-save"; /** Paths offline mode never keeps: the SDK's own routes and the canvas engine's. */ const OFFLINE_SKIPPED_PREFIXES = ["/_softr/", "/.softr/"]; const MAX_COPIES = 300; /** * Added after the platform's worker. Same-origin GET requests go to the * network first, and the last good answer is kept on the device for when the * network fails. Writes and live streams are never kept. * * It keeps nothing until `useOfflineMode()` writes the owner entry. An app that * registers the worker only for push still has its requests pass through it. */ const OFFLINE_WORKER = ` // Offline mode, added by @softr/sdk. const SOFTR_OFFLINE_CACHE = ${JSON.stringify(OFFLINE_CACHE)}; const SOFTR_OFFLINE_DATA_CACHE = ${JSON.stringify(OFFLINE_DATA_CACHE)}; const SOFTR_OFFLINE_OWNER_KEY = ${JSON.stringify(OFFLINE_OWNER_KEY)}; const SOFTR_OFFLINE_SAVE_HEADER = ${JSON.stringify(OFFLINE_SAVE_HEADER)}; const SOFTR_OFFLINE_SKIPPED = ${JSON.stringify(OFFLINE_SKIPPED_PREFIXES)}; const SOFTR_OFFLINE_MESSAGE = ${JSON.stringify(OFFLINE_MESSAGE)}; const SOFTR_OFFLINE_USER_HEADER = ${JSON.stringify(OFFLINE_USER_HEADER)}; // Unknown after the worker starts, so the first answer after a restart always reaches the page. let softrShowingCopies; function softrSetShowingCopies(showingCopies) { if (softrShowingCopies === showingCopies) return; softrShowingCopies = showingCopies; self.clients.matchAll({ type: 'window' }).then((pages) => { for (const page of pages) page.postMessage({ type: SOFTR_OFFLINE_MESSAGE, showingCopies }); }); } // Page loads start while the worker starts, so a stopped worker does not delay them. self.addEventListener('activate', (event) => { if (self.registration.navigationPreload) event.waitUntil(self.registration.navigationPreload.enable()); }); self.addEventListener('message', (event) => { if (event.data && event.data.type === SOFTR_OFFLINE_MESSAGE && event.source) { // The browser is back online. The next request that fails says so again. if (event.data.online === true) softrShowingCopies = false; event.source.postMessage({ type: SOFTR_OFFLINE_MESSAGE, showingCopies: softrShowingCopies === true }); } }); function softrOfflineOwner() { return caches.match(SOFTR_OFFLINE_OWNER_KEY, { cacheName: SOFTR_OFFLINE_CACHE }).then((owner) => owner && owner.text()); } async function softrKeepCopy(owner, cacheName, key, response) { // The copies were deleted, or now belong to someone else, while the request ran. if ((await softrOfflineOwner()) !== owner) return; const cache = await caches.open(cacheName); await cache.put(key, response); const keys = (await cache.keys()).filter((key) => new URL(key.url).pathname !== SOFTR_OFFLINE_OWNER_KEY); await Promise.all(keys.slice(0, Math.max(0, keys.length - ${MAX_COPIES})).map((key) => cache.delete(key))); } self.addEventListener('fetch', (event) => { const request = event.request; if (request.method !== 'GET') return; const url = new URL(request.url); if (url.origin !== self.location.origin) return; if (SOFTR_OFFLINE_SKIPPED.some((prefix) => url.pathname.startsWith(prefix))) return; if (request.headers.has(SOFTR_OFFLINE_SAVE_HEADER)) return; event.respondWith((async () => { const fromNetwork = () => (request.mode === 'navigate' && event.preloadResponse ? event.preloadResponse.then((preloaded) => preloaded || fetch(request)) : fetch(request)); const owner = await softrOfflineOwner(); if (owner === undefined) return fromNetwork(); // A data call from the app's code has no destination; a page or a file has one. const cacheName = request.destination === '' ? SOFTR_OFFLINE_DATA_CACHE : SOFTR_OFFLINE_CACHE; // One copy of a page per path, whatever the search, like the hook keeps. Offline, // a page opened with another search gets that copy, and its data may be missing. const key = request.mode === 'navigate' ? url.origin + url.pathname : request; try { const response = await fromNetwork(); softrSetShowingCopies(false); const user = response.headers.get(SOFTR_OFFLINE_USER_HEADER); if (user !== null && user !== owner) { // Someone else is signed in. Delete the copies even when the page no longer runs the hook. event.waitUntil(Promise.all([caches.delete(SOFTR_OFFLINE_CACHE), caches.delete(SOFTR_OFFLINE_DATA_CACHE)])); return response; } const streamed = (response.headers.get('content-type') || '').startsWith('text/event-stream'); if (response.status === 200 && response.type === 'basic' && !streamed) { event.waitUntil(softrKeepCopy(owner, cacheName, key, response.clone()).catch(() => {})); } return response; } catch (error) { const copy = await caches.match(key, { cacheName }); if (copy) { softrSetShowingCopies(true); return copy; } throw error; } })()); }); `; //#endregion export { OFFLINE_CACHE, OFFLINE_DATA_CACHE, OFFLINE_MESSAGE, OFFLINE_OWNER_KEY, OFFLINE_SAVE_HEADER, OFFLINE_SKIPPED_PREFIXES, OFFLINE_USER_HEADER, OFFLINE_WORKER, WORKER_PATH };