const CACHE_NAME = 'sgs-guide-model-v1' const INDEX_STORAGE_KEY = 'sgs.guide.model-cache-index.v1' const MAX_ENTRIES = 6 interface CacheIndexEntry { key: string touchedAt: number } export interface PersistentModelAsset { url: string release: () => void } const getCacheStorage = () => ( typeof globalThis !== 'undefined' && 'caches' in globalThis ? globalThis.caches : null ) const getStorage = () => ( typeof localStorage !== 'undefined' ? localStorage : null ) const buildCacheKey = (url: string, version?: string) => { const normalizedUrl = url.trim() const normalizedVersion = version?.trim() || normalizedUrl const separator = normalizedUrl.includes('?') ? '&' : '?' return `${normalizedUrl}${separator}__sgs_model_version=${encodeURIComponent(normalizedVersion)}` } const readIndex = (): CacheIndexEntry[] => { try { const raw = getStorage()?.getItem(INDEX_STORAGE_KEY) const parsed = raw ? JSON.parse(raw) : [] return Array.isArray(parsed) ? parsed.filter((entry): entry is CacheIndexEntry => ( Boolean(entry) && typeof entry.key === 'string' && typeof entry.touchedAt === 'number' )) : [] } catch { return [] } } const writeIndex = (entries: CacheIndexEntry[]) => { try { getStorage()?.setItem(INDEX_STORAGE_KEY, JSON.stringify(entries)) } catch { // Persistent cache is an optimization. Storage quota failures must not block map loading. } } const touchIndex = (key: string) => { const now = Date.now() const next = readIndex() .filter((entry) => entry.key !== key) next.push({ key, touchedAt: now }) writeIndex(next) return next } const removeFromIndex = (key: string) => { writeIndex(readIndex().filter((entry) => entry.key !== key)) } export class GuideModelPersistentCache { async get(url: string, version?: string): Promise { const cacheStorage = getCacheStorage() if (!cacheStorage || typeof URL === 'undefined' || typeof URL.createObjectURL !== 'function') return null const key = buildCacheKey(url, version) try { const cache = await cacheStorage.open(CACHE_NAME) const response = await cache.match(key) if (!response) return null const blob = await response.blob() if (!blob.size) { await cache.delete(key) removeFromIndex(key) return null } touchIndex(key) const objectUrl = URL.createObjectURL(blob) return { url: objectUrl, release: () => URL.revokeObjectURL(objectUrl) } } catch { return null } } async store(url: string, version?: string): Promise { const cacheStorage = getCacheStorage() if (!cacheStorage || typeof fetch !== 'function') return const key = buildCacheKey(url, version) try { const cache = await cacheStorage.open(CACHE_NAME) if (await cache.match(key)) { await this.prune(cache, touchIndex(key)) return } // The preceding GLTF request is normally still in the browser HTTP cache, so this does // not redownload a successful asset on standard H5 browsers. const response = await fetch(url, { cache: 'force-cache' }) if (!response.ok || !response.body) return await cache.put(key, response) await this.prune(cache, touchIndex(key)) } catch { // Cache writes are deliberately best-effort. } } async remove(url: string, version?: string): Promise { const cacheStorage = getCacheStorage() if (!cacheStorage) return const key = buildCacheKey(url, version) try { const cache = await cacheStorage.open(CACHE_NAME) await cache.delete(key) } catch { // Ignore cache cleanup failures and continue with a normal network request. } removeFromIndex(key) } private async prune(cache: Cache, entries: CacheIndexEntry[]) { const staleEntries = [...entries] .sort((left, right) => left.touchedAt - right.touchedAt) .slice(0, Math.max(0, entries.length - MAX_ENTRIES)) if (!staleEntries.length) return await Promise.all(staleEntries.map((entry) => cache.delete(entry.key))) const staleKeys = new Set(staleEntries.map((entry) => entry.key)) writeIndex(entries.filter((entry) => !staleKeys.has(entry.key))) } } export const guideModelPersistentCache = new GuideModelPersistentCache()