@asaidimu/utils-database 1.0.0 → 1.1.1

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/index.d.mts CHANGED
@@ -1,5 +1,81 @@
1
1
  import { QueryFilter, PaginationOptions } from '@asaidimu/query';
2
- import { SchemaDefinition, SchemaChange, DataTransform, PredicateMap } from '@asaidimu/anansi';
2
+ import { IndexDefinition, SchemaDefinition, SchemaChange, DataTransform, PredicateMap } from '@asaidimu/anansi';
3
+ import { EventBus } from '@asaidimu/events';
4
+ import { StandardSchemaV1 } from '@standard-schema/spec';
5
+
6
+ /**
7
+ * Buffers write operations across one or more stores and commits them atomically.
8
+ *
9
+ * ## How atomicity works
10
+ *
11
+ * ### IndexedDB stores (same database)
12
+ * At commit time, TransactionContext collects the names of every IDB store that
13
+ * received operations, then opens a **single** `IDBTransaction` spanning all of
14
+ * them via `ConnectionManager.openTransaction`. Each store's `executeInTransaction`
15
+ * receives that shared transaction object and performs its writes against it
16
+ * without opening a new transaction of its own. IDB commits or aborts the
17
+ * entire multi-store transaction as one unit.
18
+ *
19
+ * ### MemoryStore
20
+ * MemoryStore's `executeInTransaction` receives `null` for the shared transaction.
21
+ * It applies ops against an internal staging map and returns. If a later
22
+ * participant fails, TransactionContext calls `rollbackMemory` on each
23
+ * MemoryStore that already applied its staged ops. MemoryStore restores its
24
+ * pre-transaction snapshot.
25
+ *
26
+ * ### Mixed (IDB + Memory in the same transaction)
27
+ * All IDB stores are committed first as a single atomic IDB transaction, then
28
+ * each MemoryStore is committed. If a MemoryStore fails after IDB has already
29
+ * committed, the IDB side cannot be rolled back — this is an inherent limitation
30
+ * of mixing two different storage engines. In practice the schema store is
31
+ * always MemoryStore-or-IDB consistently, so mixed transactions should not arise
32
+ * in normal usage.
33
+ */
34
+ declare class TransactionContext {
35
+ readonly id: string;
36
+ /**
37
+ * Flat list of every operation staged so far, in the order they were added.
38
+ * We keep the store reference alongside the op so commit() can group them.
39
+ */
40
+ private staged;
41
+ private done;
42
+ constructor();
43
+ /**
44
+ * Stages a single write operation against a store.
45
+ * Does NOT touch the store — no I/O happens until commit().
46
+ */
47
+ addOp<T extends Record<string, any>>(store: Store<T>, type: "put" | "delete" | "add", data: any): Promise<void>;
48
+ /**
49
+ * Commits all staged operations atomically.
50
+ *
51
+ * For IDB stores: opens one shared IDBTransaction across all participating
52
+ * stores, then dispatches ops to each store's executeInTransaction.
53
+ * For MemoryStores: dispatches sequentially; rolls back on failure.
54
+ */
55
+ commit(): Promise<void>;
56
+ /**
57
+ * Discards all staged operations. No I/O has occurred so there is nothing
58
+ * to undo — we simply clear the buffer.
59
+ */
60
+ rollback(): void;
61
+ /**
62
+ * Opens ONE IDBTransaction across all participating IDB stores and lets
63
+ * each store execute its ops against the shared transaction handle.
64
+ *
65
+ * We obtain the IDBDatabase from the first store (they all share the same
66
+ * ConnectionManager / database) and open the transaction ourselves so that
67
+ * the commit/abort lifecycle belongs entirely to this method.
68
+ */
69
+ private commitIDB;
70
+ /**
71
+ * Commits MemoryStore groups sequentially.
72
+ * Maintains a list of stores that have already applied their ops; if any
73
+ * store throws, all previously-applied stores are rolled back via the
74
+ * store-level `_rollbackMemory(snapshot)` escape hatch.
75
+ */
76
+ private commitMemory;
77
+ completed(): boolean;
78
+ }
3
79
 
4
80
  declare const DEFAULT_KEYPATH = "$id";
