Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 | 33x 33x 79x 40x 40x 36x 36x 36x 3x 3x 3x 29x 4x 7x 7x 7x 7x 7x 8x 8x 8x 8x 8x 8x 5x 5x 5x 18x 18x 8x 7x 7x 1x 1x 1x 7x 1x 1x 7x 7x 7x 8x 7x 6x 6x 6x 6x 6x 6x 6x 6x 12x 12x 12x 12x 12x 12x 12x 12x 12x 13x 13x 1x 3x 3x 2x 2x 5x 5x 5x 5x 3x 3x 3x 301x 3x 6x 1x 5x 8x 798x 8x 5x 3x 53x 29x 4x 7x 13x 57x 57x 57x 58x 58x 58x 58x 2x 55x 2x 53x 57x 57x 57x 57x 57x 57x 57x 3x 3x 54x 54x 2x 2x 4x 4x 2x 52x 2x 2x 2x 2x 50x 57x 57x 5x 5x 1x 1x 1x 1x 1x 5x 51x 2x 2x 56x 2x 54x 54x 54x 54x 54x 54x 5x 52x 51x 51x 5x 51x 51x 3x 3x 59x 59x 5x 5x 2x 2x 5x 54x 54x 54x 52x 52x 52x 20x 3x 20x 20x 4x 4x 2x 2x 18x 2x 2x 2x 16x 16x 2x 16x 3x 3x 57x 3x 3x 51x 34x 17x 18x 17x 17x 17x 17x 17x 21x 38x 38x 1x 38x 24x 38x 38x 38x 30x 1x 1x 1x 1x 1x 1x 1x 7x 16x 15x 15x 15x 15x 15x 15x 16x 16x 57x 44x 44x 44x 44x 44x 44x 44x 44x 13x 57x 28x 5x 22x 4x 6x | /**
* @fileoverview State Persistence for Coherent.js
* Provides persistent state management with multiple storage backends
* @module @coherent.js/core/state/state-persistence
*/
/**
* @typedef {'localStorage'|'sessionStorage'|'indexedDB'|'memory'} StorageType
*/
/**
* @typedef {Object} PersistenceOptions
* @property {StorageType} [storage='localStorage'] - Storage backend to use
* @property {StorageAdapter} [adapter] - Custom storage backend; used as is,
* also on the server
* @property {string} [key='coherent-state'] - Storage key prefix
* @property {boolean} [debounce=true] - Debounce state saves
* @property {number} [debounceDelay=300] - Debounce delay in ms
* @property {Function} [serialize=JSON.stringify] - Serialization function
* @property {Function} [deserialize=JSON.parse] - Deserialization function
* @property {Array<string>} [include] - Keys to include (whitelist)
* @property {Array<string>} [exclude] - Keys to exclude (blacklist)
* @property {boolean} [encrypt=false] - Obfuscate stored data with
* `encryptionKey` (XOR — not encryption; anyone with the key, which ships
* to the browser, can read it)
* @property {string} [encryptionKey] - Obfuscation key; required with `encrypt`
* @property {Function} [onSave] - Callback when state is saved
* @property {Function} [onLoad] - Callback when state is loaded
* @property {Function} [onError] - Error callback (load, save or storage failures)
* @property {boolean} [versioning=false] - Enable versioning
* @property {string} [version='1.0.0'] - Current version
* @property {Function} [migrate] - Migration function for version changes
* @property {number} [ttl] - Time to live in milliseconds
* @property {boolean} [crossTab=false] - Enable cross-tab synchronization
* @property {string} [dbName='coherent-db'] - IndexedDB database name (`storage: 'indexedDB'`)
* @property {string} [storeName='state'] - IndexedDB object store name (`storage: 'indexedDB'`)
*/
/**
* Storage adapter interface: async get/set/remove/clear. `set` resolves to
* `true` once the value is stored and rejects (or resolves `false`) when it
* could not be.
* @interface StorageAdapter
*/
/**
* Web Storage adapter (localStorage / sessionStorage). Storage errors, such as
* QuotaExceededError, propagate to the caller.
*/
class WebStorageAdapter {
constructor(storageName) {
this.storageName = storageName;
this.available = typeof globalThis[storageName] !== 'undefined' && globalThis[storageName] !== null;
}
get storage() {
return globalThis[this.storageName];
}
async get(key) {
Iif (!this.available) return null;
return this.storage.getItem(key);
}
async set(key, value) {
Iif (!this.available) return false;
this.storage.setItem(key, value);
return true;
}
async remove(key) {
Iif (!this.available) return false;
this.storage.removeItem(key);
return true;
}
async clear() {
if (!this.available) return false;
this.storage.clear();
return true;
}
}
/**
* LocalStorage adapter
*/
class LocalStorageAdapter extends WebStorageAdapter {
constructor() {
super('localStorage');
}
}
/**
* SessionStorage adapter
*/
class SessionStorageAdapter extends WebStorageAdapter {
constructor() {
super('sessionStorage');
}
}
/**
* IndexedDB adapter: values are kept in the object store `storeName` of the
* database `dbName`.
*/
class IndexedDBAdapter {
constructor(dbName = 'coherent-db', storeName = 'state') {
this.dbName = dbName;
this.storeName = storeName;
this.available = typeof indexedDB !== 'undefined';
this.db = null;
this.opening = null;
}
/**
* Open the database, creating the store in an upgrade. Without `version`,
* opens the current version (creating version 1 for a new database).
*/
open(version) {
return new Promise((resolve, reject) => {
const request = version === undefined
? indexedDB.open(this.dbName)
: indexedDB.open(this.dbName, version);
request.onerror = () => {
console.error('IndexedDB open error:', request.error);
reject(request.error);
};
request.onsuccess = () => {
resolve(request.result);
};
request.onupgradeneeded = (event) => {
const db = event.target.result;
Eif (!db.objectStoreNames.contains(this.storeName)) {
db.createObjectStore(this.storeName);
}
};
});
}
async init() {
Iif (!this.available) return false;
if (this.db) return true;
this.opening ??= (async () => {
let db = await this.open();
// The database already exists without this store (another store with
// the same dbName created it): add the store in a version upgrade.
if (!db.objectStoreNames.contains(this.storeName)) {
const version = db.version + 1;
db.close();
db = await this.open(version);
}
// Let another store's upgrade proceed; reopen on the next access.
db.onversionchange = () => {
db.close();
Eif (this.db === db) this.db = null;
};
this.db = db;
return true;
})().finally(() => {
this.opening = null;
});
return this.opening;
}
async get(key) {
if (!this.available) return null;
await this.init();
return new Promise((resolve, reject) => {
const transaction = this.db.transaction([this.storeName], 'readonly');
const store = transaction.objectStore(this.storeName);
const request = store.get(key);
request.onerror = () => {
console.error('IndexedDB get error:', request.error);
reject(request.error);
};
request.onsuccess = () => {
resolve(request.result || null);
};
});
}
async set(key, value) {
Iif (!this.available) return false;
await this.init();
return new Promise((resolve, reject) => {
const transaction = this.db.transaction([this.storeName], 'readwrite');
const store = transaction.objectStore(this.storeName);
const request = store.put(value, key);
request.onerror = () => {
console.error('IndexedDB set error:', request.error);
reject(request.error);
};
request.onsuccess = () => {
resolve(true);
};
});
}
async remove(key) {
if (!this.available) return false;
await this.init();
return new Promise((resolve, reject) => {
const transaction = this.db.transaction([this.storeName], 'readwrite');
const store = transaction.objectStore(this.storeName);
const request = store.delete(key);
request.onerror = () => {
console.error('IndexedDB remove error:', request.error);
reject(request.error);
};
request.onsuccess = () => {
resolve(true);
};
});
}
async clear() {
if (!this.available) return false;
await this.init();
return new Promise((resolve, reject) => {
const transaction = this.db.transaction([this.storeName], 'readwrite');
const store = transaction.objectStore(this.storeName);
const request = store.clear();
request.onerror = () => {
console.error('IndexedDB clear error:', request.error);
reject(request.error);
};
request.onsuccess = () => {
resolve(true);
};
});
}
}
/**
* Memory adapter (for testing or fallback)
*/
class MemoryAdapter {
constructor() {
this.storage = new Map();
this.available = true;
}
async get(key) {
return this.storage.get(key) || null;
}
async set(key, value) {
this.storage.set(key, value);
return true;
}
async remove(key) {
return this.storage.delete(key);
}
async clear() {
this.storage.clear();
return true;
}
}
/**
* Stand-in for browser storage on the server. Web Storage there (Node's
* `--experimental-webstorage`, on by default in newer releases) is shared by
* every request in the process, so one visitor's state would be restored into
* another's render. Nothing is read or written.
*/
class ServerAdapter {
constructor() {
this.available = false;
}
async get() {
return null;
}
async set() {
return false;
}
async remove() {
return false;
}
async clear() {
return false;
}
}
function toBase64(bytes) {
let binary = '';
for (let i = 0; i < bytes.length; i += 0x8000) {
binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
}
return btoa(binary);
}
function fromBase64(encoded) {
const binary = atob(encoded);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
return bytes;
}
/**
* XOR obfuscation of the stored payload (option `encrypt`).
*
* This is NOT encryption: the key has to ship to the browser, and XOR with a
* repeating key is trivially reversible. It only keeps casual readers of the
* storage from seeing plain JSON. Do not store secrets in browser storage.
*
* Works on UTF-8 bytes, so any Unicode text round-trips.
*/
class XorObfuscation {
constructor(key) {
if (typeof key !== 'string' || key.length === 0) {
throw new TypeError(
'createPersistentState: `encrypt: true` requires a non-empty `encryptionKey`. ' +
'It is XOR obfuscation, not encryption; there is no default key.'
);
}
this.keyBytes = new globalThis.TextEncoder().encode(key);
}
xor(bytes) {
for (let i = 0; i < bytes.length; i++) {
bytes[i] ^= this.keyBytes[i % this.keyBytes.length];
}
return bytes;
}
encode(text) {
return toBase64(this.xor(new globalThis.TextEncoder().encode(text)));
}
decode(encoded) {
return new globalThis.TextDecoder().decode(this.xor(fromBase64(encoded)));
}
}
/**
* Create storage adapter
* @param {StorageType} type - Storage type
* @param {Pick<PersistenceOptions, 'dbName'|'storeName'>} [options] - IndexedDB
* database and object store names
* @returns {StorageAdapter} Storage adapter instance
*/
function createStorageAdapter(type, options = {}) {
switch (type) {
case 'localStorage':
return new LocalStorageAdapter();
case 'sessionStorage':
return new SessionStorageAdapter();
case 'indexedDB':
return new IndexedDBAdapter(options.dbName ?? undefined, options.storeName ?? undefined);
case 'memory':
return new MemoryAdapter();
default:
return new LocalStorageAdapter();
}
}
function createInstanceId() {
const cryptoApi = globalThis.crypto;
Eif (cryptoApi && typeof cryptoApi.randomUUID === 'function') {
return cryptoApi.randomUUID();
}
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
}
/**
* Create persistent state manager
*
* Unless the backend is `'memory'`, stored state is restored on creation;
* `ready` settles once that is done. Keys set before then keep the value they
* were set to rather than the stored one.
*
* On the server (no `window`), browser storage backends read and write
* nothing and cross-tab sync is off; pass an explicit `adapter` to persist
* there.
*
* @param {Object} initialState - Initial state
* @param {PersistenceOptions} options - Persistence options
* @returns {Object} Persistent state manager
*/
export function createPersistentState(initialState = {}, options = {}) {
const opts = {
storage: 'localStorage',
adapter: null,
key: 'coherent-state',
debounce: true,
debounceDelay: 300,
serialize: JSON.stringify,
deserialize: JSON.parse,
include: null,
exclude: null,
encrypt: false,
encryptionKey: null,
onSave: null,
onLoad: null,
onError: null,
versioning: false,
version: '1.0.0',
migrate: null,
ttl: null,
crossTab: false,
...options
};
const onServer = typeof window === 'undefined';
const obfuscation = opts.encrypt ? new XorObfuscation(opts.encryptionKey) : null;
let adapter;
if (opts.adapter) {
adapter = opts.adapter;
} else if (onServer && opts.storage !== 'memory') {
adapter = new ServerAdapter();
} else {
adapter = createStorageAdapter(opts.storage, opts);
}
const instanceId = createInstanceId();
let state = { ...initialState };
let saveTimeout = null;
let destroyed = false;
const listeners = new Set();
// Keys written while the initial restore is in flight; it must not
// overwrite them with the older stored values.
let initialRestorePending = false;
const touchedKeys = new Set();
function reportError(error) {
if (opts.onError) {
opts.onError(error);
} else E{
console.error('State persistence error:', error);
}
}
/**
* Filter state keys based on include/exclude options
* @param {Object} obj - State object
* @returns {Object} Filtered state
*/
function filterKeys(obj) {
Iif (!obj || typeof obj !== 'object') return obj;
// If include list is provided, only include those keys
if (opts.include && Array.isArray(opts.include)) {
const filtered = {};
opts.include.forEach(key => {
Eif (key in obj) {
filtered[key] = obj[key];
}
});
return filtered;
}
// If exclude list is provided, exclude those keys
if (opts.exclude && Array.isArray(opts.exclude)) {
const filtered = { ...obj };
opts.exclude.forEach(key => {
delete filtered[key];
});
return filtered;
}
return obj;
}
// Cross-tab synchronisation: one channel per storage key, so unrelated
// stores never merge each other's state, and messages carry the sender's
// id so a store never applies its own update.
let channel = null;
if (opts.crossTab && !onServer && typeof BroadcastChannel !== 'undefined') {
channel = new BroadcastChannel(`coherent-state-sync:${opts.key}`);
channel.onmessage = (event) => {
const message = event.data;
Iif (destroyed || !message || message.type !== 'state-update' || message.source === instanceId) {
return;
}
const oldState = { ...state };
state = { ...state, ...message.state };
notifyListeners(oldState, state);
};
// Node: do not keep the process alive for this channel
channel.unref?.();
}
function broadcast(filteredState) {
if (!channel) return;
try {
channel.postMessage({ type: 'state-update', source: instanceId, state: filteredState });
} catch (error) {
reportError(error);
}
}
/**
* Write the current state now.
* @returns {Promise<boolean>} Whether it was stored
*/
async function write() {
if (adapter.available === false) {
return false;
}
try {
const filteredState = filterKeys(state);
const serialized = opts.serialize(filteredState);
// Add metadata
const data = {
state: serialized,
version: opts.version,
timestamp: Date.now(),
ttl: opts.ttl
};
let dataString = JSON.stringify(data);
if (obfuscation) {
dataString = obfuscation.encode(dataString);
}
const stored = await adapter.set(opts.key, dataString);
Iif (stored === false) {
throw new Error(`State "${opts.key}" could not be written to storage`);
}
// Call onSave callback
if (opts.onSave) {
opts.onSave(filteredState);
}
broadcast(filteredState);
return true;
} catch (error) {
reportError(error);
return false;
}
}
/**
* Save state to storage
* @param {boolean} immediate - Save immediately without debounce
* @returns {Promise<boolean>|undefined} Whether it was stored (immediate saves)
*/
function save(immediate = false) {
Iif (destroyed) {
return Promise.resolve(false);
}
if (opts.debounce && !immediate) {
clearTimeout(saveTimeout);
saveTimeout = setTimeout(() => {
saveTimeout = null;
write();
}, opts.debounceDelay);
return undefined;
}
clearTimeout(saveTimeout);
saveTimeout = null;
return write();
}
/**
* Load state from storage
*/
async function load() {
try {
let dataString = await adapter.get(opts.key);
if (!dataString) return null;
if (obfuscation) {
dataString = obfuscation.decode(dataString);
}
const data = JSON.parse(dataString);
// Check TTL
if (data.ttl && data.timestamp) {
const age = Date.now() - data.timestamp;
if (age > data.ttl) {
await adapter.remove(opts.key);
return null;
}
}
// Check version and migrate if needed
if (opts.versioning && data.version !== opts.version) {
Eif (opts.migrate) {
const migrated = opts.migrate(data.state, data.version, opts.version);
return opts.deserialize(migrated);
}
return null;
}
const loadedState = opts.deserialize(data.state);
// Call onLoad callback
if (opts.onLoad) {
opts.onLoad(loadedState);
}
return loadedState;
} catch (error) {
reportError(error);
return null;
}
}
/**
* Subscribe to state changes
* @param {Function} listener - Change listener
* @returns {Function} Unsubscribe function
*/
function subscribe(listener) {
listeners.add(listener);
return () => listeners.delete(listener);
}
/**
* Notify listeners of state changes
* @param {Object} oldState - Previous state
* @param {Object} newState - New state
*/
function notifyListeners(oldState, newState) {
listeners.forEach(listener => {
try {
listener(newState, oldState);
} catch (error) {
console.error('Listener error:', error);
}
});
}
/**
* Merge loaded state, optionally leaving keys touched since creation alone.
* @returns {boolean} Whether stored state was found
*/
function applyLoaded(loaded, skipTouched) {
if (!loaded || typeof loaded !== 'object') {
return false;
}
// Object.fromEntries defines keys as own data properties, so a stored
// "__proto__" key cannot reach a prototype.
const updates = Object.fromEntries(
Object.entries(loaded).filter(([key]) => !skipTouched || !touchedKeys.has(key))
);
Eif (Object.keys(updates).length > 0) {
const oldState = { ...state };
state = { ...state, ...updates };
notifyListeners(oldState, state);
}
return true;
}
/**
* Get current state
* @param {string} [key] - State key
* @returns {*} State value or entire state
*/
function getState(key) {
return key ? state[key] : { ...state };
}
/**
* Set state
* @param {Object|Function} updates - State updates or updater function
* @param {boolean} persist - Persist to storage
*/
function setState(updates, persist = true) {
const oldState = { ...state };
if (typeof updates === 'function') {
updates = updates(oldState);
}
if (initialRestorePending && updates && typeof updates === 'object') {
for (const key of Object.keys(updates)) touchedKeys.add(key);
}
state = { ...state, ...updates };
notifyListeners(oldState, state);
if (persist) {
save();
}
}
/**
* Reset state to initial values
* @param {boolean} persist - Persist to storage
*/
function resetState(persist = true) {
const oldState = { ...state };
Iif (initialRestorePending) {
for (const key of Object.keys(oldState)) touchedKeys.add(key);
for (const key of Object.keys(initialState)) touchedKeys.add(key);
}
state = { ...initialState };
notifyListeners(oldState, state);
Iif (persist) {
save(true);
}
}
/**
* Clear persisted state
*/
async function clearStorage() {
try {
await adapter.remove(opts.key);
} catch (error) {
reportError(error);
}
}
/**
* Manually trigger persistence
* @returns {Promise<boolean>} Whether it was stored
*/
async function persist() {
return save(true);
}
/**
* Restore state from storage
* @returns {Promise<boolean>} Whether stored state was found
*/
async function restore() {
return applyLoaded(await load(), false);
}
/**
* Stop syncing and saving: flushes a pending debounced save, closes the
* cross-tab channel and drops listeners.
* @returns {Promise<void>}
*/
async function destroy() {
if (destroyed) return;
const pending = saveTimeout !== null;
clearTimeout(saveTimeout);
saveTimeout = null;
Iif (pending) {
await write();
}
destroyed = true;
channel?.close();
channel = null;
listeners.clear();
}
// Auto-restore on creation
let ready;
if (opts.storage !== 'memory' || opts.adapter) {
initialRestorePending = true;
ready = load().then((loaded) => {
initialRestorePending = false;
Iif (destroyed) return false;
const restored = applyLoaded(loaded, true);
// Keys set meanwhile were saved without the restored ones; save the merge
if (restored && touchedKeys.size > 0) save();
touchedKeys.clear();
return restored;
});
} else {
ready = Promise.resolve(false);
}
return {
getState,
setState,
resetState,
subscribe,
persist,
restore,
clearStorage,
load,
save: () => save(true),
destroy,
/** Settles once the automatic restore on creation is done */
ready,
get adapter() {
return adapter;
}
};
}
/**
* Create persistent state with localStorage
* @param {Object} initialState - Initial state
* @param {string} key - Storage key
* @param {Partial<PersistenceOptions>} options - Additional options
* @returns {Object} Persistent state manager
*/
export function withLocalStorage(initialState = {}, key = 'coherent-state', options = {}) {
return createPersistentState(initialState, {
...options,
storage: 'localStorage',
key
});
}
/**
* Create persistent state with sessionStorage
* @param {Object} initialState - Initial state
* @param {string} key - Storage key
* @param {Partial<PersistenceOptions>} options - Additional options
* @returns {Object} Persistent state manager
*/
export function withSessionStorage(initialState = {}, key = 'coherent-state', options = {}) {
return createPersistentState(initialState, {
...options,
storage: 'sessionStorage',
key
});
}
/**
* Create persistent state with IndexedDB
* @param {Object} initialState - Initial state
* @param {string} key - Storage key
* @param {Partial<PersistenceOptions>} options - Additional options
* @returns {Object} Persistent state manager
*/
export function withIndexedDB(initialState = {}, key = 'coherent-state', options = {}) {
return createPersistentState(initialState, {
...options,
storage: 'indexedDB',
key
});
}
export default {
createPersistentState,
withLocalStorage,
withSessionStorage,
withIndexedDB,
createStorageAdapter
};
|