Open History to see the last commit
1import { expect, it, vi } from 'vitest'
2import { z } from 'zod'
3import { createCollection } from '@tanstack/db'
4import {
5 ObjectStoreNotFoundError,
6 createIndexedDB,
7 deleteDatabase,
8 indexedDBCollectionOptions,
9 openDatabase,
10} from '../src'
11import { withHarness } from './harness'
12import type { IndexedDBCollectionConfig } from '../src'
13import type { Row } from './harness'
14
15// Fixed examples suffice for synchronous configuration validation; there is no
16// interacting history to model. The API errors, immutable database descriptor,
17// schema validation and IDs are independent of the persistence history model.
18it('validates store declarations and exposes an immutable shared descriptor', async () => {
19 for (const stores of [[], ['a', 'a'], ['']]) {
20 await expect(
21 createIndexedDB({ name: crypto.randomUUID(), version: 1, stores }),
22 ).rejects.toThrow()
23 }
24 await withHarness(async (h) => {
25 expect(Object.isFrozen(h.db)).toBe(true)
26 expect(Object.isFrozen(h.db.stores)).toBe(true)
27 const collection = await h.open()
28 expect(await collection.utils.getDatabaseInfo()).toMatchObject({
29 name: h.db.name,
30 version: 1,
31 objectStores: ['_versions', 'items', 'other'],
32 })
33 expect(collection.id).toBe('indexeddb-collection:' + h.db.name + ':items')
34 expect(h.make('items', { id: 'custom' }).id).toBe('custom')
35 })
36})
37
38it('rejects missing required configuration synchronously', async () => {
39 await withHarness((h) => {
40 const config = { db: h.db, name: 'items', getKey: (row: Row) => row.id }
41 for (const field of ['db', 'name', 'getKey'] as const) {
42 const invalid = {
43 ...config,
44 [field]: undefined,
45 } as unknown as IndexedDBCollectionConfig<Row>
46 expect(() => indexedDBCollectionOptions(invalid)).toThrow()
47 }
48 expect(() =>
49 indexedDBCollectionOptions({ ...config, name: 'absent' }),
50 ).toThrow(/not found/)
51 })
52})
53
54it('validates schema inputs before persistence', async () => {
55 await withHarness(async (h) => {
56 const collection = createCollection(
57 indexedDBCollectionOptions({
58 db: h.db,
59 name: 'items',
60 schema: z.object({ id: z.number(), name: z.string().min(1) }),
61 getKey: (row) => row.id,
62 }),
63 )
64 try {
65 await collection.preload()
66 expect(() => collection.insert({ id: 1, name: '' })).toThrow()
67 await collection.insert({ id: 1, name: 'valid' }).isPersisted.promise
68 expect(await collection.utils.exportData()).toEqual([
69 { id: 1, name: 'valid' },
70 ])
71 } finally {
72 await collection.cleanup()
73 }
74 })
75})
76
77it('supports local persistence when BroadcastChannel is unavailable', async () => {
78 await withHarness(async (h) => {
79 vi.stubGlobal('BroadcastChannel', undefined)
80 const collection = await h.open()
81 await collection.insert({ id: 1, name: 'local' }).isPersisted.promise
82 expect(await collection.utils.exportData()).toEqual([
83 { id: 1, name: 'local' },
84 ])
85 })
86})
87
88it('rejects opening without IndexedDB', async () => {
89 vi.stubGlobal('indexedDB', undefined)
90 try {
91 await expect(
92 createIndexedDB({ name: 'missing', version: 1, stores: ['items'] }),
93 ).rejects.toThrow(/not available/)
94 } finally {
95 vi.unstubAllGlobals()
96 }
97})
98
99it('exposes deletion only as an administrative function', async () => {
100 await withHarness(async (h) => {
101 const collection = await h.open()
102 await collection.insert({ id: 1, name: 'removed' }).isPersisted.promise
103 expect(collection.utils).not.toHaveProperty('deleteDatabase')
104 await deleteDatabase(h.db.name)
105 const reopened = await createIndexedDB({
106 name: h.db.name,
107 version: 1,
108 stores: ['items'],
109 })
110 try {
111 const restored = createCollection(
112 indexedDBCollectionOptions<Row>({
113 db: reopened,
114 name: 'items',
115 getKey: (row) => row.id,
116 }),
117 )
118 try {
119 await restored.preload()
120 expect(restored.size).toBe(0)
121 } finally {
122 await restored.cleanup()
123 }
124 } finally {
125 reopened.close()
126 }
127 })
128})
129
130it('validates and transforms imported schema inputs before replacing data', async () => {
131 await withHarness(async (h) => {
132 const collection = createCollection(
133 indexedDBCollectionOptions({
134 db: h.db,
135 name: 'items',
136 schema: z.object({
137 id: z.number(),
138 name: z.string().min(1).default('default'),
139 }),
140 getKey: (row) => row.id,
141 }),
142 )
143 try {
144 await collection.preload()
145 await collection.utils.importData([{ id: 1 }])
146 expect(await collection.utils.exportData()).toEqual([
147 { id: 1, name: 'default' },
148 ])
149 await expect(
150 collection.utils.importData([{ id: 2, name: '' }]),
151 ).rejects.toThrow()
152 expect(await collection.utils.exportData()).toEqual([
153 { id: 1, name: 'default' },
154 ])
155 } finally {
156 await collection.cleanup()
157 }
158 })
159})
160
161it('rejects duplicate imported keys before replacing the existing snapshot', async () => {
162 await withHarness(async (h) => {
163 const collection = await h.open()
164 const original = [{ id: 1, name: 'retained' }]
165 await collection.utils.importData(original)
166 await expect(
167 collection.utils.importData([
168 { id: 2, name: 'a' },
169 { id: 2, name: 'b' },
170 ]),
171 ).rejects.toThrow()
172 expect(await collection.utils.exportData()).toEqual(original)
173 })
174})
175
176it('reserves the version store for adapter metadata', async () => {
177 const outcome = await createIndexedDB({
178 name: crypto.randomUUID(),
179 version: 1,
180 stores: ['_versions'],
181 }).then(
182 (db) => {
183 db.close()
184 return 'accepted'
185 },
186 () => 'rejected',
187 )
188 expect(outcome).toBe('rejected')
189 await withHarness((h) => {
190 expect(() =>
191 indexedDBCollectionOptions<Row>({
192 db: h.db,
193 name: '_versions',
194 getKey: (row) => row.id,
195 }),
196 ).toThrow()
197 })
198})
199
200// A native database can predate this adapter. Reopening at the same version
201// does not run upgrade callbacks, so admission must validate metadata as well
202// as the requested store before any Collection can claim to persist writes.
203it('rejects a database without its required metadata store before startup', async () => {
204 const name = crypto.randomUUID()
205 const raw = await openDatabase(name, 1, (db) => {
206 db.createObjectStore('items')
207 })
208 raw.close()
209 const db = await createIndexedDB({ name, version: 1, stores: ['items'] })
210 try {
211 expect(() =>
212 indexedDBCollectionOptions<Row>({
213 db,
214 name: 'items',
215 getKey: (row) => row.id,
216 }),
217 ).toThrow(ObjectStoreNotFoundError)
218 } finally {
219 db.close()
220 }
221})
222
223it('labels storage estimates as origin-wide usage even for an empty database', async () => {
224 await withHarness(async (h) => {
225 vi.stubGlobal('navigator', {
226 storage: { estimate: () => Promise.resolve({ usage: 987654321 }) },
227 })
228 const c = await h.open()
229 expect(await c.utils.exportData()).toEqual([])
230 expect((await c.utils.getDatabaseInfo()).estimatedSize).toBe(987654321)
231 })
232})
233
234// Import's existing authority is schema input validation. Output from an
235// arbitrary transform need not inhabit that input domain. The invalid attempt
236// must preserve the backup; explicit inverse conversion can round trip it.
237it('preserves exported transformed rows when invalid restore input is rejected', async () => {
238 await withHarness(async (h) => {
239 const schema = z.object({
240 id: z.number(),
241 date: z.string().transform((value) => new Date(value)),
242 })
243 const c = createCollection(
244 indexedDBCollectionOptions({
245 db: h.db,
246 name: 'items',
247 schema,
248 getKey: (row) => row.id,
249 }),
250 )
251 try {
252 await c.preload()
253 await c.insert({ id: 1, date: '2026-01-01T00:00:00.000Z' }).isPersisted
254 .promise
255 const backup = await c.utils.exportData()
256 // @ts-expect-error Schema output is not the string input expected by import.
257 await expect(c.utils.importData(backup)).rejects.toThrow(
258 /Expected string/,
259 )
260 expect(await c.utils.exportData()).toEqual(backup)
261 await c.utils.importData(
262 backup.map((row) => ({ id: row.id, date: row.date.toISOString() })),
263 )
264 expect(await c.utils.exportData()).toEqual(backup)
265 } finally {
266 await c.cleanup()
267 }
268 })
269})