@signaldb/core 2.0.0-beta.0 → 2.0.0-beta.10

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 (128) hide show
  1. package/dist/.vite/manifest.json +128 -75
  2. package/dist/AsyncDataAdapter.d.ts +44 -7
  3. package/dist/AutoFetchDataAdapter.d.ts +5 -8
  4. package/dist/Collection/Cursor.d.ts +6 -5
  5. package/dist/Collection/Observer.d.ts +2 -0
  6. package/dist/Collection/index.d.ts +36 -25
  7. package/dist/Collection/types.d.ts +10 -2
  8. package/dist/DataAdapter.d.ts +18 -11
  9. package/dist/DefaultDataAdapter.d.ts +7 -6
  10. package/dist/WorkerDataAdapter.d.ts +7 -6
  11. package/dist/WorkerDataAdapterHost.d.ts +14 -11
  12. package/dist/createIndex.d.ts +2 -2
  13. package/dist/createIndexProvider.d.ts +2 -2
  14. package/dist/createReactivityAdapter.d.ts +2 -2
  15. package/dist/createStorageAdapter.d.ts +1 -1
  16. package/dist/getIndexInfo.d.ts +3 -4
  17. package/dist/index.cjs.js +33 -31
  18. package/dist/index.d.ts +3 -1
  19. package/dist/index.mjs +17 -32
  20. package/dist/index10.cjs.js +23 -0
  21. package/dist/index10.mjs +21 -17
  22. package/dist/index11.cjs.js +45 -0
  23. package/dist/index11.mjs +44 -15
  24. package/dist/index12.cjs.js +22 -0
  25. package/dist/index12.mjs +21 -339
  26. package/dist/index13.cjs.js +45 -0
  27. package/dist/index13.mjs +44 -407
  28. package/dist/index14.cjs.js +86 -0
  29. package/dist/index14.mjs +85 -190
  30. package/dist/index15.cjs.js +15 -0
  31. package/dist/index15.mjs +14 -341
  32. package/dist/index16.cjs.js +136 -0
  33. package/dist/index16.mjs +134 -569
  34. package/dist/index17.cjs.js +47 -0
  35. package/dist/index17.mjs +46 -150
  36. package/dist/index18.cjs.js +15 -0
  37. package/dist/index18.mjs +14 -26
  38. package/dist/index19.cjs.js +23 -0
  39. package/dist/index19.mjs +22 -42
  40. package/dist/index2.cjs.js +33 -0
  41. package/dist/index2.mjs +32 -254
  42. package/dist/index20.cjs.js +37 -0
  43. package/dist/index20.mjs +36 -104
  44. package/dist/index21.cjs.js +35 -0
  45. package/dist/index21.mjs +34 -128
  46. package/dist/index22.cjs.js +25 -0
  47. package/dist/index22.mjs +24 -7
  48. package/dist/index23.cjs.js +19 -0
  49. package/dist/index23.mjs +17 -26
  50. package/dist/index24.cjs.js +342 -0
  51. package/dist/index24.mjs +340 -6
  52. package/dist/index25.cjs.js +542 -0
  53. package/dist/index25.mjs +541 -10
  54. package/dist/index26.cjs.js +11 -0
  55. package/dist/index26.mjs +10 -29
  56. package/dist/index27.cjs.js +11 -0
  57. package/dist/index27.mjs +10 -5
  58. package/dist/index28.cjs.js +90 -0
  59. package/dist/index28.mjs +89 -8
  60. package/dist/index29.cjs.js +424 -0
  61. package/dist/index29.mjs +423 -29
  62. package/dist/index3.cjs.js +19 -0
  63. package/dist/index3.mjs +18 -537
  64. package/dist/index30.cjs.js +72 -0
  65. package/dist/index30.mjs +71 -42
  66. package/dist/index31.cjs.js +191 -0
  67. package/dist/index31.mjs +190 -9
  68. package/dist/index32.cjs.js +21 -0
  69. package/dist/index32.mjs +21 -0
  70. package/dist/index33.cjs.js +336 -0
  71. package/dist/index33.mjs +336 -0
  72. package/dist/index34.cjs.js +539 -0
  73. package/dist/index34.mjs +539 -0
  74. package/dist/index4.cjs.js +150 -0
  75. package/dist/index4.mjs +149 -5
  76. package/dist/index5.cjs.js +254 -0
  77. package/dist/index5.mjs +252 -4
  78. package/dist/index6.cjs.js +125 -0
  79. package/dist/index6.mjs +124 -29
  80. package/dist/index7.cjs.js +33 -0
  81. package/dist/index7.mjs +32 -12
  82. package/dist/index8.cjs.js +12 -0
  83. package/dist/index8.mjs +10 -4
  84. package/dist/index9.cjs.js +11 -0
  85. package/dist/index9.mjs +10 -133
  86. package/dist/types/IndexProvider.d.ts +2 -2
  87. package/dist/types/Modifier.d.ts +1 -1
  88. package/dist/types/ReactivityAdapter.d.ts +1 -1
  89. package/dist/utils/batchOnNextTick.d.ts +16 -0
  90. package/dist/utils/createSignal.d.ts +2 -2
  91. package/dist/utils/deepClone.d.ts +1 -1
  92. package/dist/utils/getMatchingKeys.d.ts +2 -2
  93. package/dist/utils/isFieldExpression.d.ts +1 -1
  94. package/dist/utils/match.d.ts +1 -1
  95. package/dist/utils/modify.d.ts +1 -1
  96. package/dist/utils/queryId.d.ts +2 -2
  97. package/dist/utils/reactiveOrAsync.d.ts +59 -0
  98. package/package.json +3 -3
  99. package/dist/index.cjs10.js +0 -18
  100. package/dist/index.cjs11.js +0 -15
  101. package/dist/index.cjs12.js +0 -339
  102. package/dist/index.cjs13.js +0 -407
  103. package/dist/index.cjs14.js +0 -190
  104. package/dist/index.cjs15.js +0 -341
  105. package/dist/index.cjs16.js +0 -570
  106. package/dist/index.cjs17.js +0 -150
  107. package/dist/index.cjs18.js +0 -26
  108. package/dist/index.cjs19.js +0 -43
  109. package/dist/index.cjs2.js +0 -255
  110. package/dist/index.cjs20.js +0 -104
  111. package/dist/index.cjs21.js +0 -129
  112. package/dist/index.cjs22.js +0 -7
  113. package/dist/index.cjs23.js +0 -27
  114. package/dist/index.cjs24.js +0 -7
  115. package/dist/index.cjs25.js +0 -10
  116. package/dist/index.cjs26.js +0 -29
  117. package/dist/index.cjs27.js +0 -5
  118. package/dist/index.cjs28.js +0 -7
  119. package/dist/index.cjs29.js +0 -29
  120. package/dist/index.cjs3.js +0 -538
  121. package/dist/index.cjs30.js +0 -42
  122. package/dist/index.cjs31.js +0 -9
  123. package/dist/index.cjs4.js +0 -5
  124. package/dist/index.cjs5.js +0 -5
  125. package/dist/index.cjs6.js +0 -29
  126. package/dist/index.cjs7.js +0 -12
  127. package/dist/index.cjs8.js +0 -5
  128. package/dist/index.cjs9.js +0 -133
