@signaldb/core 2.0.0-beta.3 → 2.0.0-beta.5

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 (54) hide show
  1. package/dist/.vite/manifest.json +24 -18
  2. package/dist/Collection/Observer.d.ts +2 -0
  3. package/dist/Collection/index.d.ts +11 -10
  4. package/dist/Collection/types.d.ts +7 -0
  5. package/dist/DefaultDataAdapter.d.ts +2 -0
  6. package/dist/index.cjs.js +8 -5
  7. package/dist/index.cjs12.js +41 -346
  8. package/dist/index.cjs13.js +308 -362
  9. package/dist/index.cjs14.js +387 -177
  10. package/dist/index.cjs15.js +182 -364
  11. package/dist/index.cjs16.js +287 -478
  12. package/dist/index.cjs17.js +563 -136
  13. package/dist/index.cjs18.js +154 -23
  14. package/dist/index.cjs19.js +23 -39
  15. package/dist/index.cjs2.js +1 -1
  16. package/dist/index.cjs20.js +39 -13
  17. package/dist/index.cjs21.js +14 -102
  18. package/dist/index.cjs22.js +93 -118
  19. package/dist/index.cjs23.js +127 -5
  20. package/dist/index.cjs24.js +5 -25
  21. package/dist/index.cjs25.js +24 -7
  22. package/dist/index.cjs26.js +8 -27
  23. package/dist/index.cjs27.js +25 -42
  24. package/dist/index.cjs28.js +44 -6
  25. package/dist/index.cjs29.js +6 -7
  26. package/dist/index.cjs3.js +9 -26
  27. package/dist/index.cjs34.js +9 -0
  28. package/dist/index.cjs7.js +1 -1
  29. package/dist/index.d.ts +2 -1
  30. package/dist/index.mjs +10 -7
  31. package/dist/index12.mjs +40 -346
  32. package/dist/index13.mjs +308 -362
  33. package/dist/index14.mjs +387 -177
  34. package/dist/index15.mjs +182 -364
  35. package/dist/index16.mjs +287 -478
  36. package/dist/index17.mjs +563 -136
  37. package/dist/index18.mjs +154 -23
  38. package/dist/index19.mjs +23 -38
  39. package/dist/index2.mjs +1 -1
  40. package/dist/index20.mjs +38 -13
  41. package/dist/index21.mjs +14 -102
  42. package/dist/index22.mjs +93 -117
  43. package/dist/index23.mjs +126 -5
  44. package/dist/index24.mjs +5 -25
  45. package/dist/index25.mjs +24 -7
  46. package/dist/index26.mjs +8 -27
  47. package/dist/index27.mjs +25 -42
  48. package/dist/index28.mjs +44 -6
  49. package/dist/index29.mjs +6 -7
  50. package/dist/index3.mjs +9 -26
  51. package/dist/index34.mjs +10 -0
  52. package/dist/index7.mjs +1 -1
  53. package/dist/utils/reactiveOrAsync.d.ts +59 -0
  54. package/package.json +1 -1
