@signaldb/core 1.7.0 → 2.0.0-beta.0

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 (88) hide show
  1. package/dist/.vite/manifest.json +125 -82
  2. package/dist/AsyncDataAdapter.d.ts +64 -0
  3. package/dist/AutoFetchDataAdapter.d.ts +113 -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 +52 -46
  7. package/dist/Collection/types.d.ts +4 -9
  8. package/dist/DataAdapter.d.ts +33 -0
  9. package/dist/DefaultDataAdapter.d.ts +32 -0
  10. package/dist/WorkerDataAdapter.d.ts +22 -0
  11. package/dist/WorkerDataAdapterHost.d.ts +59 -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 +337 -3
  19. package/dist/index.cjs13.js +384 -115
  20. package/dist/index.cjs14.js +183 -67
  21. package/dist/index.cjs15.js +339 -8
  22. package/dist/index.cjs16.js +563 -20
  23. package/dist/index.cjs17.js +16 -12
  24. package/dist/index.cjs18.js +24 -5
  25. package/dist/index.cjs2.js +27 -36
  26. package/dist/index.cjs20.js +102 -13
  27. package/dist/index.cjs21.js +124 -21
  28. package/dist/index.cjs22.js +5 -68
  29. package/dist/index.cjs23.js +22 -82
  30. package/dist/index.cjs24.js +5 -16
  31. package/dist/index.cjs25.js +8 -27
  32. package/dist/index.cjs26.js +27 -7
  33. package/dist/index.cjs27.js +3 -5
  34. package/dist/index.cjs28.js +5 -27
  35. package/dist/index.cjs29.js +27 -40
  36. package/dist/index.cjs3.js +242 -497
  37. package/dist/index.cjs30.js +42 -0
  38. package/dist/index.cjs31.js +9 -0
  39. package/dist/index.cjs4.js +3 -170
  40. package/dist/index.cjs5.js +3 -67
  41. package/dist/index.cjs6.js +27 -3
  42. package/dist/index.cjs7.js +10 -3
  43. package/dist/index.cjs8.js +3 -3
  44. package/dist/index.cjs9.js +131 -3
  45. package/dist/index.d.ts +10 -8
  46. package/dist/index.mjs +15 -11
  47. package/dist/index10.mjs +15 -26
  48. package/dist/index11.mjs +13 -10
  49. package/dist/index12.mjs +337 -3
  50. package/dist/index13.mjs +384 -115
  51. package/dist/index14.mjs +183 -66
  52. package/dist/index15.mjs +339 -8
  53. package/dist/index16.mjs +563 -20
  54. package/dist/index17.mjs +16 -12
  55. package/dist/index18.mjs +24 -5
  56. package/dist/index2.mjs +27 -36
  57. package/dist/index20.mjs +102 -13
  58. package/dist/index21.mjs +123 -21
  59. package/dist/index22.mjs +5 -67
  60. package/dist/index23.mjs +22 -81
  61. package/dist/index24.mjs +5 -16
  62. package/dist/index25.mjs +8 -27
  63. package/dist/index26.mjs +27 -7
  64. package/dist/index27.mjs +3 -5
  65. package/dist/index28.mjs +5 -27
  66. package/dist/index29.mjs +27 -40
  67. package/dist/index3.mjs +241 -497
  68. package/dist/index30.mjs +43 -0
  69. package/dist/index31.mjs +10 -0
  70. package/dist/index4.mjs +3 -170
  71. package/dist/index5.mjs +3 -66
  72. package/dist/index6.mjs +27 -3
  73. package/dist/index7.mjs +10 -3
  74. package/dist/index8.mjs +3 -3
  75. package/dist/index9.mjs +131 -3
  76. package/dist/types/IndexProvider.d.ts +12 -7
  77. package/dist/types/StorageAdapter.d.ts +20 -0
  78. package/dist/utils/objectId.d.ts +8 -0
  79. package/dist/utils/queryId.d.ts +9 -0
  80. package/package.json +2 -2
  81. package/dist/AutoFetchCollection.d.ts +0 -60
  82. package/dist/Collection/createIndex.d.ts +0 -15
  83. package/dist/ReplicatedCollection.d.ts +0 -60
  84. package/dist/createMemoryAdapter.d.ts +0 -7
  85. package/dist/persistence/combinePersistenceAdapters.d.ts +0 -32
  86. package/dist/persistence/createPersistenceAdapter.d.ts +0 -9
  87. package/dist/types/MemoryAdapter.d.ts +0 -15
  88. package/dist/types/PersistenceAdapter.d.ts +0 -20