5
81
  interface CursorPaginationOptions {
@@ -18,8 +94,9 @@ interface CursorCallbackResult<T> {
18
94
  * @template T - The type of records stored.
19
95
  * @param value - The current record value (cloned, not a live reference).
20
96
  * @param key - The key (ID) of the current record.
21
- * @param cursor - The underlying cursor object (implementationspecific; may be `null` in memory adapters).
22
- * @returns A promise that resolves to an object indicating whether iteration should stop, and an optional offset to advance.
97
+ * @param cursor - The underlying cursor object (implementation-specific; may be `null` in memory adapters).
98
+ * @returns A promise resolving to an object indicating whether iteration should stop,
99
+ * and an optional offset to advance.
23
100
  */
24
101
  type CursorCallback<T> = (value: T, key: string | number, cursor: any) => Promise<CursorCallbackResult<T>>;
25
102
  /**
@@ -31,123 +108,100 @@ interface StoreKeyRange {
31
108
  lowerOpen?: boolean;
32
109
  upperOpen?: boolean;
33
110
  }
111
+ /**
112
+ * A single buffered operation staged inside a TransactionContext.
113
+ * Kept intentionally minimal — the context only needs to know what to
114
+ * replay against a store during commit.
115
+ */
116
+ type BufferedOperation<T> = {
117
+ type: "add" | "put";
118
+ data: T | T[];
119
+ } | {
120
+ type: "delete";
121
+ data: string | number | (string | number)[];
122
+ };
34
123
  /**
35
124
  * Storage adapter interface for a single object store (collection).
36
125
  *
37
- * This interface abstracts all low‑level persistence operations, allowing
38
- * different backends (IndexedDB, memory, remote, etc.) to be used interchangeably.
39
- * All methods return promises and operate on clones of data to prevent
40
- * unintended mutations.
126
+ * Stores own their indexes. Index lifecycle (create, drop) and index-aware reads
127
+ * (findByIndex) are part of this contract so that both MemoryStore and IndexedDBStore
128
+ * implement them natively MemoryStore via in-memory index maps, IndexedDB via its
129
+ * native index mechanism.
41
130
  *
42
- * @template T - The type of objects stored in this store. Must include the key path property.
131
+ * @template T - The type of objects stored. Must include the key path property.
43
132
  */
44
- interface Store<T = any> {
133
+ interface Store<T extends Record<string, any> = Record<string, any>> {
134
+ /**
135
+ * Returns the name of this store (the IDB object store / collection name).
136
+ * Used by TransactionContext to group operations and open a correctly-scoped
137
+ * multi-store IDB transaction at commit time.
138
+ */
139
+ name(): string;
140
+ /**
141
+ * Opens the store, ensuring underlying storage structures exist.
142
+ */
143
+ open(): Promise<void>;
45
144
  /**
46
145
  * Adds one or more records to the store.
47
- *
48
146
  * If a record does not have a value for the store's key path, an automatic
49
- * key (e.g., auto‑incremented number) may be assigned. The store's key path
50
- * property is then updated on the added record(s).
51
- *
52
- * @param data - A single record or an array of records to add.
53
- * @returns A promise that resolves to:
54
- * - the key(s) of the added record(s) – a single key if `data` was a single record,
55
- * or an array of keys if `data` was an array.
56
- * @throws {Error} If any record lacks the key path property and auto‑keying is not supported,
57
- * or if a record with the same key already exists.
147
+ * key may be assigned. Throws if a record with the same key already exists.
58
148
  */
59
149
  add(data: T | T[]): Promise<string | number | (string | number)[]>;
60
150
  /**
61
- * Removes all records from the store.
62
- *
63
- * @returns A promise that resolves when the store is cleared.
64
- * @throws {Error} If the operation fails (e.g., store is closed).
151
+ * Removes all records from the store without destroying index structures.
65
152
  */
66
153
  clear(): Promise<void>;
67
154
  /**
68
155
  * Returns the total number of records in the store.
69
- *
70
- * @returns A promise that resolves to the record count.
71
- * @throws {Error} If the operation fails.
72
156
  */
73
157
  count(): Promise<number>;
74
158
  /**
75
159
  * Deletes one or more records by their keys.
76
- *
77
- * @param id - A single key or an array of keys to delete.
78
- * @returns A promise that resolves when the records are deleted.
79
- * @throws {Error} If any key is `undefined` or the operation fails.
80
160
  */
81
161
  delete(id: string | number | (string | number)[]): Promise<void>;
82
162
  /**
83
163
  * Retrieves a single record by its primary key.
84
- *
85
- * @param id - The key of the record to retrieve.
86
- * @returns A promise that resolves to the record (cloned) if found, otherwise `undefined`.
87
- * @throws {Error} If the key is `undefined` or the operation fails.
88
164
  */
89
165
  getById(id: string | number): Promise<T | undefined>;
90
166
  /**
91
- * Retrieves a single record by an index and index key.
167
+ * Retrieves the first record matching an exact index key (point lookup).
168
+ * Useful for unique indexes — returns the single matching record or undefined.
92
169
  *
93
- * @param index - The name of the index to query.
94
- * @param key - The exact key value to look up in the index.
95
- * @returns A promise that resolves to the first matching record (cloned), or `undefined` if none.
96
- * @throws {Error} If the index does not exist, the key is `undefined`, or the operation fails.
170
+ * @param indexName - The name of the index to query.
171
+ * @param key - The exact key value to look up.
97
172
  */
98
- getByIndex(index: string, key: any): Promise<T | undefined>;
173
+ getByIndex(indexName: string, key: any): Promise<T | undefined>;
99
174
  /**
100
- * Retrieves multiple records from an index, optionally within a key range.
175
+ * Retrieves all records from a named index, optionally filtered by a key range.
176
+ * Use this for range scans over an index (e.g. all records where age >= 18).
101
177
  *
102
- * @param index - The name of the index to query.
103
- * @param keyRange - Optional `StoreKeyRange` to filter results. If omitted, all records are returned.
104
- * @returns A promise that resolves to an array of matching records (each cloned).
105
- * @throws {Error} If the index does not exist or the operation fails.
178
+ * @param indexName - The name of the index to query.
179
+ * @param keyRange - Optional range to filter results.
106
180
  */
107
- getByKeyRange(index: string, keyRange?: StoreKeyRange): Promise<T[]>;
181
+ getByKeyRange(indexName: string, keyRange?: StoreKeyRange): Promise<T[]>;
108
182
  /**
109
- * Retrieves all records from the store.
110
- *
111
- * @returns A promise that resolves to an array of all records (each cloned).
112
- * @throws {Error} If the operation fails.
183
+ * Retrieves all records from the store without index involvement.
113
184
  */
114
185
  getAll(): Promise<T[]>;
115
186
  /**
116
- * Inserts or replaces a record.
117
- *
118
- * If a record with the same key already exists, it is replaced.
119
- * The record must contain the store's key path property.
120
- *
121
- * @param data - The record to store.
122
- * @returns A promise that resolves to the key of the stored record.
123
- * @throws {Error} If the record lacks the key path property or the operation fails.
187
+ * Inserts or replaces a record. Validates OCC if a record with the same key exists.
124
188
  */
125
189
  put(data: T): Promise<string | number>;
126
190
  /**
127
191
  * Iterates over records using a cursor, allowing early termination and skipping.
128
192
  *
129
- * The callback is invoked for each record in iteration order. The callback
130
- * can control the iteration by returning `{ done: true }` to stop, or
131
- * `{ offset: n }` to skip ahead `n` records.
132
- *
133
- * @param callback - Function called for each record.
134
- * @param direction - Iteration direction: `"forward"` (ascending keys) or `"backward"` (descending keys).
135
- * @param keyRange - An optional StoreKeyRange to start from specific points.
136
- * @returns A promise that resolves to the last record processed (or `null` if none).
137
- * @throws {Error} If the callback throws or the operation fails.
193
+ * @param callback - Invoked for each record; return `{ done: true }` to stop,
194
+ * `{ offset: n }` to skip ahead n records.
195
+ * @param direction - Iteration order.
196
+ * @param keyRange - Optional range to restrict iteration.
138
197
  */
139
198
  cursor(callback: CursorCallback<T>, direction?: "forward" | "backward", keyRange?: StoreKeyRange): Promise<T | null>;
140
199
  /**
141
- * Executes a batch of write operations atomically.
142
- *
143
- * All operations in the batch succeed or fail together. This is useful for
144
- * maintaining consistency when multiple writes are required.
200
+ * Executes a batch of write operations atomically within this store.
201
+ * All operations succeed or fail together.
145
202
  *
146
- * @param operations - An array of operations. Each operation can be:
147
- * - `{ type: "add" | "put", data: T | T[] }`
148
- * - `{ type: "delete", data: string | number | (string | number)[] }`
149
- * @returns A promise that resolves when the batch is committed.
150
- * @throws {Error} If any operation fails or the batch cannot be completed.
203
+ * Used for standalone (single-store) atomic writes. For cross-store atomicity,
204
+ * use executeInTransaction instead.
151
205
  */
152
206
  batch(operations: Array<{
153
207
  type: "add" | "put";
@@ -156,44 +210,81 @@ interface Store<T = any> {
156
210
  type: "delete";
157
211
  data: string | number | (string | number)[];
158
212
  }>): Promise<void>;
159
- open(): Promise<void>;
213
+ /**
214
+ * Registers a new index on the store. Idempotent — no-op if the index already exists.
215
+ * For IndexedDB, this triggers a database version upgrade.
216
+ * For MemoryStore, this builds the index map from existing records.
217
+ *
218
+ * @param definition - The full index definition from the schema.
219
+ */
220
+ createIndex(definition: IndexDefinition): Promise<void>;
221
+ /**
222
+ * Removes a named index from the store.
223
+ * For IndexedDB, this triggers a database version upgrade.
224
+ * For MemoryStore, this drops the in-memory index map.
225
+ *
226
+ * @param name - The index name as declared in IndexDefinition.name.
227
+ */
228
+ dropIndex(name: string): Promise<void>;
229
+ /**
230
+ * Returns all records matching an exact index key.
231
+ * Unlike getByIndex (which returns only the first match), this returns all matches —
232
+ * essential for non-unique indexes where multiple records share the same indexed value.
233
+ *
234
+ * @param indexName - The name of the index to query.
235
+ * @param value - The exact value to look up.
236
+ */
237
+ findByIndex(indexName: string, value: any): Promise<T[]>;
238
+ /**
239
+ * Executes a set of buffered operations as part of a cross-store atomic transaction.
240
+ *
241
+ * For IndexedDBStore: `sharedTx` is the single IDBTransaction opened across all
242
+ * participating stores. Operations are applied directly to `sharedTx.objectStore(name)`
243
+ * without opening a new transaction — IDB commits or aborts the whole thing atomically.
244
+ *
245
+ * For MemoryStore: `sharedTx` is null. The store applies ops against its own staging
246
+ * area. The caller (TransactionContext) is responsible for coordinating rollback across
247
+ * all MemoryStores if any participant fails.
248
+ *
249
+ * This method must NOT open, commit, or abort any transaction itself.
250
+ *
251
+ * @param ops - The buffered operations to apply.
252
+ * @param sharedTx - The shared IDBTransaction (IndexedDB only), or null (MemoryStore).
253
+ */
254
+ executeInTransaction(ops: BufferedOperation<T>[], sharedTx: IDBTransaction | null): Promise<void>;
160
255
  }
161
256
  interface Collection<T> {
162
257
  /**
163
258
  * Finds a single document matching the query.
164
- * @param query - The query to execute.
165
- * @returns A promise resolving to the matching document or `null` if not found.
166
259
  */
167
260
  find: (query: QueryFilter<T>) => Promise<Document<T> | null>;
168
261
  /**
169
- * Lists documents based on the provided query.
170
- * @param query - The query to list documents (supports pagination and sorting).
171
- * @returns A promise resolving to an array of documents.
262
+ * Lists documents with pagination. Returns an AsyncIterator so consumers can
263
+ * wrap it in their own iteration protocol (e.g. for-await-of via AsyncIterable).
172
264
  */
173
265
  list: (query: PaginationOptions) => Promise<AsyncIterator<Document<T>[]>>;
174
266
  /**
175
- * Filters documents based on the provided query.
176
- * @param query - The query to filter documents.
177
- * @returns A promise resolving to an array of matching documents.
267
+ * Filters all documents matching the query.
178
268
  */
179
269
  filter: (query: QueryFilter<T>) => Promise<Document<T>[]>;
180
270
  /**
181
- * Creates a new document in the schema.
271
+ * Creates a new document in the collection.
272
+ *
273
+ * When a TransactionContext is provided the initial store.add is buffered into
274
+ * the transaction rather than written immediately. The document is returned in
275
+ * its fully initialised in-memory state regardless — callers can use it before
276
+ * the transaction commits.
277
+ *
182
278
  * @param initial - The initial data for the document.
183
- * @returns A promise resolving to the created document.
279
+ * @param tx - Optional transaction to buffer the write into.
184
280
  */
185
- create: (initial: T) => Promise<Document<T>>;
281
+ create: (initial: T, tx?: TransactionContext) => Promise<Document<T>>;
186
282
  /**
187
- * Subscribes to schema-level events (e.g., "create", "update", "delete", "access").
188
- * @param event - The event type to subscribe to.
189
- * @param callback - The function to call when the event occurs.
190
- * @returns A promise resolving to an unsubscribe function.
283
+ * Subscribes to collection-level events.
191
284
  */
192
- subscribe: (event: CollectionEventType | TelemetryEventType, callback: (event: CollectionEvent<T> | TelemetryEvent) => void) => Promise<() => void>;
285
+ subscribe: (event: CollectionEventType | TelemetryEventType, callback: (event: CollectionEvent<T> | TelemetryEvent) => void) => () => void;
193
286
  /**
194
- * Validate data
195
- * @param data - The data to validate
196
- * @returns An object containing validation results
287
+ * Validates data against the collection's schema.
197
288
  */
198
289
  validate(data: Record<string, any>): Promise<{
199
290
  value?: any;
@@ -202,9 +293,10 @@ interface Collection<T> {
202
293
  path: Array<string>;
203
294
  }>;
204
295
  }>;
296
+ invalidate(): void;
205
297
  }
206
298
  /**
207
- * Event payload for DocumentCursor events.
299
+ * Event payload for Collection events.
208
300
  */
209
301
  type CollectionEventType = "document:create" | "collection:read" | "migration:start" | "migration:end";
210
302
  type CollectionEvent<T> = {
@@ -217,77 +309,51 @@ type CollectionEvent<T> = {
217
309
  };
218
310
  interface Database {
219
311
  /**
220
- * Accesses a schema model by name.
221
- * @param schemaName - The name of the schema to access.
222
- * @returns A promise resolving to the schema's DocumentCursor.
223
- * @throws DatabaseError
312
+ * Opens an existing collection by name.
224
313
  */
225
314
  collection: <T>(schemaName: string) => Promise<Collection<T>>;
226
315
  /**
227
- * Creates a new schema model.
228
- * @param schema - The schema definition.
229
- * @returns A promise resolving to the created schema's DocumentCursor.
230
- * @throws DatabaseError
316
+ * Creates a new collection from a schema definition.
231
317
  */
232
318
  createCollection: <T>(schema: SchemaDefinition) => Promise<Collection<T>>;
233
319
  /**
234
- * Deletes a schema by name.
235
- * @param schemaName - The name of the schema to delete.
236
- * @returns A promise resolving to `true` if successful, or `false` if an error occurs.
237
- * @throws DatabaseError
320
+ * Deletes a collection and its schema record.
238
321
  */
239
322
  deleteCollection: (schemaName: string) => Promise<boolean>;
240
323
  /**
241
- * Updates an existing schema.
242
- * @param schema - The updated schema definition.
243
- * @returns A promise resolving to `true` if successful, or `false` if an error occurs.
244
- * @throws DatabaseError
324
+ * Updates an existing collection's schema record.
245
325
  */
246
326
  updateCollection: (schema: SchemaDefinition) => Promise<boolean>;
247
327
  /**
248
- * Migrates an existing collection's data and updates its schema definition metadata.
249
- * This function processes data in a streaming fashion to prevent loading
250
- * the entire collection into memory.
251
- *
252
- * It will:
253
- * 1. Verify the target collection exists.
254
- * 2. Retrieve the collection's current schema definition from a metadata store ($index).
255
- * 3. Initialize a `MigrationEngine` with this schema.
256
- * 4. Allow a callback to define specific data transformations using the `MigrationEngine`.
257
- * 5. **Crucially, it uses `migrationEngine.dryRun()` to get the `newSchema` that results**
258
- * **from the transformations defined in the callback.**
259
- * 6. Execute these transformations by streaming data from the collection,
260
- * through the `MigrationEngine`, and back into the same collection.
261
- * 7. Finally, update the schema definition for the collection in the `$index` metadata store
262
- * to reflect this `newSchema`.
263
- * All these steps for data and metadata updates happen within a single atomic IndexedDB transaction.
264
- *
265
- * Note: This function focuses solely on *data transformation* and *metadata updates*.
266
- * It does NOT handle structural IndexedDB changes like adding/removing physical indexes or object stores,
267
- * which still require an `onupgradeneeded` event (i.e., a database version upgrade).
268
- *
269
- * @param name - The name of the collection (IndexedDB object store) to migrate.
270
- * @param {Object} opts - Options for the new migration
271
- * @param {SchemaChange<any>[]} opts.changes - Array of schema changes
272
- * @param {string} opts.description - Description of the migration
273
- * @param {SchemaChange<any>[]} [opts.rollback] - Optional rollback changes
274
- * @param {DataTransform<any, any>} [opts.transform] - Optional data transform
275
- * @returns A Promise resolving to `true` if the migration completes successfully,
276
- * @throws {DatabaseError} If the collection does not exist, its schema metadata is missing,
277
- * or any IndexedDB operation/streaming fails critically.
328
+ * Migrates an existing collection's data and schema definition.
329
+ * Processes data in a streaming fashion to avoid loading the full collection
330
+ * into memory.
331
+ */
332
+ migrateCollection: <T>(name: string, opts: CollectionMigrationOptions, batchSize?: number) => Promise<Collection<T>>;
333
+ /**
334
+ * Executes a callback within a TransactionContext.
335
+ * Writes buffered inside the callback are flushed atomically on commit.
336
+ * If the callback throws, the buffer is discarded (no writes are flushed).
278
337
  */
279
- migrateCollection: (name: string, opts: CollectionMigrationOptions, batchSize?: number) => Promise<boolean>;
338
+ transaction: (callback: (tx: TransactionContext) => Promise<void>) => Promise<void>;
280
339
  /**
281
- * Subscribes to database-level events (e.g., "schemaAdded", "schemaDeleted", "schemaAccessed", "migrate").
282
- * @param event - The event type to subscribe to.
283
- * @param callback - The function to call when the event occurs.
284
- * @returns A promise resolving to an unsubscribe function.
340
+ * Subscribes to database-level events.
285
341
  */
286
- subscribe: (event: DatabaseEventType | "telemetry", callback: (event: DatabaseEvent | TelemetryEvent) => void) => Promise<() => void>;
342
+ subscribe: (event: DatabaseEventType | "telemetry", callback: (event: DatabaseEvent | TelemetryEvent) => void) => () => void;
287
343
  /**
288
- * Closes the connection to the database
344
+ * Releases in-memory references and event bus subscriptions.
345
+ * Does not delete any persisted data.
289
346
  */
290
347
  close: () => void;
348
+ clear: () => Promise<void>;
349
+ /**
350
+ * Ensures a collection exists; creates it if it doesn't. Idempotent.
351
+ */
352
+ ensureCollection: (schema: SchemaDefinition) => Promise<void>;
353
+ /**
354
+ * Ensures multiple collections exist; creates any that don't. Idempotent.
355
+ */
356
+ setupCollections: (schemas: SchemaDefinition[]) => Promise<void>;
291
357
  }
292
358
  type CollectionMigrationOptions = {
293
359
  changes: SchemaChange<any>[];
@@ -295,9 +361,6 @@ type CollectionMigrationOptions = {
295
361
  rollback?: SchemaChange<any>[];
296
362
  transform?: string | DataTransform<any, any>;
297
363
  };
298
- /**
299
- * Event payload for Database events.
300
- */
301
364
  type DatabaseEventType = "collection:create" | "collection:delete" | "collection:update" | "collection:read" | "migrate";
302
365
  type DatabaseEvent = {
303
366
  type: DatabaseEventType;
@@ -307,51 +370,17 @@ type DatabaseEvent = {
307
370
  type Document<T> = {
308
371
  readonly [K in keyof T]: T[K];
309
372
  } & {
310
- /**
311
- * A unique identifier for the document
312
- * @returns A promise resolving to `true` if successful, or `false` if an error occurs.
313
- */
314
373
  $id?: string;
315
- /**
316
- * A timestamp indicating when the document was created
317
- */
318
374
  $created?: string | Date;
319
- /**
320
- * A timestamp indicating when the document was last updated
321
- */
322
375
  $updated?: string | Date;
323
- /**
324
- * A number representing how many times the document has changed
325
- */
326
376
  $version?: number;
327
- /**
328
- * Fetches the latest data from the database
329
- * @returns A promise resolving to `true` if successful, or `false` if an error occurs.
330
- */
331
377
  read: () => Promise<boolean>;
332
- /**
333
- * Updates the document with the provided properties.
334
- * @param props - Partial object containing the fields to update.
335
- * @returns A promise resolving to `true` if successful, or `false` if an error occurs.
336
- */
337
- update: (props: Partial<T>) => Promise<boolean>;
338
- /**
339
- * Deletes the document from the database.
340
- * @returns A promise resolving to `true` if successful, or `false` if an error occurs.
341
- */
342
- delete: () => Promise<boolean>;
343
- /**
344
- * Subscribes to document events (e.g., "update", "delete", "access").
345
- * @param event - The event type to subscribe to.
346
- * @param callback - The function to call when the event occurs.
347
- * @returns A promise resolving to an unsubscribe function.
348
- */
378
+ save: (tx?: TransactionContext) => Promise<boolean>;
379
+ update: (props: Partial<T>, tx?: TransactionContext) => Promise<boolean>;
380
+ delete: (tx?: TransactionContext) => Promise<boolean>;
349
381
  subscribe: (event: DocumentEventType | TelemetryEventType, callback: (event: DocumentEvent<T> | TelemetryEvent) => void) => () => void;
350
382
  state(): T;
351
383
  };
352
- /**
353
- * Event payload for DocumentModel events.
354
- */
355
384
  type DocumentEventType = "document:create" | "document:write" | "document:update" | "document:delete" | "document:read";
356
385
  type DocumentEvent<T> = {
357
386
  type: DocumentEventType;
@@ -375,7 +404,7 @@ type TelemetryEvent = {
375
404
  document?: string;
376
405
  };
377
406
  result?: {
378
- type: 'array' | string;
407
+ type: "array" | string;
379
408
  size?: number;
380
409
  };
381
410
  error: {
@@ -386,22 +415,88 @@ type TelemetryEvent = {
386
415
  };
387
416
  };
388
417
  interface DatabaseConfig {
389
- name: string;
418
+ database: string;
390
419
  keyPath?: string;
391
420
  schemasStoreName?: string;
392
421
  enableTelemetry?: boolean;
393
422
  predicates?: PredicateMap;
394
423
  validate?: boolean;
395
424
  }
425
+ type StoreConfig = DatabaseConfig & {
426
+ collection: string;
427
+ };
396
428
 
429
+ /**
430
+ * Internal structure for a single maintained index.
431
+ */
432
+ interface IndexEntry {
433
+ definition: IndexDefinition;
434
+ /** Maps a composite/single index key → set of record primary keys ($id) */
435
+ map: Map<string, Set<string | number>>;
436
+ }
437
+ /**
438
+ * Snapshot of the store's mutable state, used for cross-store transaction rollback.
439
+ */
440
+ interface MemoryStoreSnapshot {
441
+ data: Map<string | number, Readonly<Record<string, any>>>;
442
+ indexes: Map<string, IndexEntry>;
443
+ nextId: number;
444
+ }
397
445
  declare class MemoryStore<T extends Record<string, any>> implements Store<T> {
446
+ private readonly storeName;
398
447
  private readonly keyPath;
399
448
  private data;
449
+ private indexes;
400
450
  private nextId;
401
- constructor(keyPath?: string);
451
+ /**
452
+ * @param storeName - The logical name of this store (matches the collection name).
453
+ * @param keyPath - The primary key field name (default: "$id").
454
+ * @param indexDefs - Index definitions from the schema. The store will maintain
455
+ * these indexes on every write operation.
456
+ */
457
+ constructor(storeName: string, keyPath?: string, indexDefs?: IndexDefinition[]);
458
+ name(): string;
402
459
  open(): Promise<void>;
403
- private getKey;
404
- private clone;
460
+ /**
461
+ * Returns a deep snapshot of the store's mutable state.
462
+ * Called by TransactionContext immediately before executeInTransaction so
463
+ * that if a later store in the same transaction fails, this store can be
464
+ * fully restored via _rollbackMemory.
465
+ *
466
+ * Prefixed with underscore to signal it is an internal contract between
467
+ * MemoryStore and TransactionContext — not part of the public Store API.
468
+ */
469
+ _snapshotMemory(): MemoryStoreSnapshot;
470
+ /**
471
+ * Restores the store to a previously snapshotted state.
472
+ * Called by TransactionContext when a later participant in the same
473
+ * cross-store transaction fails, requiring all already-applied stores to
474
+ * be unwound.
475
+ */
476
+ _rollbackMemory(snapshot: MemoryStoreSnapshot): void;
477
+ /**
478
+ * Registers a new index. Idempotent — no-op if the name already exists.
479
+ * Immediately indexes all existing records so the index is consistent.
480
+ */
481
+ createIndex(definition: IndexDefinition): Promise<void>;
482
+ /**
483
+ * Removes a named index. No-op if the index does not exist.
484
+ */
485
+ dropIndex(name: string): Promise<void>;
486
+ /**
487
+ * Returns the first record whose indexed value exactly matches `value`.
488
+ * Intended for unique indexes — for non-unique indexes use findByIndex.
489
+ */
490
+ getByIndex(indexName: string, value: any): Promise<T | undefined>;
491
+ /**
492
+ * Returns all records whose indexed value exactly matches `value`.
493
+ * O(k) where k is the result set size — avoids a full table scan.
494
+ */
495
+ findByIndex(indexName: string, value: any): Promise<T[]>;
496
+ /**
497
+ * Returns all records from a named index within an optional key range.
498
+ */
499
+ getByKeyRange(indexName: string, keyRange?: StoreKeyRange): Promise<T[]>;
405
500
  add(data: T | T[]): Promise<string | number | (string | number)[]>;
406
501
  put(data: T): Promise<string | number>;
407
502
  batch(operations: Array<{
@@ -411,15 +506,47 @@ declare class MemoryStore<T extends Record<string, any>> implements Store<T> {
411
506
  type: "delete";
412
507
  data: string | number | (string | number)[];
413
508
  }>): Promise<void>;
414
- getById(id: string | number): Promise<T | undefined>;
415
509
  delete(id: string | number | (string | number)[]): Promise<void>;
416
510
  clear(): Promise<void>;
417
- count(): Promise<number>;
418
- getByIndex(index: string, key: any): Promise<T | undefined>;
419
- getByKeyRange(indexName: string, keyRange?: StoreKeyRange): Promise<T[]>;
420
- private isInKeyRange;
511
+ /**
512
+ * Applies buffered ops directly to the live data and index maps.
513
+ *
514
+ * `sharedTx` is always null for MemoryStore — there is no shared transaction
515
+ * object. Atomicity across multiple MemoryStores is managed by the caller
516
+ * (TransactionContext), which takes a snapshot via _snapshotMemory() before
517
+ * calling this method and calls _rollbackMemory(snapshot) if a later store
518
+ * in the same transaction fails.
519
+ *
520
+ * This method applies ops eagerly (no staging) because the snapshot already
521
+ * guards against partial failure at the cross-store level.
522
+ */
523
+ executeInTransaction(ops: BufferedOperation<T>[], sharedTx: IDBTransaction | null): Promise<void>;
524
+ getById(id: string | number): Promise<T | undefined>;
421
525
  getAll(): Promise<T[]>;
526
+ count(): Promise<number>;
422
527
  cursor(callback: CursorCallback<T>, direction?: "forward" | "backward", keyRange?: StoreKeyRange): Promise<T | null>;
528
+ private getKey;
529
+ private clone;
530
+ /**
531
+ * Adds a document to all index maps. Skips indexes where the document
532
+ * does not satisfy partial conditions or is missing indexed fields.
533
+ */
534
+ private indexDocument;
535
+ private indexOne;
536
+ /**
537
+ * Removes a document from all index maps.
538
+ */
539
+ private unindexDocument;
540
+ /**
541
+ * Enforces unique index constraints before a write.
542
+ * Throws CONFLICT if another record (other than `existing`) already holds the
543
+ * same indexed value for any unique index.
544
+ *
545
+ * @param incoming - The record about to be written.
546
+ * @param existing - The record currently stored at this key (undefined for new records).
547
+ */
548
+ private enforceUniqueIndexes;
549
+ private isInKeyRange;
423
550
  }
424
551
 
425
552
  declare function createEphemeralStore<T extends Record<string, any>>(config: DatabaseConfig): MemoryStore<T>;
@@ -432,77 +559,125 @@ declare class ConnectionManager {
432
559
  private readonly config;
433
560
  private connectionInitializer;
434
561
  private readonly schemasStoreName;
562
+ constructor(config: DatabaseConfig);
563
+ private openDatabase;
435
564
  /**
436
- * Initializes a new ConnectionManager.
565
+ * Bumps the database version and runs the provided upgrade callback.
566
+ * The callback receives both the IDBDatabase and the active IDBTransaction
567
+ * so callers can access existing object stores via tx.objectStore(name).
437
568
  *
438
- * @param config - The database configuration options.
569
+ * Note: IDB only allows structural changes (createObjectStore, createIndex,
570
+ * deleteIndex) inside an onupgradeneeded handler. This method is the single
571
+ * entry point for all such changes.
439
572
  */
440
- constructor(config: DatabaseConfig);
573
+ private upgradeDatabase;
441
574
  /**
442
- * Opens the database and ensures the base schemas store exists.
575
+ * Ensures a collection object store exists, creating it (and its indexes) if absent.
576
+ * Triggers an upgrade only when the store does not yet exist; if it already exists,
577
+ * this is a fast no-op.
443
578
  *
444
- * @returns A promise that resolves to the opened IDBDatabase instance.
445
- * @throws {Error} If the database fails to open.
579
+ * @param collection - Name of the IDB object store.
580
+ * @param keyPath - Primary key field (default: "$id").
581
+ * @param indexes - Index definitions to create alongside the store.
582
+ * These are only applied during the initial store creation.
583
+ * Use createStoreIndex / dropStoreIndex for post-creation changes.
446
584
  */
447
- private openDatabase;
585
+ ensureStore(collection: string, keyPath?: string, indexes?: IndexDefinition[]): Promise<void>;
448
586
  /**
449
- * Upgrades the database version and executes the provided upgrade logic.
587
+ * Adds a named index to an existing object store.
588
+ * Triggers a database version upgrade.
450
589
  *
451
- * @param currentConnection - The existing active IndexedDB connection to be closed.
452
- * @param upgradeCallback - A callback function containing the structural changes to apply during the upgrade.
453
- * @returns A promise that resolves to the newly upgraded IDBDatabase instance.
454
- * @throws {Error} If the database upgrade fails.
590
+ * @param collection - The object store to add the index to.
591
+ * @param definition - The index definition.
455
592
  */
456
- private upgradeDatabase;
593
+ createStoreIndex(collection: string, definition: IndexDefinition): Promise<void>;
457
594
  /**
458
- * Ensures a collection object store exists within the database.
459
- * Triggers an upgrade if the specified store is missing.
595
+ * Removes a named index from an existing object store.
596
+ * Triggers a database version upgrade.
460
597
  *
461
- * @param collectionName - The name of the collection store to ensure.
462
- * @param keyPath - The primary key path for the collection (defaults to "$id").
463
- * @returns A promise that resolves when the store is confirmed to exist.
598
+ * @param storeName - The object store to remove the index from.
599
+ * @param indexName - The name of the index to remove.
464
600
  */
465
- ensureStore(collectionName: string, keyPath?: string): Promise<void>;
601
+ dropStoreIndex(storeName: string, indexName: string): Promise<void>;
466
602
  /**
467
603
  * Retrieves or opens the active database connection.
468
- * Handles connection loss and version changes automatically.
469
- *
470
- * @returns A promise resolving to the active IDBDatabase connection.
471
- * @throws {DatabaseError} If the connection initialization fails.
472
604
  */
473
605
  getConnection: () => Promise<IDBDatabase>;
474
606
  /**
475
- * Performs a version upgrade using custom structural logic.
476
- * Resets the internal initialization state so subsequent callers wait for the new version.
607
+ * Opens a readwrite IDBTransaction spanning the given store names.
608
+ *
609
+ * This is the entry point for all cross-store atomic writes. The returned
610
+ * transaction is NOT managed here — the caller (TransactionContext) owns the
611
+ * commit/abort lifecycle by wiring oncomplete / onerror / onabort handlers.
612
+ *
613
+ * All named stores must already exist (i.e. ensureStore must have been called
614
+ * for each before this point). Requesting a store that doesn't exist will cause
615
+ * IDB to throw a DOMException synchronously when the transaction is opened.
616
+ *
617
+ * @param storeNames - Object store names to include in the transaction.
618
+ * @param mode - IDB transaction mode (default: "readwrite").
619
+ */
620
+ openTransaction(storeNames: string[], mode?: IDBTransactionMode): Promise<IDBTransaction>;
621
+ /**
622
+ * Performs a version upgrade. Resets the internal initialiser so concurrent
623
+ * callers wait for the upgraded connection rather than using the stale one.
477
624
  *
478
- * @param upgradeLogic - A callback executed during the IndexedDB upgradeneeded event.
479
- * @returns A promise resolving to the upgraded IDBDatabase connection.
480
- * @throws {DatabaseError} If the internal upgrade procedure fails.
625
+ * The callback receives both `db` (for creating new stores) and `tx`
626
+ * (for accessing existing stores to add/remove indexes).
481
627
  */
482
- upgrade(upgradeLogic: (db: IDBDatabase) => void): Promise<IDBDatabase>;
628
+ upgrade(upgradeLogic: (db: IDBDatabase, tx: IDBTransaction) => void): Promise<IDBDatabase>;
483
629
  /**
484
- * Closes the active database connection and resets the internal initialization state.
630
+ * Closes the active connection and resets the initialiser.
631
+ * Does not delete any persisted data.
485
632
  */
486
633
  close(): void;
487
634
  }
488
635
 
489
636
  declare class IndexedDBStore<T extends Record<string, any>> implements Store<T> {
490
- private readonly getConnection;
491
- private readonly storeName;
637
+ private readonly connectionManager;
638
+ private readonly collection;
492
639
  private readonly keyPath;
493
- private readonly onOpen;
494
- constructor(getConnection: () => Promise<IDBDatabase>, storeName: string, keyPath: string | undefined, onOpen: () => Promise<void>);
640
+ private readonly indexes;
641
+ constructor(connectionManager: ConnectionManager, collection: string, keyPath?: string, indexes?: IndexDefinition[]);
642
+ name(): string;
643
+ /**
644
+ * Internal escape hatch used by TransactionContext to obtain the shared
645
+ * IDBDatabase so it can open a single multi-store IDBTransaction.
646
+ *
647
+ * Prefixed with underscore to signal that nothing outside of
648
+ * TransactionContext should call this directly.
649
+ */
650
+ _getIDBConnection(): Promise<IDBDatabase>;
651
+ /**
652
+ * Ensures the underlying IDB object store (and its declared indexes) exist.
653
+ * Safe to call multiple times — no-op if the store is already present.
654
+ */
495
655
  open(): Promise<void>;
496
656
  /**
497
- * Map native DOMExceptions to internal DatabaseErrors.
657
+ * Adds a new index to the IDB object store. Triggers a database version upgrade.
658
+ * Idempotent — no-op if the index already exists.
498
659
  */
499
- private mapError;
660
+ createIndex(definition: IndexDefinition): Promise<void>;
500
661
  /**
501
- * Core wrapper for transaction safety. It converts IDB request callbacks
502
- * into a single Promise while preserving transaction activity.
662
+ * Removes a named index from the IDB object store. Triggers a version upgrade.
663
+ * No-op if the index does not exist.
503
664
  */
504
- private withTx;
505
- private requestToPromise;
665
+ dropIndex(name: string): Promise<void>;
666
+ /**
667
+ * Returns the first record matching an exact index key.
668
+ * Use for unique index point lookups.
669
+ */
670
+ getByIndex(indexName: string, key: any): Promise<T | undefined>;
671
+ /**
672
+ * Returns all records from a named index within an optional key range.
673
+ */
674
+ getByKeyRange(indexName: string, keyRange?: StoreKeyRange): Promise<T[]>;
675
+ /**
676
+ * Returns all records whose indexed value exactly matches `value`.
677
+ * Unlike getByIndex, this uses index.getAll(IDBKeyRange.only(value)) so it
678
+ * correctly returns multiple records for non-unique indexes.
679
+ */
680
+ findByIndex(indexName: string, value: any): Promise<T[]>;
506
681
  put(data: T): Promise<string | number>;
507
682
  add(data: T | T[]): Promise<string | number | (string | number)[]>;
508
683
  batch(operations: Array<{
@@ -512,16 +687,106 @@ declare class IndexedDBStore<T extends Record<string, any>> implements Store<T>
512
687
  type: "delete";
513
688
  data: string | number | (string | number)[];
514
689
  }>): Promise<void>;
515
- getById(id: string | number): Promise<T | undefined>;
516
690
  delete(id: string | number | (string | number)[]): Promise<void>;
517
691
  clear(): Promise<void>;
518
- count(): Promise<number>;
519
- getByIndex(indexName: string, key: any): Promise<T | undefined>;
520
- getByKeyRange(indexName: string, keyRange?: StoreKeyRange): Promise<T[]>;
692
+ /**
693
+ * Executes buffered ops against a shared IDBTransaction opened by
694
+ * TransactionContext. This method MUST NOT open, commit, or abort a
695
+ * transaction — the caller owns the transaction lifecycle entirely.
696
+ *
697
+ * @param ops - Operations to apply.
698
+ * @param sharedTx - The IDBTransaction shared across all participating stores.
699
+ * Never null for IndexedDBStore.
700
+ */
701
+ executeInTransaction(ops: BufferedOperation<T>[], sharedTx: IDBTransaction | null): Promise<void>;
702
+ getById(id: string | number): Promise<T | undefined>;
521
703
  getAll(): Promise<T[]>;
704
+ count(): Promise<number>;
522
705
  cursor(callback: CursorCallback<T>, direction?: "forward" | "backward", keyRange?: StoreKeyRange): Promise<T | null>;
706
+ private mapError;
707
+ /**
708
+ * Opens a fresh single-store IDB transaction for standalone (non-atomic)
709
+ * operations. Not used by executeInTransaction — that receives an externally
710
+ * managed shared transaction.
711
+ */
712
+ private withTx;
713
+ private requestToPromise;
714
+ }
715
+
716
+ /**
717
+ * Retrieves or creates an IndexedDB store instance.
718
+ * * This function utilizes a synchronous execution path to retrieve the
719
+ * ConnectionManager. If the connection is currently being initialized
720
+ * asynchronously, or if the lock is contended, it throws a DatabaseError.
721
+ *
722
+ * @template T - The schema type for the collection.
723
+ * @param config - The database and collection configuration.
724
+ * @returns A functional Store instance.
725
+ * @throws {DatabaseError} CONNECTION_FAILED if the manager is busy or fails to init.
726
+ */
727
+ declare const createIndexedDbStore: <T extends Record<string, any>>(config: StoreConfig) => Store<T>;
728
+
729
+ declare function DatabaseConnection(config: Omit<DatabaseConfig, "keyPath">, createStore: <T extends Record<string, any>>(config: StoreConfig, indexes: IndexDefinition[]) => Store<T>): Promise<Database>;
730
+
731
+ interface MiddlewareContext {
732
+ collection?: string;
733
+ documentId?: string;
734
+ operation: string;
735
+ args: any[];
736
+ eventBus?: EventBus<any>;
737
+ }
738
+ type MaybePromise<T> = T | Promise<T>;
739
+ type MiddlewareNext = () => MaybePromise<any>;
740
+ type Middleware = (ctx: MiddlewareContext, next: MiddlewareNext) => MaybePromise<any>;
741
+ declare class Pipeline {
742
+ private middlewares;
743
+ use(middleware: Middleware): void;
744
+ execute(ctx: MiddlewareContext, finalOperation: () => MaybePromise<any>): MaybePromise<any>;
745
+ wrap<T extends object>(target: T, baseContext: Partial<MiddlewareContext>): T;
746
+ }
747
+
748
+ declare class Mutex {
749
+ private queue;
750
+ private locked;
751
+ acquire(): Promise<() => void>;
752
+ private release;
523
753
  }
524
754
 
525
- declare const createIndexedDbStore: <T extends Record<string, any>>(config: DatabaseConfig) => Store<T>;
755
+ interface DocumentOptions<T extends Record<string, any>> {
756
+ /**
757
+ * The already-persisted initial state of the document.
758
+ * createDocument does NOT call store.add — the caller is responsible
759
+ * for having written this record before constructing the document proxy.
760
+ */
761
+ initial: Partial<T>;
762
+ collection: string;
763
+ validator?: StandardSchemaV1;
764
+ store: Store<T>;
765
+ bus: EventBus<Record<DocumentEventType | TelemetryEventType, DocumentEvent<T> | TelemetryEvent>>;
766
+ pipeline: Pipeline;
767
+ lockManager: Mutex;
768
+ }
769
+ /**
770
+ * Constructs an in-memory Document proxy around an already-persisted record.
771
+ *
772
+ * Responsibility split:
773
+ * - createDocument: validates, initialises in-memory state, wires operations. NO I/O.
774
+ * - openCollection.create: owns the initial store.add (or tx.addOp for transactional creates).
775
+ *
776
+ * This separation ensures that transactional creates are correctly buffered:
777
+ * the document object is available immediately in-memory, while the actual
778
+ * store write is deferred until transaction commit.
779
+ */
780
+ declare function createDocument<T extends Record<string, any>>(opts: DocumentOptions<T>): Promise<Document<T & {
781
+ $id: string | number;
782
+ }>>;
783
+ declare function openCollection<T extends Record<string, any>>({ collection: schema, validator, bus, store, pipeline, validate, }: {
784
+ store: Store<T>;
785
+ collection: string;
786
+ validator: StandardSchemaV1;
787
+ bus: EventBus<any>;
788
+ pipeline: Pipeline;
789
+ validate: boolean;
790
+ }): Promise<Collection<T>>;
526
791
 
527
- export { type Collection, type CollectionEvent, type CollectionEventType, type CollectionMigrationOptions, ConnectionManager, type CursorCallback, type CursorCallbackResult, type CursorPaginationOptions, DEFAULT_KEYPATH, type Database, type DatabaseConfig, type DatabaseEvent, type DatabaseEventType, type Document, type DocumentEvent, type DocumentEventType, IndexedDBStore, type Store, type StoreKeyRange, type TelemetryEvent, type TelemetryEventType, createEphemeralStore, createIndexedDbStore };
792
+ export { type BufferedOperation, type Collection, type CollectionEvent, type CollectionEventType, type CollectionMigrationOptions, ConnectionManager, type CursorCallback, type CursorCallbackResult, type CursorPaginationOptions, DEFAULT_KEYPATH, type Database, type DatabaseConfig, DatabaseConnection, type DatabaseEvent, type DatabaseEventType, type Document, type DocumentEvent, type DocumentEventType, IndexedDBStore, type Store, type StoreConfig, type StoreKeyRange, type TelemetryEvent, type TelemetryEventType, createDocument, createEphemeralStore, createIndexedDbStore, openCollection };