Persistence
localStoragePersistence and memoryPersistence from @kumbatio/energy-system/persistence
import { localStoragePersistence, memoryPersistence } from '@kumbatio/energy-system/persistence'Two built-in implementations of the EnergyPersistence contract. Pass them to createEnergyEngine or EnergyProvider.
localStoragePersistence
function localStoragePersistence(key?: string): EnergyPersistencelocalStorage-based persistence adapter. Stores the full EnergyState as JSON under key.
Prop
Type
Behavior:
load()- returnsnullwhenlocalStorageis unavailable, the key is empty, the JSON is malformed, or any field fails validation (level, source, timestamp, revision, origin). Valid data is rebuilt throughcreateEnergyState.save(state)- writesJSON.stringify(state). Failures (quota exceeded, missinglocalStorage) reject withError("Failed to save energy state to localStorage key '<key>'", { cause })rather than being swallowed, so the engine's persistence queue can observe the failure and retry with backoff.observe(onState)- listens to the windowstorageevent, so state changes from other tabs propagate into this engine (same-tab writes do not firestorage). Events for other keys or storage areas are ignored; invalid payloads are dropped. Returns an unsubscribe function; in environments withoutaddEventListener/localStorageit is a no-op.
import { createEnergyEngine } from '@kumbatio/energy-system'
import { localStoragePersistence } from '@kumbatio/energy-system/persistence'
const engine = createEnergyEngine({
persistence: localStoragePersistence('my-app:energy'),
})memoryPersistence
function memoryPersistence(initial?: EnergyState): EnergyPersistenceIn-memory persistence adapter. Useful for tests, SSR, or ephemeral sessions.
Prop
Type
Behavior:
load()- resolves the stored state, ornullwhen never saved and noinitialwas given.save(state)- stores a validated copy and synchronously notifies allobservelisteners.observe(onState)- registers a listener that fires on everysave. Returns an unsubscribe function. This makes two engines sharing onememoryPersistenceinstance converge, which is handy for simulating cross-context sync in tests.
import { createEnergyEngine, createEnergyState } from '@kumbatio/energy-system'
import { memoryPersistence } from '@kumbatio/energy-system/persistence'
const store = memoryPersistence(createEnergyState(50, 'scheduled'))
const engine = createEnergyEngine({ persistence: store })
await engine.hydrate()
engine.getState().level // 50