@signaldb/core 1.7.1 → 2.0.0-beta.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.
Files changed (93) hide show
  1. package/dist/.vite/manifest.json +138 -82
  2. package/dist/AsyncDataAdapter.d.ts +64 -0
  3. package/dist/AutoFetchDataAdapter.d.ts +112 -0
  4. package/dist/Collection/Cursor.d.ts +9 -9
  5. package/dist/Collection/Observer.d.ts +3 -2
  6. package/dist/Collection/index.d.ts +54 -46
  7. package/dist/Collection/types.d.ts +4 -9
  8. package/dist/DataAdapter.d.ts +34 -0
  9. package/dist/DefaultDataAdapter.d.ts +33 -0
  10. package/dist/WorkerDataAdapter.d.ts +25 -0
  11. package/dist/WorkerDataAdapterHost.d.ts +62 -0
  12. package/dist/createIndex.d.ts +7 -0
  13. package/dist/createStorageAdapter.d.ts +9 -0
  14. package/dist/{Collection/getIndexInfo.d.ts → getIndexInfo.d.ts} +17 -19
  15. package/dist/index.cjs.js +21 -17
  16. package/dist/index.cjs10.js +15 -26
  17. package/dist/index.cjs11.js +13 -10
  18. package/dist/index.cjs12.js +348 -3
  19. package/dist/index.cjs13.js +396 -110
  20. package/dist/index.cjs14.js +178 -68
  21. package/dist/index.cjs15.js +384 -8
  22. package/dist/index.cjs16.js +572 -20
  23. package/dist/index.cjs17.js +12 -4
  24. package/dist/index.cjs18.js +24 -5
  25. package/dist/index.cjs2.js +29 -32
  26. package/dist/index.cjs20.js +5 -13
  27. package/dist/index.cjs21.js +99 -21
  28. package/dist/index.cjs22.js +108 -58
  29. package/dist/index.cjs23.js +5 -82
  30. package/dist/index.cjs24.js +23 -14
  31. package/dist/index.cjs25.js +8 -27
  32. package/dist/index.cjs26.js +27 -7
  33. package/dist/index.cjs27.js +44 -5
  34. package/dist/index.cjs28.js +6 -27
  35. package/dist/index.cjs29.js +7 -40
  36. package/dist/index.cjs3.js +198 -444
  37. package/dist/index.cjs30.js +5 -0
  38. package/dist/index.cjs31.js +7 -0
  39. package/dist/index.cjs32.js +29 -0
  40. package/dist/index.cjs33.js +42 -0
  41. package/dist/index.cjs4.js +3 -165
  42. package/dist/index.cjs5.js +3 -66
  43. package/dist/index.cjs6.js +27 -3
  44. package/dist/index.cjs7.js +10 -3
  45. package/dist/index.cjs8.js +3 -3
  46. package/dist/index.cjs9.js +131 -3
  47. package/dist/index.d.ts +11 -8
  48. package/dist/index.mjs +15 -11
  49. package/dist/index10.mjs +15 -26
  50. package/dist/index11.mjs +13 -10
  51. package/dist/index12.mjs +348 -3
  52. package/dist/index13.mjs +396 -110
  53. package/dist/index14.mjs +178 -67
  54. package/dist/index15.mjs +384 -8
  55. package/dist/index16.mjs +572 -20
  56. package/dist/index17.mjs +12 -4
  57. package/dist/index18.mjs +24 -5
  58. package/dist/index2.mjs +29 -32
  59. package/dist/index20.mjs +5 -13
  60. package/dist/index21.mjs +99 -21
  61. package/dist/index22.mjs +108 -58
  62. package/dist/index23.mjs +5 -81
  63. package/dist/index24.mjs +23 -14
  64. package/dist/index25.mjs +8 -27
  65. package/dist/index26.mjs +27 -7
  66. package/dist/index27.mjs +44 -5
  67. package/dist/index28.mjs +6 -27
  68. package/dist/index29.mjs +7 -40
  69. package/dist/index3.mjs +198 -445
  70. package/dist/index30.mjs +6 -0
  71. package/dist/index31.mjs +8 -0
  72. package/dist/index32.mjs +30 -0
  73. package/dist/index33.mjs +43 -0
  74. package/dist/index4.mjs +3 -165
  75. package/dist/index5.mjs +3 -65
  76. package/dist/index6.mjs +27 -3
  77. package/dist/index7.mjs +10 -3
  78. package/dist/index8.mjs +3 -3
  79. package/dist/index9.mjs +131 -3
  80. package/dist/types/IndexProvider.d.ts +12 -7
  81. package/dist/types/StorageAdapter.d.ts +20 -0
  82. package/dist/utils/batchOnNextTick.d.ts +16 -0
  83. package/dist/utils/objectId.d.ts +8 -0
  84. package/dist/utils/queryId.d.ts +9 -0
  85. package/package.json +1 -1
  86. package/dist/AutoFetchCollection.d.ts +0 -60
  87. package/dist/Collection/createIndex.d.ts +0 -15
  88. package/dist/ReplicatedCollection.d.ts +0 -60
  89. package/dist/createMemoryAdapter.d.ts +0 -7
  90. package/dist/persistence/combinePersistenceAdapters.d.ts +0 -32
  91. package/dist/persistence/createPersistenceAdapter.d.ts +0 -9
  92. package/dist/types/MemoryAdapter.d.ts +0 -15
  93. package/dist/types/PersistenceAdapter.d.ts +0 -20
