// lib/cssCache.js // Per-tenant compiled-CSS cache + cache-busting (ARCHITECTURE.md 7.7) const db = require("@saltcorn/data/db"); const { compileTheme } = require("./compile"); const themeStore = require("./themeStore"); const cache = new Map(); // tenantSchema -> Map<`${themeId}:${role??"_"}`, CompiledEntry> function tkey() { return db.getTenantSchema(); } function ck(themeId, role) { return `${themeId}:${role ?? "_"}`; } function getCached(themeId, role) { return cache.get(tkey())?.get(ck(themeId, role)); } function setCached(e) { let t = cache.get(tkey()); if (!t) cache.set(tkey(), (t = new Map())); t.set(ck(e.themeId, e.role), e); } function bustTheme(themeId) { const t = cache.get(tkey()); if (t) for (const k of [...t.keys()]) if (k.startsWith(themeId + ":")) t.delete(k); } function bustAll() { cache.delete(tkey()); } async function warm(themeId, role) { // used by onLoad rehydration + activate const theme = await themeStore.getById(themeId); // resolves rows AND builtins (SEAM FIX) if (!theme) return null; const compiled = compileTheme(theme.tokens, { engine: theme.engine }); const entry = { ...compiled, themeId, role: role ?? null, builtAt: Date.now() }; setCached(entry); return entry; } module.exports = { getCached, setCached, bustTheme, bustAll, warm };