@signaldb/core 2.0.0-beta.6 → 2.0.0-beta.7

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 (104) hide show
  1. package/dist/.vite/manifest.json +118 -84
  2. package/dist/AsyncDataAdapter.d.ts +1 -1
  3. package/dist/index.cjs.js +33 -34
  4. package/dist/index.mjs +17 -35
  5. package/dist/index10.cjs.js +23 -0
  6. package/dist/index10.mjs +21 -17
  7. package/dist/index11.cjs.js +45 -0
  8. package/dist/index11.mjs +44 -15
  9. package/dist/index12.cjs.js +22 -0
  10. package/dist/index12.mjs +21 -47
  11. package/dist/index13.cjs.js +45 -0
  12. package/dist/index13.mjs +44 -365
  13. package/dist/index14.cjs.js +86 -0
  14. package/dist/index14.mjs +85 -416
  15. package/dist/index15.cjs.js +15 -0
  16. package/dist/index15.mjs +14 -206
  17. package/dist/index16.cjs.js +136 -0
  18. package/dist/index16.mjs +135 -388
  19. package/dist/index17.cjs.js +47 -0
  20. package/dist/index17.mjs +45 -578
  21. package/dist/index18.cjs.js +15 -0
  22. package/dist/index18.mjs +14 -157
  23. package/dist/index19.cjs.js +23 -0
  24. package/dist/index19.mjs +22 -26
  25. package/dist/index2.cjs.js +33 -0
  26. package/dist/index2.mjs +32 -258
  27. package/dist/index20.cjs.js +37 -0
  28. package/dist/index20.mjs +36 -41
  29. package/dist/index21.cjs.js +35 -0
  30. package/dist/index21.mjs +34 -16
  31. package/dist/index22.cjs.js +25 -0
  32. package/dist/index22.mjs +24 -104
  33. package/dist/index23.cjs.js +19 -0
  34. package/dist/index23.mjs +18 -128
  35. package/dist/index24.cjs.js +342 -0
  36. package/dist/index24.mjs +340 -6
  37. package/dist/index25.cjs.js +519 -0
  38. package/dist/index25.mjs +518 -27
  39. package/dist/index26.cjs.js +11 -0
  40. package/dist/index26.mjs +10 -10
  41. package/dist/index27.cjs.js +11 -0
  42. package/dist/index27.mjs +10 -29
  43. package/dist/index28.cjs.js +90 -0
  44. package/dist/index28.mjs +88 -46
  45. package/dist/index29.cjs.js +370 -0
  46. package/dist/index29.mjs +369 -8
  47. package/dist/index3.cjs.js +19 -0
  48. package/dist/index3.mjs +18 -539
  49. package/dist/index30.cjs.js +72 -0
  50. package/dist/index30.mjs +71 -9
  51. package/dist/index31.cjs.js +191 -0
  52. package/dist/index31.mjs +190 -7
  53. package/dist/index32.cjs.js +21 -0
  54. package/dist/index32.mjs +20 -42
  55. package/dist/index33.cjs.js +336 -0
  56. package/dist/index33.mjs +335 -29
  57. package/dist/index34.cjs.js +539 -0
  58. package/dist/index34.mjs +537 -4
  59. package/dist/index4.cjs.js +150 -0
  60. package/dist/index4.mjs +149 -5
  61. package/dist/index5.cjs.js +254 -0
  62. package/dist/index5.mjs +252 -4
  63. package/dist/index6.cjs.js +125 -0
  64. package/dist/index6.mjs +124 -29
  65. package/dist/index7.cjs.js +33 -0
  66. package/dist/index7.mjs +32 -12
  67. package/dist/index8.cjs.js +12 -0
  68. package/dist/index8.mjs +10 -4
  69. package/dist/index9.cjs.js +11 -0
  70. package/dist/index9.mjs +10 -133
  71. package/package.json +1 -1
  72. package/dist/index.cjs10.js +0 -18
  73. package/dist/index.cjs11.js +0 -15
  74. package/dist/index.cjs12.js +0 -48
  75. package/dist/index.cjs13.js +0 -365
  76. package/dist/index.cjs14.js +0 -416
  77. package/dist/index.cjs15.js +0 -206
  78. package/dist/index.cjs16.js +0 -388
  79. package/dist/index.cjs17.js +0 -579
  80. package/dist/index.cjs18.js +0 -157
  81. package/dist/index.cjs19.js +0 -26
  82. package/dist/index.cjs2.js +0 -259
  83. package/dist/index.cjs20.js +0 -42
  84. package/dist/index.cjs21.js +0 -16
  85. package/dist/index.cjs22.js +0 -104
  86. package/dist/index.cjs23.js +0 -129
  87. package/dist/index.cjs24.js +0 -7
  88. package/dist/index.cjs25.js +0 -27
  89. package/dist/index.cjs26.js +0 -10
  90. package/dist/index.cjs27.js +0 -29
  91. package/dist/index.cjs28.js +0 -46
  92. package/dist/index.cjs29.js +0 -8
  93. package/dist/index.cjs3.js +0 -540
  94. package/dist/index.cjs30.js +0 -9
  95. package/dist/index.cjs31.js +0 -7
  96. package/dist/index.cjs32.js +0 -42
  97. package/dist/index.cjs33.js +0 -29
  98. package/dist/index.cjs34.js +0 -5
  99. package/dist/index.cjs4.js +0 -5
  100. package/dist/index.cjs5.js +0 -5
  101. package/dist/index.cjs6.js +0 -29
  102. package/dist/index.cjs7.js +0 -12
  103. package/dist/index.cjs8.js +0 -5
  104. package/dist/index.cjs9.js +0 -133
