fix(store): guard localStorage calls for Node/SSR builds

This commit is contained in:
Scott Idem
2026-03-24 16:46:52 -04:00
parent a637343544
commit 66f0efb507

View File

@@ -34,27 +34,37 @@ export const AE_LOC_VERSION = 1;
export const AE_EVENTS_LOC_VERSION = 1;
// Version check side-effect: runs on import, before any persisted() call.
// Guards typeof localStorage for safety (SSR environments, test runners).
if (typeof localStorage !== 'undefined') {
// Guard presence of `localStorage` and its functions for safety (SSR, Node flags).
if (
typeof localStorage !== 'undefined' &&
typeof (localStorage as any).getItem === 'function' &&
typeof (localStorage as any).removeItem === 'function'
) {
_check_and_wipe('ae_loc', AE_LOC_VERSION);
_check_and_wipe('ae_events_loc', AE_EVENTS_LOC_VERSION);
}
function _check_and_wipe(key: string, expected_version: number): void {
try {
// Defensive: ensure methods still exist at call time.
if (typeof (localStorage as any).getItem !== 'function') return;
const raw = localStorage.getItem(key);
if (!raw) return; // No stored value — nothing to wipe.
const parsed = JSON.parse(raw);
if (parsed?.__version !== expected_version) {
localStorage.removeItem(key);
if (typeof (localStorage as any).removeItem === 'function') {
localStorage.removeItem(key);
}
console.info(
`[store_versions] '${key}' wiped — schema v${parsed?.__version ?? 'none'} → v${expected_version}`
);
}
} catch {
// Corrupt JSON — wipe unconditionally.
localStorage.removeItem(key);
// Corrupt JSON — wipe unconditionally if possible.
if (typeof (localStorage as any).removeItem === 'function') {
localStorage.removeItem(key);
}
console.warn(
`[store_versions] '${key}' wiped — corrupt JSON in localStorage`
);