@baukit/data-contracts-dexie 0.7.2 → 0.7.3

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@baukit/data-contracts-dexie",
3
- "version": "0.7.2",
3
+ "version": "0.7.3",
4
4
  "description": "Dexie 4.x implementation of @baukit/data-contracts for web applications.",
5
5
  "license": "MIT",
6
6
  "author": "Patrick Koss",
@@ -30,6 +30,7 @@
30
30
  },
31
31
  "files": [
32
32
  "dist",
33
+ "src",
33
34
  "README.md",
34
35
  "LICENSE"
35
36
  ],
@@ -52,7 +53,7 @@
52
53
  "vitest": "5.0.3"
53
54
  },
54
55
  "peerDependencies": {
55
- "@baukit/data-contracts": "^0.7.2",
56
+ "@baukit/data-contracts": "^0.7.3",
56
57
  "dexie": "^4.4.6"
57
58
  }
58
59
  }
@@ -0,0 +1,36 @@
1
+ import type { ContractTestRecord } from '@baukit/data-contracts/vitest';
2
+ import {
3
+ describeKeyValueContract,
4
+ describeScopedPersistenceContract,
5
+ describeTransactionalStorageContract,
6
+ } from '@baukit/data-contracts/vitest';
7
+ import { afterEach } from 'vitest';
8
+
9
+ import { type DexieStore, openDexieStore } from './index.js';
10
+
11
+ const stores: DexieStore<ContractTestRecord>[] = [];
12
+ let nextDatabase = 0;
13
+
14
+ async function makeStore(): Promise<DexieStore<ContractTestRecord>> {
15
+ const name = `baukit-browser-contract-${String(++nextDatabase)}-${crypto.randomUUID()}`;
16
+ const store = await openDexieStore<ContractTestRecord>(name);
17
+ stores.push(store);
18
+ return store;
19
+ }
20
+
21
+ afterEach(async () => {
22
+ await Promise.all(stores.splice(0).map((store) => store.close()));
23
+ });
24
+
25
+ describeKeyValueContract(async () => (await makeStore()).keyValues);
26
+ describeTransactionalStorageContract(makeStore);
27
+ describeScopedPersistenceContract(() => {
28
+ const prefix = `baukit-browser-identity-${crypto.randomUUID()}`;
29
+ return {
30
+ open: async (storeName) => {
31
+ const store = await openDexieStore<ContractTestRecord>(`${prefix}-${storeName}`);
32
+ stores.push(store);
33
+ return store;
34
+ },
35
+ };
36
+ });
@@ -0,0 +1,87 @@
1
+ import type { ContractTestRecord } from '@baukit/data-contracts/vitest';
2
+ import {
3
+ describeKeyValueContract,
4
+ describeRecordStoreContract,
5
+ describeSchemaMetadataContract,
6
+ describeScopedPersistenceContract,
7
+ describeTransactionalStorageContract,
8
+ } from '@baukit/data-contracts/vitest';
9
+ import { IDBFactory, IDBKeyRange } from 'fake-indexeddb';
10
+ import { afterEach, describe, expect, it } from 'vitest';
11
+
12
+ import { type DexieStore, openDexieStore } from './index.js';
13
+
14
+ const stores: DexieStore<ContractTestRecord>[] = [];
15
+ let nextDatabase = 0;
16
+
17
+ async function makeStore(): Promise<DexieStore<ContractTestRecord>> {
18
+ const name = `baukit-dexie-contract-${String(++nextDatabase)}`;
19
+ const store = await openDexieStore<ContractTestRecord>(name, {
20
+ indexedDB: new IDBFactory(),
21
+ IDBKeyRange,
22
+ });
23
+ stores.push(store);
24
+ return store;
25
+ }
26
+
27
+ afterEach(async () => {
28
+ await Promise.all(stores.splice(0).map((store) => store.close()));
29
+ });
30
+
31
+ describeKeyValueContract(async () => (await makeStore()).keyValues);
32
+ describeRecordStoreContract(async () => (await makeStore()).records);
33
+ describeSchemaMetadataContract(async () => (await makeStore()).schemaMetadata);
34
+ describeTransactionalStorageContract(makeStore);
35
+ describeScopedPersistenceContract(() => {
36
+ const indexedDB = new IDBFactory();
37
+ return {
38
+ open: async (storeName) => {
39
+ const store = await openDexieStore<ContractTestRecord>(storeName, {
40
+ indexedDB,
41
+ IDBKeyRange,
42
+ });
43
+ stores.push(store);
44
+ return store;
45
+ },
46
+ };
47
+ });
48
+
49
+ describe('DexieStore', () => {
50
+ it('clears a prefix made only of the highest code unit', async () => {
51
+ const { keyValues } = await makeStore();
52
+ const max = String.fromCharCode(0xffff);
53
+ for (const key of [max, `${max}${max}`, `${max}a`, 'z']) {
54
+ await keyValues.set(key, key);
55
+ }
56
+
57
+ await keyValues.clearPrefix(max);
58
+
59
+ await expect(keyValues.get(`${max}a`)).resolves.toBeUndefined();
60
+ await expect(keyValues.get(`${max}${max}`)).resolves.toBeUndefined();
61
+ await expect(keyValues.get('z')).resolves.toBe('z');
62
+ });
63
+
64
+ it('isolates separate databases', async () => {
65
+ const first = await makeStore();
66
+ const second = await makeStore();
67
+ await first.keyValues.set('same', 'first');
68
+ await second.keyValues.set('same', 'second');
69
+ await expect(first.keyValues.get('same')).resolves.toBe('first');
70
+ await expect(second.keyValues.get('same')).resolves.toBe('second');
71
+ });
72
+
73
+ it('commits the complete write set across callback microtasks', async () => {
74
+ const store = await makeStore();
75
+ await store.withTransaction(async (transaction) => {
76
+ await transaction.records.put({ id: 'a', label: 'first', payload: 1 });
77
+ await Promise.resolve('callback microtask');
78
+ await transaction.records.put({ id: 'b', label: 'second', payload: 2 });
79
+ });
80
+ await expect(store.records.list()).resolves.toMatchObject({
81
+ items: [
82
+ { id: 'a', label: 'first', payload: 1 },
83
+ { id: 'b', label: 'second', payload: 2 },
84
+ ],
85
+ });
86
+ });
87
+ });
package/src/index.ts ADDED
@@ -0,0 +1,387 @@
1
+ import {
2
+ DEFAULT_PAGE_SIZE,
3
+ MAX_PAGE_SIZE,
4
+ type JsonValue,
5
+ type KeyValueStore,
6
+ type Page,
7
+ type PageOptions,
8
+ type RecordStore,
9
+ type ReentrantStorageTransaction,
10
+ type SchemaMeta,
11
+ type SchemaMetadataStore,
12
+ StorageError,
13
+ type StoredRecord,
14
+ type TransactionalStorageStore,
15
+ normalizeStorageError,
16
+ } from '@baukit/data-contracts';
17
+ import { Dexie, type DexieOptions, type Table } from 'dexie';
18
+
19
+ interface KeyValueRow {
20
+ readonly key: string;
21
+ readonly payload: string;
22
+ }
23
+
24
+ interface RecordRow {
25
+ readonly id: string;
26
+ readonly payload: string;
27
+ }
28
+
29
+ interface SchemaRow extends SchemaMeta {
30
+ readonly key: 'schema';
31
+ }
32
+
33
+ interface Lifecycle {
34
+ status: 'closed' | 'closing' | 'open';
35
+ }
36
+
37
+ const CURSOR_PREFIX = 'dexie1:';
38
+
39
+ class BaukitDexieDatabase extends Dexie {
40
+ public readonly keyValues: Table<KeyValueRow, string>;
41
+ public readonly records: Table<RecordRow, string>;
42
+ public readonly schemaMetadata: Table<SchemaRow, string>;
43
+
44
+ public constructor(name: string, options?: DexieOptions) {
45
+ super(name, options);
46
+ this.version(1).stores({
47
+ keyValues: 'key',
48
+ records: 'id',
49
+ schemaMetadata: 'key',
50
+ });
51
+ this.keyValues = this.table('keyValues');
52
+ this.records = this.table('records');
53
+ this.schemaMetadata = this.table('schemaMetadata');
54
+ }
55
+ }
56
+
57
+ function assertOpen(lifecycle: Lifecycle): void {
58
+ if (lifecycle.status !== 'open') {
59
+ throw new StorageError('storage_closed', 'The storage adapter is closed.');
60
+ }
61
+ }
62
+
63
+ async function write<TResult>(operation: () => Promise<TResult>): Promise<TResult> {
64
+ try {
65
+ return await operation();
66
+ } catch (cause) {
67
+ throw normalizeStorageError(cause);
68
+ }
69
+ }
70
+
71
+ /** Dexie implementation of the provider-neutral key/value contract. */
72
+ export class DexieKeyValueStore implements KeyValueStore {
73
+ public constructor(
74
+ private readonly table: Table<KeyValueRow, string>,
75
+ private readonly assertAvailable: () => void,
76
+ ) {}
77
+
78
+ public async get(key: string): Promise<JsonValue | undefined> {
79
+ this.assertAvailable();
80
+ const row = await this.table.get(key);
81
+ return row === undefined ? undefined : parseJson(row.payload, 'key/value');
82
+ }
83
+
84
+ public async set(key: string, value: JsonValue): Promise<void> {
85
+ this.assertAvailable();
86
+ await write(() =>
87
+ this.table.put({ key, payload: serialize(value, 'Value') }).then(() => undefined),
88
+ );
89
+ }
90
+
91
+ public async delete(key: string): Promise<void> {
92
+ this.assertAvailable();
93
+ await write(() => this.table.delete(key));
94
+ }
95
+
96
+ public async clear(): Promise<void> {
97
+ this.assertAvailable();
98
+ await write(() => this.table.clear());
99
+ }
100
+
101
+ public async clearPrefix(prefix: string): Promise<void> {
102
+ this.assertAvailable();
103
+ const upper = prefixUpperBound(prefix);
104
+ const keys = this.table.where('key');
105
+ const range =
106
+ upper === undefined ? keys.aboveOrEqual(prefix) : keys.between(prefix, upper, true, false);
107
+ await write(() => range.delete().then(() => undefined));
108
+ }
109
+ }
110
+
111
+ const MAX_CODE_UNIT = 0xffff;
112
+
113
+ /** The smallest string above every string that starts with `prefix`, by UTF-16 code units. */
114
+ function prefixUpperBound(prefix: string): string | undefined {
115
+ for (let index = prefix.length - 1; index >= 0; index -= 1) {
116
+ const unit = prefix.charCodeAt(index);
117
+ if (unit < MAX_CODE_UNIT) {
118
+ return prefix.slice(0, index) + String.fromCharCode(unit + 1);
119
+ }
120
+ }
121
+ return undefined;
122
+ }
123
+
124
+ /** Dexie implementation of ID-ordered record storage. */
125
+ export class DexieRecordStore<T extends StoredRecord> implements RecordStore<T> {
126
+ public constructor(
127
+ private readonly table: Table<RecordRow, string>,
128
+ private readonly assertAvailable: () => void,
129
+ ) {}
130
+
131
+ public async put(record: T): Promise<void> {
132
+ this.assertAvailable();
133
+ if (record.id.length === 0) {
134
+ throw new TypeError('Record id must not be empty.');
135
+ }
136
+ await write(() =>
137
+ this.table.put({ id: record.id, payload: serialize(record, 'Record') }).then(() => undefined),
138
+ );
139
+ }
140
+
141
+ public async get(id: string): Promise<T | undefined> {
142
+ this.assertAvailable();
143
+ const row = await this.table.get(id);
144
+ return row === undefined ? undefined : (parseRecord(row.payload) as T);
145
+ }
146
+
147
+ public async delete(id: string): Promise<void> {
148
+ this.assertAvailable();
149
+ await write(() => this.table.delete(id));
150
+ }
151
+
152
+ public async list(options: PageOptions = {}): Promise<Page<T>> {
153
+ this.assertAvailable();
154
+ const limit = pageLimit(options.limit);
155
+ const afterId = decodeCursor(options.cursor);
156
+ const collection =
157
+ afterId === undefined ? this.table.orderBy('id') : this.table.where('id').above(afterId);
158
+ const rows = await collection.limit(limit + 1).toArray();
159
+ const hasNext = rows.length > limit;
160
+ const pageRows = rows.slice(0, limit);
161
+ const last = pageRows.at(-1);
162
+ return {
163
+ items: pageRows.map((row) => parseRecord(row.payload) as T),
164
+ nextCursor: hasNext && last !== undefined ? encodeCursor(last.id) : null,
165
+ };
166
+ }
167
+ }
168
+
169
+ /** Dexie implementation of portable schema metadata. */
170
+ export class DexieSchemaMetadataStore implements SchemaMetadataStore {
171
+ public constructor(
172
+ private readonly table: Table<SchemaRow, string>,
173
+ private readonly assertAvailable: () => void,
174
+ ) {}
175
+
176
+ public async getSchemaMeta(): Promise<SchemaMeta | undefined> {
177
+ this.assertAvailable();
178
+ const row = await this.table.get('schema');
179
+ return row === undefined ? undefined : { name: row.name, version: row.version };
180
+ }
181
+
182
+ public async setSchemaMeta(metadata: SchemaMeta): Promise<void> {
183
+ this.assertAvailable();
184
+ validateSchemaMeta(metadata);
185
+ await write(() =>
186
+ this.table
187
+ .put({ key: 'schema', name: metadata.name, version: metadata.version })
188
+ .then(() => undefined),
189
+ );
190
+ }
191
+ }
192
+
193
+ class DexieTransaction<T extends StoredRecord> implements ReentrantStorageTransaction<T> {
194
+ public readonly keyValues: DexieKeyValueStore;
195
+ public readonly records: DexieRecordStore<T>;
196
+ public readonly schemaMetadata: DexieSchemaMetadataStore;
197
+ private active = true;
198
+
199
+ public constructor(database: BaukitDexieDatabase) {
200
+ const assertActive = (): void => {
201
+ if (!this.active) {
202
+ throw new StorageError('storage_closed', 'The transaction context is no longer active.');
203
+ }
204
+ };
205
+ this.keyValues = new DexieKeyValueStore(database.keyValues, assertActive);
206
+ this.records = new DexieRecordStore<T>(database.records, assertActive);
207
+ this.schemaMetadata = new DexieSchemaMetadataStore(database.schemaMetadata, assertActive);
208
+ }
209
+
210
+ public async withTransaction<TResult>(
211
+ operation: (context: ReentrantStorageTransaction<T>) => Promise<TResult> | TResult,
212
+ ): Promise<TResult> {
213
+ if (!this.active) {
214
+ throw new StorageError('storage_closed', 'The transaction context is no longer active.');
215
+ }
216
+ try {
217
+ return await operation(this);
218
+ } catch (cause) {
219
+ throw normalizeStorageError(cause);
220
+ }
221
+ }
222
+
223
+ public finish(): void {
224
+ this.active = false;
225
+ }
226
+ }
227
+
228
+ export interface OpenDexieStoreOptions {
229
+ readonly indexedDB?: DexieOptions['indexedDB'];
230
+ readonly IDBKeyRange?: DexieOptions['IDBKeyRange'];
231
+ }
232
+
233
+ /** Complete Dexie 4.x adapter for Baukit's base storage contracts. */
234
+ export class DexieStore<T extends StoredRecord> implements TransactionalStorageStore<T> {
235
+ public readonly keyValues: DexieKeyValueStore;
236
+ public readonly records: DexieRecordStore<T>;
237
+ public readonly schemaMetadata: DexieSchemaMetadataStore;
238
+ private readonly lifecycle: Lifecycle = { status: 'open' };
239
+ private transactionTail: Promise<void> = Promise.resolve();
240
+
241
+ private constructor(private readonly database: BaukitDexieDatabase) {
242
+ const assertAvailable = (): void => {
243
+ assertOpen(this.lifecycle);
244
+ };
245
+ this.keyValues = new DexieKeyValueStore(database.keyValues, assertAvailable);
246
+ this.records = new DexieRecordStore<T>(database.records, assertAvailable);
247
+ this.schemaMetadata = new DexieSchemaMetadataStore(database.schemaMetadata, assertAvailable);
248
+ }
249
+
250
+ public static async open<TRecord extends StoredRecord>(
251
+ databaseName: string,
252
+ options: OpenDexieStoreOptions = {},
253
+ ): Promise<DexieStore<TRecord>> {
254
+ if (databaseName.length === 0) {
255
+ throw new TypeError('Database name must not be empty.');
256
+ }
257
+ const dexieOptions: DexieOptions = {
258
+ ...(options.indexedDB === undefined ? {} : { indexedDB: options.indexedDB }),
259
+ ...(options.IDBKeyRange === undefined ? {} : { IDBKeyRange: options.IDBKeyRange }),
260
+ };
261
+ const database = new BaukitDexieDatabase(databaseName, dexieOptions);
262
+ try {
263
+ await database.open();
264
+ return new DexieStore<TRecord>(database);
265
+ } catch (cause) {
266
+ database.close();
267
+ throw normalizeStorageError(cause);
268
+ }
269
+ }
270
+
271
+ public async withTransaction<TResult>(
272
+ operation: (context: ReentrantStorageTransaction<T>) => Promise<TResult> | TResult,
273
+ ): Promise<TResult> {
274
+ assertOpen(this.lifecycle);
275
+ const previous = this.transactionTail;
276
+ let release = (): void => undefined;
277
+ this.transactionTail = new Promise<void>((resolve) => {
278
+ release = resolve;
279
+ });
280
+ await previous;
281
+
282
+ let transaction: DexieTransaction<T> | undefined;
283
+ try {
284
+ assertOpen(this.lifecycle);
285
+ return await this.database.transaction(
286
+ 'rw!',
287
+ [this.database.keyValues, this.database.records, this.database.schemaMetadata],
288
+ async () => {
289
+ transaction = new DexieTransaction<T>(this.database);
290
+ return operation(transaction);
291
+ },
292
+ );
293
+ } catch (cause) {
294
+ throw normalizeStorageError(cause);
295
+ } finally {
296
+ transaction?.finish();
297
+ release();
298
+ }
299
+ }
300
+
301
+ public async close(): Promise<void> {
302
+ if (this.lifecycle.status === 'closed') {
303
+ return;
304
+ }
305
+ this.lifecycle.status = 'closing';
306
+ await this.transactionTail;
307
+ this.database.close();
308
+ this.lifecycle.status = 'closed';
309
+ }
310
+ }
311
+
312
+ /** Opens a Dexie-backed store and closes it if initialization fails. */
313
+ export async function openDexieStore<T extends StoredRecord>(
314
+ databaseName: string,
315
+ options: OpenDexieStoreOptions = {},
316
+ ): Promise<DexieStore<T>> {
317
+ return DexieStore.open<T>(databaseName, options);
318
+ }
319
+
320
+ function pageLimit(requested: number | undefined): number {
321
+ const limit = requested ?? DEFAULT_PAGE_SIZE;
322
+ if (!Number.isInteger(limit) || limit < 1 || limit > MAX_PAGE_SIZE) {
323
+ throw new RangeError(`Page limit must be an integer from 1 to ${String(MAX_PAGE_SIZE)}.`);
324
+ }
325
+ return limit;
326
+ }
327
+
328
+ function encodeCursor(id: string): string {
329
+ return `${CURSOR_PREFIX}${encodeURIComponent(id)}`;
330
+ }
331
+
332
+ function decodeCursor(cursor: string | null | undefined): string | undefined {
333
+ if (cursor === undefined || cursor === null) {
334
+ return undefined;
335
+ }
336
+ if (!cursor.startsWith(CURSOR_PREFIX)) {
337
+ throw new TypeError('Invalid record cursor.');
338
+ }
339
+ try {
340
+ return decodeURIComponent(cursor.slice(CURSOR_PREFIX.length));
341
+ } catch {
342
+ throw new TypeError('Invalid record cursor.');
343
+ }
344
+ }
345
+
346
+ function serialize(value: unknown, kind: string): string {
347
+ try {
348
+ const payload = JSON.stringify(value);
349
+ return payload;
350
+ } catch {
351
+ throw new TypeError(`${kind} must be JSON serializable.`);
352
+ }
353
+ }
354
+
355
+ function parseJson(payload: string, kind: string): JsonValue {
356
+ try {
357
+ return JSON.parse(payload) as JsonValue;
358
+ } catch {
359
+ throw new TypeError(`The local database contains an invalid ${kind} value.`);
360
+ }
361
+ }
362
+
363
+ function parseRecord(payload: string): StoredRecord {
364
+ try {
365
+ const value: unknown = JSON.parse(payload);
366
+ if (
367
+ typeof value !== 'object' ||
368
+ value === null ||
369
+ Array.isArray(value) ||
370
+ typeof Reflect.get(value, 'id') !== 'string'
371
+ ) {
372
+ throw new TypeError('invalid record');
373
+ }
374
+ return value as StoredRecord;
375
+ } catch {
376
+ throw new TypeError('The local database contains an invalid record.');
377
+ }
378
+ }
379
+
380
+ function validateSchemaMeta(metadata: SchemaMeta): void {
381
+ if (metadata.name.length === 0) {
382
+ throw new TypeError('Schema name must not be empty.');
383
+ }
384
+ if (!Number.isInteger(metadata.version) || metadata.version < 0) {
385
+ throw new TypeError('Schema version must be a non-negative integer.');
386
+ }
387
+ }