react-mnemonic 0.1.1-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +21 -0
- package/README.md +497 -0
- package/dist/index.cjs +996 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +1151 -0
- package/dist/index.d.ts +1151 -0
- package/dist/index.js +987 -0
- package/dist/index.js.map +1 -0
- package/package.json +80 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/Mnemonic/provider.tsx","../src/Mnemonic/codecs.ts","../src/Mnemonic/schema.ts","../src/Mnemonic/json-schema.ts","../src/Mnemonic/use.ts"],"names":["createContext","useContext","useMemo","store","useEffect","useCallback","value","decoded","envelope","useSyncExternalStore","useRef"],"mappings":";;;;;;AA+BA,IAAM,eAAA,GAAkBA,oBAA+B,IAAI,CAAA;AAyBpD,SAAS,WAAA,GAAwB;AACpC,EAAA,MAAM,OAAA,GAAUC,iBAAW,eAAe,CAAA;AAC1C,EAAA,IAAI,CAAC,OAAA,EAAS;AACV,IAAA,MAAM,IAAI,MAAM,oDAAoD,CAAA;AAAA,EACxE;AACA,EAAA,OAAO,OAAA;AACX;AA2BA,SAAS,qBAAA,GAAiD;AACtD,EAAA,IAAI,OAAO,MAAA,KAAW,WAAA,EAAa,OAAO,MAAA;AAC1C,EAAA,IAAI;AACA,IAAA,OAAO,MAAA,CAAO,YAAA;AAAA,EAClB,CAAA,CAAA,MAAQ;AACJ,IAAA,OAAO,MAAA;AAAA,EACX;AACJ;AAiGO,SAAS,gBAAA,CAAiB;AAAA,EAC7B,QAAA;AAAA,EACA,SAAA;AAAA,EACA,OAAA;AAAA,EACA,cAAA,GAAiB,KAAA;AAAA,EACjB,UAAA,GAAa,SAAA;AAAA,EACb;AACJ,CAAA,EAA0B;AACtB,EAAA,IAAI,UAAA,KAAe,QAAA,IAAY,CAAC,cAAA,EAAgB;AAC5C,IAAA,MAAM,IAAI,MAAM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AAA,IAAI,eAAe,UAAA,EAAY;AAC3B,UAAA,OAAA,CAAQ,KAAA,CAAM,CAAA,uCAAA,EAA0C,GAAG,CAAA,EAAA,CAAA,EAAM,IAAI,OAAO,CAAA;AAAA,QAChF;AACA,QAAA;AAAA,MACJ;AAAA,IACJ,CAAA;AAAA,EACJ,GAAG,CAAC,GAAA,EAAK,GAAA,EAAK,WAAA,EAAa,cAAc,CAAC,CAAA;AAM1C,EAAA,MAAM,MAAA,GAASA,cAAQ,MAAM;AACzB,IAAA,OAAO,MAAM,GAAA,CAAI,SAAA,CAAU,GAAG,CAAA;AAAA,EAClC,CAAA,EAAG,CAAC,GAAA,EAAK,GAAG,CAAC,CAAA;AAEb,EAAA,OAAOA,aAAAA;AAAA,IACH;AAAA;AAAA,MAEK;AAAA;AAAA,QAEG,KAAA;AAAA;AAAA,QAEA,GAAA;AAAA;AAAA,QAEA,KAAA;AAAA;AAAA,QAEA;AAAA;AACJ,KAAA;AAAA,IACJ,CAAC,KAAA,EAAO,GAAA,EAAK,KAAA,EAAO,MAAM;AAAA,GAC9B;AACJ","file":"index.cjs","sourcesContent":["// SPDX-License-Identifier: MIT\n// Copyright Scott Dixon\n\n/**\n * @fileoverview React Context provider for persistent state management.\n *\n * This module exports the MnemonicProvider component and useMnemonic hook,\n * which together provide a namespace-scoped storage API to child components.\n * The provider creates an in-memory cache with read-through behavior to localStorage\n * (or a custom storage backend) and implements the React external store contract.\n */\n\nimport { createContext, useContext, useMemo, useEffect, ReactNode } from \"react\";\nimport type {\n Mnemonic,\n MnemonicProviderOptions,\n StorageLike,\n Listener,\n Unsubscribe,\n SchemaMode,\n SchemaRegistry,\n} from \"./types\";\n\n/**\n * React Context for the Mnemonic store.\n *\n * Provides access to the low-level storage API. Consumer code should use\n * `useMnemonicKey` instead of accessing this context directly.\n *\n * @internal\n */\nconst MnemonicContext = createContext<Mnemonic | null>(null);\n\n/**\n * Hook to access the Mnemonic store from context.\n *\n * This is a low-level hook used internally by `useMnemonicKey`. Most applications\n * should use `useMnemonicKey` instead, which provides a higher-level, type-safe API.\n *\n * @returns The Mnemonic store instance\n *\n * @throws {Error} If called outside of a MnemonicProvider\n *\n * @example\n * ```tsx\n * // Internal usage (prefer useMnemonicKey for application code)\n * function MyComponent() {\n * const store = useMnemonic();\n * const raw = store.getRawSnapshot('myKey');\n * // ...\n * }\n * ```\n *\n * @see {@link useMnemonicKey} - Higher-level hook for application code\n * @see {@link MnemonicProvider} - Required provider component\n */\nexport function useMnemonic(): Mnemonic {\n const context = useContext(MnemonicContext);\n if (!context) {\n throw new Error(\"useMnemonic must be used within a MnemonicProvider\");\n }\n return context;\n}\n\n/**\n * Props for the MnemonicProvider component.\n *\n * Extends MnemonicProviderOptions with required children prop.\n *\n * @see {@link MnemonicProviderOptions} - Configuration options\n * @see {@link MnemonicProvider} - Provider component\n */\nexport interface MnemonicProviderProps extends MnemonicProviderOptions {\n /**\n * React children to render within the provider.\n */\n children: ReactNode;\n}\n\n/**\n * Helper function to safely access window.localStorage in browser environments.\n *\n * Returns undefined in non-browser environments (SSR) or when localStorage\n * is unavailable (e.g., in private browsing mode with strict settings).\n *\n * @returns localStorage if available, undefined otherwise\n *\n * @internal\n */\nfunction defaultBrowserStorage(): StorageLike | undefined {\n if (typeof window === \"undefined\") return undefined;\n try {\n return window.localStorage;\n } catch {\n return undefined;\n }\n}\n\n/** Internal store type with reload capability, not exposed to consumers. */\ntype MnemonicInternal = Mnemonic & {\n reloadFromStorage: (changedKeys?: string[]) => void;\n};\n\n/**\n * React Context provider for namespace-isolated persistent state.\n *\n * Creates a scoped storage environment where all keys are automatically prefixed\n * with the namespace to prevent collisions. Implements an in-memory cache with\n * read-through behavior to the underlying storage backend (localStorage by default).\n *\n * This provider must wrap any components that use `useMnemonicKey`. Multiple\n * providers with different namespaces can coexist in the same application.\n *\n * @param props - Provider configuration and children\n * @param props.children - React children to render within the provider\n * @param props.namespace - Unique namespace for isolating storage keys\n * @param props.storage - Optional custom storage backend (defaults to localStorage)\n * @param props.enableDevTools - Enable DevTools debugging interface (defaults to false)\n * @param props.schemaMode - Schema enforcement mode (default: \"default\")\n * @param props.schemaRegistry - Optional schema registry for storing schemas and migrations\n *\n * @example\n * ```tsx\n * // Basic usage with default settings\n * function App() {\n * return (\n * <MnemonicProvider namespace=\"myApp\">\n * <MyComponents />\n * </MnemonicProvider>\n * );\n * }\n * ```\n *\n * @example\n * ```tsx\n * // With custom storage backend\n * function App() {\n * return (\n * <MnemonicProvider\n * namespace=\"myApp\"\n * storage={window.sessionStorage}\n * >\n * <MyComponents />\n * </MnemonicProvider>\n * );\n * }\n * ```\n *\n * @example\n * ```tsx\n * // With DevTools enabled (development only)\n * function App() {\n * return (\n * <MnemonicProvider\n * namespace=\"myApp\"\n * enableDevTools={process.env.NODE_ENV === 'development'}\n * >\n * <MyComponents />\n * </MnemonicProvider>\n * );\n * }\n *\n * // Then in browser console:\n * window.__REACT_MNEMONIC_DEVTOOLS__.myApp.dump()\n * window.__REACT_MNEMONIC_DEVTOOLS__.myApp.get('user')\n * window.__REACT_MNEMONIC_DEVTOOLS__.myApp.set('theme', 'dark')\n * ```\n *\n * @example\n * ```tsx\n * // Multiple providers with different namespaces\n * function App() {\n * return (\n * <MnemonicProvider namespace=\"user-prefs\">\n * <UserSettings />\n * <MnemonicProvider namespace=\"app-state\">\n * <Dashboard />\n * </MnemonicProvider>\n * </MnemonicProvider>\n * );\n * }\n * ```\n *\n * @remarks\n * - Creates a stable store instance that only recreates when namespace, storage, or enableDevTools change\n * - All storage operations are cached in memory for fast reads\n * - Storage failures are handled gracefully (logged but not thrown)\n * - In SSR environments, the provider works but no storage persistence occurs\n * - The store implements React's useSyncExternalStore contract for efficient updates\n *\n * @see {@link useMnemonicKey} - Hook for using persistent state\n * @see {@link MnemonicProviderOptions} - Configuration options\n */\nexport function MnemonicProvider({\n children,\n namespace,\n storage,\n enableDevTools = false,\n schemaMode = \"default\",\n schemaRegistry,\n}: MnemonicProviderProps) {\n if (schemaMode === \"strict\" && !schemaRegistry) {\n throw new Error(\"MnemonicProvider strict mode requires schemaRegistry\");\n }\n if (schemaMode === \"autoschema\" && typeof schemaRegistry?.registerSchema !== \"function\") {\n throw new Error(\"MnemonicProvider autoschema mode requires schemaRegistry.registerSchema\");\n }\n\n const store = useMemo<MnemonicInternal>(() => {\n const prefix = `${namespace}.`;\n const st = storage ?? defaultBrowserStorage();\n\n /**\n * In-memory cache of raw string values.\n * Maps unprefixed keys to their raw string values (or null if not present).\n * Provides fast reads without hitting storage on every access.\n */\n const cache = new Map<string, string | null>();\n\n /**\n * Per-key listener registry.\n * Maps unprefixed keys to sets of listener functions.\n * Used to notify React components when values change.\n */\n const listeners = new Map<string, Set<Listener>>();\n\n /** Whether a QuotaExceededError has already been logged since the last successful write. */\n let quotaErrorLogged = false;\n\n /** Whether a non-quota DOMException has already been logged since the last successful storage access. */\n let accessErrorLogged = false;\n\n /**\n * Converts an unprefixed key to a fully-qualified storage key.\n *\n * @param key - Unprefixed key\n * @returns Prefixed key with namespace\n */\n const fullKey = (key: string) => prefix + key;\n\n /**\n * Notifies all listeners subscribed to a specific key.\n * Called after mutations (set/remove) to trigger React re-renders.\n *\n * @param key - Unprefixed key that changed\n */\n const emit = (key: string) => {\n const set = listeners.get(key);\n if (!set) return;\n for (const fn of set) fn();\n };\n\n /**\n * Logs a storage-access DOMException once, squelching repeats until\n * a successful storage operation resets the flag. Ignores\n * QuotaExceededError (handled separately in writeRaw) and silently\n * swallows all non-DOMException errors.\n */\n const logAccessError = (err: unknown): void => {\n if (!accessErrorLogged && err instanceof DOMException && err.name !== \"QuotaExceededError\") {\n console.error(\n `[Mnemonic] Storage access error (${err.name}): ${err.message}. ` +\n \"Data is cached in memory but may not persist.\",\n );\n accessErrorLogged = true;\n }\n };\n\n /**\n * Read-through cache accessor.\n * Returns cached value if available, otherwise reads from storage and caches.\n *\n * @param key - Unprefixed key to read\n * @returns Raw string value, or null if not present\n */\n const readThrough = (key: string): string | null => {\n if (cache.has(key)) return cache.get(key) ?? null;\n if (!st) {\n cache.set(key, null);\n return null;\n }\n try {\n const raw = st.getItem(fullKey(key));\n cache.set(key, raw);\n accessErrorLogged = false;\n return raw;\n } catch (err) {\n logAccessError(err);\n cache.set(key, null);\n return null;\n }\n };\n\n /**\n * Writes a raw string value to both cache and storage.\n * Notifies listeners after the write completes.\n *\n * @param key - Unprefixed key to write\n * @param raw - Raw string value to store\n */\n const writeRaw = (key: string, raw: string) => {\n cache.set(key, raw);\n if (st) {\n try {\n st.setItem(fullKey(key), raw);\n quotaErrorLogged = false;\n accessErrorLogged = false;\n } catch (err) {\n if (!quotaErrorLogged && err instanceof DOMException && err.name === \"QuotaExceededError\") {\n console.error(\n `[Mnemonic] Storage quota exceeded writing key \"${key}\". ` +\n \"Data is cached in memory but will not persist.\",\n );\n quotaErrorLogged = true;\n }\n logAccessError(err);\n }\n }\n emit(key);\n };\n\n /**\n * Removes a key from both cache and storage.\n * Notifies listeners after the removal completes.\n *\n * @param key - Unprefixed key to remove\n */\n const removeRaw = (key: string) => {\n cache.set(key, null);\n if (st) {\n try {\n st.removeItem(fullKey(key));\n accessErrorLogged = false;\n } catch (err) {\n logAccessError(err);\n }\n }\n emit(key);\n };\n\n /**\n * Subscribes a listener to changes for a specific key.\n * Implements the React external store subscription contract.\n *\n * @param key - Unprefixed key to subscribe to\n * @param listener - Callback invoked when the value changes\n * @returns Unsubscribe function\n */\n const subscribeRaw = (key: string, listener: Listener): Unsubscribe => {\n let set = listeners.get(key);\n if (!set) {\n set = new Set();\n listeners.set(key, set);\n }\n set.add(listener);\n\n // Ensure cache is primed so snapshots are stable.\n readThrough(key);\n\n return () => {\n const s = listeners.get(key);\n if (!s) return;\n s.delete(listener);\n if (s.size === 0) listeners.delete(key);\n };\n };\n\n /**\n * Gets the current snapshot of a key's raw value.\n * Implements the React external store snapshot contract.\n *\n * @param key - Unprefixed key to read\n * @returns Raw string value, or null if not present\n */\n const getRawSnapshot = (key: string) => readThrough(key);\n\n /**\n * Enumerates all keys in this namespace.\n * Iterates through storage and filters keys by namespace prefix.\n *\n * @returns Array of unprefixed key names\n */\n const keys = () => {\n if (!st || typeof st.length !== \"number\" || typeof st.key !== \"function\") return [];\n const out: string[] = [];\n try {\n for (let i = 0; i < st.length; i++) {\n const k = st.key(i);\n if (!k) continue;\n if (k.startsWith(prefix)) out.push(k.slice(prefix.length));\n }\n accessErrorLogged = false;\n } catch (err) {\n logAccessError(err);\n }\n return out;\n };\n\n /**\n * Dumps all key-value pairs in this namespace.\n * Useful for debugging and DevTools integration.\n *\n * @returns Object mapping unprefixed keys to raw string values\n */\n const dump = () => {\n const out: Record<string, string> = {};\n for (const k of keys()) {\n const raw = readThrough(k);\n if (raw != null) out[k] = raw;\n }\n return out;\n };\n\n /**\n * Re-reads keys from the underlying storage, updating the cache and\n * emitting change notifications for any keys whose values differ.\n *\n * @param changedKeys - Optional array of fully-qualified storage keys\n * that changed. When undefined, performs a blanket reload of all\n * actively subscribed keys. When an empty array, does nothing.\n *\n * Called by the onExternalChange subscription when the storage adapter\n * signals that data has changed externally (e.g., from another tab).\n */\n const reloadFromStorage = (changedKeys?: string[]) => {\n if (!st) return;\n\n // Empty array → explicit no-op\n if (changedKeys !== undefined && changedKeys.length === 0) return;\n\n if (changedKeys !== undefined) {\n // Granular path: only reload the specified keys\n for (const fk of changedKeys) {\n // Skip keys outside our namespace\n if (!fk.startsWith(prefix)) continue;\n const key = fk.slice(prefix.length);\n\n const listenerSet = listeners.get(key);\n if (listenerSet && listenerSet.size > 0) {\n // Subscribed: re-read and diff\n let fresh: string | null;\n try {\n fresh = st.getItem(fk);\n accessErrorLogged = false;\n } catch (err) {\n logAccessError(err);\n fresh = null;\n }\n const cached = cache.get(key) ?? null;\n if (fresh !== cached) {\n cache.set(key, fresh);\n emit(key);\n }\n } else if (cache.has(key)) {\n // Cached but not subscribed: evict so next read is fresh\n cache.delete(key);\n }\n }\n return;\n }\n\n // Blanket path: re-read all subscribed keys\n for (const [key, listenerSet] of listeners) {\n if (listenerSet.size === 0) continue;\n let fresh: string | null;\n try {\n fresh = st.getItem(fullKey(key));\n accessErrorLogged = false;\n } catch (err) {\n logAccessError(err);\n fresh = null;\n }\n const cached = cache.get(key) ?? null;\n if (fresh !== cached) {\n cache.set(key, fresh);\n emit(key);\n }\n }\n\n // Evict unsubscribed cache entries so next readThrough re-reads\n for (const key of cache.keys()) {\n if (!listeners.has(key) || listeners.get(key)!.size === 0) {\n cache.delete(key);\n }\n }\n };\n\n /**\n * The Mnemonic store API object.\n * Implements the contract expected by useSyncExternalStore.\n */\n const store = {\n prefix,\n subscribeRaw,\n getRawSnapshot,\n setRaw: writeRaw,\n removeRaw,\n keys,\n dump,\n reloadFromStorage,\n schemaMode: schemaMode as SchemaMode,\n ...(schemaRegistry ? { schemaRegistry: schemaRegistry as SchemaRegistry } : {}),\n };\n\n /**\n * DevTools integration.\n * Exposes a debugging interface on the window object when enabled.\n */\n if (enableDevTools && typeof window !== \"undefined\") {\n (window as any).__REACT_MNEMONIC_DEVTOOLS__ = (window as any).__REACT_MNEMONIC_DEVTOOLS__ || {};\n (window as any).__REACT_MNEMONIC_DEVTOOLS__[namespace] = {\n /** Access the underlying store instance */\n getStore: () => store,\n\n /** Dump all key-value pairs and display as a console table */\n dump: () => {\n const data = dump();\n console.table(\n Object.entries(data).map(([key, value]) => ({\n key,\n value,\n decoded: (() => {\n try {\n return JSON.parse(value);\n } catch {\n return value;\n }\n })(),\n })),\n );\n return data;\n },\n\n /** Get a decoded value by key */\n get: (key: string) => {\n const raw = readThrough(key);\n if (raw == null) return undefined;\n try {\n return JSON.parse(raw);\n } catch {\n return raw;\n }\n },\n\n /** Set a value by key (automatically JSON-encoded) */\n set: (key: string, value: any) => {\n writeRaw(key, JSON.stringify(value));\n },\n\n /** Remove a key from storage */\n remove: (key: string) => removeRaw(key),\n\n /** Clear all keys in this namespace */\n clear: () => {\n for (const k of keys()) {\n removeRaw(k);\n }\n },\n\n /** List all keys in this namespace */\n keys,\n };\n console.info(\n `[Mnemonic DevTools] Namespace \"${namespace}\" available at window.__REACT_MNEMONIC_DEVTOOLS__.${namespace}`,\n );\n }\n\n return store;\n }, [namespace, storage, enableDevTools, schemaMode, schemaRegistry]);\n\n // Subscribe to external storage changes (e.g., cross-tab BroadcastChannel)\n useEffect(() => {\n if (!storage?.onExternalChange) return;\n return storage.onExternalChange((changedKeys) => store.reloadFromStorage(changedKeys));\n }, [storage, store]);\n\n return <MnemonicContext.Provider value={store}>{children}</MnemonicContext.Provider>;\n}\n","// SPDX-License-Identifier: MIT\n// Copyright Scott Dixon\n\n/**\n * @fileoverview Codec implementations for encoding and decoding values to/from storage.\n *\n * This module provides the built-in JSON codec and a factory for creating custom\n * codecs. Codecs handle the bidirectional transformation between typed JavaScript\n * values and their string representations for storage.\n *\n * Codecs are a low-level mechanism for keys that opt out of the JSON Schema\n * validation system. When a schema is registered for a key, the schema's\n * JSON Schema is used for validation and the payload is stored as a JSON value\n * directly (no codec encoding needed).\n */\n\nimport type { Codec } from \"./types\";\n\n/**\n * Custom error class for codec encoding and decoding failures.\n *\n * Thrown when a codec cannot successfully encode a value to a string or\n * decode a string back to its typed representation. This allows callers\n * to distinguish codec errors from other types of errors.\n *\n * @example\n * ```typescript\n * try {\n * const value = JSONCodec.decode('not-valid-json');\n * } catch (error) {\n * if (error instanceof CodecError) {\n * console.error('Failed to decode:', error.message);\n * }\n * }\n * ```\n */\nexport class CodecError extends Error {\n /**\n * The underlying error that caused the codec failure, if any.\n *\n * Useful for debugging when wrapping errors from JSON.parse or\n * other parsing operations.\n */\n readonly cause?: unknown;\n\n /**\n * Creates a new CodecError.\n *\n * @param message - Human-readable error description\n * @param cause - Optional underlying error that caused this failure\n */\n constructor(message: string, cause?: unknown) {\n super(message);\n this.name = \"CodecError\";\n this.cause = cause;\n\n // Required for proper instanceof behavior when targeting ES5\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * JSON codec for encoding and decoding JSON-serializable values.\n *\n * This is the default codec used by `useMnemonicKey` when no codec is specified.\n * It uses `JSON.stringify` for encoding and `JSON.parse` for decoding, making it\n * suitable for objects, arrays, and primitive values.\n *\n * @remarks\n * - Supports any JSON-serializable type: objects, arrays, strings, numbers, booleans, null\n * - Does not preserve JavaScript-specific types like Date, Map, Set, or undefined\n * - Throws standard JSON parsing errors for malformed JSON strings\n *\n * @example\n * ```typescript\n * // Used automatically as the default\n * const { value, set } = useMnemonicKey('userProfile', {\n * defaultValue: { name: 'Guest', preferences: { theme: 'dark' } }\n * // codec: JSONCodec is implicit\n * });\n *\n * // Can be specified explicitly\n * const { value, set } = useMnemonicKey('settings', {\n * defaultValue: { notifications: true },\n * codec: JSONCodec\n * });\n * ```\n *\n * @see {@link createCodec} - For custom encoding schemes\n */\nexport const JSONCodec: Codec<any> = {\n encode: (value) => JSON.stringify(value),\n decode: (encoded) => JSON.parse(encoded),\n};\n\n/**\n * Factory function for creating custom codecs.\n *\n * Creates a `Codec<T>` from separate encode and decode functions. This is\n * useful for implementing custom serialization strategies for types that\n * aren't supported by JSONCodec. Using a custom codec on a key opts out\n * of JSON Schema validation for that key.\n *\n * @template T - The TypeScript type of values to encode/decode\n *\n * @param encode - Function that converts a typed value to a string\n * @param decode - Function that converts a string back to a typed value\n * @returns A `Codec<T>` object compatible with useMnemonicKey\n *\n * @example\n * ```typescript\n * // Codec for Date objects\n * const DateCodec = createCodec<Date>(\n * (date) => date.toISOString(),\n * (str) => new Date(str)\n * );\n *\n * const { value, set } = useMnemonicKey('lastLogin', {\n * defaultValue: new Date(),\n * codec: DateCodec\n * });\n * ```\n *\n * @example\n * ```typescript\n * // Codec for Set<string>\n * const StringSetCodec = createCodec<Set<string>>(\n * (set) => JSON.stringify(Array.from(set)),\n * (str) => new Set(JSON.parse(str))\n * );\n *\n * const { value, set } = useMnemonicKey('tags', {\n * defaultValue: new Set<string>(),\n * codec: StringSetCodec\n * });\n * ```\n *\n * @see {@link Codec} - The codec interface\n * @see {@link CodecError} - Error to throw when encoding/decoding fails\n * @see {@link JSONCodec} - Built-in codec for JSON values\n */\nexport function createCodec<T>(encode: (value: T) => string, decode: (encoded: string) => T): Codec<T> {\n return { encode, decode };\n}\n","// SPDX-License-Identifier: MIT\n// Copyright Scott Dixon\n\n/**\n * @fileoverview Schema versioning primitives for Mnemonic.\n *\n * This module defines the envelope format used to wrap every persisted value\n * and the error class thrown when schema-related operations fail.\n */\n\n/**\n * Error thrown for schema registry, versioning, and migration failures.\n *\n * Each instance carries a machine-readable {@link code} that categorises\n * the failure. When a `defaultValue` factory is provided to\n * `useMnemonicKey`, the `SchemaError` is passed as the `error` argument\n * so the factory can inspect the failure reason.\n *\n * Error codes:\n *\n * | Code | Meaning |\n * | ------------------------------- | --------------------------------------------------------------- |\n * | `INVALID_ENVELOPE` | The raw stored value is not a valid `MnemonicEnvelope`. |\n * | `SCHEMA_NOT_FOUND` | No schema registered for the stored key + version. |\n * | `WRITE_SCHEMA_REQUIRED` | Strict mode requires a schema to write, but none was found. |\n * | `MIGRATION_PATH_NOT_FOUND` | No contiguous migration path between the stored and latest version. |\n * | `MIGRATION_FAILED` | A migration step threw during execution. |\n * | `SCHEMA_REGISTRATION_CONFLICT` | `registerSchema` was called with a conflicting definition. |\n * | `TYPE_MISMATCH` | The decoded value failed JSON Schema validation. |\n * | `MODE_CONFIGURATION_INVALID` | The schema mode requires a capability the registry doesn't provide. |\n *\n * @example\n * ```typescript\n * defaultValue: (error) => {\n * if (error instanceof SchemaError) {\n * console.warn(`Schema issue [${error.code}]:`, error.message);\n * }\n * return { name: \"Guest\" };\n * }\n * ```\n *\n * @see {@link SchemaMode} - How the provider uses schemas\n * @see {@link SchemaRegistry} - Where schemas and migrations are registered\n */\nexport class SchemaError extends Error {\n /**\n * Machine-readable code identifying the category of schema failure.\n */\n readonly code:\n | \"INVALID_ENVELOPE\"\n | \"SCHEMA_NOT_FOUND\"\n | \"WRITE_SCHEMA_REQUIRED\"\n | \"MIGRATION_PATH_NOT_FOUND\"\n | \"MIGRATION_FAILED\"\n | \"SCHEMA_REGISTRATION_CONFLICT\"\n | \"TYPE_MISMATCH\"\n | \"MODE_CONFIGURATION_INVALID\";\n\n /**\n * The underlying error that caused this failure, if any.\n */\n readonly cause?: unknown;\n\n /**\n * Creates a new SchemaError.\n *\n * @param code - Machine-readable failure category\n * @param message - Human-readable error description\n * @param cause - Optional underlying error\n */\n constructor(code: SchemaError[\"code\"], message: string, cause?: unknown) {\n super(message);\n this.name = \"SchemaError\";\n this.code = code;\n this.cause = cause;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * The JSON envelope that wraps every value persisted by the library.\n *\n * All values are stored as `JSON.stringify({ version, payload })`. The\n * `version` field tells the read path which schema to use for validating\n * the `payload`.\n *\n * - When no schema is active (codec-only mode), `version` is `0` and\n * `payload` is a codec-encoded string.\n * - When a schema is active, `version` corresponds to the schema version\n * and `payload` is the JSON value directly (not string-encoded).\n *\n * @internal\n */\nexport type MnemonicEnvelope = {\n /**\n * Schema version number.\n *\n * Non-negative integer. Any version (including `0`) may have a\n * registered {@link KeySchema}.\n */\n version: number;\n\n /**\n * The stored value.\n *\n * For schema-managed keys, this is a JSON value (object, array,\n * string, number, boolean, or null). For codec-managed keys, this\n * is a string produced by `Codec.encode`.\n */\n payload: unknown;\n};\n","// SPDX-License-Identifier: MIT\n// Copyright Scott Dixon\n\n/**\n * @fileoverview JSON Schema subset validator for Mnemonic.\n *\n * This module implements a minimal JSON Schema validator sufficient for\n * validating localStorage state. Only a subset of JSON Schema keywords\n * are supported; see {@link JsonSchema} for the full list.\n *\n * JSON Schema documents are plain JSON objects (inherently serializable),\n * making them suitable for storage alongside the data they describe.\n */\n\n/**\n * Supported JSON Schema type keywords.\n *\n * `\"integer\"` is a JSON Schema keyword meaning \"a number that is a whole number.\"\n */\nexport type JsonSchemaType = \"string\" | \"number\" | \"integer\" | \"boolean\" | \"null\" | \"object\" | \"array\";\n\n/**\n * A subset of JSON Schema sufficient for localStorage state management.\n *\n * Supported keywords:\n * type, enum, const,\n * minimum, maximum, exclusiveMinimum, exclusiveMaximum,\n * minLength, maxLength,\n * properties, required, additionalProperties,\n * items, minItems, maxItems\n *\n * Deliberately omitted: $ref, $id, $schema, $defs, allOf, anyOf,\n * oneOf, not, pattern, format, patternProperties, if/then/else,\n * dependencies, uniqueItems, multipleOf, propertyNames.\n *\n * An empty schema `{}` accepts any value.\n */\nexport interface JsonSchema {\n /** The expected JSON type(s). An array form like `[\"string\", \"null\"]` accepts either type. */\n type?: JsonSchemaType | JsonSchemaType[];\n\n /** The value must be deeply equal to one of these entries. */\n enum?: readonly unknown[];\n\n /** The value must be deeply equal to this exact value. */\n const?: unknown;\n\n /** Inclusive lower bound for numbers. */\n minimum?: number;\n\n /** Inclusive upper bound for numbers. */\n maximum?: number;\n\n /** Exclusive lower bound for numbers. */\n exclusiveMinimum?: number;\n\n /** Exclusive upper bound for numbers. */\n exclusiveMaximum?: number;\n\n /** Minimum string length (inclusive). */\n minLength?: number;\n\n /** Maximum string length (inclusive). */\n maxLength?: number;\n\n /** Property name to sub-schema mapping for objects. */\n properties?: Record<string, JsonSchema>;\n\n /** Properties that must be present on the object. */\n required?: readonly string[];\n\n /**\n * Controls extra properties not listed in `properties`.\n * `false` disallows them. A schema validates their values.\n * `true` (or omitted) allows anything.\n */\n additionalProperties?: boolean | JsonSchema;\n\n /** Schema applied to every element of an array. */\n items?: JsonSchema;\n\n /** Minimum array length (inclusive). */\n minItems?: number;\n\n /** Maximum array length (inclusive). */\n maxItems?: number;\n}\n\n/**\n * A single validation error produced by {@link validateJsonSchema}.\n */\nexport type JsonSchemaValidationError = {\n /** JSON Pointer path to the failing value (e.g., \"/foo/bar/0\"). Empty string for root. */\n path: string;\n /** Human-readable error description. */\n message: string;\n /** The JSON Schema keyword that failed. */\n keyword: string;\n};\n\n/**\n * Tests whether a value matches a single JSON Schema type keyword.\n */\nfunction matchesType(value: unknown, type: JsonSchemaType): boolean {\n switch (type) {\n case \"string\":\n return typeof value === \"string\";\n case \"number\":\n return typeof value === \"number\" && Number.isFinite(value);\n case \"integer\":\n return typeof value === \"number\" && Number.isInteger(value);\n case \"boolean\":\n return typeof value === \"boolean\";\n case \"null\":\n return value === null;\n case \"object\":\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n case \"array\":\n return Array.isArray(value);\n default:\n return false;\n }\n}\n\n/**\n * Structural deep equality for JSON values (null, booleans, numbers, strings,\n * arrays, and plain objects). Used by `enum` and `const` keywords.\n */\nexport function jsonDeepEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (a === null || b === null) return false;\n if (typeof a !== typeof b) return false;\n\n if (Array.isArray(a)) {\n if (!Array.isArray(b)) return false;\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (!jsonDeepEqual(a[i], b[i])) return false;\n }\n return true;\n }\n\n if (typeof a === \"object\") {\n if (Array.isArray(b)) return false;\n const aObj = a as Record<string, unknown>;\n const bObj = b as Record<string, unknown>;\n const aKeys = Object.keys(aObj);\n const bKeys = Object.keys(bObj);\n if (aKeys.length !== bKeys.length) return false;\n for (const key of aKeys) {\n if (!Object.prototype.hasOwnProperty.call(bObj, key)) return false;\n if (!jsonDeepEqual(aObj[key], bObj[key])) return false;\n }\n return true;\n }\n\n return false;\n}\n\n/**\n * A pre-compiled validation function generated by {@link compileSchema}.\n *\n * Accepts a value and an optional JSON Pointer path for error reporting.\n * Returns an array of validation errors (empty = valid).\n */\nexport type CompiledValidator = (value: unknown, path?: string) => JsonSchemaValidationError[];\n\n/** Module-level cache: schema object identity → compiled validator. */\nconst compiledCache = new WeakMap<JsonSchema, CompiledValidator>();\n\n/**\n * Pre-compiles a {@link JsonSchema} into a reusable validation function.\n *\n * Inspects the schema once and builds a specialized closure that\n * eliminates runtime branching for unused keywords, pre-converts\n * `required` arrays to `Set`s, recursively pre-compiles nested property\n * and item schemas, and pre-builds primitive `Set`s for O(1) enum\n * lookups when possible.\n *\n * Results are cached by schema object identity in a `WeakMap`, so\n * calling `compileSchema` with the same schema reference is free\n * after the first call.\n *\n * @param schema - The JSON Schema to compile\n * @returns A compiled validation function\n */\nexport function compileSchema(schema: JsonSchema): CompiledValidator {\n const cached = compiledCache.get(schema);\n if (cached) return cached;\n\n const compiled = buildValidator(schema);\n compiledCache.set(schema, compiled);\n return compiled;\n}\n\n/** Determines whether a value is a JSON primitive (not object/array). */\nfunction isJsonPrimitive(value: unknown): boolean {\n return value === null || typeof value !== \"object\";\n}\n\n/**\n * Internal: builds a compiled validator closure for a single schema.\n * All keyword-specific logic is resolved at build time so the returned\n * function contains only the checks that are relevant.\n */\nfunction buildValidator(schema: JsonSchema): CompiledValidator {\n // --- Pre-compute: type ---\n const resolvedTypes: readonly JsonSchemaType[] | null =\n schema.type !== undefined ? (Array.isArray(schema.type) ? schema.type : [schema.type]) : null;\n const typeLabel = resolvedTypes !== null ? JSON.stringify(schema.type) : \"\";\n\n // --- Pre-compute: enum ---\n const enumMembers = schema.enum;\n let enumPrimitiveSet: Set<unknown> | null = null;\n let enumComplexMembers: readonly unknown[] | null = null;\n if (enumMembers !== undefined) {\n const primitives: unknown[] = [];\n const complex: unknown[] = [];\n for (const member of enumMembers) {\n if (isJsonPrimitive(member)) {\n primitives.push(member);\n } else {\n complex.push(member);\n }\n }\n if (primitives.length > 0) enumPrimitiveSet = new Set(primitives);\n if (complex.length > 0) enumComplexMembers = complex;\n }\n\n // --- Pre-compute: const ---\n const hasConst = \"const\" in schema;\n const constValue = schema.const;\n\n // --- Pre-compute: number constraints ---\n const hasMinimum = schema.minimum !== undefined;\n const minimum = schema.minimum!;\n const hasMaximum = schema.maximum !== undefined;\n const maximum = schema.maximum!;\n const hasExMin = schema.exclusiveMinimum !== undefined;\n const exMin = schema.exclusiveMinimum!;\n const hasExMax = schema.exclusiveMaximum !== undefined;\n const exMax = schema.exclusiveMaximum!;\n const hasNumberConstraints = hasMinimum || hasMaximum || hasExMin || hasExMax;\n\n // --- Pre-compute: string constraints ---\n const hasMinLength = schema.minLength !== undefined;\n const minLen = schema.minLength!;\n const hasMaxLength = schema.maxLength !== undefined;\n const maxLen = schema.maxLength!;\n const hasStringConstraints = hasMinLength || hasMaxLength;\n\n // --- Pre-compute: object constraints ---\n const requiredKeys = schema.required;\n const hasRequired = requiredKeys !== undefined && requiredKeys.length > 0;\n const hasProperties = schema.properties !== undefined;\n const propertyValidators: [string, CompiledValidator][] | null = hasProperties\n ? Object.entries(schema.properties!).map(\n ([name, propSchema]) => [name, compileSchema(propSchema)] as [string, CompiledValidator],\n )\n : null;\n const checkAdditional = schema.additionalProperties !== undefined && schema.additionalProperties !== true;\n const additionalIsFalse = schema.additionalProperties === false;\n const additionalValidator: CompiledValidator | null =\n checkAdditional && !additionalIsFalse ? compileSchema(schema.additionalProperties as JsonSchema) : null;\n const definedPropKeys: Set<string> | null = checkAdditional\n ? new Set(schema.properties ? Object.keys(schema.properties) : [])\n : null;\n const hasObjectConstraints = hasRequired || hasProperties || checkAdditional;\n\n // --- Pre-compute: array constraints ---\n const hasMinItems = schema.minItems !== undefined;\n const minItems = schema.minItems!;\n const hasMaxItems = schema.maxItems !== undefined;\n const maxItems = schema.maxItems!;\n const itemsValidator: CompiledValidator | null = schema.items !== undefined ? compileSchema(schema.items) : null;\n const hasArrayConstraints = hasMinItems || hasMaxItems || itemsValidator !== null;\n\n // --- Empty schema fast path ---\n if (\n resolvedTypes === null &&\n enumMembers === undefined &&\n !hasConst &&\n !hasNumberConstraints &&\n !hasStringConstraints &&\n !hasObjectConstraints &&\n !hasArrayConstraints\n ) {\n return (_value: unknown, _path?: string) => [];\n }\n\n // --- Compiled validator ---\n return (value: unknown, path: string = \"\"): JsonSchemaValidationError[] => {\n const errors: JsonSchemaValidationError[] = [];\n\n // --- type ---\n if (resolvedTypes !== null) {\n const matched = resolvedTypes.some((t) => matchesType(value, t));\n if (!matched) {\n errors.push({\n path,\n message: `Expected type ${typeLabel}, got ${jsonTypeLabel(value)}`,\n keyword: \"type\",\n });\n return errors; // short-circuit\n }\n }\n\n // --- enum ---\n if (enumMembers !== undefined) {\n let matched = false;\n if (enumPrimitiveSet !== null && isJsonPrimitive(value)) {\n matched = enumPrimitiveSet.has(value);\n }\n if (!matched && enumComplexMembers !== null) {\n matched = enumComplexMembers.some((entry) => jsonDeepEqual(value, entry));\n }\n if (!matched) {\n errors.push({\n path,\n message: `Value does not match any enum member`,\n keyword: \"enum\",\n });\n }\n }\n\n // --- const ---\n if (hasConst) {\n if (!jsonDeepEqual(value, constValue)) {\n errors.push({\n path,\n message: `Value does not match const`,\n keyword: \"const\",\n });\n }\n }\n\n // --- number constraints ---\n if (hasNumberConstraints && typeof value === \"number\") {\n if (hasMinimum && value < minimum) {\n errors.push({\n path,\n message: `Value ${value} is less than minimum ${minimum}`,\n keyword: \"minimum\",\n });\n }\n if (hasMaximum && value > maximum) {\n errors.push({\n path,\n message: `Value ${value} is greater than maximum ${maximum}`,\n keyword: \"maximum\",\n });\n }\n if (hasExMin && value <= exMin) {\n errors.push({\n path,\n message: `Value ${value} is not greater than exclusiveMinimum ${exMin}`,\n keyword: \"exclusiveMinimum\",\n });\n }\n if (hasExMax && value >= exMax) {\n errors.push({\n path,\n message: `Value ${value} is not less than exclusiveMaximum ${exMax}`,\n keyword: \"exclusiveMaximum\",\n });\n }\n }\n\n // --- string constraints ---\n if (hasStringConstraints && typeof value === \"string\") {\n if (hasMinLength && value.length < minLen) {\n errors.push({\n path,\n message: `String length ${value.length} is less than minLength ${minLen}`,\n keyword: \"minLength\",\n });\n }\n if (hasMaxLength && value.length > maxLen) {\n errors.push({\n path,\n message: `String length ${value.length} is greater than maxLength ${maxLen}`,\n keyword: \"maxLength\",\n });\n }\n }\n\n // --- object constraints ---\n if (hasObjectConstraints && typeof value === \"object\" && value !== null && !Array.isArray(value)) {\n const obj = value as Record<string, unknown>;\n\n if (hasRequired) {\n for (const reqKey of requiredKeys!) {\n if (!Object.prototype.hasOwnProperty.call(obj, reqKey)) {\n errors.push({\n path,\n message: `Missing required property \"${reqKey}\"`,\n keyword: \"required\",\n });\n }\n }\n }\n\n if (propertyValidators !== null) {\n for (const [propName, propValidator] of propertyValidators) {\n if (Object.prototype.hasOwnProperty.call(obj, propName)) {\n const propErrors = propValidator(obj[propName], `${path}/${propName}`);\n errors.push(...propErrors);\n }\n }\n }\n\n if (checkAdditional) {\n for (const objKey of Object.keys(obj)) {\n if (!definedPropKeys!.has(objKey)) {\n if (additionalIsFalse) {\n errors.push({\n path,\n message: `Additional property \"${objKey}\" is not allowed`,\n keyword: \"additionalProperties\",\n });\n } else {\n const propErrors = additionalValidator!(obj[objKey], `${path}/${objKey}`);\n errors.push(...propErrors);\n }\n }\n }\n }\n }\n\n // --- array constraints ---\n if (hasArrayConstraints && Array.isArray(value)) {\n if (hasMinItems && value.length < minItems) {\n errors.push({\n path,\n message: `Array length ${value.length} is less than minItems ${minItems}`,\n keyword: \"minItems\",\n });\n }\n if (hasMaxItems && value.length > maxItems) {\n errors.push({\n path,\n message: `Array length ${value.length} is greater than maxItems ${maxItems}`,\n keyword: \"maxItems\",\n });\n }\n if (itemsValidator !== null) {\n for (let i = 0; i < value.length; i++) {\n const itemErrors = itemsValidator(value[i], `${path}/${i}`);\n errors.push(...itemErrors);\n }\n }\n }\n\n return errors;\n };\n}\n\n/**\n * Validates a value against a {@link JsonSchema}.\n *\n * Returns an empty array when the value is valid.\n * Returns one or more {@link JsonSchemaValidationError} entries on failure.\n * Short-circuits on type mismatch (does not report downstream keyword errors).\n *\n * @param value - The value to validate\n * @param schema - The JSON Schema to validate against\n * @param path - Internal: JSON Pointer path for error reporting (default: `\"\"`)\n * @returns Array of validation errors (empty = valid)\n */\nexport function validateJsonSchema(value: unknown, schema: JsonSchema, path: string = \"\"): JsonSchemaValidationError[] {\n const compiled = compileSchema(schema);\n return compiled(value, path);\n}\n\n/**\n * Returns a human-readable label for the JSON type of a value.\n */\nfunction jsonTypeLabel(value: unknown): string {\n if (value === null) return \"null\";\n if (Array.isArray(value)) return \"array\";\n return typeof value;\n}\n\n/**\n * Infers a minimal {@link JsonSchema} from a sample value.\n *\n * Used by autoschema mode to register a schema from the first\n * successfully decoded value. The inferred schema only constrains\n * the top-level type.\n *\n * @param sample - A decoded value to infer a schema from\n * @returns A minimal JsonSchema that accepts values of the same top-level type\n */\nexport function inferJsonSchema(sample: unknown): JsonSchema {\n if (sample === null) return { type: \"null\" };\n if (Array.isArray(sample)) return { type: \"array\" };\n switch (typeof sample) {\n case \"string\":\n return { type: \"string\" };\n case \"number\":\n return Number.isInteger(sample) ? { type: \"number\" } : { type: \"number\" };\n case \"boolean\":\n return { type: \"boolean\" };\n case \"object\":\n return { type: \"object\" };\n default:\n return {};\n }\n}\n","// SPDX-License-Identifier: MIT\n// Copyright Scott Dixon\n\n/**\n * @fileoverview React hook for type-safe, persistent state management.\n *\n * This module exports the `useMnemonicKey` hook, which provides a React-friendly\n * API for reading and writing persistent state with automatic synchronization,\n * encoding/decoding, and JSON Schema validation.\n */\n\nimport { useSyncExternalStore, useMemo, useEffect, useRef, useCallback } from \"react\";\nimport { useMnemonic } from \"./provider\";\nimport { JSONCodec, CodecError } from \"./codecs\";\nimport { SchemaError, type MnemonicEnvelope } from \"./schema\";\nimport { validateJsonSchema, inferJsonSchema } from \"./json-schema\";\nimport type { JsonSchema } from \"./json-schema\";\nimport type { UseMnemonicKeyOptions, KeySchema, MigrationPath } from \"./types\";\n\n/**\n * React hook for persistent, type-safe state management.\n *\n * Creates a stateful value that persists to storage and synchronizes across\n * components. Works like `useState` but with persistent storage, automatic\n * encoding/decoding, JSON Schema validation, and optional cross-tab synchronization.\n *\n * Must be used within a `MnemonicProvider`. Uses React's `useSyncExternalStore`\n * internally for efficient, tearing-free state synchronization.\n *\n * @template T - The TypeScript type of the stored value\n *\n * @param key - The storage key (unprefixed, namespace is applied automatically)\n * @param options - Configuration options controlling persistence, encoding, and behavior\n *\n * @returns Object with the current value and methods to update it\n *\n * @throws {Error} If used outside of a MnemonicProvider\n */\nexport function useMnemonicKey<T>(key: string, options: UseMnemonicKeyOptions<T>) {\n const api = useMnemonic();\n\n const { defaultValue, onMount, onChange, listenCrossTab, codec: codecOpt, schema } = options;\n const codec = codecOpt ?? JSONCodec;\n const schemaMode = api.schemaMode;\n const schemaRegistry = api.schemaRegistry;\n\n /**\n * Helper to get the fallback/default value.\n * Factory functions receive an optional error describing why the fallback is used.\n */\n const getFallback = useCallback(\n (error?: CodecError | SchemaError) =>\n typeof defaultValue === \"function\"\n ? (defaultValue as (error?: CodecError | SchemaError) => T)(error)\n : defaultValue,\n [defaultValue],\n );\n\n const parseEnvelope = useCallback(\n (rawText: string): { ok: true; envelope: MnemonicEnvelope } | { ok: false; error: SchemaError } => {\n try {\n const parsed = JSON.parse(rawText) as MnemonicEnvelope;\n if (\n typeof parsed !== \"object\" ||\n parsed == null ||\n !Number.isInteger(parsed.version) ||\n parsed.version < 0 ||\n !Object.prototype.hasOwnProperty.call(parsed, \"payload\")\n ) {\n return {\n ok: false,\n error: new SchemaError(\"INVALID_ENVELOPE\", `Invalid envelope for key \"${key}\"`),\n };\n }\n return { ok: true, envelope: parsed };\n } catch (err) {\n return {\n ok: false,\n error: new SchemaError(\"INVALID_ENVELOPE\", `Invalid envelope for key \"${key}\"`, err),\n };\n }\n },\n [key],\n );\n\n /**\n * Decode a string payload using a codec (for codec-managed / no-schema keys).\n */\n const decodeStringPayload = useCallback(\n <V>(payload: unknown, activeCodec: { decode: (encoded: string) => V }) => {\n if (typeof payload !== \"string\") {\n throw new SchemaError(\n \"INVALID_ENVELOPE\",\n `Envelope payload must be a string for codec-managed key \"${key}\"`,\n );\n }\n try {\n return activeCodec.decode(payload);\n } catch (err) {\n throw err instanceof CodecError ? err : new CodecError(`Codec decode failed for key \"${key}\"`, err);\n }\n },\n [key],\n );\n\n /**\n * Validate a value against a JSON Schema, throwing SchemaError on failure.\n */\n const validateAgainstSchema = useCallback(\n (value: unknown, jsonSchema: JsonSchema): void => {\n const errors = validateJsonSchema(value, jsonSchema);\n if (errors.length > 0) {\n const message = errors.map((e) => `${e.path || \"/\"}: ${e.message}`).join(\"; \");\n throw new SchemaError(\"TYPE_MISMATCH\", `Schema validation failed for key \"${key}\": ${message}`);\n }\n },\n [key],\n );\n\n const registryCache = useMemo(() => {\n if (!schemaRegistry || schemaMode === \"autoschema\") return null;\n return {\n latestSchema: undefined as KeySchema | undefined,\n latestSchemaSet: false,\n schemaByVersion: new Map<number, KeySchema | undefined>(),\n migrationPaths: new Map<string, MigrationPath | null>(),\n };\n }, [schemaRegistry, schemaMode, key]);\n\n const getSchemaForVersion = useCallback(\n (version: number): KeySchema | undefined => {\n if (!schemaRegistry) return undefined;\n if (!registryCache) return schemaRegistry.getSchema(key, version);\n if (registryCache.schemaByVersion.has(version)) {\n return registryCache.schemaByVersion.get(version);\n }\n const s = schemaRegistry.getSchema(key, version);\n registryCache.schemaByVersion.set(version, s);\n return s;\n },\n [schemaRegistry, registryCache, key],\n );\n\n const getLatestSchemaForKey = useCallback((): KeySchema | undefined => {\n if (!schemaRegistry) return undefined;\n if (!registryCache) return schemaRegistry.getLatestSchema(key);\n if (registryCache.latestSchemaSet) return registryCache.latestSchema;\n const s = schemaRegistry.getLatestSchema(key);\n registryCache.latestSchema = s;\n registryCache.latestSchemaSet = true;\n return s;\n }, [schemaRegistry, registryCache, key]);\n\n const getMigrationPathForKey = useCallback(\n (fromVersion: number, toVersion: number): MigrationPath | null => {\n if (!schemaRegistry) return null;\n if (!registryCache) return schemaRegistry.getMigrationPath(key, fromVersion, toVersion) ?? null;\n const cacheKey = `${fromVersion}->${toVersion}`;\n if (registryCache.migrationPaths.has(cacheKey)) {\n return registryCache.migrationPaths.get(cacheKey) ?? null;\n }\n const path = schemaRegistry.getMigrationPath(key, fromVersion, toVersion) ?? null;\n registryCache.migrationPaths.set(cacheKey, path);\n return path;\n },\n [schemaRegistry, registryCache, key],\n );\n\n const decodeForRead = useCallback(\n (rawText: string | null): { value: T; rewriteRaw?: string; pendingSchema?: KeySchema } => {\n if (rawText == null) return { value: getFallback() };\n\n const parsed = parseEnvelope(rawText);\n if (!parsed.ok) return { value: getFallback(parsed.error) };\n const envelope = parsed.envelope;\n\n const schemaForVersion = getSchemaForVersion(envelope.version);\n const latestSchema = getLatestSchemaForKey();\n\n // Strict mode always requires schema for the stored version.\n if (schemaMode === \"strict\" && !schemaForVersion) {\n return {\n value: getFallback(\n new SchemaError(\"SCHEMA_NOT_FOUND\", `No schema for key \"${key}\" v${envelope.version}`),\n ),\n };\n }\n\n // Autoschema only infers when no schema exists yet for this key.\n if (schemaMode === \"autoschema\" && !schemaForVersion) {\n if (latestSchema) {\n return {\n value: getFallback(\n new SchemaError(\"SCHEMA_NOT_FOUND\", `No schema for key \"${key}\" v${envelope.version}`),\n ),\n };\n }\n if (!schemaRegistry || typeof schemaRegistry.registerSchema !== \"function\") {\n return {\n value: getFallback(\n new SchemaError(\n \"MODE_CONFIGURATION_INVALID\",\n `Autoschema mode requires schema registry registration for key \"${key}\"`,\n ),\n ),\n };\n }\n try {\n // Payload may be a codec string or already a JSON value (seeded data).\n const decoded =\n typeof envelope.payload === \"string\"\n ? decodeStringPayload<T>(envelope.payload, codec)\n : (envelope.payload as T);\n const inferredJsonSchema = inferJsonSchema(decoded);\n const inferred: KeySchema = {\n key,\n version: 1,\n schema: inferredJsonSchema,\n };\n // Rewrite as a schema-managed envelope (payload is JSON value directly)\n const rewriteEnvelope: MnemonicEnvelope = {\n version: inferred.version,\n payload: decoded,\n };\n return {\n value: decoded,\n pendingSchema: inferred,\n rewriteRaw: JSON.stringify(rewriteEnvelope),\n };\n } catch (err) {\n const typedErr =\n err instanceof SchemaError || err instanceof CodecError\n ? err\n : new SchemaError(\"TYPE_MISMATCH\", `Autoschema inference failed for key \"${key}\"`, err);\n return { value: getFallback(typedErr) };\n }\n }\n\n // No schema found: default mode ignores version and uses hook codec.\n if (!schemaForVersion) {\n // If payload is already a non-string JSON value (e.g. seeded data,\n // or previously schema-managed data whose schema was removed),\n // return it directly without codec decoding.\n if (typeof envelope.payload !== \"string\") {\n return { value: envelope.payload as T };\n }\n try {\n const decoded = decodeStringPayload<T>(envelope.payload, codec);\n return { value: decoded };\n } catch (err) {\n const typedErr =\n err instanceof SchemaError || err instanceof CodecError\n ? err\n : new CodecError(`Codec decode failed for key \"${key}\"`, err);\n return { value: getFallback(typedErr) };\n }\n }\n\n // Schema exists for stored version.\n // Payload is a JSON value directly (no codec decoding needed).\n let current: unknown;\n try {\n current = envelope.payload;\n validateAgainstSchema(current, schemaForVersion.schema);\n } catch (err) {\n const typedErr =\n err instanceof SchemaError || err instanceof CodecError\n ? err\n : new SchemaError(\"TYPE_MISMATCH\", `Schema decode failed for key \"${key}\"`, err);\n return { value: getFallback(typedErr) };\n }\n\n // No migration needed.\n if (!latestSchema || envelope.version >= latestSchema.version) {\n return { value: current as T };\n }\n\n const path = getMigrationPathForKey(envelope.version, latestSchema.version);\n if (!path) {\n return {\n value: getFallback(\n new SchemaError(\n \"MIGRATION_PATH_NOT_FOUND\",\n `No migration path for key \"${key}\" from v${envelope.version} to v${latestSchema.version}`,\n ),\n ),\n };\n }\n\n try {\n let migrated = current;\n for (const step of path) {\n migrated = step.migrate(migrated);\n }\n validateAgainstSchema(migrated, latestSchema.schema);\n // Rewrite as schema-managed envelope (payload is JSON value)\n const rewriteEnvelope: MnemonicEnvelope = {\n version: latestSchema.version,\n payload: migrated,\n };\n return {\n value: migrated as T,\n rewriteRaw: JSON.stringify(rewriteEnvelope),\n };\n } catch (err) {\n const typedErr =\n err instanceof SchemaError || err instanceof CodecError\n ? err\n : new SchemaError(\"MIGRATION_FAILED\", `Migration failed for key \"${key}\"`, err);\n return { value: getFallback(typedErr) };\n }\n },\n [\n codec,\n decodeStringPayload,\n getFallback,\n key,\n parseEnvelope,\n schemaMode,\n schemaRegistry,\n getSchemaForVersion,\n getLatestSchemaForKey,\n getMigrationPathForKey,\n validateAgainstSchema,\n ],\n );\n\n const encodeForWrite = useCallback(\n (nextValue: T): string => {\n const explicitVersion = schema?.version;\n const latestSchema = getLatestSchemaForKey();\n const explicitSchema = explicitVersion !== undefined ? getSchemaForVersion(explicitVersion) : undefined;\n\n let targetSchema = explicitSchema;\n\n if (!targetSchema) {\n if (explicitVersion !== undefined) {\n if (schemaMode !== \"strict\") {\n targetSchema = latestSchema;\n }\n } else {\n targetSchema = latestSchema;\n }\n }\n\n if (!targetSchema) {\n if (explicitVersion !== undefined && schemaMode === \"strict\") {\n throw new SchemaError(\n \"WRITE_SCHEMA_REQUIRED\",\n `Write requires schema for key \"${key}\" in strict mode`,\n );\n }\n // No schema: codec-only path. Encode with hook codec, version 0.\n const envelope: MnemonicEnvelope = {\n version: 0,\n payload: codec.encode(nextValue),\n };\n return JSON.stringify(envelope);\n }\n\n // Schema exists: validate and apply write-time migration if available.\n let valueToStore: unknown = nextValue;\n\n // Check for write-time normalizer (fromVersion === toVersion)\n const writeMigration = schemaRegistry?.getWriteMigration?.(key, targetSchema.version);\n if (writeMigration) {\n try {\n valueToStore = writeMigration.migrate(valueToStore);\n } catch (err) {\n throw err instanceof SchemaError\n ? err\n : new SchemaError(\"MIGRATION_FAILED\", `Write-time migration failed for key \"${key}\"`, err);\n }\n }\n\n validateAgainstSchema(valueToStore, targetSchema.schema);\n\n // Schema-managed envelope: payload is JSON value directly\n const envelope: MnemonicEnvelope = {\n version: targetSchema.version,\n payload: valueToStore,\n };\n return JSON.stringify(envelope);\n },\n [\n schema?.version,\n key,\n schemaMode,\n codec,\n schemaRegistry,\n validateAgainstSchema,\n getLatestSchemaForKey,\n getSchemaForVersion,\n ],\n );\n\n /**\n * Subscribe to raw storage changes using React's useSyncExternalStore.\n * This ensures efficient, tearing-free updates when storage changes.\n */\n const raw = useSyncExternalStore(\n (listener) => api.subscribeRaw(key, listener),\n () => api.getRawSnapshot(key),\n () => null, // SSR snapshot - no storage in server environment\n );\n\n const decoded = useMemo(() => decodeForRead(raw), [decodeForRead, raw]);\n const value = decoded.value;\n\n // Persist opportunistic read-time upgrades (migrations, autoschema rewrite).\n useEffect(() => {\n if (decoded.rewriteRaw && decoded.rewriteRaw !== raw) {\n api.setRaw(key, decoded.rewriteRaw);\n }\n }, [api, decoded.rewriteRaw, key, raw]);\n\n // Register inferred schema for autoschema mode once read succeeds.\n useEffect(() => {\n if (!decoded.pendingSchema || !schemaRegistry?.registerSchema) return;\n if (schemaRegistry.getSchema(decoded.pendingSchema.key, decoded.pendingSchema.version)) return;\n try {\n schemaRegistry.registerSchema(decoded.pendingSchema);\n } catch {\n // Ignore registration races; write/read paths will enforce schema validity.\n }\n }, [decoded.pendingSchema, schemaRegistry]);\n\n /**\n * Track previous value for onChange callback.\n */\n const prevRef = useRef<T>(value);\n\n /**\n * Call onMount callback once when the hook first mounts.\n * Receives the initial value loaded from storage.\n */\n const mounted = useRef(false);\n useEffect(() => {\n if (mounted.current) return;\n mounted.current = true;\n onMount?.(value);\n prevRef.current = value;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n /**\n * Call onChange callback whenever the decoded value changes.\n * Provides both the new value and the previous value.\n */\n useEffect(() => {\n const prev = prevRef.current;\n if (Object.is(prev, value)) return;\n prevRef.current = value;\n onChange?.(value, prev);\n }, [value, onChange]);\n\n /**\n * Optional cross-tab synchronization.\n * Listens for storage events from other tabs and syncs changes\n * into this tab's store cache.\n */\n useEffect(() => {\n if (!listenCrossTab) return;\n if (typeof window === \"undefined\") return;\n\n const storageKey = api.prefix + key;\n\n const handler = (e: StorageEvent) => {\n // localStorage.clear() in another tab emits `key === null`.\n if (e.key === null) {\n api.removeRaw(key);\n return;\n }\n if (e.key !== storageKey) return;\n // Another tab removed the key:\n if (e.newValue == null) {\n api.removeRaw(key);\n return;\n }\n api.setRaw(key, e.newValue);\n };\n\n window.addEventListener(\"storage\", handler);\n return () => window.removeEventListener(\"storage\", handler);\n }, [listenCrossTab, api, key]);\n\n /**\n * Update function - supports both direct values and updater functions.\n */\n const set = useMemo(() => {\n return (next: T | ((cur: T) => T)) => {\n const nextVal =\n typeof next === \"function\" ? (next as (c: T) => T)(decodeForRead(api.getRawSnapshot(key)).value) : next;\n try {\n const encoded = encodeForWrite(nextVal);\n api.setRaw(key, encoded);\n } catch (err) {\n if (err instanceof SchemaError) {\n console.error(`[Mnemonic] Schema error for key \"${key}\" (${err.code}):`, err.message);\n return;\n }\n if (err instanceof CodecError) {\n console.error(`[Mnemonic] Codec encode error for key \"${key}\":`, err.message);\n return;\n }\n console.error(`[Mnemonic] Failed to persist key \"${key}\":`, err);\n }\n };\n // Note: does not depend on `value` to avoid stale closures\n }, [api, key, decodeForRead, encodeForWrite]);\n\n /**\n * Reset function - sets the value back to the default and persists it.\n */\n const reset = useMemo(() => {\n return () => {\n const v = getFallback();\n try {\n const encoded = encodeForWrite(v);\n api.setRaw(key, encoded);\n } catch (err) {\n if (err instanceof SchemaError) {\n console.error(`[Mnemonic] Schema error for key \"${key}\" (${err.code}):`, err.message);\n return;\n }\n if (err instanceof CodecError) {\n console.error(`[Mnemonic] Codec encode error for key \"${key}\":`, err.message);\n }\n return;\n }\n };\n }, [api, key, getFallback, encodeForWrite]);\n\n /**\n * Remove function - completely removes the key from storage.\n * Future reads will return the default value.\n */\n const remove = useMemo(() => {\n return () => api.removeRaw(key);\n }, [api, key]);\n\n return useMemo(\n () =>\n /** @see {@link UseMnemonicKeyOptions} for configuration details */\n ({\n /** Current decoded value, or the default when the key is absent or invalid. */\n value,\n /** Persist a new value (direct or updater function). */\n set,\n /** Reset to `defaultValue` and persist it. */\n reset,\n /** Delete the key from storage entirely. */\n remove,\n }),\n [value, set, reset, remove],\n );\n}\n"]}
|