@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/index15.mjs CHANGED
@@ -1,389 +1,207 @@
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
- import compact from "./index28.mjs";
11
- class WorkerDataAdapterHost {
12
- workerContext;
1
+ import queryId from "./index21.mjs";
2
+ import randomId from "./index8.mjs";
3
+ import batchOnNextTick from "./index28.mjs";
4
+ class WorkerDataAdapter {
5
+ worker;
13
6
  options;
14
7
  id;
8
+ isDisposed = false;
9
+ workerReady;
15
10
  log = () => {
16
11
  };
17
- storageAdapters = /* @__PURE__ */ new Map();
18
- storageAdapterReady = /* @__PURE__ */ new Map();
19
- collectionIndices = /* @__PURE__ */ new Map();
20
- queries = /* @__PURE__ */ new Map();
21
- onError = (error) => {
22
- console.error(error);
23
- };
24
- constructor(workerContext, options) {
25
- this.workerContext = workerContext;
12
+ collectionReady = /* @__PURE__ */ new Map();
13
+ batchExecutionHelpers = /* @__PURE__ */ new Map();
14
+ queries = {};
15
+ constructor(worker, options) {
16
+ this.worker = worker;
26
17
  this.options = options;
27
18
  this.id = this.options.id || "default-worker-data-adapter";
28
- if (this.options.onError) {
29
- this.onError = this.options.onError;
30
- }
31
19
  if (this.options.log)
32
20
  this.log = this.options.log;
33
- if (typeof addEventListener === "undefined" || typeof postMessage === "undefined") {
34
- throw new TypeError("WorkerDataAdapterHost can only be used in a Web Worker context");
35
- }
36
- this.workerContext.addEventListener("message", async (event) => {
37
- try {
38
- const { workerId, id, method, args } = event.data;
39
- await this.handleMessage(workerId, id, method, args);
40
- } catch (error) {
41
- this.onError(error);
42
- }
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);
43
36
  });
44
- this.respond("ready", null, null, "ready");
45
- }
46
- respond(id, data, error = null, type = "response") {
47
- this.workerContext.postMessage({ id, workerId: this.id, type, data, error });
48
37
  }
49
- async handleMessage(workerId, id, method, args) {
50
- if (workerId !== this.id)
51
- return;
52
- const fn = this[method];
53
- if (typeof fn !== "function") {
54
- this.respond(id, null, new Error(`Method ${method} not found`));
55
- return;
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;
56
45
  }
57
- this.log(method, ...args);
58
- await this.isReady(args[0]);
59
- try {
60
- const result = await fn.apply(this, args);
61
- this.respond(id, result);
62
- } catch (error) {
63
- this.respond(id, null, error);
64
- }
65
- }
66
- async getIndexInfo(collectionName, selector) {
67
- const storageAdapter = this.storageAdapters.get(collectionName);
68
- if (!storageAdapter)
69
- throw new Error(`No persistence adapter for collection ${collectionName}`);
70
- if (selector != null && Object.keys(selector).length === 1 && "id" in selector && typeof selector.id !== "object") {
71
- return {
72
- matched: true,
73
- ids: compact([selector.id]),
74
- optimizedSelector: {}
75
- };
76
- }
77
- if (selector == null) {
78
- return {
79
- matched: false,
80
- ids: [],
81
- optimizedSelector: {}
82
- };
46
+ if (this.isDisposed) {
47
+ throw new Error("WorkerDataAdapter is disposed");
83
48
  }
84
- const indices = this.collectionIndices.get(collectionName) ?? [];
85
- return getIndexInfo(indices.map((field) => async (flatSelector) => {
86
- if (!Object.hasOwnProperty.call(flatSelector, field)) {
87
- return { matched: false };
88
- }
89
- const index = await storageAdapter.readIndex(field);
90
- const fieldSelector = flatSelector[field];
91
- const filteresForNull = fieldSelector == null || fieldSelector.$exists === false;
92
- const keys = filteresForNull ? { include: null, exclude: [...index.keys()].filter((key) => key != null) } : getMatchingKeys(field, flatSelector);
93
- if (keys.include == null && keys.exclude == null)
94
- return { matched: false };
95
- let includedIds = [];
96
- if (keys.include == null) {
97
- for (const set of index.values()) {
98
- for (const pos of set) {
99
- includedIds.push(pos);
100
- }
101
- }
102
- } else {
103
- for (const key of keys.include) {
104
- const idSet = index.get(key);
105
- if (idSet) {
106
- for (const id of idSet) {
107
- includedIds.push(id);
108
- }
109
- }
110
- }
111
- }
112
- if (keys.exclude != null) {
113
- const excludeIds = /* @__PURE__ */ new Set();
114
- for (const key of keys.exclude) {
115
- const idSet = index.get(key);
116
- if (idSet) {
117
- for (const id of idSet) {
118
- excludeIds.add(id);
119
- }
120
- }
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);
121
64
  }
122
- includedIds = includedIds.filter((pos) => !excludeIds.has(pos));
123
- }
124
- return {
125
- matched: true,
126
- ids: includedIds,
127
- fields: [field],
128
- keepSelector: filteresForNull
129
- };
130
- }), selector);
131
- }
132
- async queryItems(collectionName, selector) {
133
- const storageAdapter = this.storageAdapters.get(collectionName);
134
- if (!storageAdapter)
135
- throw new Error(`No persistence adapter for collection ${collectionName}`);
136
- const indexInfo = await this.getIndexInfo(collectionName, selector);
137
- const matchItems = (item) => {
138
- if (indexInfo.optimizedSelector == null)
139
- return true;
140
- if (Object.keys(indexInfo.optimizedSelector).length <= 0)
141
- return true;
142
- const matches = match(item, indexInfo.optimizedSelector);
143
- return matches;
144
- };
145
- if (indexInfo.matched) {
146
- const items = await storageAdapter.readIds(indexInfo.ids);
147
- if (isEqual(indexInfo.optimizedSelector, {}))
148
- return items;
149
- return items.filter(matchItems);
150
- } else {
151
- const allItems = await storageAdapter.readAll();
152
- if (isEqual(selector, {}))
153
- return allItems;
154
- return allItems.filter(matchItems);
155
- }
156
- }
157
- async executeQuery(collectionName, selector, options) {
158
- if (selector === null)
159
- return [];
160
- const items = await this.queryItems(collectionName, selector || {});
161
- const { sort, skip, limit, fields } = options || {};
162
- const sorted = sort ? sortItems(items, sort) : items;
163
- const skipped = skip ? sorted.slice(skip) : sorted;
164
- const limited = limit ? skipped.slice(0, limit) : skipped;
165
- const idExcluded = fields && fields.id === 0;
166
- return limited.map((item) => {
167
- if (!fields)
168
- return item;
169
- return {
170
- ...idExcluded ? {} : { id: item.id },
171
- ...project(item, fields)
65
+ this.worker.removeEventListener("message", handleMessage);
172
66
  };
67
+ this.worker.addEventListener("message", handleMessage);
68
+ this.worker.postMessage({
69
+ id: messageId,
70
+ workerId: this.id,
71
+ method,
72
+ args: [collectionName, ...args]
73
+ });
173
74
  });
174
75
  }
175
- ensureQuery(collectionName, selector, options) {
176
- const id = queryId(selector, options);
177
- if (!this.queries.get(collectionName)) {
178
- throw new Error(`Collection ${collectionName} not initialized!`);
179
- }
180
- let query = this.queries.get(collectionName)?.get(id);
181
- if (!query) {
182
- query = { selector, options };
183
- this.queries.get(collectionName)?.set(id, query);
184
- }
185
- return query;
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);
186
81
  }
187
- emitQueryUpdate(collectionName, selector, options, state, error, items) {
188
- const id = queryId(selector, options);
189
- const collectionQueries = this.queries.get(collectionName);
82
+ // ---------- end batching integration ----------
83
+ updateQuery(collectionName, query, update) {
84
+ const id = queryId(query.selector, query.options);
85
+ const collectionQueries = this.queries[collectionName];
190
86
  if (!collectionQueries)
191
- throw new Error(`Collection ${collectionName} not initialized!`);
192
- this.respond(id, { collectionName, selector, options, state, error, items }, null, "queryUpdate");
193
- }
194
- ensureStorageAdapter(name) {
195
- if (this.storageAdapters.has(name))
196
- return;
197
- const adapter = this.options.storage(name);
198
- if (!adapter)
199
87
  return;
200
- this.storageAdapters.set(name, adapter);
201
- }
202
- async checkQueryUpdates(collectionName, items) {
203
- const queries = this.queries.get(collectionName);
204
- if (!queries)
205
- throw new Error(`Collection ${collectionName} not initialized!`);
206
- const affectedQueries = [...queries.values()].filter(({ selector }) => items.some((item) => match(item, selector))) ?? [];
207
- if (affectedQueries.length === 0)
208
- return;
209
- affectedQueries.forEach(({ selector, options }) => {
210
- this.emitQueryUpdate(collectionName, selector, options, "active", null);
211
- });
212
- await Promise.all(affectedQueries.map(async ({ selector, options }) => {
213
- const queryItems = await this.executeQuery(collectionName, selector, options);
214
- this.emitQueryUpdate(collectionName, selector, options, "complete", null, queryItems);
215
- }));
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
97
+ };
98
+ collectionQueries.set(id, newState);
99
+ this.queries[collectionName] = collectionQueries;
216
100
  }
217
- registerCollection = async (collectionName, indices) => {
218
- this.collectionIndices.set(collectionName, indices);
219
- this.queries.set(collectionName, /* @__PURE__ */ new Map());
220
- this.ensureStorageAdapter(collectionName);
221
- const storageAdapter = this.storageAdapters.get(collectionName);
222
- if (!storageAdapter)
223
- throw new Error(`No persistence adapter for collection ${collectionName}`);
224
- const setupPromise = (async () => {
225
- await Promise.all(indices.map((index) => storageAdapter.createIndex(index)));
226
- await storageAdapter.setup();
227
- })();
228
- this.storageAdapterReady.set(collectionName, setupPromise);
229
- await setupPromise;
230
- };
231
- unregisterCollection = async (collectionName) => {
232
- this.storageAdapters.delete(collectionName);
233
- this.queries.delete(collectionName);
234
- };
235
- registerQuery = async (collectionName, selector, options) => {
236
- this.ensureQuery(collectionName, selector, options);
237
- const queryItems = await this.executeQuery(collectionName, selector, options);
238
- this.emitQueryUpdate(collectionName, selector, options, "complete", null, queryItems);
239
- };
240
- unregisterQuery = async (collectionName, selector, options) => {
241
- const id = queryId(selector, options);
242
- if (!this.queries.get(collectionName))
243
- throw new Error(`Collection ${collectionName} not initialized!`);
244
- this.queries.get(collectionName)?.delete(id);
245
- };
246
- insert = async (collectionName, input) => {
247
- const storageAdapter = this.storageAdapters.get(collectionName);
248
- if (!storageAdapter)
249
- throw new Error(`No persistence adapter for collection ${collectionName}`);
250
- const existingItems = await this.executeQuery(collectionName, { id: { $in: input.map((i) => i[0].id) } });
251
- const result = input.map(([item]) => {
252
- if (item.id == null)
253
- return new Error("Item must have an id");
254
- if (existingItems.some((existing) => existing.id === item.id)) {
255
- return new Error(`Item with id ${item.id} already exists`);
256
- }
257
- return item;
258
- });
259
- const newItems = result.filter((item) => !(item instanceof Error));
260
- await storageAdapter.insert(newItems);
261
- await this.checkQueryUpdates(collectionName, newItems);
262
- return result;
263
- };
264
- updateOne = async (collectionName, parameters) => {
265
- const storageAdapter = this.storageAdapters.get(collectionName);
266
- if (!storageAdapter)
267
- throw new Error(`No persistence adapter for collection ${collectionName}`);
268
- const previousItems = [];
269
- const result = await Promise.all(parameters.map(async ([selector, modifier]) => {
270
- const item = await this.executeQuery(collectionName, selector, { limit: 1 }).then((items) => items[0] ?? null);
271
- const { $setOnInsert, ...restModifier } = modifier;
272
- if (item == null)
273
- return [];
274
- previousItems.push(item);
275
- const modifiedItem = modify(deepClone(item), restModifier);
276
- if (item.id !== modifiedItem.id) {
277
- const existingItems = await this.executeQuery(collectionName, { id: modifiedItem.id }, { limit: 1 });
278
- if (existingItems.length > 0) {
279
- return new Error(`Item with id ${modifiedItem.id} already exists`);
280
- }
281
- }
282
- return [modifiedItem];
283
- }));
284
- const modifiedItems = compact(result.filter((item) => !(item instanceof Error)).flat());
285
- if (modifiedItems.length > 0) {
286
- await storageAdapter.replace(modifiedItems);
287
- await this.checkQueryUpdates(collectionName, [...modifiedItems, ...previousItems]);
288
- }
289
- return result;
290
- };
291
- updateMany = async (collectionName, parameters) => {
292
- const storageAdapter = this.storageAdapters.get(collectionName);
293
- if (!storageAdapter)
294
- throw new Error(`No persistence adapter for collection ${collectionName}`);
295
- const previousItems = [];
296
- const result = await Promise.all(parameters.map(async ([selector, modifier]) => {
297
- const items = await this.executeQuery(collectionName, selector);
298
- if (items.length === 0)
299
- return [];
300
- const { $setOnInsert, ...restModifier } = modifier;
301
- try {
302
- const changedItems = await Promise.all(items.map(async (item) => {
303
- const modifiedItem = modify(deepClone(item), restModifier);
304
- if (item.id !== modifiedItem.id) {
305
- const existingItems = await this.executeQuery(collectionName, { id: modifiedItem.id }, { limit: 1 });
306
- if (existingItems.length > 0) {
307
- throw new Error(`Item with id ${modifiedItem.id} already exists`);
308
- }
309
- }
310
- previousItems.push(item);
311
- return modifiedItem;
312
- }));
313
- return changedItems;
314
- } catch (error) {
315
- return error;
316
- }
317
- }));
318
- const modifiedItems = compact(result.filter((item) => !(item instanceof Error)).flat());
319
- if (modifiedItems.length > 0) {
320
- await storageAdapter.replace(modifiedItems);
321
- await this.checkQueryUpdates(collectionName, [...modifiedItems, ...previousItems]);
322
- }
323
- return result;
324
- };
325
- replaceOne = async (collectionName, parameters) => {
326
- const storageAdapter = this.storageAdapters.get(collectionName);
327
- if (!storageAdapter)
328
- throw new Error(`No persistence adapter for collection ${collectionName}`);
329
- const previousItems = [];
330
- const result = await Promise.all(parameters.map(async ([selector, replacement]) => {
331
- const item = await this.executeQuery(collectionName, selector, { limit: 1 }).then((items) => items[0] ?? null);
332
- if (item == null)
333
- return [];
334
- previousItems.push(item);
335
- const modifiedItem = {
336
- ...replacement,
337
- id: replacement.id ?? item.id
338
- };
339
- if (item.id !== modifiedItem.id) {
340
- const existingItems = await this.executeQuery(collectionName, { id: modifiedItem.id }, { limit: 1 });
341
- if (existingItems.length > 0) {
342
- return new Error(`Item with id ${modifiedItem.id} already exists`);
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
+ return {
107
+ insert: async (item) => {
108
+ return this.enqueueBatched(collection.name, "insert", [item]);
109
+ },
110
+ updateOne: async (selector, modifier) => {
111
+ return this.enqueueBatched(collection.name, "updateOne", [selector, modifier]);
112
+ },
113
+ updateMany: async (selector, modifier) => {
114
+ return this.enqueueBatched(collection.name, "updateMany", [selector, modifier]);
115
+ },
116
+ replaceOne: async (selector, replacement) => {
117
+ return this.enqueueBatched(collection.name, "replaceOne", [selector, replacement]);
118
+ },
119
+ removeOne: async (selector) => {
120
+ return this.enqueueBatched(collection.name, "removeOne", [selector]);
121
+ },
122
+ removeMany: async (selector) => {
123
+ return this.enqueueBatched(collection.name, "removeMany", [selector]);
124
+ },
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);
343
160
  }
161
+ this.queries[collection.name]?.delete(qid);
162
+ void this.exec("unregisterQuery", collection.name, selector, options);
163
+ },
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
+ dispose: async () => {
195
+ await this.exec("unregisterCollection", collection.name);
196
+ this.isDisposed = true;
197
+ this.worker.terminate();
198
+ },
199
+ isReady: async () => {
200
+ await this.exec("isReady", collection.name);
344
201
  }
345
- return [modifiedItem];
346
- }));
347
- const modifiedItems = compact(result.filter((item) => !(item instanceof Error)).flat());
348
- if (modifiedItems.length > 0) {
349
- await storageAdapter.replace(modifiedItems);
350
- await this.checkQueryUpdates(collectionName, [...modifiedItems, ...previousItems]);
351
- }
352
- return result;
353
- };
354
- removeOne = async (collectionName, selectors) => {
355
- const storageAdapter = this.storageAdapters.get(collectionName);
356
- if (!storageAdapter)
357
- throw new Error(`No persistence adapter for collection ${collectionName}`);
358
- const result = await Promise.all(selectors.map(async ([selector]) => {
359
- const item = await this.executeQuery(collectionName, selector, { limit: 1 }).then((items2) => items2[0] ?? null);
360
- if (item == null)
361
- return [];
362
- return [item];
363
- }));
364
- const items = result.flat();
365
- if (items.length > 0) {
366
- await storageAdapter.remove(items);
367
- await this.checkQueryUpdates(collectionName, items);
368
- }
369
- return result;
370
- };
371
- removeMany = async (collectionName, selectors) => {
372
- const storageAdapter = this.storageAdapters.get(collectionName);
373
- if (!storageAdapter)
374
- throw new Error(`No persistence adapter for collection ${collectionName}`);
375
- const result = await Promise.all(selectors.map(async ([selector]) => this.executeQuery(collectionName, selector)));
376
- const items = result.flat();
377
- if (items.length > 0) {
378
- await storageAdapter.remove(items);
379
- await this.checkQueryUpdates(collectionName, items);
380
- }
381
- return result;
382
- };
383
- isReady = async (collectionName) => {
384
- return this.storageAdapterReady.get(collectionName);
385
- };
202
+ };
203
+ }
386
204
  }
387
205
  export {
388
- WorkerDataAdapterHost as default
206
+ WorkerDataAdapter as default
389
207
  };