import { activeWorkspaceId } from "./workspace-scope"; type CacheEntry = { data?: T; promise?: Promise; expiresAt: number; }; const clientCache = new Map>(); interface CacheOptions { ttlMs?: number; force?: boolean; } /** A synchronous, workspace-scoped snapshot for views re-entered during SPA navigation. */ export function readClientCache(key: string): T | undefined { if (typeof window === "undefined") return undefined; const cached = clientCache.get(`${key}:workspace=${activeWorkspaceId()}`) as CacheEntry | undefined; return cached && cached.expiresAt > Date.now() ? cached.data : undefined; } export async function withClientCache( key: string, loader: () => Promise, options: CacheOptions = {}, ): Promise { const { ttlMs = 30_000, force = false } = options; if (typeof window === "undefined") { return loader(); } const now = Date.now(); key = `${key}:workspace=${activeWorkspaceId()}`; const cached = clientCache.get(key) as CacheEntry | undefined; if (!force && cached) { if (cached.data !== undefined && cached.expiresAt > now) { return cached.data; } if (cached.promise) { return cached.promise; } } const promise = loader() .then(value => { // Invalidated or superseded requests must not repopulate stale data. if (clientCache.get(key)?.promise === promise) { clientCache.set(key, { data: value, expiresAt: Date.now() + ttlMs, }); } return value; }) .catch(error => { if (clientCache.get(key)?.promise === promise) clientCache.delete(key); throw error; }); clientCache.set(key, { data: cached?.data, promise, expiresAt: now + ttlMs, }); return promise; } export function invalidateClientCache(prefix: string): void { for (const key of clientCache.keys()) { if (key.startsWith(prefix)) { clientCache.delete(key); } } }