@@ -0,0 +1,336 @@
1
+ const require_isEqual = require("./index2.cjs.js");
2
+ const require_getMatchingKeys = require("./index13.cjs.js");
3
+ const require_getIndexInfo = require("./index16.cjs.js");
4
+ const require_deepClone = require("./index17.cjs.js");
5
+ const require_match = require("./index18.cjs.js");
6
+ const require_modify = require("./index19.cjs.js");
7
+ const require_project = require("./index21.cjs.js");
8
+ const require_queryId = require("./index22.cjs.js");
9
+ const require_sortItems = require("./index23.cjs.js");
10
+ const require_compact = require("./index32.cjs.js");
11
+ //#region src/WorkerDataAdapterHost.ts
12
+ var WorkerDataAdapterHost = class {
13
+ workerContext;
14
+ options;
15
+ id;
16
+ log = () => {};
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) this.onError = this.options.onError;
29
+ if (this.options.log) this.log = this.options.log;
30
+ if (typeof addEventListener === "undefined" || typeof postMessage === "undefined") throw new TypeError("WorkerDataAdapterHost can only be used in a Web Worker context");
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({
43
+ id,
44
+ workerId: this.id,
45
+ type,
46
+ data,
47
+ error
48
+ });
49
+ }
50
+ async handleMessage(workerId, id, method, args) {
51
+ if (workerId !== this.id) return;
52
+ const fn = this[method];
53
+ if (typeof fn !== "function") {
54
+ this.respond(id, null, /* @__PURE__ */ 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) throw new Error(`No persistence adapter for collection ${collectionName}`);
69
+ if (selector != null && Object.keys(selector).length === 1 && "id" in selector && typeof selector.id !== "object") return {
70
+ matched: true,
71
+ ids: require_compact.default([selector.id]),
72
+ optimizedSelector: {}
73
+ };
74
+ if (selector == null) return {
75
+ matched: false,
76
+ ids: [],
77
+ optimizedSelector: {}
78
+ };
79
+ return require_getIndexInfo.default((this.collectionIndices.get(collectionName) ?? []).map((field) => async (flatSelector) => {
80
+ if (!Object.hasOwnProperty.call(flatSelector, field)) return { matched: false };
81
+ const index = await storageAdapter.readIndex(field);
82
+ const fieldSelector = flatSelector[field];
83
+ const filteresForNull = fieldSelector == null || fieldSelector.$exists === false;
84
+ const keys = filteresForNull ? {
85
+ include: null,
86
+ exclude: [...index.keys()].filter((key) => key != null)
87
+ } : require_getMatchingKeys.default(field, flatSelector);
88
+ if (keys.include == null && keys.exclude == null) return { matched: false };
89
+ let includedIds = [];
90
+ if (keys.include == null) for (const set of index.values()) for (const pos of set) includedIds.push(pos);
91
+ else for (const key of keys.include) {
92
+ const idSet = index.get(key);
93
+ if (idSet) for (const id of idSet) includedIds.push(id);
94
+ }
95
+ if (keys.exclude != null) {
96
+ const excludeIds = /* @__PURE__ */ new Set();
97
+ for (const key of keys.exclude) {
98
+ const idSet = index.get(key);
99
+ if (idSet) for (const id of idSet) excludeIds.add(id);
100
+ }
101
+ includedIds = includedIds.filter((pos) => !excludeIds.has(pos));
102
+ }
103
+ return {
104
+ matched: true,
105
+ ids: includedIds,
106
+ fields: [field],
107
+ keepSelector: filteresForNull
108
+ };
109
+ }), selector);
110
+ }
111
+ async queryItems(collectionName, selector) {
112
+ const storageAdapter = this.storageAdapters.get(collectionName);
113
+ if (!storageAdapter) throw new Error(`No persistence adapter for collection ${collectionName}`);
114
+ const indexInfo = await this.getIndexInfo(collectionName, selector);
115
+ const matchItems = (item) => {
116
+ if (indexInfo.optimizedSelector == null) return true;
117
+ if (Object.keys(indexInfo.optimizedSelector).length <= 0) return true;
118
+ return require_match.default(item, indexInfo.optimizedSelector);
119
+ };
120
+ if (indexInfo.matched) {
121
+ const items = await storageAdapter.readIds(indexInfo.ids);
122
+ if (require_isEqual.default(indexInfo.optimizedSelector, {})) return items;
123
+ return items.filter(matchItems);
124
+ } else {
125
+ const allItems = await storageAdapter.readAll();
126
+ if (require_isEqual.default(selector, {})) return allItems;
127
+ return allItems.filter(matchItems);
128
+ }
129
+ }
130
+ async executeQuery(collectionName, selector, options) {
131
+ if (selector === null) return [];
132
+ const items = await this.queryItems(collectionName, selector || {});
133
+ const { sort, skip, limit, fields } = options || {};
134
+ const sorted = sort ? require_sortItems.default(items, sort) : items;
135
+ const skipped = skip ? sorted.slice(skip) : sorted;
136
+ const limited = limit ? skipped.slice(0, limit) : skipped;
137
+ const idExcluded = fields && fields.id === 0;
138
+ return limited.map((item) => {
139
+ if (!fields) return item;
140
+ return {
141
+ ...idExcluded ? {} : { id: item.id },
142
+ ...require_project.default(item, fields)
143
+ };
144
+ });
145
+ }
146
+ ensureQuery(collectionName, selector, options) {
147
+ const id = require_queryId.default(selector, options);
148
+ if (!this.queries.get(collectionName)) throw new Error(`Collection ${collectionName} not initialized!`);
149
+ let query = this.queries.get(collectionName)?.get(id);
150
+ if (!query) {
151
+ query = {
152
+ selector,
153
+ options
154
+ };
155
+ this.queries.get(collectionName)?.set(id, query);
156
+ }
157
+ return query;
158
+ }
159
+ emitQueryUpdate(collectionName, selector, options, state, error, items) {
160
+ const id = require_queryId.default(selector, options);
161
+ if (!this.queries.get(collectionName)) throw new Error(`Collection ${collectionName} not initialized!`);
162
+ this.respond(id, {
163
+ collectionName,
164
+ selector,
165
+ options,
166
+ state,
167
+ error,
168
+ items
169
+ }, null, "queryUpdate");
170
+ }
171
+ ensureStorageAdapter(name) {
172
+ if (this.storageAdapters.has(name)) return;
173
+ const adapter = this.options.storage(name);
174
+ if (!adapter) return;
175
+ this.storageAdapters.set(name, adapter);
176
+ }
177
+ async checkQueryUpdates(collectionName, items) {
178
+ const queries = this.queries.get(collectionName);
179
+ if (!queries) throw new Error(`Collection ${collectionName} not initialized!`);
180
+ const affectedQueries = [...queries.values()].filter(({ selector }) => items.some((item) => require_match.default(item, selector))) ?? [];
181
+ if (affectedQueries.length === 0) return;
182
+ affectedQueries.forEach(({ selector, options }) => {
183
+ this.emitQueryUpdate(collectionName, selector, options, "active", null);
184
+ });
185
+ await Promise.all(affectedQueries.map(async ({ selector, options }) => {
186
+ const queryItems = await this.executeQuery(collectionName, selector, options);
187
+ this.emitQueryUpdate(collectionName, selector, options, "complete", null, queryItems);
188
+ }));
189
+ }
190
+ registerCollection = async (collectionName, indices) => {
191
+ this.collectionIndices.set(collectionName, indices);
192
+ this.queries.set(collectionName, /* @__PURE__ */ new Map());
193
+ this.ensureStorageAdapter(collectionName);
194
+ const storageAdapter = this.storageAdapters.get(collectionName);
195
+ if (!storageAdapter) throw new Error(`No persistence adapter for collection ${collectionName}`);
196
+ const setupPromise = (async () => {
197
+ await storageAdapter.setup();
198
+ await Promise.all(indices.map((index) => storageAdapter.createIndex(index)));
199
+ })();
200
+ this.storageAdapterReady.set(collectionName, setupPromise);
201
+ await setupPromise;
202
+ };
203
+ unregisterCollection = async (collectionName) => {
204
+ this.storageAdapters.delete(collectionName);
205
+ this.queries.delete(collectionName);
206
+ };
207
+ registerQuery = async (collectionName, selector, options) => {
208
+ this.ensureQuery(collectionName, selector, options);
209
+ const queryItems = await this.executeQuery(collectionName, selector, options);
210
+ this.emitQueryUpdate(collectionName, selector, options, "complete", null, queryItems);
211
+ };
212
+ unregisterQuery = async (collectionName, selector, options) => {
213
+ const id = require_queryId.default(selector, options);
214
+ if (!this.queries.get(collectionName)) throw new Error(`Collection ${collectionName} not initialized!`);
215
+ this.queries.get(collectionName)?.delete(id);
216
+ };
217
+ insert = async (collectionName, input) => {
218
+ const storageAdapter = this.storageAdapters.get(collectionName);
219
+ if (!storageAdapter) throw new Error(`No persistence adapter for collection ${collectionName}`);
220
+ const existingItems = await this.executeQuery(collectionName, { id: { $in: input.map((i) => i[0].id) } });
221
+ const result = input.map(([item]) => {
222
+ if (item.id == null) return /* @__PURE__ */ new Error("Item must have an id");
223
+ if (existingItems.some((existing) => existing.id === item.id)) return /* @__PURE__ */ new Error(`Item with id ${item.id} already exists`);
224
+ return item;
225
+ });
226
+ const newItems = result.filter((item) => !(item instanceof Error));
227
+ await storageAdapter.insert(newItems);
228
+ await this.checkQueryUpdates(collectionName, newItems);
229
+ return result;
230
+ };
231
+ updateOne = async (collectionName, parameters) => {
232
+ const storageAdapter = this.storageAdapters.get(collectionName);
233
+ if (!storageAdapter) throw new Error(`No persistence adapter for collection ${collectionName}`);
234
+ const previousItems = [];
235
+ const result = await Promise.all(parameters.map(async ([selector, modifier]) => {
236
+ const item = await this.executeQuery(collectionName, selector, { limit: 1 }).then((items) => items[0] ?? null);
237
+ const { $setOnInsert, ...restModifier } = modifier;
238
+ if (item == null) return [];
239
+ previousItems.push(item);
240
+ const modifiedItem = require_modify.default(require_deepClone.default(item), restModifier);
241
+ if (item.id !== modifiedItem.id) {
242
+ if ((await this.executeQuery(collectionName, { id: modifiedItem.id }, { limit: 1 })).length > 0) return /* @__PURE__ */ new Error(`Item with id ${modifiedItem.id} already exists`);
243
+ }
244
+ return [modifiedItem];
245
+ }));
246
+ const modifiedItems = require_compact.default(result.filter((item) => !(item instanceof Error)).flat());
247
+ if (modifiedItems.length > 0) {
248
+ await storageAdapter.replace(modifiedItems);
249
+ await this.checkQueryUpdates(collectionName, [...modifiedItems, ...previousItems]);
250
+ }
251
+ return result;
252
+ };
253
+ updateMany = async (collectionName, parameters) => {
254
+ const storageAdapter = this.storageAdapters.get(collectionName);
255
+ if (!storageAdapter) throw new Error(`No persistence adapter for collection ${collectionName}`);
256
+ const previousItems = [];
257
+ const result = await Promise.all(parameters.map(async ([selector, modifier]) => {
258
+ const items = await this.executeQuery(collectionName, selector);
259
+ if (items.length === 0) return [];
260
+ const { $setOnInsert, ...restModifier } = modifier;
261
+ try {
262
+ return await Promise.all(items.map(async (item) => {
263
+ const modifiedItem = require_modify.default(require_deepClone.default(item), restModifier);
264
+ if (item.id !== modifiedItem.id) {
265
+ if ((await this.executeQuery(collectionName, { id: modifiedItem.id }, { limit: 1 })).length > 0) throw new Error(`Item with id ${modifiedItem.id} already exists`);
266
+ }
267
+ previousItems.push(item);
268
+ return modifiedItem;
269
+ }));
270
+ } catch (error) {
271
+ return error;
272
+ }
273
+ }));
274
+ const modifiedItems = require_compact.default(result.filter((item) => !(item instanceof Error)).flat());
275
+ if (modifiedItems.length > 0) {
276
+ await storageAdapter.replace(modifiedItems);
277
+ await this.checkQueryUpdates(collectionName, [...modifiedItems, ...previousItems]);
278
+ }
279
+ return result;
280
+ };
281
+ replaceOne = async (collectionName, parameters) => {
282
+ const storageAdapter = this.storageAdapters.get(collectionName);
283
+ if (!storageAdapter) throw new Error(`No persistence adapter for collection ${collectionName}`);
284
+ const previousItems = [];
285
+ const result = await Promise.all(parameters.map(async ([selector, replacement]) => {
286
+ const item = await this.executeQuery(collectionName, selector, { limit: 1 }).then((items) => items[0] ?? null);
287
+ if (item == null) return [];
288
+ previousItems.push(item);
289
+ const modifiedItem = {
290
+ ...replacement,
291
+ id: replacement.id ?? item.id
292
+ };
293
+ if (item.id !== modifiedItem.id) {
294
+ if ((await this.executeQuery(collectionName, { id: modifiedItem.id }, { limit: 1 })).length > 0) return /* @__PURE__ */ new Error(`Item with id ${modifiedItem.id} already exists`);
295
+ }
296
+ return [modifiedItem];
297
+ }));
298
+ const modifiedItems = require_compact.default(result.filter((item) => !(item instanceof Error)).flat());
299
+ if (modifiedItems.length > 0) {
300
+ await storageAdapter.replace(modifiedItems);
301
+ await this.checkQueryUpdates(collectionName, [...modifiedItems, ...previousItems]);
302
+ }
303
+ return result;
304
+ };
305
+ removeOne = async (collectionName, selectors) => {
306
+ const storageAdapter = this.storageAdapters.get(collectionName);
307
+ if (!storageAdapter) throw new Error(`No persistence adapter for collection ${collectionName}`);
308
+ const result = await Promise.all(selectors.map(async ([selector]) => {
309
+ const item = await this.executeQuery(collectionName, selector, { limit: 1 }).then((items) => items[0] ?? null);
310
+ if (item == null) return [];
311
+ return [item];
312
+ }));
313
+ const items = result.flat();
314
+ if (items.length > 0) {
315
+ await storageAdapter.remove(items);
316
+ await this.checkQueryUpdates(collectionName, items);
317
+ }
318
+ return result;
319
+ };
320
+ removeMany = async (collectionName, selectors) => {
321
+ const storageAdapter = this.storageAdapters.get(collectionName);
322
+ if (!storageAdapter) throw new Error(`No persistence adapter for collection ${collectionName}`);
323
+ const result = await Promise.all(selectors.map(async ([selector]) => this.executeQuery(collectionName, selector)));
324
+ const items = result.flat();
325
+ if (items.length > 0) {
326
+ await storageAdapter.remove(items);
327
+ await this.checkQueryUpdates(collectionName, items);
328
+ }
329
+ return result;
330
+ };
331
+ isReady = async (collectionName) => {
332
+ return this.storageAdapterReady.get(collectionName);
333
+ };
334
+ };
335
+ //#endregion
336
+ exports.default = WorkerDataAdapterHost;
@@ -0,0 +1,336 @@
1
+ import isEqual from "./index2.mjs";
2
+ import getMatchingKeys from "./index13.mjs";
3
+ import getIndexInfo from "./index16.mjs";
4
+ import deepClone from "./index17.mjs";
5
+ import match from "./index18.mjs";
6
+ import modify from "./index19.mjs";
7
+ import project from "./index21.mjs";
8
+ import queryId from "./index22.mjs";
9
+ import sortItems from "./index23.mjs";
10
+ import compact from "./index32.mjs";
11
+ //#region src/WorkerDataAdapterHost.ts
12
+ var WorkerDataAdapterHost = class {
13
+ workerContext;
14
+ options;
15
+ id;
16
+ log = () => {};
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) this.onError = this.options.onError;
29
+ if (this.options.log) this.log = this.options.log;
30
+ if (typeof addEventListener === "undefined" || typeof postMessage === "undefined") throw new TypeError("WorkerDataAdapterHost can only be used in a Web Worker context");
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({
43
+ id,
44
+ workerId: this.id,
45
+ type,
46
+ data,
47
+ error
48
+ });
49
+ }
50
+ async handleMessage(workerId, id, method, args) {
51
+ if (workerId !== this.id) return;
52
+ const fn = this[method];
53
+ if (typeof fn !== "function") {
54
+ this.respond(id, null, /* @__PURE__ */ 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) throw new Error(`No persistence adapter for collection ${collectionName}`);
69
+ if (selector != null && Object.keys(selector).length === 1 && "id" in selector && typeof selector.id !== "object") return {
70
+ matched: true,
71
+ ids: compact([selector.id]),
72
+ optimizedSelector: {}
73
+ };
74
+ if (selector == null) return {
75
+ matched: false,
76
+ ids: [],
77
+ optimizedSelector: {}
78
+ };
79
+ return getIndexInfo((this.collectionIndices.get(collectionName) ?? []).map((field) => async (flatSelector) => {
80
+ if (!Object.hasOwnProperty.call(flatSelector, field)) return { matched: false };
81
+ const index = await storageAdapter.readIndex(field);
82
+ const fieldSelector = flatSelector[field];
83
+ const filteresForNull = fieldSelector == null || fieldSelector.$exists === false;
84
+ const keys = filteresForNull ? {
85
+ include: null,
86
+ exclude: [...index.keys()].filter((key) => key != null)
87
+ } : getMatchingKeys(field, flatSelector);
88
+ if (keys.include == null && keys.exclude == null) return { matched: false };
89
+ let includedIds = [];
90
+ if (keys.include == null) for (const set of index.values()) for (const pos of set) includedIds.push(pos);
91
+ else for (const key of keys.include) {
92
+ const idSet = index.get(key);
93
+ if (idSet) for (const id of idSet) includedIds.push(id);
94
+ }
95
+ if (keys.exclude != null) {
96
+ const excludeIds = /* @__PURE__ */ new Set();
97
+ for (const key of keys.exclude) {
98
+ const idSet = index.get(key);
99
+ if (idSet) for (const id of idSet) excludeIds.add(id);
100
+ }
101
+ includedIds = includedIds.filter((pos) => !excludeIds.has(pos));
102
+ }
103
+ return {
104
+ matched: true,
105
+ ids: includedIds,
106
+ fields: [field],
107
+ keepSelector: filteresForNull
108
+ };
109
+ }), selector);
110
+ }
111
+ async queryItems(collectionName, selector) {
112
+ const storageAdapter = this.storageAdapters.get(collectionName);
113
+ if (!storageAdapter) throw new Error(`No persistence adapter for collection ${collectionName}`);
114
+ const indexInfo = await this.getIndexInfo(collectionName, selector);
115
+ const matchItems = (item) => {
116
+ if (indexInfo.optimizedSelector == null) return true;
117
+ if (Object.keys(indexInfo.optimizedSelector).length <= 0) return true;
118
+ return match(item, indexInfo.optimizedSelector);
119
+ };
120
+ if (indexInfo.matched) {
121
+ const items = await storageAdapter.readIds(indexInfo.ids);
122
+ if (isEqual(indexInfo.optimizedSelector, {})) return items;
123
+ return items.filter(matchItems);
124
+ } else {
125
+ const allItems = await storageAdapter.readAll();
126
+ if (isEqual(selector, {})) return allItems;
127
+ return allItems.filter(matchItems);
128
+ }
129
+ }
130
+ async executeQuery(collectionName, selector, options) {
131
+ if (selector === null) return [];
132
+ const items = await this.queryItems(collectionName, selector || {});
133
+ const { sort, skip, limit, fields } = options || {};
134
+ const sorted = sort ? sortItems(items, sort) : items;
135
+ const skipped = skip ? sorted.slice(skip) : sorted;
136
+ const limited = limit ? skipped.slice(0, limit) : skipped;
137
+ const idExcluded = fields && fields.id === 0;
138
+ return limited.map((item) => {
139
+ if (!fields) return item;
140
+ return {
141
+ ...idExcluded ? {} : { id: item.id },
142
+ ...project(item, fields)
143
+ };
144
+ });
145
+ }
146
+ ensureQuery(collectionName, selector, options) {
147
+ const id = queryId(selector, options);
148
+ if (!this.queries.get(collectionName)) throw new Error(`Collection ${collectionName} not initialized!`);
149
+ let query = this.queries.get(collectionName)?.get(id);
150
+ if (!query) {
151
+ query = {
152
+ selector,
153
+ options
154
+ };
155
+ this.queries.get(collectionName)?.set(id, query);
156
+ }
157
+ return query;
158
+ }
159
+ emitQueryUpdate(collectionName, selector, options, state, error, items) {
160
+ const id = queryId(selector, options);
161
+ if (!this.queries.get(collectionName)) throw new Error(`Collection ${collectionName} not initialized!`);
162
+ this.respond(id, {
163
+ collectionName,
164
+ selector,
165
+ options,
166
+ state,
167
+ error,
168
+ items
169
+ }, null, "queryUpdate");
170
+ }
171
+ ensureStorageAdapter(name) {
172
+ if (this.storageAdapters.has(name)) return;
173
+ const adapter = this.options.storage(name);
174
+ if (!adapter) return;
175
+ this.storageAdapters.set(name, adapter);
176
+ }
177
+ async checkQueryUpdates(collectionName, items) {
178
+ const queries = this.queries.get(collectionName);
179
+ if (!queries) throw new Error(`Collection ${collectionName} not initialized!`);
180
+ const affectedQueries = [...queries.values()].filter(({ selector }) => items.some((item) => match(item, selector))) ?? [];
181
+ if (affectedQueries.length === 0) return;
182
+ affectedQueries.forEach(({ selector, options }) => {
183
+ this.emitQueryUpdate(collectionName, selector, options, "active", null);
184
+ });
185
+ await Promise.all(affectedQueries.map(async ({ selector, options }) => {
186
+ const queryItems = await this.executeQuery(collectionName, selector, options);
187
+ this.emitQueryUpdate(collectionName, selector, options, "complete", null, queryItems);
188
+ }));
189
+ }
190
+ registerCollection = async (collectionName, indices) => {
191
+ this.collectionIndices.set(collectionName, indices);
192
+ this.queries.set(collectionName, /* @__PURE__ */ new Map());
193
+ this.ensureStorageAdapter(collectionName);
194
+ const storageAdapter = this.storageAdapters.get(collectionName);
195
+ if (!storageAdapter) throw new Error(`No persistence adapter for collection ${collectionName}`);
196
+ const setupPromise = (async () => {
197
+ await storageAdapter.setup();
198
+ await Promise.all(indices.map((index) => storageAdapter.createIndex(index)));
199
+ })();
200
+ this.storageAdapterReady.set(collectionName, setupPromise);
201
+ await setupPromise;
202
+ };
203
+ unregisterCollection = async (collectionName) => {
204
+ this.storageAdapters.delete(collectionName);
205
+ this.queries.delete(collectionName);
206
+ };
207
+ registerQuery = async (collectionName, selector, options) => {
208
+ this.ensureQuery(collectionName, selector, options);
209
+ const queryItems = await this.executeQuery(collectionName, selector, options);
210
+ this.emitQueryUpdate(collectionName, selector, options, "complete", null, queryItems);
211
+ };
212
+ unregisterQuery = async (collectionName, selector, options) => {
213
+ const id = queryId(selector, options);
214
+ if (!this.queries.get(collectionName)) throw new Error(`Collection ${collectionName} not initialized!`);
215
+ this.queries.get(collectionName)?.delete(id);
216
+ };
217
+ insert = async (collectionName, input) => {
218
+ const storageAdapter = this.storageAdapters.get(collectionName);
219
+ if (!storageAdapter) throw new Error(`No persistence adapter for collection ${collectionName}`);
220
+ const existingItems = await this.executeQuery(collectionName, { id: { $in: input.map((i) => i[0].id) } });
221
+ const result = input.map(([item]) => {
222
+ if (item.id == null) return /* @__PURE__ */ new Error("Item must have an id");
223
+ if (existingItems.some((existing) => existing.id === item.id)) return /* @__PURE__ */ new Error(`Item with id ${item.id} already exists`);
224
+ return item;
225
+ });
226
+ const newItems = result.filter((item) => !(item instanceof Error));
227
+ await storageAdapter.insert(newItems);
228
+ await this.checkQueryUpdates(collectionName, newItems);
229
+ return result;
230
+ };
231
+ updateOne = async (collectionName, parameters) => {
232
+ const storageAdapter = this.storageAdapters.get(collectionName);
233
+ if (!storageAdapter) throw new Error(`No persistence adapter for collection ${collectionName}`);
234
+ const previousItems = [];
235
+ const result = await Promise.all(parameters.map(async ([selector, modifier]) => {
236
+ const item = await this.executeQuery(collectionName, selector, { limit: 1 }).then((items) => items[0] ?? null);
237
+ const { $setOnInsert, ...restModifier } = modifier;
238
+ if (item == null) return [];
239
+ previousItems.push(item);
240
+ const modifiedItem = modify(deepClone(item), restModifier);
241
+ if (item.id !== modifiedItem.id) {
242
+ if ((await this.executeQuery(collectionName, { id: modifiedItem.id }, { limit: 1 })).length > 0) return /* @__PURE__ */ new Error(`Item with id ${modifiedItem.id} already exists`);
243
+ }
244
+ return [modifiedItem];
245
+ }));
246
+ const modifiedItems = compact(result.filter((item) => !(item instanceof Error)).flat());
247
+ if (modifiedItems.length > 0) {
248
+ await storageAdapter.replace(modifiedItems);
249
+ await this.checkQueryUpdates(collectionName, [...modifiedItems, ...previousItems]);
250
+ }
251
+ return result;
252
+ };
253
+ updateMany = async (collectionName, parameters) => {
254
+ const storageAdapter = this.storageAdapters.get(collectionName);
255
+ if (!storageAdapter) throw new Error(`No persistence adapter for collection ${collectionName}`);
256
+ const previousItems = [];
257
+ const result = await Promise.all(parameters.map(async ([selector, modifier]) => {
258
+ const items = await this.executeQuery(collectionName, selector);
259
+ if (items.length === 0) return [];
260
+ const { $setOnInsert, ...restModifier } = modifier;
261
+ try {
262
+ return await Promise.all(items.map(async (item) => {
263
+ const modifiedItem = modify(deepClone(item), restModifier);
264
+ if (item.id !== modifiedItem.id) {
265
+ if ((await this.executeQuery(collectionName, { id: modifiedItem.id }, { limit: 1 })).length > 0) throw new Error(`Item with id ${modifiedItem.id} already exists`);
266
+ }
267
+ previousItems.push(item);
268
+ return modifiedItem;
269
+ }));
270
+ } catch (error) {
271
+ return error;
272
+ }
273
+ }));
274
+ const modifiedItems = compact(result.filter((item) => !(item instanceof Error)).flat());
275
+ if (modifiedItems.length > 0) {
276
+ await storageAdapter.replace(modifiedItems);
277
+ await this.checkQueryUpdates(collectionName, [...modifiedItems, ...previousItems]);
278
+ }
279
+ return result;
280
+ };
281
+ replaceOne = async (collectionName, parameters) => {
282
+ const storageAdapter = this.storageAdapters.get(collectionName);
283
+ if (!storageAdapter) throw new Error(`No persistence adapter for collection ${collectionName}`);
284
+ const previousItems = [];
285
+ const result = await Promise.all(parameters.map(async ([selector, replacement]) => {
286
+ const item = await this.executeQuery(collectionName, selector, { limit: 1 }).then((items) => items[0] ?? null);
287
+ if (item == null) return [];
288
+ previousItems.push(item);
289
+ const modifiedItem = {
290
+ ...replacement,
291
+ id: replacement.id ?? item.id
292
+ };
293
+ if (item.id !== modifiedItem.id) {
294
+ if ((await this.executeQuery(collectionName, { id: modifiedItem.id }, { limit: 1 })).length > 0) return /* @__PURE__ */ new Error(`Item with id ${modifiedItem.id} already exists`);
295
+ }
296
+ return [modifiedItem];
297
+ }));
298
+ const modifiedItems = compact(result.filter((item) => !(item instanceof Error)).flat());
299
+ if (modifiedItems.length > 0) {
300
+ await storageAdapter.replace(modifiedItems);
301
+ await this.checkQueryUpdates(collectionName, [...modifiedItems, ...previousItems]);
302
+ }
303
+ return result;
304
+ };
305
+ removeOne = async (collectionName, selectors) => {
306
+ const storageAdapter = this.storageAdapters.get(collectionName);
307
+ if (!storageAdapter) throw new Error(`No persistence adapter for collection ${collectionName}`);
308
+ const result = await Promise.all(selectors.map(async ([selector]) => {
309
+ const item = await this.executeQuery(collectionName, selector, { limit: 1 }).then((items) => items[0] ?? null);
310
+ if (item == null) return [];
311
+ return [item];
312
+ }));
313
+ const items = result.flat();
314
+ if (items.length > 0) {
315
+ await storageAdapter.remove(items);
316
+ await this.checkQueryUpdates(collectionName, items);
317
+ }
318
+ return result;
319
+ };
320
+ removeMany = async (collectionName, selectors) => {
321
+ const storageAdapter = this.storageAdapters.get(collectionName);
322
+ if (!storageAdapter) throw new Error(`No persistence adapter for collection ${collectionName}`);
323
+ const result = await Promise.all(selectors.map(async ([selector]) => this.executeQuery(collectionName, selector)));
324
+ const items = result.flat();
325
+ if (items.length > 0) {
326
+ await storageAdapter.remove(items);
327
+ await this.checkQueryUpdates(collectionName, items);
328
+ }
329
+ return result;
330
+ };
331
+ isReady = async (collectionName) => {
332
+ return this.storageAdapterReady.get(collectionName);
333
+ };
334
+ };
335
+ //#endregion
336
+ export { WorkerDataAdapterHost as default };