package/dist/index16.mjs CHANGED
@@ -1,389 +1,136 @@
1
- import deepClone from "./index20.mjs";
2
- import match from "./index24.mjs";
3
- import modify from "./index7.mjs";
4
- import queryId from "./index21.mjs";
5
- import isEqual from "./index6.mjs";
6
- import getIndexInfo from "./index23.mjs";
7
- import getMatchingKeys from "./index27.mjs";
8
- import sortItems from "./index26.mjs";
9
- import project from "./index25.mjs";
10
- import compact from "./index29.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
- if (selector === null)
159
- return [];
160
- const items = await this.queryItems(collectionName, selector || {});
161
- const { sort, skip, limit, fields } = options || {};
162
- const sorted = sort ? sortItems(items, sort) : items;
163
- const skipped = skip ? sorted.slice(skip) : sorted;
164
- const limited = limit ? skipped.slice(0, limit) : skipped;
165
- const idExcluded = fields && fields.id === 0;
166
- return limited.map((item) => {
167
- if (!fields)
168
- return item;
169
- return {
170
- ...idExcluded ? {} : { id: item.id },
171
- ...project(item, fields)
172
- };
173
- });
174
- }
175
- ensureQuery(collectionName, selector, options) {
176
- const id = queryId(selector, options);
177
- if (!this.queries.get(collectionName)) {
178
- throw new Error(`Collection ${collectionName} not initialized!`);
179
- }
180
- let query = this.queries.get(collectionName)?.get(id);
181
- if (!query) {
182
- query = { selector, options };
183
- this.queries.get(collectionName)?.set(id, query);
184
- }
185
- return query;
186
- }
187
- emitQueryUpdate(collectionName, selector, options, state, error, items) {
188
- const id = queryId(selector, options);
189
- const collectionQueries = this.queries.get(collectionName);
190
- if (!collectionQueries)
191
- throw new Error(`Collection ${collectionName} not initialized!`);
192
- this.respond(id, { collectionName, selector, options, state, error, items }, null, "queryUpdate");
193
- }
194
- ensureStorageAdapter(name) {
195
- if (this.storageAdapters.has(name))
196
- return;
197
- const adapter = this.options.storage(name);
198
- if (!adapter)
199
- return;
200
- this.storageAdapters.set(name, adapter);
201
- }
202
- async checkQueryUpdates(collectionName, items) {
203
- const queries = this.queries.get(collectionName);
204
- if (!queries)
205
- throw new Error(`Collection ${collectionName} not initialized!`);
206
- const affectedQueries = [...queries.values()].filter(({ selector }) => items.some((item) => match(item, selector))) ?? [];
207
- if (affectedQueries.length === 0)
208
- return;
209
- affectedQueries.forEach(({ selector, options }) => {
210
- this.emitQueryUpdate(collectionName, selector, options, "active", null);
211
- });
212
- await Promise.all(affectedQueries.map(async ({ selector, options }) => {
213
- const queryItems = await this.executeQuery(collectionName, selector, options);
214
- this.emitQueryUpdate(collectionName, selector, options, "complete", null, queryItems);
215
- }));
216
- }
217
- registerCollection = async (collectionName, indices) => {
218
- this.collectionIndices.set(collectionName, indices);
219
- this.queries.set(collectionName, /* @__PURE__ */ new Map());
220
- this.ensureStorageAdapter(collectionName);
221
- const storageAdapter = this.storageAdapters.get(collectionName);
222
- if (!storageAdapter)
223
- throw new Error(`No persistence adapter for collection ${collectionName}`);
224
- const setupPromise = (async () => {
225
- await storageAdapter.setup();
226
- await Promise.all(indices.map((index) => storageAdapter.createIndex(index)));
227
- })();
228
- this.storageAdapterReady.set(collectionName, setupPromise);
229
- await setupPromise;
230
- };
231
- unregisterCollection = async (collectionName) => {
232
- this.storageAdapters.delete(collectionName);
233
- this.queries.delete(collectionName);
234
- };
235
- registerQuery = async (collectionName, selector, options) => {
236
- this.ensureQuery(collectionName, selector, options);
237
- const queryItems = await this.executeQuery(collectionName, selector, options);
238
- this.emitQueryUpdate(collectionName, selector, options, "complete", null, queryItems);
239
- };
240
- unregisterQuery = async (collectionName, selector, options) => {
241
- const id = queryId(selector, options);
242
- if (!this.queries.get(collectionName))
243
- throw new Error(`Collection ${collectionName} not initialized!`);
244
- this.queries.get(collectionName)?.delete(id);
245
- };
246
- insert = async (collectionName, input) => {
247
- const storageAdapter = this.storageAdapters.get(collectionName);
248
- if (!storageAdapter)
249
- throw new Error(`No persistence adapter for collection ${collectionName}`);
250
- const existingItems = await this.executeQuery(collectionName, { id: { $in: input.map((i) => i[0].id) } });
251
- const result = input.map(([item]) => {
252
- if (item.id == null)
253
- return new Error("Item must have an id");
254
- if (existingItems.some((existing) => existing.id === item.id)) {
255
- return new Error(`Item with id ${item.id} already exists`);
256
- }
257
- return item;
258
- });
259
- const newItems = result.filter((item) => !(item instanceof Error));
260
- await storageAdapter.insert(newItems);
261
- await this.checkQueryUpdates(collectionName, newItems);
262
- return result;
263
- };
264
- updateOne = async (collectionName, parameters) => {
265
- const storageAdapter = this.storageAdapters.get(collectionName);
266
- if (!storageAdapter)
267
- throw new Error(`No persistence adapter for collection ${collectionName}`);
268
- const previousItems = [];
269
- const result = await Promise.all(parameters.map(async ([selector, modifier]) => {
270
- const item = await this.executeQuery(collectionName, selector, { limit: 1 }).then((items) => items[0] ?? null);
271
- const { $setOnInsert, ...restModifier } = modifier;
272
- if (item == null)
273
- return [];
274
- previousItems.push(item);
275
- const modifiedItem = modify(deepClone(item), restModifier);
276
- if (item.id !== modifiedItem.id) {
277
- const existingItems = await this.executeQuery(collectionName, { id: modifiedItem.id }, { limit: 1 });
278
- if (existingItems.length > 0) {
279
- return new Error(`Item with id ${modifiedItem.id} already exists`);
280
- }
281
- }
282
- return [modifiedItem];
283
- }));
284
- const modifiedItems = compact(result.filter((item) => !(item instanceof Error)).flat());
285
- if (modifiedItems.length > 0) {
286
- await storageAdapter.replace(modifiedItems);
287
- await this.checkQueryUpdates(collectionName, [...modifiedItems, ...previousItems]);
288
- }
289
- return result;
290
- };
291
- updateMany = async (collectionName, parameters) => {
292
- const storageAdapter = this.storageAdapters.get(collectionName);
293
- if (!storageAdapter)
294
- throw new Error(`No persistence adapter for collection ${collectionName}`);
295
- const previousItems = [];
296
- const result = await Promise.all(parameters.map(async ([selector, modifier]) => {
297
- const items = await this.executeQuery(collectionName, selector);
298
- if (items.length === 0)
299
- return [];
300
- const { $setOnInsert, ...restModifier } = modifier;
301
- try {
302
- const changedItems = await Promise.all(items.map(async (item) => {
303
- const modifiedItem = modify(deepClone(item), restModifier);
304
- if (item.id !== modifiedItem.id) {
305
- const existingItems = await this.executeQuery(collectionName, { id: modifiedItem.id }, { limit: 1 });
306
- if (existingItems.length > 0) {
307
- throw new Error(`Item with id ${modifiedItem.id} already exists`);
308
- }
309
- }
310
- previousItems.push(item);
311
- return modifiedItem;
312
- }));
313
- return changedItems;
314
- } catch (error) {
315
- return error;
316
- }
317
- }));
318
- const modifiedItems = compact(result.filter((item) => !(item instanceof Error)).flat());
319
- if (modifiedItems.length > 0) {
320
- await storageAdapter.replace(modifiedItems);
321
- await this.checkQueryUpdates(collectionName, [...modifiedItems, ...previousItems]);
322
- }
323
- return result;
324
- };
325
- replaceOne = async (collectionName, parameters) => {
326
- const storageAdapter = this.storageAdapters.get(collectionName);
327
- if (!storageAdapter)
328
- throw new Error(`No persistence adapter for collection ${collectionName}`);
329
- const previousItems = [];
330
- const result = await Promise.all(parameters.map(async ([selector, replacement]) => {
331
- const item = await this.executeQuery(collectionName, selector, { limit: 1 }).then((items) => items[0] ?? null);
332
- if (item == null)
333
- return [];
334
- previousItems.push(item);
335
- const modifiedItem = {
336
- ...replacement,
337
- id: replacement.id ?? item.id
338
- };
339
- if (item.id !== modifiedItem.id) {
340
- const existingItems = await this.executeQuery(collectionName, { id: modifiedItem.id }, { limit: 1 });
341
- if (existingItems.length > 0) {
342
- return new Error(`Item with id ${modifiedItem.id} already exists`);
343
- }
344
- }
345
- return [modifiedItem];
346
- }));
347
- const modifiedItems = compact(result.filter((item) => !(item instanceof Error)).flat());
348
- if (modifiedItems.length > 0) {
349
- await storageAdapter.replace(modifiedItems);
350
- await this.checkQueryUpdates(collectionName, [...modifiedItems, ...previousItems]);
351
- }
352
- return result;
353
- };
354
- removeOne = async (collectionName, selectors) => {
355
- const storageAdapter = this.storageAdapters.get(collectionName);
356
- if (!storageAdapter)
357
- throw new Error(`No persistence adapter for collection ${collectionName}`);
358
- const result = await Promise.all(selectors.map(async ([selector]) => {
359
- const item = await this.executeQuery(collectionName, selector, { limit: 1 }).then((items2) => items2[0] ?? null);
360
- if (item == null)
361
- return [];
362
- return [item];
363
- }));
364
- const items = result.flat();
365
- if (items.length > 0) {
366
- await storageAdapter.remove(items);
367
- await this.checkQueryUpdates(collectionName, items);
368
- }
369
- return result;
370
- };
371
- removeMany = async (collectionName, selectors) => {
372
- const storageAdapter = this.storageAdapters.get(collectionName);
373
- if (!storageAdapter)
374
- throw new Error(`No persistence adapter for collection ${collectionName}`);
375
- const result = await Promise.all(selectors.map(async ([selector]) => this.executeQuery(collectionName, selector)));
376
- const items = result.flat();
377
- if (items.length > 0) {
378
- await storageAdapter.remove(items);
379
- await this.checkQueryUpdates(collectionName, items);
380
- }
381
- return result;
382
- };
383
- isReady = async (collectionName) => {
384
- return this.storageAdapterReady.get(collectionName);
385
- };
1
+ import intersection from "./index15.mjs";
2
+ //#region src/getIndexInfo.ts
3
+ /**
4
+ * Retrieves merged index information for a given flat selector by querying multiple
5
+ * index providers. Combines results from all index providers to determine matched ids
6
+ * and an optimized selector.
7
+ * @template T - The type of the items in the collection.
8
+ * @template I - The type of the unique identifier for the items.
9
+ * @param queryFunctions - An array of index providers to query.
10
+ * @param selector - The flat selector used to filter items.
11
+ * @returns An object containing:
12
+ * - `matched`: A boolean indicating if the selector matched any items.
13
+ * - `ids`: An array of matched item ids.
14
+ * - `optimizedSelector`: A flat selector optimized based on the index results.
15
+ */
16
+ function getMergedIndexInfo(queryFunctions, selector) {
17
+ return queryFunctions.reduce((memoOrPromise, queryFunction) => {
18
+ const resultOrPromise = queryFunction(selector);
19
+ const processResult = (memo, result) => {
20
+ if (!result.matched) return memo;
21
+ const optimizedSelector = result.keepSelector ? memo.optimizedSelector : Object.fromEntries(Object.entries(memo.optimizedSelector).filter(([key]) => !result.fields.includes(key)));
22
+ return {
23
+ matched: true,
24
+ ids: [...new Set(memo.matched ? intersection(memo.ids, result.ids) : result.ids)],
25
+ optimizedSelector
26
+ };
27
+ };
28
+ if (resultOrPromise instanceof Promise) return resultOrPromise.then(async (result) => {
29
+ return processResult(memoOrPromise instanceof Promise ? await memoOrPromise : memoOrPromise, result);
30
+ });
31
+ const memo = memoOrPromise;
32
+ if (memo instanceof Promise) throw new Error("Mixing async and sync index providers is not supported");
33
+ return processResult(memo, resultOrPromise);
34
+ }, {
35
+ matched: false,
36
+ ids: [],
37
+ optimizedSelector: { ...selector }
38
+ });
386
39
  }