package/dist/index14.mjs CHANGED
@@ -1,74 +1,191 @@
1
- import createIndexProvider from "./index6.mjs";
2
- import get from "./index24.mjs";
3
- import getMatchingKeys from "./index28.mjs";
4
- import serializeValue from "./index20.mjs";
5
- function createExternalIndex(field, index) {
6
- return createIndexProvider({
7
- query(selector) {
8
- if (!Object.hasOwnProperty.call(selector, field)) {
9
- return { matched: false };
10
- }
11
- const fieldSelector = selector[field];
12
- const filteresForNull = fieldSelector == null || fieldSelector.$exists === false;
13
- const keys = filteresForNull ? { include: null, exclude: [...index.keys()].filter((key) => key != null) } : getMatchingKeys(field, selector);
14
- if (keys.include == null && keys.exclude == null)
15
- return { matched: false };
16
- let includedPositions = [];
17
- if (keys.include == null) {
18
- for (const set of index.values()) {
19
- for (const pos of set) {
20
- includedPositions.push(pos);
21
- }
22
- }
23
- } else {
24
- for (const key of keys.include) {
25
- const posSet = index.get(key);
26
- if (posSet) {
27
- for (const pos of posSet) {
28
- includedPositions.push(pos);
29
- }
30
- }
1
+ import queryId from "./index24.mjs";
2
+ import randomId from "./index8.mjs";
3
+ class WorkerDataAdapter {
4
+ worker;
5
+ options;
6
+ id;
7
+ isDisposed = false;
8
+ workerReady;
9
+ collectionReady = /* @__PURE__ */ new Map();
10
+ queries = {};
11
+ constructor(worker, options) {
12
+ this.worker = worker;
13
+ this.options = options;
14
+ this.id = this.options.id || "default-worker-data-adapter";
15
+ this.workerReady = new Promise((resolve, reject) => {
16
+ const timeoutId = setTimeout(() => {
17
+ reject(new Error("WorkerDataAdapter initialization timed out"));
18
+ }, 5e3);
19
+ const handleMessage = (event) => {
20
+ const { type, workerId } = event.data;
21
+ if (workerId !== this.id)
22
+ return;
23
+ if (type === "ready") {
24
+ resolve();
25
+ clearTimeout(timeoutId);
26
+ this.worker.removeEventListener("message", handleMessage);
31
27
  }
32
- }
33
- if (keys.exclude != null) {
34
- const excludeSet = /* @__PURE__ */ new Set();
35
- for (const key of keys.exclude) {
36
- const posSet = index.get(key);
37
- if (posSet) {
38
- for (const pos of posSet) {
39
- excludeSet.add(pos);
40
- }
41
- }
42
- }
43
- includedPositions = includedPositions.filter((pos) => !excludeSet.has(pos));
44
- }
45
- return {
46
- matched: true,
47
- positions: includedPositions,
48
- fields: [field],
49
- keepSelector: filteresForNull
50
28
  };
51
- },
52
- rebuild() {
29
+ this.worker.addEventListener("message", handleMessage);
30
+ });
31
+ }
32
+ async exec(method, collectionName, ...args) {
33
+ await this.workerReady;
34
+ if (method !== "isReady") {
35
+ const collectionReady = this.collectionReady.get(collectionName);
36
+ if (!collectionReady)
37
+ throw new Error(`Collection "${collectionName}" is not registered in WorkerDataAdapter`);
38
+ await collectionReady;
53
39
  }
54
- });
55
- }
56
- function createIndex(field) {
57
- const index = /* @__PURE__ */ new Map();
58
- return {
59
- ...createExternalIndex(field, index),
60
- rebuild(items) {
61
- index.clear();
62
- items.forEach((item, i) => {
63
- const value = serializeValue(get(item, field));
64
- const current = index.get(value) || /* @__PURE__ */ new Set();
65
- current.add(i);
66
- index.set(value, current);
40
+ if (this.isDisposed) {
41
+ throw new Error("WorkerDataAdapter is disposed");
42
+ }
43
+ return new Promise((resolve, reject) => {
44
+ const messageId = randomId();
45
+ const handleMessage = (event) => {
46
+ const { id, workerId, type, data, error } = event.data;
47
+ if (workerId !== this.id)
48
+ return;
49
+ if (type !== "response")
50
+ return;
51
+ if (id !== messageId)
52
+ return;
53
+ if (error) {
54
+ reject(error);
55
+ } else {
56
+ resolve(data);
57
+ }
58
+ this.worker.removeEventListener("message", handleMessage);
59
+ };
60
+ this.worker.addEventListener("message", handleMessage);
61
+ this.worker.postMessage({
62
+ id: messageId,
63
+ workerId: this.id,
64
+ method,
65
+ args: [collectionName, ...args]
67
66
  });
67
+ });
68
+ }
69
+ queryListeners(collectionName, query, listeners) {
70
+ if (listeners != null) {
71
+ return this.updateQuery(collectionName, query, { listeners });
68
72
  }
69
- };
73
+ const id = queryId(query.selector, query.options);
74
+ const collectionQueries = this.queries[collectionName];
75
+ if (!collectionQueries)
76
+ return 0;
77
+ const existing = collectionQueries.get(id);
78
+ return existing?.listeners || 0;
79
+ }
80
+ updateQuery(collectionName, query, update) {
81
+ const id = queryId(query.selector, query.options);
82
+ const collectionQueries = this.queries[collectionName];
83
+ if (!collectionQueries)
84
+ return;
85
+ const existing = collectionQueries.get(id);
86
+ collectionQueries.set(id, {
87
+ listeners: 0,
88
+ state: "active",
89
+ error: null,
90
+ items: [],
91
+ ...existing,
92
+ ...update
93
+ });
94
+ this.queries[collectionName] = collectionQueries;
95
+ }
96
+ createCollectionBackend(collection, indices = []) {
97
+ this.queries[collection.name] = /* @__PURE__ */ new Map();
98
+ void this.exec("registerCollection", collection.name, indices);
99
+ this.collectionReady.set(collection.name, this.exec("isReady", collection.name));
100
+ return {
101
+ insert: async (item) => {
102
+ return this.exec("insert", collection.name, item);
103
+ },
104
+ updateOne: async (selector, modifier) => {
105
+ return this.exec("updateOne", collection.name, selector, modifier);
106
+ },
107
+ updateMany: async (selector, modifier) => {
108
+ return this.exec("updateMany", collection.name, selector, modifier);
109
+ },
110
+ replaceOne: async (selector, replacement) => {
111
+ return this.exec("replaceOne", collection.name, selector, replacement);
112
+ },
113
+ removeOne: async (selector) => {
114
+ return this.exec("removeOne", collection.name, selector);
115
+ },
116
+ removeMany: async (selector) => {
117
+ return this.exec("removeMany", collection.name, selector);
118
+ },
119
+ // methods for registering and unregistering queries that will be called from the collection during find/findOne
120
+ registerQuery: (selector, options) => {
121
+ const listeners = this.queryListeners(collection.name, { selector, options });
122
+ if (listeners === 0) {
123
+ this.updateQuery(collection.name, { selector, options }, { state: "active", error: null, items: [] });
124
+ void this.exec("registerQuery", collection.name, selector, options);
125
+ }
126
+ this.queryListeners(collection.name, { selector, options }, listeners + 1);
127
+ },
128
+ unregisterQuery: (selector, options) => {
129
+ setTimeout(() => {
130
+ const listeners = this.queryListeners(collection.name, { selector, options });
131
+ const newListeners = Math.max(0, listeners - 1);
132
+ if (newListeners === 0) {
133
+ this.queries[collection.name]?.delete(queryId(selector, options));
134
+ void this.exec("unregisterQuery", collection.name, selector, options);
135
+ }
136
+ }, 0);
137
+ },
138
+ getQueryState: (selector, options) => {
139
+ const query = this.queries[collection.name]?.get(queryId(selector, options));
140
+ return query?.state || "active";
141
+ },
142
+ getQueryError: (selector, options) => {
143
+ const query = this.queries[collection.name]?.get(queryId(selector, options));
144
+ return query?.error || null;
145
+ },
146
+ getQueryResult: (selector, options) => {
147
+ const query = this.queries[collection.name]?.get(queryId(selector, options));
148
+ return query?.items || [];
149
+ },
150
+ onQueryStateChange: (selector, options, callback) => {
151
+ const handler = (event) => {
152
+ const { type, data, workerId, error } = event.data;
153
+ if (type !== "queryUpdate")
154
+ return;
155
+ if (data == null)
156
+ return;
157
+ const { collectionName, selector: responseSelector, options: responseOptions, state, items } = data;
158
+ if (workerId !== this.id)
159
+ return;
160
+ if (collectionName !== collection.name)
161
+ return;
162
+ if (JSON.stringify(responseSelector) !== JSON.stringify(selector))
163
+ return;
164
+ if (JSON.stringify(responseOptions) !== JSON.stringify(options))
165
+ return;
166
+ this.updateQuery(collection.name, {
167
+ selector: responseSelector,
168
+ options: responseOptions
169
+ }, { state, error, items });
170
+ callback(state);
171
+ };
172
+ this.worker.addEventListener("message", handler);
173
+ return () => {
174
+ this.worker.removeEventListener("message", handler);
175
+ };
176
+ },
177
+ // lifecycle methods
178
+ dispose: async () => {
179
+ await this.exec("unregisterCollection", collection.name);
180
+ this.isDisposed = true;
181
+ this.worker.terminate();
182
+ },
183
+ isReady: async () => {
184
+ await this.exec("isReady", collection.name);
185
+ }
186
+ };
187
+ }
70
188
  }
71
189
  export {
72
- createExternalIndex,
73
- createIndex as default
190
+ WorkerDataAdapter as default
74
191
  };
package/dist/index15.mjs CHANGED
@@ -1,11 +1,342 @@
1
- import { sort } from "fast-sort";
2
- import get from "./index24.mjs";
3
- function sortItems(items, sortFields) {
4
- return sort(items).by(Object.entries(sortFields).map(([key, value]) => {
5
- const order = value === 1 ? "asc" : "desc";
6
- return { [order]: (i) => get(i, key) };
7
- }));
1
+ import deepClone from "./index19.mjs";
2
+ import match from "./index22.mjs";
3
+ import modify from "./index7.mjs";
4
+ import queryId from "./index24.mjs";
5
+ import isEqual from "./index6.mjs";
6
+ import getIndexInfo from "./index21.mjs";
7
+ import getMatchingKeys from "./index26.mjs";
8
+ import sortItems from "./index25.mjs";
9
+ import project from "./index23.mjs";
10
+ class WorkerDataAdapterHost {
11
+ workerContext;
12
+ options;
13
+ id;
14
+ storageAdapters = /* @__PURE__ */ new Map();
15
+ storageAdapterReady = /* @__PURE__ */ new Map();
16
+ collectionIndices = /* @__PURE__ */ new Map();
17
+ queries = /* @__PURE__ */ new Map();
18
+ onError = (error) => {
19
+ console.error(error);
20
+ };
21
+ constructor(workerContext, options) {
22
+ this.workerContext = workerContext;
23
+ this.options = options;
24
+ this.id = this.options.id || "default-worker-data-adapter";
25
+ if (this.options.onError) {
26
+ this.onError = this.options.onError;
27
+ }
28
+ if (typeof addEventListener === "undefined" || typeof postMessage === "undefined") {
29
+ throw new TypeError("WorkerDataAdapterHost can only be used in a Web Worker context");
30
+ }
31
+ this.workerContext.addEventListener("message", async (event) => {
32
+ try {
33
+ const { workerId, id, method, args } = event.data;
34
+ await this.handleMessage(workerId, id, method, args);
35
+ } catch (error) {
36
+ this.onError(error);
37
+ }
38
+ });
39
+ this.respond("ready", null, null, "ready");
40
+ }
41
+ respond(id, data, error = null, type = "response") {
42
+ this.workerContext.postMessage({ id, workerId: this.id, type, data, error });
43
+ }
44
+ async handleMessage(workerId, id, method, args) {
45
+ if (workerId !== this.id)
46
+ return;
47
+ const fn = this[method];
48
+ if (typeof fn !== "function") {
49
+ this.respond(id, null, new Error(`Method ${method} not found`));
50
+ return;
51
+ }
52
+ try {
53
+ const result = await fn.apply(this, args);
54
+ this.respond(id, result);
55
+ } catch (error) {
56
+ this.respond(id, null, error);
57
+ }
58
+ }
59
+ async getIndexInfo(collectionName, selector) {
60
+ const storageAdapter = this.storageAdapters.get(collectionName);
61
+ if (!storageAdapter)
62
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
63
+ if (selector != null && Object.keys(selector).length === 1 && "id" in selector && typeof selector.id !== "object") {
64
+ return {
65
+ matched: true,
66
+ ids: [selector.id],
67
+ optimizedSelector: {}
68
+ };
69
+ }
70
+ if (selector == null) {
71
+ return {
72
+ matched: false,
73
+ ids: [],
74
+ optimizedSelector: {}
75
+ };
76
+ }
77
+ const indices = this.collectionIndices.get(collectionName) ?? [];
78
+ return getIndexInfo(indices.map((field) => async (flatSelector) => {
79
+ if (!Object.hasOwnProperty.call(flatSelector, field)) {
80
+ return { matched: false };
81
+ }
82
+ const index = await storageAdapter.readIndex(field);
83
+ const fieldSelector = flatSelector[field];
84
+ const filteresForNull = fieldSelector == null || fieldSelector.$exists === false;
85
+ const keys = filteresForNull ? { include: null, exclude: [...index.keys()].filter((key) => key != null) } : getMatchingKeys(field, flatSelector);
86
+ if (keys.include == null && keys.exclude == null)
87
+ return { matched: false };
88
+ let includedIds = [];
89
+ if (keys.include == null) {
90
+ for (const set of index.values()) {
91
+ for (const pos of set) {
92
+ includedIds.push(pos);
93
+ }
94
+ }
95
+ } else {
96
+ for (const key of keys.include) {
97
+ const idSet = index.get(key);
98
+ if (idSet) {
99
+ for (const id of idSet) {
100
+ includedIds.push(id);
101
+ }
102
+ }
103
+ }
104
+ }
105
+ if (keys.exclude != null) {
106
+ const excludeIds = /* @__PURE__ */ new Set();
107
+ for (const key of keys.exclude) {
108
+ const idSet = index.get(key);
109
+ if (idSet) {
110
+ for (const id of idSet) {
111
+ excludeIds.add(id);
112
+ }
113
+ }
114
+ }
115
+ includedIds = includedIds.filter((pos) => !excludeIds.has(pos));
116
+ }
117
+ return {
118
+ matched: true,
119
+ ids: includedIds,
120
+ fields: [field],
121
+ keepSelector: filteresForNull
122
+ };
123
+ }), selector);
124
+ }
125
+ async queryItems(collectionName, selector) {
126
+ const storageAdapter = this.storageAdapters.get(collectionName);
127
+ if (!storageAdapter)
128
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
129
+ const indexInfo = await this.getIndexInfo(collectionName, selector);
130
+ const matchItems = (item) => {
131
+ if (indexInfo.optimizedSelector == null)
132
+ return true;
133
+ if (Object.keys(indexInfo.optimizedSelector).length <= 0)
134
+ return true;
135
+ const matches = match(item, indexInfo.optimizedSelector);
136
+ return matches;
137
+ };
138
+ if (indexInfo.matched) {
139
+ const items = await storageAdapter.readIds(indexInfo.ids);
140
+ if (isEqual(indexInfo.optimizedSelector, {}))
141
+ return items;
142
+ return items.filter(matchItems);
143
+ } else {
144
+ const allItems = await storageAdapter.readAll();
145
+ if (isEqual(selector, {}))
146
+ return allItems;
147
+ return allItems.filter(matchItems);
148
+ }
149
+ }
150
+ async executeQuery(collectionName, selector, options) {
151
+ const items = await this.queryItems(collectionName, selector || {});
152
+ const { sort, skip, limit, fields } = options || {};
153
+ const sorted = sort ? sortItems(items, sort) : items;
154
+ const skipped = skip ? sorted.slice(skip) : sorted;
155
+ const limited = limit ? skipped.slice(0, limit) : skipped;
156
+ const idExcluded = fields && fields.id === 0;
157
+ return limited.map((item) => {
158
+ if (!fields)
159
+ return item;
160
+ return {
161
+ ...idExcluded ? {} : { id: item.id },
162
+ ...project(item, fields)
163
+ };
164
+ });
165
+ }
166
+ ensureQuery(collectionName, selector, options) {
167
+ const id = queryId(selector, options);
168
+ if (!this.queries.get(collectionName)) {
169
+ throw new Error(`Collection ${collectionName} not initialized!`);
170
+ }
171
+ let query = this.queries.get(collectionName)?.get(id);
172
+ if (!query) {
173
+ query = { selector, options };
174
+ this.queries.get(collectionName)?.set(id, query);
175
+ }
176
+ return query;
177
+ }
178
+ emitQueryUpdate(collectionName, selector, options, state, error, items) {
179
+ const id = queryId(selector, options);
180
+ const collectionQueries = this.queries.get(collectionName);
181
+ if (!collectionQueries)
182
+ throw new Error(`Collection ${collectionName} not initialized!`);
183
+ this.respond(id, { collectionName, selector, options, state, error, items }, null, "queryUpdate");
184
+ }
185
+ ensureStorageAdapter(name) {
186
+ if (this.storageAdapters.has(name))
187
+ return;
188
+ const adapter = this.options.storage(name);
189
+ if (!adapter)
190
+ return;
191
+ this.storageAdapters.set(name, adapter);
192
+ }
193
+ async checkQueryUpdates(collectionName, items) {
194
+ const queries = this.queries.get(collectionName);
195
+ if (!queries)
196
+ throw new Error(`Collection ${collectionName} not initialized!`);
197
+ const affectedQueries = [...queries.values()].filter(({ selector }) => items.some((item) => match(item, selector))) ?? [];
198
+ if (affectedQueries.length === 0)
199
+ return;
200
+ affectedQueries.forEach(({ selector, options }) => {
201
+ this.emitQueryUpdate(collectionName, selector, options, "active", null);
202
+ });
203
+ await Promise.all(affectedQueries.map(async ({ selector, options }) => {
204
+ const queryItems = await this.executeQuery(collectionName, selector, options);
205
+ this.emitQueryUpdate(collectionName, selector, options, "complete", null, queryItems);
206
+ }));
207
+ }
208
+ registerCollection = async (collectionName, indices) => {
209
+ this.collectionIndices.set(collectionName, indices);
210
+ this.queries.set(collectionName, /* @__PURE__ */ new Map());
211
+ this.ensureStorageAdapter(collectionName);
212
+ const storageAdapter = this.storageAdapters.get(collectionName);
213
+ if (!storageAdapter)
214
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
215
+ const setupPromise = (async () => {
216
+ await Promise.all([
217
+ storageAdapter.createIndex("id"),
218
+ ...indices.map((index) => storageAdapter.createIndex(index))
219
+ ]);
220
+ await storageAdapter.setup();
221
+ })();
222
+ this.storageAdapterReady.set(collectionName, setupPromise);
223
+ await setupPromise;
224
+ };
225
+ unregisterCollection = async (collectionName) => {
226
+ this.storageAdapters.delete(collectionName);
227
+ this.queries.delete(collectionName);
228
+ };
229
+ registerQuery = async (collectionName, selector, options) => {
230
+ this.ensureQuery(collectionName, selector, options);
231
+ const queryItems = await this.executeQuery(collectionName, selector, options);
232
+ this.emitQueryUpdate(collectionName, selector, options, "complete", null, queryItems);
233
+ };
234
+ unregisterQuery = async (collectionName, selector, options) => {
235
+ const id = queryId(selector, options);
236
+ if (!this.queries.get(collectionName))
237
+ throw new Error(`Collection ${collectionName} not initialized!`);
238
+ this.queries.get(collectionName)?.delete(id);
239
+ };
240
+ insert = async (collectionName, newItem) => {
241
+ const storageAdapter = this.storageAdapters.get(collectionName);
242
+ if (!storageAdapter)
243
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
244
+ const existingItems = await this.executeQuery(collectionName, { id: newItem.id }, { limit: 1 });
245
+ if (existingItems.length > 0) {
246
+ throw new Error(`Item with id ${newItem.id} already exists`);
247
+ }
248
+ await storageAdapter.insert([newItem]);
249
+ await this.checkQueryUpdates(collectionName, [newItem]);
250
+ return newItem;
251
+ };
252
+ updateOne = async (collectionName, selector, modifier) => {
253
+ const storageAdapter = this.storageAdapters.get(collectionName);
254
+ if (!storageAdapter)
255
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
256
+ const item = await this.executeQuery(collectionName, selector, { limit: 1 }).then((items) => items[0] ?? null);
257
+ const { $setOnInsert, ...restModifier } = modifier;
258
+ if (item == null)
259
+ return [];
260
+ const modifiedItem = modify(deepClone(item), restModifier);
261
+ if (item.id !== modifiedItem.id) {
262
+ const existingItems = await this.executeQuery(collectionName, { id: modifiedItem.id }, { limit: 1 });
263
+ if (existingItems.length > 0) {
264
+ throw new Error(`Item with id ${modifiedItem.id} already exists`);
265
+ }
266
+ }
267
+ await storageAdapter.replace([modifiedItem]);
268
+ await this.checkQueryUpdates(collectionName, [modifiedItem]);
269
+ return [modifiedItem];
270
+ };
271
+ updateMany = async (collectionName, selector, modifier) => {
272
+ const storageAdapter = this.storageAdapters.get(collectionName);
273
+ if (!storageAdapter)
274
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
275
+ const items = await this.executeQuery(collectionName, selector);
276
+ if (items.length === 0)
277
+ return [];
278
+ const { $setOnInsert, ...restModifier } = modifier;
279
+ const changedItems = await Promise.all(items.map(async (item) => {
280
+ const modifiedItem = modify(deepClone(item), restModifier);
281
+ if (item.id !== modifiedItem.id) {
282
+ const existingItems = await this.executeQuery(collectionName, { id: modifiedItem.id }, { limit: 1 });
283
+ if (existingItems.length > 0) {
284
+ throw new Error(`Item with id ${modifiedItem.id} already exists`);
285
+ }
286
+ }
287
+ return modifiedItem;
288
+ }));
289
+ await storageAdapter.replace(changedItems);
290
+ await this.checkQueryUpdates(collectionName, changedItems);
291
+ return changedItems;
292
+ };
293
+ replaceOne = async (collectionName, selector, replacement) => {
294
+ const storageAdapter = this.storageAdapters.get(collectionName);
295
+ if (!storageAdapter)
296
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
297
+ const item = await this.executeQuery(collectionName, selector, { limit: 1 }).then((items) => items[0] ?? null);
298
+ if (item == null)
299
+ return [];
300
+ const modifiedItem = {
301
+ ...replacement,
302
+ id: replacement.id ?? item.id
303
+ };
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
+ await storageAdapter.replace([modifiedItem]);
311
+ await this.checkQueryUpdates(collectionName, [modifiedItem]);
312
+ return [modifiedItem];
313
+ };
314
+ removeOne = async (collectionName, selector) => {
315
+ const storageAdapter = this.storageAdapters.get(collectionName);
316
+ if (!storageAdapter)
317
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
318
+ const item = await this.executeQuery(collectionName, selector, { limit: 1 }).then((items) => items[0] ?? null);
319
+ if (item == null)
320
+ return [];
321
+ await storageAdapter.remove([item]);
322
+ await this.checkQueryUpdates(collectionName, [item]);
323
+ return [item];
324
+ };
325
+ removeMany = async (collectionName, selector) => {
326
+ const storageAdapter = this.storageAdapters.get(collectionName);
327
+ if (!storageAdapter)
328
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
329
+ const items = await this.executeQuery(collectionName, selector);
330
+ if (items.length === 0)
331
+ return [];
332
+ await storageAdapter.remove(items);
333
+ await this.checkQueryUpdates(collectionName, items);
334
+ return items;
335
+ };
336
+ isReady = async (collectionName) => {
337
+ return this.storageAdapterReady.get(collectionName);
338
+ };
8
339
  }
9
340
  export {
10
- sortItems as default
341
+ WorkerDataAdapterHost as default
11
342
  };