UNPKG

@stainless-code/persist

Version:

Hydration-aware persistence for any reactive store — zero-dep persistSource core; codecs, backends, cross-tab transport, source + framework hydration adapters ship as opt-in recipes

54 lines (53 loc) • 2.02 kB
import { a as createSessionStorage, c as jsonCodec, i as createPersistRegistry, l as persistSource, n as createJSONStorage, o as createStorage, r as createMigrationChain, s as identityCodec, t as PersistDecodeRethrowError } from "../persist-core-B5VikEft.mjs"; //#region src/core/hydration.ts /** * Derive a `HydrationSignal` from a `HydrationSource` (e.g. a `PersistApi`), * bridging `onHydrate` / `onFinishHydration` into one external-store * subscribe target that notifies on either transition. Null-tolerant: * `null` / `undefined` in → `null` out, so a conditional-persist consumer * drops its hydration ternary (`persist ? toHydrationSignal(persist) : null` * → `toHydrationSignal(persist)`). */ function toHydrationSignal(source) { if (!source) return null; const listeners = /* @__PURE__ */ new Set(); const emit = () => { for (const listener of listeners) listener(); }; let unsubHydrate = null; let unsubFinish = null; return { subscribeHydrated(listener) { const entry = () => listener(); listeners.add(entry); if (listeners.size === 1) { unsubHydrate = source.onHydrate(emit); unsubFinish = source.onFinishHydration(emit); } return () => { if (!listeners.delete(entry)) return; if (listeners.size === 0) { unsubHydrate?.(); unsubFinish?.(); unsubHydrate = null; unsubFinish = null; } }; }, isHydrated: () => source.hasHydrated() }; } /** * Always-hydrated `HydrationSignal` for the no-persist path — a uniform * handle instead of a `null` branch at the call site. Solves null-tolerance * once in the core so framework adapters stay dumb (subscribe + snapshot, * nothing else). */ function alwaysHydratedSignal() { return { subscribeHydrated: () => () => {}, isHydrated: () => true }; } //#endregion export { PersistDecodeRethrowError, alwaysHydratedSignal, createJSONStorage, createMigrationChain, createPersistRegistry, createSessionStorage, createStorage, identityCodec, jsonCodec, persistSource, toHydrationSignal };