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