387
- export {
388
- WorkerDataAdapterHost as default
389
- };
40
+ /**
41
+ * Optimizes a logic gate ($and/$or) of selectors by querying multiple index providers.
42
+ * @param queryFunctions - An array of index providers to query.
43
+ * @param logicGate - An array of selectors representing the logic gate.
44
+ * @param idsCallback - A callback function called with matched ids.
45
+ * @returns An array of optimized selectors or a promise that resolves to such an array.
46
+ */
47
+ function optimizeLogicGate(queryFunctions, logicGate, idsCallback) {
48
+ return logicGate.reduce((memoOrPromise, sel) => {
49
+ const getSelector = (indexInfo) => {
50
+ const { matched: selMatched, ids: selIds, optimizedSelector } = indexInfo;
51
+ if (selMatched) {
52
+ idsCallback(true, selIds);
53
+ if (Object.keys(optimizedSelector).length > 0) return optimizedSelector;
54
+ } else {
55
+ idsCallback(false, []);
56
+ return sel;
57
+ }
58
+ };
59
+ const indexInfoOrPromise = getIndexInfo(queryFunctions, sel);
60
+ if (indexInfoOrPromise instanceof Promise) return indexInfoOrPromise.then(async (indexInfo) => {
61
+ const memo = memoOrPromise instanceof Promise ? await memoOrPromise : memoOrPromise;
62
+ const optimizedSelector = getSelector(indexInfo);
63
+ if (optimizedSelector) memo.push(optimizedSelector);
64
+ return memo;
65
+ });
66
+ const memo = memoOrPromise;
67
+ if (memo instanceof Promise) throw new Error("Mixing async and sync index providers is not supported");
68
+ const optimizedSelector = getSelector(indexInfoOrPromise);
69
+ if (optimizedSelector) memo.push(optimizedSelector);
70
+ return memo;
71
+ }, []);
72
+ }
73
+ /**
74
+ * Retrieves index information for a given complex selector by querying multiple
75
+ * index providers. Handles nested `$and` and `$or` conditions in the selector and
76
+ * optimizes the selector to minimize processing overhead.
77
+ * @template T - The type of the items in the collection.
78
+ * @template I - The type of the unique identifier for the items.
79
+ * @param queryFunctions - An array of index providers to query.
80
+ * @param selector - The complex selector used to filter items.
81
+ * @returns An object containing:
82
+ * - `matched`: A boolean indicating if the selector matched any items.
83
+ * - `ids`: An array of matched item ids.
84
+ * - `optimizedSelector`: A selector optimized based on the index results, with unused
85
+ * conditions removed.
86
+ */
87
+ function getIndexInfo(queryFunctions, selector) {
88
+ if (selector == null || Object.keys(selector).length <= 0) return {
89
+ matched: false,
90
+ ids: [],
91
+ optimizedSelector: selector
92
+ };
93
+ const { $and, $or, ...rest } = selector;
94
+ const flatInfoOrPromise = getMergedIndexInfo(queryFunctions, rest);
95
+ const processFlatInfo = (flatInfo) => {
96
+ let { matched, ids } = flatInfo;
97
+ const newSelector = flatInfo.optimizedSelector;
98
+ const $andNewOrPromise = Array.isArray($and) ? optimizeLogicGate(queryFunctions, $and, (match, selIds) => {
99
+ if (!match) return;
100
+ ids = matched ? intersection(ids, selIds) : selIds;
101
+ matched = true;
102
+ }) : void 0;
103
+ const process$and = ($andNew) => {
104
+ if ($andNew && $andNew.length > 0) newSelector.$and = $andNew;
105
+ let hasNonIndexField = false;
106
+ const matchedBefore = matched;
107
+ const idsBefore = ids;
108
+ const process$or = ($orNew) => {
109
+ if (hasNonIndexField || $orNew && $orNew.length > 0) {
110
+ newSelector.$or = $or;
111
+ matched = matchedBefore;
112
+ ids = idsBefore;
113
+ }
114
+ return {
115
+ matched,
116
+ ids: ids || [],
117
+ optimizedSelector: newSelector
118
+ };
119
+ };
120
+ const $orNewOrPromise = Array.isArray($or) ? optimizeLogicGate(queryFunctions, $or, (match, selIds) => {
121
+ if (match) {
122
+ ids = [...new Set([...ids, ...selIds])];
123
+ matched = true;
124
+ } else hasNonIndexField = true;
125
+ }) : void 0;
126
+ if ($orNewOrPromise instanceof Promise) return $orNewOrPromise.then(($orNew) => process$or($orNew));
127
+ return process$or($orNewOrPromise);
128
+ };
129
+ if ($andNewOrPromise instanceof Promise) return $andNewOrPromise.then(($andNew) => process$and($andNew));
130
+ return process$and($andNewOrPromise);
131
+ };
132
+ if (flatInfoOrPromise instanceof Promise) return flatInfoOrPromise.then(processFlatInfo);
133
+ return processFlatInfo(flatInfoOrPromise);
134
+ }
135
+ //#endregion
136
+ export { getIndexInfo as default };
@@ -0,0 +1,47 @@
1
+ //#region src/utils/deepClone.ts
2
+ /**
3
+ * Performs a deep clone of a value, supporting various types including arrays, objects,
4
+ * Maps, Sets, Dates, and RegExps. Functions are not supported and will throw an error.
5
+ * @template T - The type of the value to clone.
6
+ * @param value - The value to deep clone.
7
+ * @returns A deep copy of the provided value.
8
+ * @throws {Error} An error if the value is a function, as cloning functions is not supported.
9
+ */
10
+ function clone(value) {
11
+ if (typeof value === "function") throw new Error("Cloning functions is not supported");
12
+ if (value === null || typeof value !== "object") return value;
13
+ if (value instanceof Date) return new Date(value);
14
+ if (Array.isArray(value)) return value.map((item) => clone(item));
15
+ if (value instanceof Map) {
16
+ const result = /* @__PURE__ */ new Map();
17
+ value.forEach((currentValue, key) => {
18
+ result.set(key, clone(currentValue));
19
+ });
20
+ return result;
21
+ }
22
+ if (value instanceof Set) {
23
+ const result = /* @__PURE__ */ new Set();
24
+ value.forEach((currentValue) => {
25
+ result.add(clone(currentValue));
26
+ });
27
+ return result;
28
+ }
29
+ if (value instanceof RegExp) return new RegExp(value);
30
+ const result = {};
31
+ for (const key in value) if (Object.hasOwnProperty.call(value, key)) result[key] = clone(value[key]);
32
+ return result;
33
+ }
34
+ /**
35
+ * Creates a deep clone of an object. Uses the `structuredClone` function if available,
36
+ * otherwise falls back to a manual deep clone implementation.
37
+ * @template T - The type of the object to clone.
38
+ * @param object - The object to deep clone.
39
+ * @returns A deep copy of the provided object.
40
+ */
41
+ function deepClone(object) {
42
+ if (typeof structuredClone === "function") return structuredClone(object);
43
+ /* istanbul ignore next -- @preserve */
44
+ return clone(object);
45
+ }
46
+ //#endregion
47
+ exports.default = deepClone;