@signaldb/core 2.0.0-beta.5 → 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 -7
  51. package/dist/index31.cjs.js +191 -0
  52. package/dist/index31.mjs +190 -42
  53. package/dist/index32.cjs.js +21 -0
  54. package/dist/index32.mjs +20 -29
  55. package/dist/index33.cjs.js +336 -0
  56. package/dist/index33.mjs +335 -5
  57. package/dist/index34.cjs.js +539 -0
  58. package/dist/index34.mjs +537 -8
  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 -7
  95. package/dist/index.cjs31.js +0 -42
  96. package/dist/index.cjs32.js +0 -29
  97. package/dist/index.cjs33.js +0 -5
  98. package/dist/index.cjs34.js +0 -9
  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
@@ -0,0 +1,90 @@
1
+ //#region src/utils/reactiveOrAsync.ts
2
+ /**
3
+ * A generator helper that makes TypeScript infer the “synchronous value type” for maybe-async expressions.
4
+ *
5
+ * Usage:
6
+ * const doc = yield* unwrap(Collection.findOne(...))
7
+ * const list = yield* unwrap(Collection.find(...).fetch())
8
+ *
9
+ * Runtime note:
10
+ * This does not “unwrap” Promises by itself. It yields the value/Promise to the runner and returns the
11
+ * value that the runner feeds back via `.next(...)`.
12
+ * @param value The value (or Promise of a value) to yield to the runner.
13
+ * @returns A generator that yields `value` and resolves to the runner-supplied unwrapped `T`.
14
+ */
15
+ function unwrap(value) {
16
+ return (function* () {
17
+ return yield value;
18
+ })();
19
+ }
20
+ /**
21
+ * Internal: checks for thenables (Promise-like).
22
+ * @param value The value to test.
23
+ * @returns `true` if `value` looks like a Promise/thenable.
24
+ */
25
+ function isThenable(value) {
26
+ return typeof value === "object" && value !== null && typeof value.then === "function";
27
+ }
28
+ /**
29
+ * Internal runner: executes a generator either synchronously (reactive) or asynchronously (imperative).
30
+ *
31
+ * - In sync mode, yielding a Promise is a programming error and throws.
32
+ * - In async mode, yielded Promises are awaited.
33
+ * @param thisArgument The `this` value to bind when invoking `gen`.
34
+ * @param mode Execution mode options.
35
+ * @param gen The generator workflow to run.
36
+ * @returns The workflow result (a plain value in sync mode, or a Promise in async mode).
37
+ */
38
+ function runReactiveOrAsync(thisArgument, mode, gen) {
39
+ const a = !!mode?.async;
40
+ const it = gen.call(thisArgument, a);
41
+ if (!a) {
42
+ let step = it.next();
43
+ while (!step.done) {
44
+ const y = step.value;
45
+ if (isThenable(y)) throw new Error("Promise yielded in sync flow");
46
+ step = it.next(y);
47
+ }
48
+ return step.value;
49
+ }
50
+ return (async function() {
51
+ let step = it.next();
52
+ while (!step.done) {
53
+ const y = step.value;
54
+ const v = isThenable(y) ? await y : y;
55
+ step = it.next(v);
56
+ }
57
+ return step.value;
58
+ })();
59
+ }
60
+ /**
61
+ * Factory that turns a generator workflow into a callable method that can run in sync (reactive) or async mode.
62
+ *
63
+ * Call style:
64
+ * fn(a, b) -> sync/reactive return
65
+ * await fn(a, b, { async: true }) -> async return
66
+ * @param gen Generator workflow. Receives `(a)` which indicates async mode and should `yield`/`yield* unwrap(...)`
67
+ * any values that may be Promises.
68
+ * @returns A callable method with overloads plus a `.generator` property for composition.
69
+ */
70
+ function reactiveOrAsync(gen) {
71
+ /**
72
+ * The generated method wrapper.
73
+ * @param allArguments Method arguments, optionally ending with a `ModeOptions` object.
74
+ * @returns The workflow result (sync) or a Promise of the result (async).
75
+ */
76
+ function method(...allArguments) {
77
+ const last = allArguments.length > 0 ? allArguments.at(-1) : void 0;
78
+ const hasMode = typeof last === "object" && last !== null && "async" in last;
79
+ const mode = hasMode ? last : void 0;
80
+ const parameters = hasMode ? allArguments.slice(0, -1) : allArguments;
81
+ return runReactiveOrAsync(this, mode, function* (a) {
82
+ return yield* gen.call(this, a, ...parameters);
83
+ });
84
+ }
85
+ method.generator = gen;
86
+ return method;
87
+ }
88
+ //#endregion
89
+ exports.default = reactiveOrAsync;
90
+ exports.unwrap = unwrap;
package/dist/index28.mjs CHANGED
@@ -1,47 +1,89 @@
1
- function batchOnNextTick(onFlush) {
2
- const queues = /* @__PURE__ */ new Map();
3
- function enqueue(key, args) {
4
- return new Promise((resolve, reject) => {
5
- let q = queues.get(key);
6
- if (!q) {
7
- q = {
8
- timer: null,
9
- items: [],
10
- flush: () => flush(key)
11
- };
12
- queues.set(key, q);
13
- }
14
- q.items.push({ args, resolve, reject });
15
- if (q.timer == null) {
16
- q.timer = setTimeout(() => {
17
- q.timer = null;
18
- void q.flush();
19
- }, 0);
20
- }
21
- });
22
- }
23
- async function flush(key) {
24
- const q = queues.get(key);
25
- if (!q || q.items.length === 0)
26
- return;
27
- if (q.timer != null) {
28
- clearTimeout(q.timer);
29
- q.timer = null;
30
- }
31
- const items = q.items.splice(0);
32
- onFlush(key, items.map((i) => i.args)).then((results) => {
33
- for (const [index, result] of results.entries()) {
34
- const { resolve } = items[index];
35
- resolve(result);
36
- }
37
- }).catch((error) => {
38
- for (const { reject } of items) {
39
- reject(error);
40
- }
41
- });
42
- }
43
- return { enqueue, flush };
1
+ //#region src/utils/reactiveOrAsync.ts
2
+ /**
3
+ * A generator helper that makes TypeScript infer the “synchronous value type” for maybe-async expressions.
4
+ *
5
+ * Usage:
6
+ * const doc = yield* unwrap(Collection.findOne(...))
7
+ * const list = yield* unwrap(Collection.find(...).fetch())
8
+ *
9
+ * Runtime note:
10
+ * This does not “unwrap” Promises by itself. It yields the value/Promise to the runner and returns the
11
+ * value that the runner feeds back via `.next(...)`.
12
+ * @param value The value (or Promise of a value) to yield to the runner.
13
+ * @returns A generator that yields `value` and resolves to the runner-supplied unwrapped `T`.
14
+ */
15
+ function unwrap(value) {
16
+ return (function* () {
17
+ return yield value;
18
+ })();
44
19
  }
45
- export {
46
- batchOnNextTick as default
47
- };
20
+ /**
21
+ * Internal: checks for thenables (Promise-like).
22
+ * @param value The value to test.
23
+ * @returns `true` if `value` looks like a Promise/thenable.
24
+ */
25
+ function isThenable(value) {
26
+ return typeof value === "object" && value !== null && typeof value.then === "function";
27
+ }
28
+ /**
29
+ * Internal runner: executes a generator either synchronously (reactive) or asynchronously (imperative).
30
+ *
31
+ * - In sync mode, yielding a Promise is a programming error and throws.
32
+ * - In async mode, yielded Promises are awaited.
33
+ * @param thisArgument The `this` value to bind when invoking `gen`.
34
+ * @param mode Execution mode options.
35
+ * @param gen The generator workflow to run.
36
+ * @returns The workflow result (a plain value in sync mode, or a Promise in async mode).
37
+ */
38
+ function runReactiveOrAsync(thisArgument, mode, gen) {
39
+ const a = !!mode?.async;
40
+ const it = gen.call(thisArgument, a);
41
+ if (!a) {
42
+ let step = it.next();
43
+ while (!step.done) {
44
+ const y = step.value;
45
+ if (isThenable(y)) throw new Error("Promise yielded in sync flow");
46
+ step = it.next(y);
47
+ }
48
+ return step.value;
49
+ }
50
+ return (async function() {
51
+ let step = it.next();
52
+ while (!step.done) {
53
+ const y = step.value;
54
+ const v = isThenable(y) ? await y : y;
55
+ step = it.next(v);
56
+ }
57
+ return step.value;
58
+ })();
59
+ }
60
+ /**
61
+ * Factory that turns a generator workflow into a callable method that can run in sync (reactive) or async mode.
62
+ *
63
+ * Call style:
64
+ * fn(a, b) -> sync/reactive return
65
+ * await fn(a, b, { async: true }) -> async return
66
+ * @param gen Generator workflow. Receives `(a)` which indicates async mode and should `yield`/`yield* unwrap(...)`
67
+ * any values that may be Promises.
68
+ * @returns A callable method with overloads plus a `.generator` property for composition.
69
+ */
70
+ function reactiveOrAsync(gen) {
71
+ /**
72
+ * The generated method wrapper.
73
+ * @param allArguments Method arguments, optionally ending with a `ModeOptions` object.
74
+ * @returns The workflow result (sync) or a Promise of the result (async).
75
+ */
76
+ function method(...allArguments) {
77
+ const last = allArguments.length > 0 ? allArguments.at(-1) : void 0;
78
+ const hasMode = typeof last === "object" && last !== null && "async" in last;
79
+ const mode = hasMode ? last : void 0;
80
+ const parameters = hasMode ? allArguments.slice(0, -1) : allArguments;
81
+ return runReactiveOrAsync(this, mode, function* (a) {
82
+ return yield* gen.call(this, a, ...parameters);
83
+ });
84
+ }
85
+ method.generator = gen;
86
+ return method;
87
+ }
88
+ //#endregion
89
+ export { reactiveOrAsync as default, unwrap };
@@ -0,0 +1,370 @@
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
+ //#region src/AsyncDataAdapter.ts
11
+ /**
12
+ * AsyncDataAdapter
13
+ * Combines WorkerDataAdapter + WorkerDataAdapterHost into a single, transport-free adapter.
14
+ * - Keeps the DataAdapter/CollectionBackend surface identical to the Worker version.
15
+ * - Executes queries and mutations directly against the provided StorageAdapter.
16
+ * - Preserves index-aware query optimization and push-style query updates to listeners.
17
+ */
18
+ var AsyncDataAdapter = class {
19
+ options;
20
+ id;
21
+ onError;
22
+ storageAdapters = /* @__PURE__ */ new Map();
23
+ storageAdapterReady = /* @__PURE__ */ new Map();
24
+ collectionIndices = /* @__PURE__ */ new Map();
25
+ queries = /* @__PURE__ */ new Map();
26
+ constructor(options) {
27
+ this.options = options;
28
+ this.id = options.id || "async-data-adapter";
29
+ this.onError = options.onError ?? ((error) => {
30
+ console.error(error);
31
+ });
32
+ }
33
+ createCollectionBackend(collection, indices) {
34
+ this.collectionIndices.set(collection.name, indices);
35
+ this.queries.set(collection.name, /* @__PURE__ */ new Map());
36
+ this.ensureStorageAdapter(collection.name);
37
+ const ready = (async () => {
38
+ try {
39
+ await this.setupStorage(collection.name, indices);
40
+ } catch (error) {
41
+ this.onError(error);
42
+ throw error;
43
+ }
44
+ })();
45
+ this.storageAdapterReady.set(collection.name, ready);
46
+ const registerQuery = (selector, options) => {
47
+ const qid = require_queryId.default(selector, options);
48
+ const registry = this.queries.get(collection.name);
49
+ if (!registry) throw new Error(`Collection ${collection.name} not initialized!`);
50
+ registry.set(qid, {
51
+ selector,
52
+ options,
53
+ items: [],
54
+ listeners: /* @__PURE__ */ new Set(),
55
+ ...registry.get(qid),
56
+ state: "active",
57
+ error: null
58
+ });
59
+ this.fulfillQuery(collection.name, selector, options).catch(this.onError);
60
+ };
61
+ const unregisterQuery = (selector, options) => {
62
+ const qid = require_queryId.default(selector, options);
63
+ this.queries.get(collection.name)?.delete(qid);
64
+ };
65
+ const getQueryState = (selector, options) => {
66
+ return (this.queries.get(collection.name)?.get(require_queryId.default(selector, options)))?.state ?? "active";
67
+ };
68
+ const getQueryError = (selector, options) => {
69
+ return (this.queries.get(collection.name)?.get(require_queryId.default(selector, options)))?.error ?? null;
70
+ };
71
+ const getQueryResult = (selector, options) => {
72
+ return (this.queries.get(collection.name)?.get(require_queryId.default(selector, options)))?.items ?? [];
73
+ };
74
+ const onQueryStateChange = (selector, options, callback) => {
75
+ const qid = require_queryId.default(selector, options);
76
+ const registry = this.queries.get(collection.name);
77
+ if (!registry) throw new Error(`Collection ${collection.name} not initialized!`);
78
+ if (!registry.has(qid)) registry.set(qid, {
79
+ selector,
80
+ options,
81
+ state: "active",
82
+ error: null,
83
+ items: [],
84
+ listeners: /* @__PURE__ */ new Set()
85
+ });
86
+ registry.get(qid)?.listeners.add(callback);
87
+ return () => registry.get(qid)?.listeners.delete(callback);
88
+ };
89
+ return {
90
+ insert: async (item) => {
91
+ await ready;
92
+ return await this.insert(collection.name, item);
93
+ },
94
+ updateOne: async (selector, modifier) => {
95
+ await ready;
96
+ return this.updateOne(collection.name, selector, modifier);
97
+ },
98
+ updateMany: async (selector, modifier) => {
99
+ await ready;
100
+ return this.updateMany(collection.name, selector, modifier);
101
+ },
102
+ replaceOne: async (selector, replacement) => {
103
+ await ready;
104
+ return this.replaceOne(collection.name, selector, replacement);
105
+ },
106
+ removeOne: async (selector) => {
107
+ await ready;
108
+ return this.removeOne(collection.name, selector);
109
+ },
110
+ removeMany: async (selector) => {
111
+ await ready;
112
+ return this.removeMany(collection.name, selector);
113
+ },
114
+ registerQuery,
115
+ unregisterQuery,
116
+ getQueryState,
117
+ getQueryError,
118
+ getQueryResult,
119
+ onQueryStateChange,
120
+ executeQuery: async (selector, options) => {
121
+ await ready;
122
+ return this.executeQuery(collection.name, selector, options);
123
+ },
124
+ dispose: async () => {
125
+ this.storageAdapters.delete(collection.name);
126
+ this.queries.delete(collection.name);
127
+ this.collectionIndices.delete(collection.name);
128
+ this.storageAdapterReady.delete(collection.name);
129
+ },
130
+ isReady: async () => {
131
+ await ready;
132
+ }
133
+ };
134
+ }
135
+ async setupStorage(collectionName, indices) {
136
+ const storage = this.storageAdapters.get(collectionName);
137
+ if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
138
+ await storage.setup();
139
+ await Promise.all(indices.map((index) => storage.createIndex(index)));
140
+ }
141
+ ensureStorageAdapter(name) {
142
+ if (this.storageAdapters.has(name)) return;
143
+ const adapter = this.options.storage(name);
144
+ if (!adapter) return;
145
+ this.storageAdapters.set(name, adapter);
146
+ }
147
+ /**
148
+ * Compute and publish the result for a specific query
149
+ * @param collectionName - name of the collection
150
+ * @param selector - query selector
151
+ * @param options - query options
152
+ */
153
+ async fulfillQuery(collectionName, selector, options) {
154
+ const qid = require_queryId.default(selector, options);
155
+ const registry = this.queries.get(collectionName);
156
+ if (!registry) throw new Error(`Collection ${collectionName} not initialized!`);
157
+ if (!registry.get(qid)) return;
158
+ this.publishState(collectionName, qid, "active", null);
159
+ try {
160
+ const items = await this.executeQuery(collectionName, selector, options);
161
+ this.publishResult(collectionName, qid, items);
162
+ this.publishState(collectionName, qid, "complete", null);
163
+ } catch (error) {
164
+ this.publishState(collectionName, qid, "error", error);
165
+ }
166
+ }
167
+ /**
168
+ * Notify listeners about state changes and keep the cache updated
169
+ * @param collectionName - name of the collection
170
+ * @param qid - query id
171
+ * @param state - new state
172
+ * @param error - error if state is 'error', null otherwise
173
+ */
174
+ publishState(collectionName, qid, state, error) {
175
+ const rec = this.queries.get(collectionName)?.get(qid);
176
+ if (!rec) return;
177
+ rec.state = state;
178
+ rec.error = error;
179
+ for (const callback of rec.listeners) try {
180
+ callback(state);
181
+ } catch (error_) {
182
+ this.onError(error_);
183
+ }
184
+ }
185
+ publishResult(collectionName, qid, items) {
186
+ const rec = this.queries.get(collectionName)?.get(qid);
187
+ if (!rec) return;
188
+ rec.items = items;
189
+ }
190
+ async getIndexInfo(collectionName, selector) {
191
+ const storageAdapter = this.storageAdapters.get(collectionName);
192
+ if (!storageAdapter) throw new Error(`No persistence adapter for collection ${collectionName}`);
193
+ if (selector != null && Object.keys(selector).length === 1 && "id" in selector && typeof selector.id !== "object") return {
194
+ matched: true,
195
+ ids: [selector.id].filter(Boolean),
196
+ optimizedSelector: {}
197
+ };
198
+ if (selector == null) return {
199
+ matched: false,
200
+ ids: [],
201
+ optimizedSelector: {}
202
+ };
203
+ return require_getIndexInfo.default((this.collectionIndices.get(collectionName) ?? []).map((field) => async (flatSelector) => {
204
+ if (!Object.hasOwnProperty.call(flatSelector, field)) return { matched: false };
205
+ const index = await storageAdapter.readIndex(field);
206
+ const fieldSelector = flatSelector[field];
207
+ const filtersForNull = fieldSelector == null || fieldSelector.$exists === false;
208
+ const keys = filtersForNull ? {
209
+ include: null,
210
+ exclude: [...index.keys()].filter((key) => key != null)
211
+ } : require_getMatchingKeys.default(field, flatSelector);
212
+ if (keys.include == null && keys.exclude == null) return { matched: false };
213
+ let includedIds = [];
214
+ if (keys.include == null) for (const set of index.values()) for (const pos of set) includedIds.push(pos);
215
+ else for (const key of keys.include) {
216
+ const idSet = index.get(key);
217
+ if (idSet) for (const id of idSet) includedIds.push(id);
218
+ }
219
+ if (keys.exclude != null) {
220
+ const excludeIds = /* @__PURE__ */ new Set();
221
+ for (const key of keys.exclude) {
222
+ const idSet = index.get(key);
223
+ if (idSet) for (const id of idSet) excludeIds.add(id);
224
+ }
225
+ includedIds = includedIds.filter((pos) => !excludeIds.has(pos));
226
+ }
227
+ return {
228
+ matched: true,
229
+ ids: includedIds,
230
+ fields: [field],
231
+ keepSelector: filtersForNull
232
+ };
233
+ }), selector);
234
+ }
235
+ async queryItems(collectionName, selector) {
236
+ const storage = this.storageAdapters.get(collectionName);
237
+ if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
238
+ const index = await this.getIndexInfo(collectionName, selector);
239
+ const matchItems = (item) => {
240
+ if (index.optimizedSelector == null) return true;
241
+ if (Object.keys(index.optimizedSelector).length <= 0) return true;
242
+ return require_match.default(item, index.optimizedSelector);
243
+ };
244
+ if (index.matched) {
245
+ const items = await storage.readIds(index.ids);
246
+ if (require_isEqual.default(index.optimizedSelector, {})) return items;
247
+ return items.filter(matchItems);
248
+ } else {
249
+ const allItems = await storage.readAll();
250
+ if (require_isEqual.default(selector, {})) return allItems;
251
+ return allItems.filter(matchItems);
252
+ }
253
+ }
254
+ async executeQuery(collectionName, selector, options) {
255
+ const items = await this.queryItems(collectionName, selector || {});
256
+ const { sort, skip, limit, fields } = options || {};
257
+ const sorted = sort ? require_sortItems.default(items, sort) : items;
258
+ const skipped = skip ? sorted.slice(skip) : sorted;
259
+ const limited = limit ? skipped.slice(0, limit) : skipped;
260
+ const idExcluded = fields && fields.id === 0;
261
+ return limited.map((item) => {
262
+ if (!fields) return item;
263
+ return {
264
+ ...idExcluded ? {} : { id: item.id },
265
+ ...require_project.default(item, fields)
266
+ };
267
+ });
268
+ }
269
+ /**
270
+ * After mutations, recompute and push updates for affected active queries
271
+ * @param collectionName - name of the collection
272
+ * @param affectedItems - item states before and/or after the mutation
273
+ */
274
+ async checkQueryUpdates(collectionName, affectedItems) {
275
+ const registry = this.queries.get(collectionName);
276
+ if (!registry) throw new Error(`Collection ${collectionName} not initialized!`);
277
+ if (registry.size === 0) return;
278
+ const affected = [...registry.values()].filter(({ selector }) => affectedItems.some((item) => require_match.default(item, selector)));
279
+ if (affected.length === 0) return;
280
+ for (const { selector, options } of affected) {
281
+ const qid = require_queryId.default(selector, options);
282
+ this.publishState(collectionName, qid, "active", null);
283
+ }
284
+ await Promise.all(affected.map(async ({ selector, options }) => {
285
+ const qid = require_queryId.default(selector, options);
286
+ try {
287
+ const items = await this.executeQuery(collectionName, selector, options);
288
+ this.publishResult(collectionName, qid, items);
289
+ this.publishState(collectionName, qid, "complete", null);
290
+ } catch (error) {
291
+ this.publishState(collectionName, qid, "error", error);
292
+ }
293
+ }));
294
+ }
295
+ async insert(collectionName, newItem) {
296
+ const storage = this.storageAdapters.get(collectionName);
297
+ if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
298
+ if ((await storage.readIds([newItem.id])).length > 0) throw new Error(`Item with id ${String(newItem.id)} already exists`);
299
+ await storage.insert([newItem]);
300
+ await this.checkQueryUpdates(collectionName, [newItem]);
301
+ return newItem;
302
+ }
303
+ async updateOne(collectionName, selector, modifier) {
304
+ const storage = this.storageAdapters.get(collectionName);
305
+ if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
306
+ const [item] = await this.executeQuery(collectionName, selector, { limit: 1 });
307
+ const { $setOnInsert, ...rest } = modifier;
308
+ if (item == null) return [];
309
+ const modified = require_modify.default(require_deepClone.default(item), rest);
310
+ if (item.id !== modified.id) {
311
+ if ((await storage.readIds([modified.id])).length > 0) throw new Error(`Item with id ${String(modified.id)} already exists`);
312
+ }
313
+ await storage.replace([modified]);
314
+ await this.checkQueryUpdates(collectionName, [item, modified]);
315
+ return [modified];
316
+ }
317
+ async updateMany(collectionName, selector, modifier) {
318
+ const storage = this.storageAdapters.get(collectionName);
319
+ if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
320
+ const items = await this.executeQuery(collectionName, selector);
321
+ if (items.length === 0) return [];
322
+ const { $setOnInsert, ...rest } = modifier;
323
+ const changed = await Promise.all(items.map(async (item) => {
324
+ const modified = require_modify.default(require_deepClone.default(item), rest);
325
+ if (item.id !== modified.id) {
326
+ if ((await storage.readIds([modified.id])).length > 0) throw new Error(`Item with id ${String(modified.id)} already exists`);
327
+ }
328
+ return modified;
329
+ }));
330
+ await storage.replace(changed);
331
+ await this.checkQueryUpdates(collectionName, [...items, ...changed]);
332
+ return changed;
333
+ }
334
+ async replaceOne(collectionName, selector, replacement) {
335
+ const storage = this.storageAdapters.get(collectionName);
336
+ if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
337
+ const [item] = await this.executeQuery(collectionName, selector, { limit: 1 });
338
+ if (item == null) return [];
339
+ const modified = {
340
+ ...replacement,
341
+ id: replacement.id ?? item.id
342
+ };
343
+ if (item.id !== modified.id) {
344
+ if ((await storage.readIds([modified.id])).length > 0) throw new Error(`Item with id ${String(modified.id)} already exists`);
345
+ }
346
+ await storage.replace([modified]);
347
+ await this.checkQueryUpdates(collectionName, [item, modified]);
348
+ return [modified];
349
+ }
350
+ async removeOne(collectionName, selector) {
351
+ const storage = this.storageAdapters.get(collectionName);
352
+ if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
353
+ const [item] = await this.executeQuery(collectionName, selector, { limit: 1 });
354
+ if (item == null) return [];
355
+ await storage.remove([item]);
356
+ await this.checkQueryUpdates(collectionName, [item]);
357
+ return [item];
358
+ }
359
+ async removeMany(collectionName, selector) {
360
+ const storage = this.storageAdapters.get(collectionName);
361
+ if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
362
+ const items = await this.executeQuery(collectionName, selector);
363
+ if (items.length === 0) return [];
364
+ await storage.remove(items);
365
+ await this.checkQueryUpdates(collectionName, items);
366
+ return items;
367
+ }
368
+ };
369
+ //#endregion
370
+ exports.default = AsyncDataAdapter;