import type { QueryClient } from "@tanstack/react-query"; const STORAGE_KEY = "blink:query-cache:v1"; const MAX_AGE_MS = 1000 * 60 * 60 * 24 * 7; const MAX_ENTRIES = 60; type PersistedEntry = { key: readonly unknown[]; data: unknown; updatedAt: number; }; type PersistedCache = { owner: string; entries: PersistedEntry[]; }; const isPersistableKey = (key: readonly unknown[]) => typeof key[0] === "string" && (key[0] === "home" || key[0] === "libraries"); /** * Synchronously hydrate the most useful home/library queries from * localStorage. React Query then renders cached content immediately and * refetches in the background. */ export const restoreQueryCache = (client: QueryClient, owner: string) => { try { const raw = localStorage.getItem(STORAGE_KEY); if (!raw) return; const cached = JSON.parse(raw) as PersistedCache; if (cached.owner !== owner || !Array.isArray(cached.entries)) return; const now = Date.now(); for (const entry of cached.entries) { if (!Array.isArray(entry.key) || !isPersistableKey(entry.key)) continue; if (!entry.updatedAt || now - entry.updatedAt > MAX_AGE_MS) continue; client.setQueryData(entry.key, entry.data, { updatedAt: entry.updatedAt, }); } } catch (error) { console.warn("Could not restore the query cache", error); } }; /** Persist only home/library query data; throttled and silently forgiving. */ export const persistQueryCache = ( client: QueryClient, getOwner: () => string | undefined, ) => { let timer: number | undefined; const save = () => { const owner = getOwner(); if (!owner) return; try { const entries = client .getQueryCache() .getAll() .filter( (query) => query.state.status === "success" && query.state.data !== undefined && isPersistableKey(query.queryKey), ) .sort((a, b) => b.state.dataUpdatedAt - a.state.dataUpdatedAt) .slice(0, MAX_ENTRIES) .map((query) => ({ key: query.queryKey, data: query.state.data, updatedAt: query.state.dataUpdatedAt, })); const payload: PersistedCache = { owner, entries }; localStorage.setItem(STORAGE_KEY, JSON.stringify(payload)); } catch (error) { // A full storage quota must never break navigation. console.warn("Could not persist the query cache", error); try { localStorage.removeItem(STORAGE_KEY); } catch { // Ignore. } } }; const schedule = () => { window.clearTimeout(timer); timer = window.setTimeout(save, 400); }; const unsubscribe = client.getQueryCache().subscribe(schedule); window.addEventListener("beforeunload", save); return () => { window.clearTimeout(timer); unsubscribe(); window.removeEventListener("beforeunload", save); }; }; export const clearPersistedQueryCache = () => { try { localStorage.removeItem(STORAGE_KEY); } catch { // Ignore. } };