Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

indexeddb.ts

891 lines26.7 KB

1/**
2 * IndexedDB Collection for TanStack DB
3 *
4 * This module provides a factory function that creates IndexedDB-backed collections
5 * compatible with TanStack DB's collection system.
6 */
7​
8import {
9 SchemaMustBeSynchronousError,
10 SchemaValidationError,
11 safeRandomUUID,
12 withCollectionConfigFactory,
13} from '@tanstack/db'
14import {
15 clear,
16 executeTransaction,
17 getAll,
18 getByKey,
19 openDatabase,
20} from './wrapper'
21import type {
22 BaseCollectionConfig,
23 ChangeMessageOrDeleteKeyMessage,
24 CollectionConfig,
25 DeleteMutationFnParams,
26 InsertMutationFnParams,
27 OperationType,
28 PendingMutation,
29 SyncConfig,
30 UpdateMutationFnParams,
31 UtilsRecord,
32} from '@tanstack/db'
33import type { StandardSchemaV1 } from '@standard-schema/spec'
34​
35export class DatabaseRequiredError extends Error {
36 constructor() {
37 super(
38 `IndexedDB collection requires a "db" configuration option. ` +
39 `Create a database instance using createIndexedDB() and pass it to the collection.`,
40 )
41 this.name = `DatabaseRequiredError`
42 }
44​
45/**
46 * Thrown when the specified object store doesn't exist in the database
47 */
48export class ObjectStoreNotFoundError extends Error {
49 constructor(
50 storeName: string,
51 databaseName: string,
52 availableStores: ReadonlyArray<string>,
53 ) {
54 super(
55 `Object store "${storeName}" not found in database "${databaseName}". ` +
56 `Available stores: [${availableStores.join(', ')}]. ` +
57 `Add "${storeName}" to the stores array when calling createIndexedDB().`,
58 )
59 this.name = 'ObjectStoreNotFoundError'
60 }
62​
63/**
64 * Thrown when the name (object store) configuration is missing
65 */
66export class NameRequiredError extends Error {
67 constructor() {
68 super(
69 `IndexedDB collection requires a "name" configuration option. ` +
70 `This is the name of the object store within the database.`,
71 )
72 this.name = `NameRequiredError`
73 }
75​
76/**
77 * Thrown when the getKey function is missing
78 */
79export class GetKeyRequiredError extends Error {
80 constructor() {
81 super(
82 `IndexedDB collection requires a "getKey" configuration option. ` +
83 `This function extracts the unique key from each item.`,
84 )
85 this.name = `GetKeyRequiredError`
86 }
88​
89export interface CreateIndexedDBOptions {
90 /** Database name */
91 name: string
92 /** Schema version (increment when adding stores) */
93 version: number
94 /** Object store names to create */
95 stores: ReadonlyArray<string>
96 /** Custom IDBFactory for testing/mocking */
97 idbFactory?: IDBFactory
98 /** Reports a native blocker without settling the open request. */
99 onBlocked?: (event: IDBVersionChangeEvent) => void
101​
102/**
103 * A shared IndexedDB database instance.
104 * Create with createIndexedDB() and pass to collections.
105 */
106export interface IndexedDBInstance {
107 /** The underlying IDBDatabase connection */
108 readonly db: IDBDatabase
109 /** Database name */
110 readonly name: string
111 /** Database version */
112 readonly version: number
113 /** Requested object store names (frozen); omissions do not remove stores */
114 readonly stores: ReadonlyArray<string>
115 /** IDBFactory used to create this database (for testing) */
116 readonly idbFactory?: IDBFactory
117 /** Close the connection and mark its managed Collections as errored. */
118 close: () => void
120​
121type InferSchemaOutput<T> = T extends StandardSchemaV1
122 ? StandardSchemaV1.InferOutput<T> extends object
123 ? StandardSchemaV1.InferOutput<T>
124 : Record<string, unknown>
125 : Record<string, unknown>
126​
127/**
128 * Schema input type inference helper
129 */
130type InferSchemaInput<T> = T extends StandardSchemaV1
131 ? StandardSchemaV1.InferInput<T> extends object
132 ? StandardSchemaV1.InferInput<T>
133 : Record<string, unknown>
134 : Record<string, unknown>
135​
136/**
137 * Configuration options for creating an IndexedDB Collection
138 */
139export interface IndexedDBCollectionConfig<
140 T extends object = object,
141 TSchema extends StandardSchemaV1 = never,
142 TKey extends string | number = string | number,
143> extends BaseCollectionConfig<T, TKey, TSchema> {
144 /**
145 * IndexedDB instance from createIndexedDB()
146 * REQUIRED - must create database before collections
147 */
148 db: IndexedDBInstance
149​
150 /**
151 * Name of the object store within the database
152 * Must exist in the underlying database
153 */
154 name: string
156​
157/**
158 * Version entry stored in the shared _versions object store
159 * Key is a tuple: [name, itemKey]
160 */
161interface VersionEntry {
162 versionKey: string // UUID for change detection
164​
165/**
166 * Cross-tab message format via BroadcastChannel
167 */
168interface CrossTabMessage {
169 type: 'data-changed' | 'database-cleared'
170 database: string
171 name: string // Object store name
172 changedKeys: Array<string | number> // Keys that changed (for targeted loading)
173 tabId: string // To avoid processing own messages
175​
176// BroadcastChannel is shared transport. Admit only this protocol before reading
177// its routing fields or issuing storage work. Invalid messages carry no writes.
178function isCrossTabMessage(value: unknown): value is CrossTabMessage {
179 if (!value || typeof value !== 'object') return false
180 const message = value as Record<string, unknown>
181 return (
182 (message.type === 'data-changed' || message.type === 'database-cleared') &&
183 typeof message.database === 'string' &&
184 typeof message.name === 'string' &&
185 typeof message.tabId === 'string' &&
186 Array.isArray(message.changedKeys) &&
187 message.changedKeys.every(
188 (key: unknown) =>
189 typeof key === 'string' ||
190 (typeof key === 'number' && !Number.isNaN(key)),
191 )
192 )
194​
195/**
196 * Database information returned by getDatabaseInfo()
197 */
198export interface DatabaseInfo {
199 name: string
200 version: number
201 objectStores: Array<string>
202 /** Origin-wide storage usage in bytes, including other databases and caches. */
203 estimatedSize?: number
205​
206/**
207 * Utility functions exposed on collection.utils
208 */
209export interface IndexedDBCollectionUtils<
210 TItem extends object = Record<string, unknown>,
211 TInsertInput extends object = TItem,
212> extends UtilsRecord {
213 /**
214 * Removes all data from the object store
215 * Does NOT delete the database itself
216 */
217 clearObjectStore: () => Promise<void>
218​
219 /**
220 * Returns database information for debugging
221 */
222 getDatabaseInfo: () => Promise<DatabaseInfo>
223​
224 /**
225 * Accepts mutations from a manual transaction and persists to IndexedDB
226 */
227 acceptMutations: (transaction: {
228 mutations: Array<PendingMutation>
229 }) => Promise<void>
230​
231 /**
232 * Exports all data from the object store as an array
233 * Useful for backup/debugging
234 */
235 exportData: () => Promise<Array<TItem>>
236​
237 /**
238 * Validates input rows and atomically replaces the object store.
239 * Failure preserves the previous rows and versions.
240 */
241 importData: (items: Array<TInsertInput>) => Promise<void>
243​
244const VERSIONS_STORE_NAME = '_versions'
245// Connection closure is sticky, including Collections started after close.
246// Keep core's sync run alive: admitted writes and accepted sync transactions
247// still owe their confirmations, while new reads have no publication authority.
248const connections = new WeakMap<
249 IDBDatabase,
250 {
251 error?: Error
252 listeners: Set<() => void>
253 }
254>()
255​
256/**
257 * Creates or opens an IndexedDB database with the specified stores.
258 * Call this once at app startup, then pass the instance to collections.
259 * The connection closes on versionchange so another context can upgrade or
260 * delete the database. Affected Collections enter error and retain their rows.
261 * Recreate affected Collections with a new instance before
262 * further persistence.
263 *
264 * All stores are created in a single upgrade transaction, avoiding
265 * version race conditions when multiple collections share a database.
266 *
267 * @example
268 * ```typescript
269 * const db = await createIndexedDB({
270 * name: 'myApp',
271 * version: 1,
272 * stores: ['todos', 'users', 'settings'],
273 * })
274 *
275 * const todosCollection = createCollection(
276 * indexedDBCollectionOptions({
277 * db,
278 * name: 'todos',
279 * getKey: (item: { id: string }) => item.id,
280 * })
281 * )
282 * ```
283 */
284export async function createIndexedDB(
285 options: CreateIndexedDBOptions,
286): Promise<IndexedDBInstance> {
287 const { name, version, stores, idbFactory, onBlocked } = options
288​
289 // Validate options
290 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- runtime safety for JS consumers
291 if (!stores || stores.length === 0) {
292 throw new Error(
293 'createIndexedDB requires at least one store in the stores array.',
294 )
295 }
296​
297 const storeSet = new Set(stores)
298 if (storeSet.size !== stores.length) {
299 throw new Error(
300 'createIndexedDB stores array contains duplicate store names.',
301 )
302 }
303​
304 for (const storeName of stores) {
305 if (storeName === VERSIONS_STORE_NAME) {
306 throw new Error(
307 'The "_versions" store is reserved for IndexedDB Collection metadata.',
308 )
309 }
310 if (!storeName || typeof storeName !== 'string') {
311 throw new Error(
312 'createIndexedDB stores array contains invalid store names. ' +
313 'Each store name must be a non-empty string.',
314 )
315 }
316 }
317​
318 const db = await openDatabase(
319 name,
320 version,
321 (database) => {
322 // Always create _versions store for cross-tab sync
323 if (!database.objectStoreNames.contains(VERSIONS_STORE_NAME)) {
324 database.createObjectStore(VERSIONS_STORE_NAME)
325 }
326​
327 // Create each requested store
328 for (const storeName of stores) {
329 if (!database.objectStoreNames.contains(storeName)) {
330 database.createObjectStore(storeName)
331 }
332 }
333 },
334 idbFactory,
335 onBlocked,
336 )
337​
338 const connection: { error?: Error; listeners: Set<() => void> } = {
339 listeners: new Set(),
340 }
341 connections.set(db, connection)
342 const close = () => {
343 db.close()
344 if (connection.error) return
345 connection.error = new Error(
346 `IndexedDB connection "${name}" closed. Recreate its Collections with a new database instance.`,
347 )
348 // Record closure before reentrant listeners can request more work. Core
349 // reports user event-listener failures asynchronously and notifies siblings.
350 for (const notify of [...connection.listeners]) notify()
351 }
352 db.addEventListener('versionchange', close)
353 db.addEventListener('close', close)
354​
355 // Create frozen stores array for immutability
356 const frozenStores = Object.freeze([...stores])
357​
358 return Object.freeze({
359 db,
360 name,
361 version: db.version,
362 stores: frozenStores,
363 idbFactory,
364 close,
365 })
367​
368/**
369 * Creates IndexedDB collection options for use with a standard Collection.
370 * This provides persistent local storage with cross-tab synchronization.
371 *
372 * IMPORTANT: You must first create the database with createIndexedDB() and
373 * pass the instance to this function. This ensures all stores are created
374 * upfront in a single upgrade transaction.
375 *
376 * @example
377 * // Step 1: Create database with all stores
378 * const db = await createIndexedDB({
379 * name: 'myApp',
380 * version: 1,
381 * stores: ['todos', 'users'],
382 * })
383 *
384 * // Step 2: Create collections using the shared database
385 * const todosCollection = createCollection(
386 * indexedDBCollectionOptions({
387 * db,
388 * name: 'todos',
389 * schema: todoSchema,
390 * getKey: (item: { id: string }) => item.id,
391 * })
392 * )
393 *
394 * @example
395 * // Without schema (explicit type)
396 * const todosCollection = createCollection(
397 * indexedDBCollectionOptions<Todo>({
398 * db,
399 * name: 'todos',
400 * getKey: (item: { id: string }) => item.id,
401 * })
402 * )
403 */
404​
405// Overload for when schema is provided
406export function indexedDBCollectionOptions<
407 T extends StandardSchemaV1,
408 TKey extends string | number = string | number,
409>(
410 config: IndexedDBCollectionConfig<InferSchemaOutput<T>, T, TKey> & {
411 schema: T
412 },
413): CollectionConfig<
414 InferSchemaOutput<T>,
415 TKey,
416 T,
417 IndexedDBCollectionUtils<InferSchemaOutput<T>, InferSchemaInput<T>>
418> & {
419 schema: T
420 utils: IndexedDBCollectionUtils<InferSchemaOutput<T>, InferSchemaInput<T>>
422​
423// Overload for when no schema is provided
424export function indexedDBCollectionOptions<
425 T extends object,
426 TKey extends string | number = string | number,
427>(
428 config: IndexedDBCollectionConfig<T, never, TKey> & {
429 schema?: never
430 },
431): CollectionConfig<T, TKey, never, IndexedDBCollectionUtils<T>> & {
432 schema?: never
433 utils: IndexedDBCollectionUtils<T>
435​
436export function indexedDBCollectionOptions(
437 config: IndexedDBCollectionConfig<Record<string, unknown>, StandardSchemaV1>,
438): CollectionConfig<
439 Record<string, unknown>,
440 string | number,
441 StandardSchemaV1,
442 IndexedDBCollectionUtils
443> & {
444 utils: IndexedDBCollectionUtils
445} {
446 const {
447 db: dbInstance,
448 name,
449 getKey,
450 onInsert,
451 onUpdate,
452 onDelete,
453 ...baseCollectionConfig
454 } = config
455​
456 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- runtime safety for JS consumers
457 if (!dbInstance) {
458 throw new DatabaseRequiredError()
459 }
460​
461 if (!name) {
462 throw new NameRequiredError()
463 }
464 if (name === VERSIONS_STORE_NAME) {
465 throw new Error(
466 'The "_versions" store is reserved for IndexedDB Collection metadata.',
467 )
468 }
469​
470 // Validate that the store exists in the database (sync check)
471 for (const storeName of [name, VERSIONS_STORE_NAME]) {
472 if (!dbInstance.db.objectStoreNames.contains(storeName)) {
473 throw new ObjectStoreNotFoundError(
474 storeName,
475 dbInstance.name,
476 Array.from(dbInstance.db.objectStoreNames),
477 )
478 }
479 }
480​
481 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
482 if (!getKey) {
483 throw new GetKeyRequiredError()
484 }
485​
486 type Item = Record<string, unknown>
487 type Mutation = {
488 type: OperationType
489 key: string | number
490 modified: Item
491 }
492 type Sync = Parameters<SyncConfig<Item>['sync']>[0]
493 const collectionId =
494 baseCollectionConfig.id ?? `indexeddb-collection:${dbInstance.name}:${name}`
495 const connection = connections.get(dbInstance.db)
496 const tabId = safeRandomUUID()
497 const versionCache = new Map<string | number, string>()
498 let collection: Sync['collection'] | undefined
499 let acceptance: Promise<void> = Promise.resolve()
500 let activeSync: Sync | undefined
501 let broadcastChannel: BroadcastChannel | undefined
502​
503 function broadcastChange(
504 changedKeys: Array<string | number>,
505 type: CrossTabMessage['type'] = 'data-changed',
506 ): void {
507 let channel = broadcastChannel
508 if (!channel) {
509 try {
510 channel = new BroadcastChannel(`tanstack-db:${dbInstance.name}`)
511 } catch {
512 return // Local persistence does not require BroadcastChannel.
513 }
514 }
515 try {
516 channel.postMessage({
517 type,
518 database: dbInstance.name,
519 name,
520 changedKeys,
521 tabId,
522 } satisfies CrossTabMessage)
523 } finally {
524 // Utility writes are legal before startup and after cleanup. Their
525 // send-only channel owns no subscription and ends with the send.
526 if (channel !== broadcastChannel) channel.close()
527 }
528 }
529​
530 // Jump to this store's compound-key prefix without ambient IDBKeyRange.
531 // Stop after its last key; sibling rows are never visited. Request errors must
532 // reject the surrounding transaction, including failures while deleting.
533 function visitVersions(
534 store: IDBObjectStore,
535 visit: (cursor: IDBCursorWithValue) => void,
536 ): Promise<void> {
537 return new Promise((resolve, reject) => {
538 const request = store.openCursor()
539 request.onerror = () => reject(request.error)
540 request.onsuccess = () => {
541 const cursor = request.result
542 if (!cursor) {
543 resolve()
544 return
545 }
546 try {
547 const [storeName] = cursor.key as [string, string | number]
548 if (storeName < name) {
549 cursor.continue([name])
550 } else if (storeName === name) {
551 visit(cursor)
552 cursor.continue()
553 } else {
554 resolve()
555 }
556 } catch (error) {
557 reject(error)
558 }
559 }
560 })
561 }
562​
563 // Stage cache changes until the ONE data-and-version transaction completes.
564 // A failed request, including synchronous structured-clone failure, aborts
565 // every mutation in this Collection's batch.
566 async function persist(
567 mutations: Array<Mutation>,
568 replace = false,
569 ): Promise<void> {
570 const versions = new Map<string | number, string>()
571 await executeTransaction(
572 dbInstance.db,
573 [name, VERSIONS_STORE_NAME],
574 'readwrite',
575 async (_, stores) => {
576 if (replace) {
577 await clear(stores[name]!)
578 await visitVersions(stores[VERSIONS_STORE_NAME]!, (cursor) => {
579 cursor.delete()
580 })
581 }
582 for (const mutation of mutations) {
583 const { key } = mutation
584 if (mutation.type === 'delete') {
585 stores[name]!.delete(key)
586 stores[VERSIONS_STORE_NAME]!.delete([name, key])
587 } else {
588 const versionKey = safeRandomUUID()
589 stores[name]!.put(mutation.modified, key)
590 stores[VERSIONS_STORE_NAME]!.put(
591 {
592 versionKey,
593 } satisfies VersionEntry,
594 [name, key],
595 )
596 versions.set(key, versionKey)
597 }
598 }
599 },
600 )
601 if (replace) versionCache.clear()
602 for (const mutation of mutations) {
603 const version = versions.get(mutation.key)
604 if (version === undefined) versionCache.delete(mutation.key)
605 else versionCache.set(mutation.key, version)
606 }
607 }
608​
609 function confirm(mutations: Array<Mutation>, replace = false): void {
610 if (!activeSync) return
611 // Core queues ordinary confirmation until optimistic settlement.
612 // Full-row update confirms put even if a peer inserted during the handler.
613 // A replacement's truncate already supplies its own publication boundary.
614 activeSync.begin()
615 if (replace) activeSync.truncate({ markReady: !connection?.error })
616 for (const mutation of mutations) {
617 activeSync.write(
618 mutation.type === 'delete'
619 ? { type: 'delete', key: mutation.key }
620 : { type: 'update', value: mutation.modified },
621 )
622 }
623 activeSync.commit()
624 }
625​
626 // Startup and replacement notifications read rows and versions from one
627 // native snapshot, then publish only into the sync run that requested it.
628 async function restore(params: Sync, replace: boolean): Promise<void> {
629 const snapshot = await executeTransaction(
630 dbInstance.db,
631 [name, VERSIONS_STORE_NAME],
632 'readonly',
633 async (_, stores) => {
634 const items = await getAll<Item>(stores[name]!)
635 const versions = new Map<string | number, string>()
636 await visitVersions(stores[VERSIONS_STORE_NAME]!, (cursor) => {
637 const [, key] = cursor.key as [string, string | number]
638 versions.set(key, (cursor.value as VersionEntry).versionKey)
639 })
640 return { items, versions }
641 },
642 )
643 if (activeSync !== params || connection?.error) return
644 versionCache.clear()
645 for (const [key, version] of snapshot.versions)
646 versionCache.set(key, version)
647 params.begin()
648 if (replace) params.truncate()
649 for (const item of snapshot.items)
650 params.write({ type: 'insert', value: item })
651 params.commit()
652 if (!replace) params.markReady()
653 }
654​
655 const internalSync: SyncConfig<Item>['sync'] = (params) => {
656 const { begin, write, commit, markError } = params
657 activeSync = params
658 collection = params.collection
659 let channel: BroadcastChannel | undefined
660 const retire = () => {
661 channel?.close()
662 if (activeSync === params) {
663 broadcastChannel = undefined
664 markError(connection?.error)
665 }
666 }
667 if (connection?.error) {
668 retire()
669 return
670 }
671 connection?.listeners.add(retire)
672​
673 try {
674 channel = new BroadcastChannel(`tanstack-db:${dbInstance.name}`)
675 broadcastChannel = channel
676 channel.onmessage = async (event: MessageEvent<CrossTabMessage>) => {
677 const message: unknown = event.data
678 if (!isCrossTabMessage(message)) return
679 if (
680 activeSync !== params ||
681 connection?.error ||
682 message.tabId === tabId ||
683 message.database !== dbInstance.name ||
684 message.name !== name
685 )
686 return
687 try {
688 if (message.type === 'database-cleared') {
689 // The notification describes an earlier replacement. Current
690 // durable rows may also contain later accepted writes.
691 await restore(params, true)
692 return
693 }
694 if (!message.changedKeys.length) return
695 const rows = await executeTransaction(
696 dbInstance.db,
697 [name, VERSIONS_STORE_NAME],
698 'readonly',
699 async (_, stores) => {
700 const result = []
701 for (const key of message.changedKeys) {
702 const [version, value] = await Promise.all([
703 getByKey<VersionEntry>(stores[VERSIONS_STORE_NAME]!, [
704 name,
705 key,
706 ]),
707 getByKey<Item>(stores[name]!, key),
708 ])
709 result.push({ key, version, value })
710 }
711 return result
712 },
713 )
714 if (activeSync !== params || connection?.error) return
715 const changes: Array<ChangeMessageOrDeleteKeyMessage<Item>> = []
716 for (const { key, version, value } of rows) {
717 const cached = versionCache.get(key)
718 if (value) {
719 if (!version || cached !== version.versionKey) {
720 changes.push({
721 type: 'update',
722 value,
723 })
724 if (version) versionCache.set(key, version.versionKey)
725 else versionCache.delete(key)
726 }
727 } else {
728 // Source deletion is independent of the optimistic public view.
729 changes.push({ type: 'delete', key })
730 versionCache.delete(key)
731 }
732 }
733 if (changes.length) {
734 begin()
735 for (const change of changes) write(change)
736 commit()
737 }
738 } catch (error) {
739 if (activeSync === params) markError(error)
740 }
741 }
742 } catch {
743 // Persistence also works in environments without BroadcastChannel.
744 }
745​
746 void restore(params, false).catch((error: unknown) => {
747 if (activeSync === params) markError(error)
748 })
749​
750 return {
751 cleanup: () => {
752 connection?.listeners.delete(retire)
753 channel?.close()
754 if (activeSync === params) {
755 activeSync = undefined
756 broadcastChannel = undefined
757 versionCache.clear()
758 }
759 },
760 }
761 }
762​
763 const acceptMutations = async (transaction: {
764 mutations: Array<PendingMutation<Item>>
765 }): Promise<void> => {
766 const mutations = transaction.mutations
767 .filter((m) => m.collection === collection)
768 .map((m) => ({
769 type: m.type,
770 key: getKey(m.modified),
771 modified: m.modified,
772 }))
773 if (!mutations.length) return
774 await persist(mutations)
775 confirm(mutations)
776 broadcastChange(mutations.map((m) => m.key))
777 }
778​
779 // Start handlers immediately, but accept successful automatic writes in
780 // invocation order. Observe rejection immediately even while a predecessor
781 // is held. Each rejected decision releases its place without persisting.
782 function persistInOrder(
783 transaction: { mutations: Array<PendingMutation<Item>> },
784 handler: () => unknown,
785 ): Promise<unknown> {
786 const result = acceptance.then(async () => {
787 const outcome = await decision
788 if (!outcome.accepted) throw outcome.error
789 await acceptMutations(transaction)
790 return outcome.value
791 })
792 acceptance = result.then(
793 () => undefined,
794 () => undefined,
795 )
796 // Reserve the position before application code can author another write.
797 const decision = new Promise<unknown>((resolve) => resolve(handler())).then(
798 (value) => ({ accepted: true as const, value }),
799 (error: unknown) => ({ accepted: false as const, error }),
800 )
801 return result
802 }
803​
804 const wrappedOnInsert = (params: InsertMutationFnParams<Item>) =>
805 persistInOrder(params.transaction, () => onInsert?.(params))
806 const wrappedOnUpdate = (params: UpdateMutationFnParams<Item>) =>
807 persistInOrder(params.transaction, () => onUpdate?.(params))
808 const wrappedOnDelete = (params: DeleteMutationFnParams<Item>) =>
809 persistInOrder(params.transaction, () => onDelete?.(params))
810​
811 const clearObjectStore = async (): Promise<void> => {
812 await persist([], true)
813 confirm([], true)
814 broadcastChange([], 'database-cleared')
815 }
816​
817 const getDatabaseInfo = async (): Promise<DatabaseInfo> => {
818 const db = dbInstance.db
819 const info: DatabaseInfo = {
820 name: db.name,
821 version: db.version,
822 objectStores: Array.from(db.objectStoreNames),
823 }
824 // Storage estimates are optional diagnostics, not a persistence prerequisite.
825 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- optional browser API at runtime
826 if (typeof navigator !== 'undefined' && navigator.storage?.estimate) {
827 try {
828 info.estimatedSize = (await navigator.storage.estimate()).usage
829 } catch {}
830 }
831 return info
832 }
833​
834 const exportData = (): Promise<Array<Item>> =>
835 executeTransaction(dbInstance.db, name, 'readonly', (_, stores) =>
836 getAll<Item>(stores[name]!),
837 )
838​
839 const importData = async (items: Array<Item>): Promise<void> => {
840 const keys = new Set<string | number>()
841 const mutations = items.map((input) => {
842 let item = input
843 if (config.schema) {
844 const result = config.schema['~standard'].validate(input)
845 if (result instanceof Promise) throw new SchemaMustBeSynchronousError()
846 if (result.issues) {
847 throw new SchemaValidationError(
848 'insert',
849 result.issues.map((issue) => ({
850 message: issue.message,
851 path: issue.path?.map(String),
852 })),
853 )
854 }
855 item = result.value as Item
856 }
857 const key = getKey(item)
858 if (keys.has(key)) throw new Error(`Duplicate imported key: ${key}`)
859 keys.add(key)
860 return { type: 'insert' as const, key, modified: structuredClone(item) }
861 })
862 await persist(mutations, true)
863 confirm(mutations, true)
864 broadcastChange([], 'database-cleared')
865 }
866​
867 const utils: IndexedDBCollectionUtils = {
868 clearObjectStore,
869 getDatabaseInfo,
870 acceptMutations,
871 exportData,
872 importData,
873 }
874 const options = {
875 ...baseCollectionConfig,
876 id: collectionId,
877 getKey,
878 sync: { sync: internalSync, rowUpdateMode: 'full' as const },
879 onInsert: wrappedOnInsert,
880 onUpdate: wrappedOnUpdate,
881 onDelete: wrappedOnDelete,
882 utils,
883 }
884 return withCollectionConfigFactory(options, () =>
885 (
886 indexedDBCollectionOptions as (
887 nextConfig: IndexedDBCollectionConfig<Item, StandardSchemaV1>,
888 ) => typeof options
889 )({ ...config, id: collectionId }),
890 )