package/dist/index14.mjs CHANGED
@@ -1,207 +1,417 @@
1
- import queryId from "./index20.mjs";
2
- import randomId from "./index8.mjs";
3
- import batchOnNextTick from "./index27.mjs";
4
- class WorkerDataAdapter {
5
- worker;
1
+ import deepClone from "./index20.mjs";
2
+ import match from "./index24.mjs";
3
+ import modify from "./index7.mjs";
4
+ import queryId from "./index21.mjs";
5
+ import isEqual from "./index6.mjs";
6
+ import getIndexInfo from "./index23.mjs";
7
+ import getMatchingKeys from "./index27.mjs";
8
+ import sortItems from "./index26.mjs";
9
+ import project from "./index25.mjs";
10
+ class AsyncDataAdapter {
6
11
  options;
7
12
  id;
8
- isDisposed = false;
9
- workerReady;
10
- log = () => {
11
- };
12
- collectionReady = /* @__PURE__ */ new Map();
13
- batchExecutionHelpers = /* @__PURE__ */ new Map();
14
- queries = {};
15
- constructor(worker, options) {
16
- this.worker = worker;
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) {
17
21
  this.options = options;
18
- this.id = this.options.id || "default-worker-data-adapter";
19
- if (this.options.log)
20
- this.log = this.options.log;
21
- this.workerReady = new Promise((resolve, reject) => {
22
- const timeoutId = setTimeout(() => {
23
- reject(new Error("WorkerDataAdapter initialization timed out"));
24
- }, 5e3);
25
- const handleMessage = (event) => {
26
- const { type, workerId } = event.data;
27
- if (workerId !== this.id)
28
- return;
29
- if (type === "ready") {
30
- resolve();
31
- clearTimeout(timeoutId);
32
- this.worker.removeEventListener("message", handleMessage);
33
- }
34
- };
35
- this.worker.addEventListener("message", handleMessage);
22
+ this.id = options.id || "async-data-adapter";
23
+ this.onError = options.onError ?? ((error) => {
24
+ console.error(error);
36
25
  });
37
26
  }
38
- async exec(method, collectionName, ...args) {
39
- await this.workerReady;
40
- if (method !== "isReady") {
41
- const collectionReady = this.collectionReady.get(collectionName);
42
- if (!collectionReady)
43
- throw new Error(`Collection "${collectionName}" is not registered in WorkerDataAdapter`);
44
- await collectionReady;
45
- }
46
- if (this.isDisposed) {
47
- throw new Error("WorkerDataAdapter is disposed");
48
- }
49
- return new Promise((resolve, reject) => {
50
- const messageId = randomId();
51
- const handleMessage = (event) => {
52
- const { id, workerId, type, data, error } = event.data;
53
- if (workerId !== this.id)
54
- return;
55
- if (type !== "response")
56
- return;
57
- if (id !== messageId)
58
- return;
59
- this.log(method, "result", data ?? error);
60
- if (error) {
61
- reject(error);
62
- } else {
63
- resolve(data);
64
- }
65
- this.worker.removeEventListener("message", handleMessage);
66
- };
67
- this.worker.addEventListener("message", handleMessage);
68
- this.worker.postMessage({
69
- id: messageId,
70
- workerId: this.id,
71
- method,
72
- args: [collectionName, ...args]
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
73
53
  });
74
- });
75
- }
76
- enqueueBatched(collectionName, method, args) {
77
- const helper = this.batchExecutionHelpers.get(collectionName);
78
- if (!helper)
79
- throw new Error(`Collection "${collectionName}" is not registered in WorkerDataAdapter`);
80
- return helper.enqueue(method, args);
81
- }
82
- // ---------- end batching integration ----------
83
- updateQuery(collectionName, query, update) {
84
- const id = queryId(query.selector, query.options);
85
- const collectionQueries = this.queries[collectionName];
86
- if (!collectionQueries)
87
- return;
88
- const existing = collectionQueries.get(id);
89
- const newState = {
90
- state: "active",
91
- error: null,
92
- items: [],
93
- stateChangeCallbacks: [],
94
- eventHandler: existing?.eventHandler,
95
- ...existing,
96
- ...update
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);
97
89
  };
98
- collectionQueries.set(id, newState);
99
- this.queries[collectionName] = collectionQueries;
100
- }
101
- createCollectionBackend(collection, indices) {
102
- this.queries[collection.name] = /* @__PURE__ */ new Map();
103
- void this.exec("registerCollection", collection.name, indices);
104
- this.collectionReady.set(collection.name, this.exec("isReady", collection.name));
105
- this.batchExecutionHelpers.set(collection.name, batchOnNextTick(async (method, args) => this.exec(method, collection.name, args)));
106
90
  return {
107
91
  insert: async (item) => {
108
- return this.enqueueBatched(collection.name, "insert", [item]);
92
+ await ready;
93
+ const inserted = await this.insert(collection.name, item);
94
+ return inserted;
109
95
  },
110
96
  updateOne: async (selector, modifier) => {
111
- return this.enqueueBatched(collection.name, "updateOne", [selector, modifier]);
97
+ await ready;
98
+ return this.updateOne(collection.name, selector, modifier);
112
99
  },
113
100
  updateMany: async (selector, modifier) => {
114
- return this.enqueueBatched(collection.name, "updateMany", [selector, modifier]);
101
+ await ready;
102
+ return this.updateMany(collection.name, selector, modifier);
115
103
  },
116
104
  replaceOne: async (selector, replacement) => {
117
- return this.enqueueBatched(collection.name, "replaceOne", [selector, replacement]);
105
+ await ready;
106
+ return this.replaceOne(collection.name, selector, replacement);
118
107
  },
119
108
  removeOne: async (selector) => {
120
- return this.enqueueBatched(collection.name, "removeOne", [selector]);
109
+ await ready;
110
+ return this.removeOne(collection.name, selector);
121
111
  },
122
112
  removeMany: async (selector) => {
123
- return this.enqueueBatched(collection.name, "removeMany", [selector]);
113
+ await ready;
114
+ return this.removeMany(collection.name, selector);
124
115
  },
125
- // methods for registering and unregistering queries that will be called from the collection during find/findOne
126
- registerQuery: (selector, options) => {
127
- this.updateQuery(collection.name, { selector, options }, { state: "active", error: null, items: [] });
128
- void this.exec("registerQuery", collection.name, selector, options);
129
- const handler = (event) => {
130
- const { type, data, workerId, error } = event.data;
131
- if (type !== "queryUpdate")
132
- return;
133
- if (data == null)
134
- return;
135
- const { collectionName, selector: responseSelector, options: responseOptions, state, items } = data;
136
- if (workerId !== this.id)
137
- return;
138
- if (collectionName !== collection.name)
139
- return;
140
- if (queryId(responseSelector, responseOptions) !== queryId(selector, options))
141
- return;
142
- this.log("queryUpdate", responseSelector, responseOptions, state, data ?? error);
143
- this.updateQuery(collection.name, {
144
- selector: responseSelector,
145
- options: responseOptions
146
- }, { state, error, items });
147
- const query = this.queries[collection.name]?.get(queryId(selector, options));
148
- if (!query)
149
- return;
150
- query.stateChangeCallbacks.forEach((callback) => callback(state));
151
- };
152
- this.worker.addEventListener("message", handler);
153
- this.updateQuery(collection.name, { selector, options }, { eventHandler: handler });
154
- },
155
- unregisterQuery: (selector, options) => {
156
- const qid = queryId(selector, options);
157
- const query = this.queries[collection.name]?.get(qid);
158
- if (query?.eventHandler) {
159
- this.worker.removeEventListener("message", query.eventHandler);
160
- }
161
- this.queries[collection.name]?.delete(qid);
162
- void this.exec("unregisterQuery", collection.name, selector, options);
116
+ registerQuery,
117
+ unregisterQuery,
118
+ getQueryState,
119
+ getQueryError,
120
+ getQueryResult,
121
+ onQueryStateChange,
122
+ executeQuery: async (selector, options) => {
123
+ await ready;
124
+ return this.executeQuery(collection.name, selector, options);
163
125
  },
164
- getQueryState: (selector, options) => {
165
- const query = this.queries[collection.name]?.get(queryId(selector, options));
166
- return query?.state || "active";
167
- },
168
- getQueryError: (selector, options) => {
169
- const query = this.queries[collection.name]?.get(queryId(selector, options));
170
- return query?.error || null;
171
- },
172
- getQueryResult: (selector, options) => {
173
- const query = this.queries[collection.name]?.get(queryId(selector, options));
174
- return query?.items || [];
175
- },
176
- onQueryStateChange: (selector, options, callback) => {
177
- this.updateQuery(collection.name, { selector, options }, {
178
- stateChangeCallbacks: [
179
- ...this.queries[collection.name]?.get(queryId(selector, options))?.stateChangeCallbacks || [],
180
- callback
181
- ]
182
- });
183
- return () => {
184
- const currentCallbacks = this.queries[collection.name]?.get(queryId(selector, options))?.stateChangeCallbacks;
185
- if (!currentCallbacks)
186
- throw new Error("State change callbacks are not defined!");
187
- this.updateQuery(collection.name, { selector, options }, {
188
- stateChangeCallbacks: currentCallbacks.filter((existingCallback) => existingCallback !== callback)
189
- });
190
- };
191
- },
192
- executeQuery: (selector, options) => this.exec("executeQuery", collection.name, selector, options),
193
- // lifecycle methods
194
126
  dispose: async () => {
195
- await this.exec("unregisterCollection", collection.name);
196
- this.isDisposed = true;
197
- this.worker.terminate();
127
+ this.storageAdapters.delete(collection.name);
128
+ this.queries.delete(collection.name);
129
+ this.collectionIndices.delete(collection.name);
130
+ this.storageAdapterReady.delete(collection.name);
198
131
  },
199
132
  isReady: async () => {
200
- await this.exec("isReady", collection.name);
133
+ await ready;
134
+ }
135
+ };
136
+ }
137
+ async setupStorage(collectionName, indices) {
138
+ const storage = this.storageAdapters.get(collectionName);
139
+ if (!storage)
140
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
141
+ await storage.setup();
142
+ await Promise.all(indices.map((index) => storage.createIndex(index)));
143
+ }
144
+ ensureStorageAdapter(name) {
145
+ if (this.storageAdapters.has(name))
146
+ return;
147
+ const adapter = this.options.storage(name);
148
+ if (!adapter)
149
+ return;
150
+ this.storageAdapters.set(name, adapter);
151
+ }
152
+ /**
153
+ * Compute and publish the result for a specific query
154
+ * @param collectionName - name of the collection
155
+ * @param selector - query selector
156
+ * @param options - query options
157
+ */
158
+ async fulfillQuery(collectionName, selector, options) {
159
+ const qid = queryId(selector, options);
160
+ const registry = this.queries.get(collectionName);
161
+ if (!registry)
162
+ throw new Error(`Collection ${collectionName} not initialized!`);
163
+ const rec = registry.get(qid);
164
+ if (!rec)
165
+ return;
166
+ this.publishState(collectionName, qid, "active", null);
167
+ try {
168
+ const items = await this.executeQuery(collectionName, selector, options);
169
+ this.publishResult(collectionName, qid, items);
170
+ this.publishState(collectionName, qid, "complete", null);
171
+ } catch (error) {
172
+ this.publishState(collectionName, qid, "error", error);
173
+ }
174
+ }
175
+ /**
176
+ * Notify listeners about state changes and keep the cache updated
177
+ * @param collectionName - name of the collection
178
+ * @param qid - query id
179
+ * @param state - new state
180
+ * @param error - error if state is 'error', null otherwise
181
+ */
182
+ publishState(collectionName, qid, state, error) {
183
+ const rec = this.queries.get(collectionName)?.get(qid);
184
+ if (!rec)
185
+ return;
186
+ rec.state = state;
187
+ rec.error = error;
188
+ for (const callback of rec.listeners) {
189
+ try {
190
+ callback(state);
191
+ } catch (error_) {
192
+ this.onError(error_);
201
193
  }
194
+ }
195
+ }
196
+ publishResult(collectionName, qid, items) {
197
+ const rec = this.queries.get(collectionName)?.get(qid);
198
+ if (!rec)
199
+ return;
200
+ rec.items = items;
201
+ }
202
+ async getIndexInfo(collectionName, selector) {
203
+ const storageAdapter = this.storageAdapters.get(collectionName);
204
+ if (!storageAdapter)
205
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
206
+ if (selector != null && Object.keys(selector).length === 1 && "id" in selector && typeof selector.id !== "object") {
207
+ return {
208
+ matched: true,
209
+ ids: [selector.id].filter(Boolean),
210
+ optimizedSelector: {}
211
+ };
212
+ }
213
+ if (selector == null) {
214
+ return {
215
+ matched: false,
216
+ ids: [],
217
+ optimizedSelector: {}
218
+ };
219
+ }
220
+ const indices = this.collectionIndices.get(collectionName) ?? [];
221
+ return getIndexInfo(indices.map((field) => async (flatSelector) => {
222
+ if (!Object.hasOwnProperty.call(flatSelector, field))
223
+ return { matched: false };
224
+ const index = await storageAdapter.readIndex(field);
225
+ const fieldSelector = flatSelector[field];
226
+ const filtersForNull = fieldSelector == null || fieldSelector.$exists === false;
227
+ const keys = filtersForNull ? { include: null, exclude: [...index.keys()].filter((key) => key != null) } : getMatchingKeys(field, flatSelector);
228
+ if (keys.include == null && keys.exclude == null)
229
+ return { matched: false };
230
+ let includedIds = [];
231
+ if (keys.include == null) {
232
+ for (const set of index.values())
233
+ for (const pos of set)
234
+ includedIds.push(pos);
235
+ } else {
236
+ for (const key of keys.include) {
237
+ const idSet = index.get(key);
238
+ if (idSet)
239
+ for (const id of idSet)
240
+ includedIds.push(id);
241
+ }
242
+ }
243
+ if (keys.exclude != null) {
244
+ const excludeIds = /* @__PURE__ */ new Set();
245
+ for (const key of keys.exclude) {
246
+ const idSet = index.get(key);
247
+ if (idSet)
248
+ for (const id of idSet)
249
+ excludeIds.add(id);
250
+ }
251
+ includedIds = includedIds.filter((pos) => !excludeIds.has(pos));
252
+ }
253
+ return { matched: true, ids: includedIds, fields: [field], keepSelector: filtersForNull };
254
+ }), selector);
255
+ }
256
+ async queryItems(collectionName, selector) {
257
+ const storage = this.storageAdapters.get(collectionName);
258
+ if (!storage)
259
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
260
+ const index = await this.getIndexInfo(collectionName, selector);
261
+ const matchItems = (item) => {
262
+ if (index.optimizedSelector == null)
263
+ return true;
264
+ if (Object.keys(index.optimizedSelector).length <= 0)
265
+ return true;
266
+ return match(item, index.optimizedSelector);
202
267
  };
268
+ if (index.matched) {
269
+ const items = await storage.readIds(index.ids);
270
+ if (isEqual(index.optimizedSelector, {}))
271
+ return items;
272
+ return items.filter(matchItems);
273
+ } else {
274
+ const allItems = await storage.readAll();
275
+ if (isEqual(selector, {}))
276
+ return allItems;
277
+ return allItems.filter(matchItems);
278
+ }
279
+ }
280
+ async executeQuery(collectionName, selector, options) {
281
+ const items = await this.queryItems(collectionName, selector || {});
282
+ const { sort, skip, limit, fields } = options || {};
283
+ const sorted = sort ? sortItems(items, sort) : items;
284
+ const skipped = skip ? sorted.slice(skip) : sorted;
285
+ const limited = limit ? skipped.slice(0, limit) : skipped;
286
+ const idExcluded = fields && fields.id === 0;
287
+ return limited.map((item) => {
288
+ if (!fields)
289
+ return item;
290
+ return { ...idExcluded ? {} : { id: item.id }, ...project(item, fields) };
291
+ });
292
+ }
293
+ /**
294
+ * After mutations, recompute and push updates for affected active queries
295
+ * @param collectionName - name of the collection
296
+ * @param changedItems - items that were inserted/updated/replaced/removed
297
+ */
298
+ async checkQueryUpdates(collectionName, changedItems) {
299
+ const registry = this.queries.get(collectionName);
300
+ if (!registry)
301
+ throw new Error(`Collection ${collectionName} not initialized!`);
302
+ if (registry.size === 0)
303
+ return;
304
+ const affected = [...registry.values()].filter(({ selector }) => changedItems.some((item) => match(item, selector)));
305
+ if (affected.length === 0)
306
+ return;
307
+ for (const { selector, options } of affected) {
308
+ const qid = queryId(selector, options);
309
+ this.publishState(collectionName, qid, "active", null);
310
+ }
311
+ await Promise.all(affected.map(async ({ selector, options }) => {
312
+ const qid = queryId(selector, options);
313
+ try {
314
+ const items = await this.executeQuery(collectionName, selector, options);
315
+ this.publishResult(collectionName, qid, items);
316
+ this.publishState(collectionName, qid, "complete", null);
317
+ } catch (error) {
318
+ this.publishState(collectionName, qid, "error", error);
319
+ }
320
+ }));
321
+ }
322
+ async insert(collectionName, newItem) {
323
+ const storage = this.storageAdapters.get(collectionName);
324
+ if (!storage)
325
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
326
+ const existingItems = await storage.readIds([newItem.id]);
327
+ if (existingItems.length > 0)
328
+ throw new Error(`Item with id ${String(newItem.id)} already exists`);
329
+ await storage.insert([newItem]);
330
+ await this.checkQueryUpdates(collectionName, [newItem]);
331
+ return newItem;
332
+ }
333
+ async updateOne(collectionName, selector, modifier) {
334
+ const storage = this.storageAdapters.get(collectionName);
335
+ if (!storage)
336
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
337
+ const items = await this.executeQuery(collectionName, selector, { limit: 1 });
338
+ const [item] = items;
339
+ const { $setOnInsert, ...rest } = modifier;
340
+ if (item == null)
341
+ return [];
342
+ const modified = modify(deepClone(item), rest);
343
+ if (item.id !== modified.id) {
344
+ const existing = await storage.readIds([modified.id]);
345
+ if (existing.length > 0)
346
+ throw new Error(`Item with id ${String(modified.id)} already exists`);
347
+ }
348
+ await storage.replace([modified]);
349
+ await this.checkQueryUpdates(collectionName, [modified]);
350
+ return [modified];
351
+ }
352
+ async updateMany(collectionName, selector, modifier) {
353
+ const storage = this.storageAdapters.get(collectionName);
354
+ if (!storage)
355
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
356
+ const items = await this.executeQuery(collectionName, selector);
357
+ if (items.length === 0)
358
+ return [];
359
+ const { $setOnInsert, ...rest } = modifier;
360
+ const changed = await Promise.all(items.map(async (item) => {
361
+ const modified = modify(deepClone(item), rest);
362
+ if (item.id !== modified.id) {
363
+ const existing = await storage.readIds([modified.id]);
364
+ if (existing.length > 0)
365
+ throw new Error(`Item with id ${String(modified.id)} already exists`);
366
+ }
367
+ return modified;
368
+ }));
369
+ await storage.replace(changed);
370
+ await this.checkQueryUpdates(collectionName, changed);
371
+ return changed;
372
+ }
373
+ async replaceOne(collectionName, selector, replacement) {
374
+ const storage = this.storageAdapters.get(collectionName);
375
+ if (!storage)
376
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
377
+ const items = await this.executeQuery(collectionName, selector, { limit: 1 });
378
+ const [item] = items;
379
+ if (item == null)
380
+ return [];
381
+ const modified = { ...replacement, id: replacement.id ?? item.id };
382
+ if (item.id !== modified.id) {
383
+ const existing = await storage.readIds([modified.id]);
384
+ if (existing.length > 0)
385
+ throw new Error(`Item with id ${String(modified.id)} already exists`);
386
+ }
387
+ await storage.replace([modified]);
388
+ await this.checkQueryUpdates(collectionName, [modified]);
389
+ return [modified];
390
+ }
391
+ async removeOne(collectionName, selector) {
392
+ const storage = this.storageAdapters.get(collectionName);
393
+ if (!storage)
394
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
395
+ const items = await this.executeQuery(collectionName, selector, { limit: 1 });
396
+ const [item] = items;
397
+ if (item == null)
398
+ return [];
399
+ await storage.remove([item]);
400
+ await this.checkQueryUpdates(collectionName, [item]);
401
+ return [item];
402
+ }
403
+ async removeMany(collectionName, selector) {
404
+ const storage = this.storageAdapters.get(collectionName);
405
+ if (!storage)
406
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
407
+ const items = await this.executeQuery(collectionName, selector);
408
+ if (items.length === 0)
409
+ return [];
410
+ await storage.remove(items);
411
+ await this.checkQueryUpdates(collectionName, items);
412
+ return items;
203
413
  }
204
414
  }
205
415
  export {
206
- WorkerDataAdapter as default
416
+ AsyncDataAdapter as default
207
417
  };