( config: LocalStorageCollectionConfig<any, any, string | number>, )
| 348 | } |
| 349 | |
| 350 | export function localStorageCollectionOptions( |
| 351 | config: LocalStorageCollectionConfig<any, any, string | number>, |
| 352 | ): Omit< |
| 353 | CollectionConfig<any, string | number, any, LocalStorageCollectionUtils>, |
| 354 | `id` |
| 355 | > & { |
| 356 | id: string |
| 357 | utils: LocalStorageCollectionUtils |
| 358 | schema?: StandardSchemaV1 |
| 359 | } { |
| 360 | // Validate required parameters |
| 361 | if (!config.storageKey) { |
| 362 | throw new StorageKeyRequiredError() |
| 363 | } |
| 364 | |
| 365 | // Default to window.localStorage if no storage is provided |
| 366 | // Fall back to in-memory storage if localStorage is not available (e.g., server-side rendering) |
| 367 | const storage = |
| 368 | config.storage || |
| 369 | (typeof window !== `undefined` ? window.localStorage : null) || |
| 370 | createInMemoryStorage() |
| 371 | |
| 372 | // Default to window for storage events if not provided |
| 373 | // Fall back to no-op storage event API if window is not available (e.g., server-side rendering) |
| 374 | const storageEventApi = |
| 375 | config.storageEventApi || |
| 376 | (typeof window !== `undefined` ? window : null) || |
| 377 | createNoOpStorageEventApi() |
| 378 | |
| 379 | // Default to JSON parser if no parser is provided |
| 380 | const parser = config.parser || JSON |
| 381 | |
| 382 | // Track the last known state to detect changes |
| 383 | const lastKnownData = new Map<string | number, StoredItem<any>>() |
| 384 | |
| 385 | // Create the sync configuration |
| 386 | const sync = createLocalStorageSync<any>( |
| 387 | config.storageKey, |
| 388 | storage, |
| 389 | storageEventApi, |
| 390 | parser, |
| 391 | config.getKey, |
| 392 | lastKnownData, |
| 393 | ) |
| 394 | |
| 395 | /** |
| 396 | * Save data to storage |
| 397 | * @param dataMap - Map of items with version tracking to save to storage |
| 398 | */ |
| 399 | const saveToStorage = ( |
| 400 | dataMap: Map<string | number, StoredItem<any>>, |
| 401 | ): void => { |
| 402 | try { |
| 403 | // Convert Map to object format for storage |
| 404 | const objectData: Record<string, StoredItem<any>> = {} |
| 405 | dataMap.forEach((storedItem, key) => { |
| 406 | objectData[encodeStorageKey(key)] = storedItem |
| 407 | }) |
no test coverage detected