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