import type { CompanyInfo } from "../../services/mm-api-service/company-info.js"; import { getRuntimeStateJson, setRuntimeStateJson, } from "./sdk-runtime-state-db.js"; /** * Cross-process runtime state shared between Bree workers (company info, token cache, * initial-load flag). Stored in SQLite (`sdk_runtime_state`) keyed by SQLITE_DB_PATH so * each key is updated independently under WAL — no whole-file read-modify-write races. */ const COMPANY_INFO_STORAGE_KEY = "companyInfo"; const INITIAL_LOAD_COMPLETE_KEY = "initialLoadComplete"; const MM_API_TOKEN_KEY = "mmApiToken"; function isPersistedCompanyInfo(value: unknown): value is CompanyInfo { if (!value || typeof value !== "object") { return false; } const o = value as Record; return ( typeof o.timezone === "string" && o.timezone.length > 0 && typeof o.locationRef === "string" && typeof o.companyId === "string" ); } /** * Reads company info written by initialization (or a prior API fetch) for use across processes. */ export const readPersistedCompanyInfo = (): CompanyInfo | null => { const raw = getRuntimeStateJson(COMPANY_INFO_STORAGE_KEY); return isPersistedCompanyInfo(raw) ? raw : null; }; /** * Persists company info for other processes sharing the same SQLite database file. */ export const writePersistedCompanyInfo = (info: CompanyInfo): void => { setRuntimeStateJson(COMPANY_INFO_STORAGE_KEY, info); }; export const getInitialLoadComplete = (): boolean => { return getRuntimeStateJson(INITIAL_LOAD_COMPLETE_KEY) ?? false; }; export const setInitialLoadComplete = (complete: boolean): void => { setRuntimeStateJson(INITIAL_LOAD_COMPLETE_KEY, complete); }; interface CachedToken { token: string; expiration: number | null; } /** * Gets the cached MM API token and its expiration * @returns The cached token and expiration or null if not found */ export const getCachedMMToken = (): CachedToken | null => { return getRuntimeStateJson(MM_API_TOKEN_KEY); }; /** * Sets the MM API token and its expiration in the cache * @param tokenData The token and expiration to cache */ export const setCachedMMToken = (tokenData: CachedToken): void => { setRuntimeStateJson(MM_API_TOKEN_KEY, tokenData); };