package/dist/index13.mjs CHANGED
@@ -1,134 +1,420 @@
1
- class EventEmitter {
2
- _maxListeners = 100;
3
- /**
4
- * We store a set of the listeners for each event.
5
- */
6
- _listenerStore = /* @__PURE__ */ new Map();
7
- setMaxListeners(max) {
8
- this._maxListeners = max;
9
- return this;
1
+ import deepClone from "./index19.mjs";
2
+ import match from "./index23.mjs";
3
+ import modify from "./index7.mjs";
4
+ import queryId from "./index20.mjs";
5
+ import isEqual from "./index6.mjs";
6
+ import getIndexInfo from "./index22.mjs";
7
+ import getMatchingKeys from "./index26.mjs";
8
+ import sortItems from "./index25.mjs";
9
+ import project from "./index24.mjs";
10
+ class AsyncDataAdapter {
11
+ options;
12
+ id;
13
+ onError;
14
+ // Per-collection resources
15
+ storageAdapters = /* @__PURE__ */ new Map();
16
+ storageAdapterReady = /* @__PURE__ */ new Map();
17
+ collectionIndices = /* @__PURE__ */ new Map();
18
+ // Per-collection query registries
19
+ queries = /* @__PURE__ */ new Map();
20
+ constructor(options) {
21
+ this.options = options;
22
+ this.id = options.id || "async-data-adapter";
23
+ this.onError = options.onError ?? ((error) => {
24
+ console.error(error);
25
+ });
26
+ }
27
+ createCollectionBackend(collection, indices) {
28
+ this.collectionIndices.set(collection.name, indices);
29
+ this.queries.set(collection.name, /* @__PURE__ */ new Map());
30
+ this.ensureStorageAdapter(collection.name);
31
+ const ready = (async () => {
32
+ try {
33
+ await this.setupStorage(collection.name, indices);
34
+ } catch (error) {
35
+ this.onError(error);
36
+ throw error;
37
+ }
38
+ })();
39
+ this.storageAdapterReady.set(collection.name, ready);
40
+ const registerQuery = (selector, options) => {
41
+ const qid = queryId(selector, options);
42
+ const registry = this.queries.get(collection.name);
43
+ if (!registry)
44
+ throw new Error(`Collection ${collection.name} not initialized!`);
45
+ registry.set(qid, {
46
+ selector,
47
+ options,
48
+ items: [],
49
+ listeners: /* @__PURE__ */ new Set(),
50
+ ...registry.get(qid),
51
+ state: "active",
52
+ error: null
53
+ });
54
+ void this.fulfillQuery(collection.name, selector, options).catch(this.onError);
55
+ };
56
+ const unregisterQuery = (selector, options) => {
57
+ const qid = queryId(selector, options);
58
+ this.queries.get(collection.name)?.delete(qid);
59
+ };
60
+ const getQueryState = (selector, options) => {
61
+ const q = this.queries.get(collection.name)?.get(queryId(selector, options));
62
+ return q?.state ?? "active";
63
+ };
64
+ const getQueryError = (selector, options) => {
65
+ const q = this.queries.get(collection.name)?.get(queryId(selector, options));
66
+ return q?.error ?? null;
67
+ };
68
+ const getQueryResult = (selector, options) => {
69
+ const q = this.queries.get(collection.name)?.get(queryId(selector, options));
70
+ return q?.items ?? [];
71
+ };
72
+ const onQueryStateChange = (selector, options, callback) => {
73
+ const qid = queryId(selector, options);
74
+ const registry = this.queries.get(collection.name);
75
+ if (!registry)
76
+ throw new Error(`Collection ${collection.name} not initialized!`);
77
+ if (!registry.has(qid)) {
78
+ registry.set(qid, {
79
+ selector,
80
+ options,
81
+ state: "active",
82
+ error: null,
83
+ items: [],
84
+ listeners: /* @__PURE__ */ new Set()
85
+ });
86
+ }
87
+ registry.get(qid)?.listeners.add(callback);
88
+ return () => registry.get(qid)?.listeners.delete(callback);
89
+ };
90
+ return {
91
+ insert: async (item) => {
92
+ await ready;
93
+ const inserted = await this.insert(collection.name, item);
94
+ return inserted;
95
+ },
96
+ updateOne: async (selector, modifier) => {
97
+ await ready;
98
+ return this.updateOne(collection.name, selector, modifier);
99
+ },
100
+ updateMany: async (selector, modifier) => {
101
+ await ready;
102
+ return this.updateMany(collection.name, selector, modifier);
103
+ },
104
+ replaceOne: async (selector, replacement) => {
105
+ await ready;
106
+ return this.replaceOne(collection.name, selector, replacement);
107
+ },
108
+ removeOne: async (selector) => {
109
+ await ready;
110
+ return this.removeOne(collection.name, selector);
111
+ },
112
+ removeMany: async (selector) => {
113
+ await ready;
114
+ return this.removeMany(collection.name, selector);
115
+ },
116
+ registerQuery,
117
+ unregisterQuery,
118
+ getQueryState,
119
+ getQueryError,
120
+ getQueryResult,
121
+ onQueryStateChange,
122
+ executeQuery: async (selector, options) => {
123
+ await ready;
124
+ registerQuery(selector, options);
125
+ const result = getQueryResult(selector, options);
126
+ unregisterQuery(selector, options);
127
+ return result;
128
+ },
129
+ dispose: async () => {
130
+ this.storageAdapters.delete(collection.name);
131
+ this.queries.delete(collection.name);
132
+ this.collectionIndices.delete(collection.name);
133
+ this.storageAdapterReady.delete(collection.name);
134
+ },
135
+ isReady: async () => {
136
+ await ready;
137
+ }
138
+ };
139
+ }
140
+ async setupStorage(collectionName, indices) {
141
+ const storage = this.storageAdapters.get(collectionName);
142
+ if (!storage)
143
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
144
+ await Promise.all(indices.map((index) => storage.createIndex(index)));
145
+ await storage.setup();
146
+ }
147
+ ensureStorageAdapter(name) {
148
+ if (this.storageAdapters.has(name))
149
+ return;
150
+ const adapter = this.options.storage(name);
151
+ if (!adapter)
152
+ return;
153
+ this.storageAdapters.set(name, adapter);
10
154
  }
11
155
  /**
12
- * Subscribe to an event with a listener function.
13
- * @param eventName The event name (key of E).
14
- * @param listener A function that receives the emitted arguments.
15
- * @returns The emitter instance (for chaining).
156
+ * Compute and publish the result for a specific query
157
+ * @param collectionName - name of the collection
158
+ * @param selector - query selector
159
+ * @param options - query options
16
160
  */
17
- on(eventName, listener) {
18
- let listenersSet = this._listenerStore.get(eventName);
19
- if (!listenersSet) {
20
- listenersSet = /* @__PURE__ */ new Set();
21
- this._listenerStore.set(eventName, listenersSet);
22
- }
23
- listenersSet.add(listener);
24
- if (listenersSet.size > this._maxListeners) {
25
- console.warn(`Possible EventEmitter memory leak detected. ${listenersSet.size} ${String(eventName)} listeners added. Use emitter.setMaxListeners() to increase limit.`);
161
+ async fulfillQuery(collectionName, selector, options) {
162
+ const qid = queryId(selector, options);
163
+ const registry = this.queries.get(collectionName);
164
+ if (!registry)
165
+ throw new Error(`Collection ${collectionName} not initialized!`);
166
+ const rec = registry.get(qid);
167
+ if (!rec)
168
+ return;
169
+ this.publishState(collectionName, qid, "active", null);
170
+ try {
171
+ const items = await this.executeQuery(collectionName, selector, options);
172
+ this.publishResult(collectionName, qid, items);
173
+ this.publishState(collectionName, qid, "complete", null);
174
+ } catch (error) {
175
+ this.publishState(collectionName, qid, "error", error);
26
176
  }
27
- return this;
28
177
  }
29
178
  /**
30
- * Subscribe to an event with a listener function.
31
- * @param eventName The event name (key of E).
32
- * @param listener A function that receives the emitted arguments.
33
- * @returns The emitter instance (for chaining).
179
+ * Notify listeners about state changes and keep the cache updated
180
+ * @param collectionName - name of the collection
181
+ * @param qid - query id
182
+ * @param state - new state
183
+ * @param error - error if state is 'error', null otherwise
34
184
  */
35
- addListener(eventName, listener) {
36
- return this.on(eventName, listener);
185
+ publishState(collectionName, qid, state, error) {
186
+ const rec = this.queries.get(collectionName)?.get(qid);
187
+ if (!rec)
188
+ return;
189
+ rec.state = state;
190
+ rec.error = error;
191
+ for (const callback of rec.listeners) {
192
+ try {
193
+ callback(state);
194
+ } catch (error_) {
195
+ this.onError(error_);
196
+ }
197
+ }
37
198
  }
38
- /**
39
- * Subscribe to an event, handling it only once. Automatically removes
40
- * the listener after it fires the first time.
41
- * @param eventName The event name (key of E).
42
- * @param listener A function that receives the emitted arguments.
43
- * @returns The emitter instance (for chaining).
44
- */
45
- once(eventName, listener) {
46
- const onceWrapper = ((...args) => {
47
- listener(...args);
48
- this.off(eventName, onceWrapper);
49
- });
50
- return this.on(eventName, onceWrapper);
199
+ publishResult(collectionName, qid, items) {
200
+ const rec = this.queries.get(collectionName)?.get(qid);
201
+ if (!rec)
202
+ return;
203
+ rec.items = items;
51
204
  }
52
- /**
53
- * Unsubscribe a previously subscribed listener.
54
- * @param eventName The event name (key of E).
55
- * @param listener The original function passed to `on` or `once`.
56
- * @returns The emitter instance (for chaining).
57
- */
58
- off(eventName, listener) {
59
- const listenersSet = this._listenerStore.get(eventName);
60
- if (!listenersSet)
61
- return this;
62
- listenersSet.delete(listener);
63
- if (listenersSet.size === 0) {
64
- this._listenerStore.delete(eventName);
205
+ async getIndexInfo(collectionName, selector) {
206
+ const storageAdapter = this.storageAdapters.get(collectionName);
207
+ if (!storageAdapter)
208
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
209
+ if (selector != null && Object.keys(selector).length === 1 && "id" in selector && typeof selector.id !== "object") {
210
+ return {
211
+ matched: true,
212
+ ids: [selector.id].filter(Boolean),
213
+ optimizedSelector: {}
214
+ };
215
+ }
216
+ if (selector == null) {
217
+ return {
218
+ matched: false,
219
+ ids: [],
220
+ optimizedSelector: {}
221
+ };
65
222
  }
66
- return this;
223
+ const indices = this.collectionIndices.get(collectionName) ?? [];
224
+ return getIndexInfo(indices.map((field) => async (flatSelector) => {
225
+ if (!Object.hasOwnProperty.call(flatSelector, field))
226
+ return { matched: false };
227
+ const index = await storageAdapter.readIndex(field);
228
+ const fieldSelector = flatSelector[field];
229
+ const filtersForNull = fieldSelector == null || fieldSelector.$exists === false;
230
+ const keys = filtersForNull ? { include: null, exclude: [...index.keys()].filter((key) => key != null) } : getMatchingKeys(field, flatSelector);
231
+ if (keys.include == null && keys.exclude == null)
232
+ return { matched: false };
233
+ let includedIds = [];
234
+ if (keys.include == null) {
235
+ for (const set of index.values())
236
+ for (const pos of set)
237
+ includedIds.push(pos);
238
+ } else {
239
+ for (const key of keys.include) {
240
+ const idSet = index.get(key);
241
+ if (idSet)
242
+ for (const id of idSet)
243
+ includedIds.push(id);
244
+ }
245
+ }
246
+ if (keys.exclude != null) {
247
+ const excludeIds = /* @__PURE__ */ new Set();
248
+ for (const key of keys.exclude) {
249
+ const idSet = index.get(key);
250
+ if (idSet)
251
+ for (const id of idSet)
252
+ excludeIds.add(id);
253
+ }
254
+ includedIds = includedIds.filter((pos) => !excludeIds.has(pos));
255
+ }
256
+ return { matched: true, ids: includedIds, fields: [field], keepSelector: filtersForNull };
257
+ }), selector);
67
258
  }
68
- /**
69
- * Unsubscribe a previously subscribed listener.
70
- * @param eventName The event name (key of E).
71
- * @param listener The original function passed to `on` or `once`.
72
- * @returns The emitter instance (for chaining).
73
- */
74
- removeListener(eventName, listener) {
75
- return this.off(eventName, listener);
259
+ async queryItems(collectionName, selector) {
260
+ const storage = this.storageAdapters.get(collectionName);
261
+ if (!storage)
262
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
263
+ const index = await this.getIndexInfo(collectionName, selector);
264
+ const matchItems = (item) => {
265
+ if (index.optimizedSelector == null)
266
+ return true;
267
+ if (Object.keys(index.optimizedSelector).length <= 0)
268
+ return true;
269
+ return match(item, index.optimizedSelector);
270
+ };
271
+ if (index.matched) {
272
+ const items = await storage.readIds(index.ids);
273
+ if (isEqual(index.optimizedSelector, {}))
274
+ return items;
275
+ return items.filter(matchItems);
276
+ } else {
277
+ const allItems = await storage.readAll();
278
+ if (isEqual(selector, {}))
279
+ return allItems;
280
+ return allItems.filter(matchItems);
281
+ }
76
282
  }
77
- /**
78
- * Emit (dispatch) an event with a variable number of arguments.
79
- * @param eventName The event name (key of E).
80
- * @param args The arguments to pass to subscribed listeners.
81
- */
82
- emit(eventName, ...args) {
83
- this.listeners(eventName).forEach((listener) => {
84
- listener(...args);
283
+ async executeQuery(collectionName, selector, options) {
284
+ const items = await this.queryItems(collectionName, selector || {});
285
+ const { sort, skip, limit, fields } = options || {};
286
+ const sorted = sort ? sortItems(items, sort) : items;
287
+ const skipped = skip ? sorted.slice(skip) : sorted;
288
+ const limited = limit ? skipped.slice(0, limit) : skipped;
289
+ const idExcluded = fields && fields.id === 0;
290
+ return limited.map((item) => {
291
+ if (!fields)
292
+ return item;
293
+ return { ...idExcluded ? {} : { id: item.id }, ...project(item, fields) };
85
294
  });
86
295
  }
87
296
  /**
88
- * Returns the array of listener functions currently registered for a given event.
89
- * @param eventName The event name (key of E).
90
- * @returns An array of listener functions.
297
+ * After mutations, recompute and push updates for affected active queries
298
+ * @param collectionName - name of the collection
299
+ * @param changedItems - items that were inserted/updated/replaced/removed
91
300
  */
92
- listeners(eventName) {
93
- const listenersSet = this._listenerStore.get(eventName);
94
- if (!listenersSet)
95
- return [];
96
- return [...listenersSet.values()];
301
+ async checkQueryUpdates(collectionName, changedItems) {
302
+ const registry = this.queries.get(collectionName);
303
+ if (!registry)
304
+ throw new Error(`Collection ${collectionName} not initialized!`);
305
+ if (registry.size === 0)
306
+ return;
307
+ const affected = [...registry.values()].filter(({ selector }) => changedItems.some((item) => match(item, selector)));
308
+ if (affected.length === 0)
309
+ return;
310
+ for (const { selector, options } of affected) {
311
+ const qid = queryId(selector, options);
312
+ this.publishState(collectionName, qid, "active", null);
313
+ }
314
+ await Promise.all(affected.map(async ({ selector, options }) => {
315
+ const qid = queryId(selector, options);
316
+ try {
317
+ const items = await this.executeQuery(collectionName, selector, options);
318
+ this.publishResult(collectionName, qid, items);
319
+ this.publishState(collectionName, qid, "complete", null);
320
+ } catch (error) {
321
+ this.publishState(collectionName, qid, "error", error);
322
+ }
323
+ }));
97
324
  }
98
- /**
99
- * Returns the number of listeners for a given event.
100
- * @param eventName The event name (key of E).
101
- * @returns The number of listeners.
102
- */
103
- listenerCount(eventName) {
104
- const listenersSet = this._listenerStore.get(eventName);
105
- return listenersSet ? listenersSet.size : 0;
325
+ async insert(collectionName, newItem) {
326
+ const storage = this.storageAdapters.get(collectionName);
327
+ if (!storage)
328
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
329
+ const existing = await this.executeQuery(collectionName, { id: newItem.id }, { limit: 1 });
330
+ if (existing.length > 0)
331
+ throw new Error(`Item with id ${String(newItem.id)} already exists`);
332
+ await storage.insert([newItem]);
333
+ await this.checkQueryUpdates(collectionName, [newItem]);
334
+ return newItem;
106
335
  }
107
- /**
108
- * Removes all listeners for a given event, or all events if none is specified.
109
- * @param eventName Optional. If omitted, clears all events’ listeners.
110
- * @returns The emitter instance (for chaining).
111
- */
112
- removeAllListeners(eventName) {
113
- if (eventName === void 0) {
114
- for (const [eventName_, listenersSet] of this._listenerStore.entries()) {
115
- for (const listener of listenersSet.values()) {
116
- this.off(eventName_, listener);
117
- }
118
- }
119
- this._listenerStore.clear();
120
- } else {
121
- const listenersSet = this._listenerStore.get(eventName);
122
- if (listenersSet) {
123
- for (const listener of listenersSet.values()) {
124
- this.off(eventName, listener);
125
- }
126
- this._listenerStore.delete(eventName);
336
+ async updateOne(collectionName, selector, modifier) {
337
+ const storage = this.storageAdapters.get(collectionName);
338
+ if (!storage)
339
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
340
+ const items = await this.executeQuery(collectionName, selector, { limit: 1 });
341
+ const [item] = items;
342
+ const { $setOnInsert, ...rest } = modifier;
343
+ if (item == null)
344
+ return [];
345
+ const modified = modify(deepClone(item), rest);
346
+ if (item.id !== modified.id) {
347
+ const existing = await this.executeQuery(collectionName, { id: modified.id }, { limit: 1 });
348
+ if (existing.length > 0)
349
+ throw new Error(`Item with id ${String(modified.id)} already exists`);
350
+ }
351
+ await storage.replace([modified]);
352
+ await this.checkQueryUpdates(collectionName, [modified]);
353
+ return [modified];
354
+ }
355
+ async updateMany(collectionName, selector, modifier) {
356
+ const storage = this.storageAdapters.get(collectionName);
357
+ if (!storage)
358
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
359
+ const items = await this.executeQuery(collectionName, selector);
360
+ if (items.length === 0)
361
+ return [];
362
+ const { $setOnInsert, ...rest } = modifier;
363
+ const changed = await Promise.all(items.map(async (item) => {
364
+ const modified = modify(deepClone(item), rest);
365
+ if (item.id !== modified.id) {
366
+ const existing = await this.executeQuery(collectionName, { id: modified.id }, { limit: 1 });
367
+ if (existing.length > 0)
368
+ throw new Error(`Item with id ${String(modified.id)} already exists`);
127
369
  }
370
+ return modified;
371
+ }));
372
+ await storage.replace(changed);
373
+ await this.checkQueryUpdates(collectionName, changed);
374
+ return changed;
375
+ }
376
+ async replaceOne(collectionName, selector, replacement) {
377
+ const storage = this.storageAdapters.get(collectionName);
378
+ if (!storage)
379
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
380
+ const items = await this.executeQuery(collectionName, selector, { limit: 1 });
381
+ const [item] = items;
382
+ if (item == null)
383
+ return [];
384
+ const modified = { ...replacement, id: replacement.id ?? item.id };
385
+ if (item.id !== modified.id) {
386
+ const existing = await this.executeQuery(collectionName, { id: modified.id }, { limit: 1 });
387
+ if (existing.length > 0)
388
+ throw new Error(`Item with id ${String(modified.id)} already exists`);
128
389
  }
129
- return this;
390
+ await storage.replace([modified]);
391
+ await this.checkQueryUpdates(collectionName, [modified]);
392
+ return [modified];
393
+ }
394
+ async removeOne(collectionName, selector) {
395
+ const storage = this.storageAdapters.get(collectionName);
396
+ if (!storage)
397
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
398
+ const items = await this.executeQuery(collectionName, selector, { limit: 1 });
399
+ const [item] = items;
400
+ if (item == null)
401
+ return [];
402
+ await storage.remove([item]);
403
+ await this.checkQueryUpdates(collectionName, [item]);
404
+ return [item];
405
+ }
406
+ async removeMany(collectionName, selector) {
407
+ const storage = this.storageAdapters.get(collectionName);
408
+ if (!storage)
409
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
410
+ const items = await this.executeQuery(collectionName, selector);
411
+ if (items.length === 0)
412
+ return [];
413
+ await storage.remove(items);
414
+ await this.checkQueryUpdates(collectionName, items);
415
+ return items;
130
416
  }
131
417
  }
132
418
  export {
133
- EventEmitter as default
419
+ AsyncDataAdapter as default
134
420
  };