@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,59 @@
1
+ export type MaybePromise<T> = T | Promise<T>;
2
+ /**
3
+ * Options that control execution mode (and potential future mode-specific behavior).
4
+ * Keep this minimal; you can extend it later (e.g. signal, timeoutMs, debugLabel).
5
+ */
6
+ export type ModeOptions = {
7
+ async?: boolean;
8
+ };
9
+ /**
10
+ * A generator helper that makes TypeScript infer the “synchronous value type” for maybe-async expressions.
11
+ *
12
+ * Usage:
13
+ * const doc = yield* unwrap(Collection.findOne(...))
14
+ * const list = yield* unwrap(Collection.find(...).fetch())
15
+ *
16
+ * Runtime note:
17
+ * This does not “unwrap” Promises by itself. It yields the value/Promise to the runner and returns the
18
+ * value that the runner feeds back via `.next(...)`.
19
+ * @param value The value (or Promise of a value) to yield to the runner.
20
+ * @returns A generator that yields `value` and resolves to the runner-supplied unwrapped `T`.
21
+ */
22
+ export declare function unwrap<T>(value: MaybePromise<T>): Generator<MaybePromise<T>, T, T>;
23
+ /**
24
+ * Generator shape used by the factory.
25
+ *
26
+ * `TThis` is the type of `this` inside the generator.
27
+ * `Args` are the method parameters (excluding the mode flag).
28
+ * `TReturn` is the final return value of the workflow.
29
+ * `TNext` is the type that is yielded/awaited and fed back via `.next(...)`.
30
+ *
31
+ * Note:
32
+ * - For best inference at yield sites, prefer `yield* unwrap(expr)` for maybe-async expressions.
33
+ */
34
+ export type ReactiveOrAsyncGen<TThis, Arguments extends any[], TReturn, TNext> = (this: TThis, a: boolean, ...args: Arguments) => Generator<MaybePromise<TNext>, TReturn, TNext>;
35
+ /**
36
+ * The method type produced from the generator signature.
37
+ * Adds overloads so that `{ async: true }` yields a `Promise<...>` return type.
38
+ */
39
+ export type ReactiveOrAsyncMethod<TThis, P extends any[], R, N> = {
40
+ (this: TThis, ...args: P): R;
41
+ (this: TThis, ...args: [...P, ModeOptions?]): MaybePromise<R>;
42
+ (this: TThis, ...args: [...P, {
43
+ async: true;
44
+ }]): Promise<R>;
45
+ } & {
46
+ /** Exposes the underlying generator for composition via `yield* method.generator.call(this, a, ...)` */
47
+ generator: (this: TThis, a: boolean, ...args: P) => Generator<MaybePromise<N>, R, N>;
48
+ };
49
+ /**
50
+ * Factory that turns a generator workflow into a callable method that can run in sync (reactive) or async mode.
51
+ *
52
+ * Call style:
53
+ * fn(a, b) -> sync/reactive return
54
+ * await fn(a, b, { async: true }) -> async return
55
+ * @param gen Generator workflow. Receives `(a)` which indicates async mode and should `yield`/`yield* unwrap(...)`
56
+ * any values that may be Promises.
57
+ * @returns A callable method with overloads plus a `.generator` property for composition.
58
+ */
59
+ export default function reactiveOrAsync<TThis, P extends any[], R, N>(gen: (this: TThis, a: boolean, ...args: P) => Generator<MaybePromise<N>, R, N>): ReactiveOrAsyncMethod<TThis, P, R, N>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@signaldb/core",
3
- "version": "2.0.0-beta.0",
3
+ "version": "2.0.0-beta.10",
4
4
  "description": "SignalDB is a client-side database that provides a simple MongoDB-like interface to the data with first-class typescript support to achieve an optimistic UI. Data persistence can be achieved by using storage providers that store the data through a JSON interface to places such as localStorage.",
5
5
  "scripts": {
6
6
  "build": "rimraf dist && vite build",
@@ -55,9 +55,9 @@
55
55
  ],
56
56
  "dependencies": {
57
57
  "fast-sort": "^3.4.1",
58
- "mingo": "^6.5.1"
58
+ "mingo": "^7.1.1"
59
59
  },
60
60
  "devDependencies": {
61
- "zod": "^4.0.14"
61
+ "zod": "^4.3.5"
62
62
  }
63
63
  }
@@ -1,18 +0,0 @@
1
- "use strict";
2
- function get(value, path) {
3
- const normalized = path.replaceAll(/\[(\w+)\]/g, ".$1");
4
- if (normalized.includes("..") || normalized.startsWith(".") || normalized.endsWith(".")) {
5
- return;
6
- }
7
- const segments = normalized.split(".");
8
- let current = value;
9
- for (const key of segments) {
10
- if (current == null)
11
- return;
12
- current = current[key];
13
- }
14
- if (current === void 0)
15
- return;
16
- return current;
17
- }
18
- module.exports = get;
@@ -1,15 +0,0 @@
1
- "use strict";
2
- function serializeValue(value) {
3
- if (value == null)
4
- return null;
5
- if (typeof value === "string")
6
- return value;
7
- if (typeof value === "number")
8
- return value.toString();
9
- if (typeof value === "boolean")
10
- return value.toString();
11
- if (value instanceof Date)
12
- return value.toISOString();
13
- return JSON.stringify(value);
14
- }
15
- module.exports = serializeValue;
@@ -1,339 +0,0 @@
1
- "use strict";
2
- const createIndex = require("./index.cjs20.js");
3
- const getIndexInfo = require("./index.cjs21.js");
4
- const deepClone = require("./index.cjs19.js");
5
- const EventEmitter = require("./index.cjs9.js");
6
- const isEqual = require("./index.cjs6.js");
7
- const match = require("./index.cjs22.js");
8
- const modify = require("./index.cjs7.js");
9
- const project = require("./index.cjs23.js");
10
- const queryId = require("./index.cjs24.js");
11
- const serializeValue = require("./index.cjs11.js");
12
- const sortItems = require("./index.cjs25.js");
13
- function hasPendingUpdates(pendingUpdates) {
14
- return pendingUpdates.added.length > 0 || pendingUpdates.modified.length > 0 || pendingUpdates.removed.length > 0;
15
- }
16
- class DefaultDataAdapter {
17
- items = /* @__PURE__ */ new Map();
18
- options;
19
- storageAdapters = /* @__PURE__ */ new Map();
20
- indices = /* @__PURE__ */ new Map();
21
- activeQueries = /* @__PURE__ */ new Map();
22
- queryEmitters = /* @__PURE__ */ new Map();
23
- queuedQueryUpdates = /* @__PURE__ */ new Map();
24
- cachedQueryResults = /* @__PURE__ */ new Map();
25
- constructor(options) {
26
- this.options = options || {};
27
- }
28
- ensureStorageAdapter(name) {
29
- if (this.storageAdapters.get(name))
30
- return;
31
- if (!this.options.storage)
32
- return;
33
- const adapter = this.options.storage(name);
34
- if (!adapter)
35
- return;
36
- this.storageAdapters.set(name, adapter);
37
- }
38
- rebuildIndices(collection) {
39
- const items = this.items.get(collection.name);
40
- if (!items)
41
- throw new Error(`Items not found for collection ${collection.name}`);
42
- const indices = this.indices.get(collection.name);
43
- if (!indices)
44
- throw new Error(`Indices not found for collection ${collection.name}`);
45
- indices.forEach((index) => index.rebuild([...items.values()]));
46
- }
47
- async setupStorageAdapter(collection) {
48
- const storageAdapter = this.storageAdapters.get(collection.name);
49
- if (!storageAdapter)
50
- return;
51
- return storageAdapter.setup().then(async () => {
52
- const items = await storageAdapter.readAll();
53
- this.items.set(collection.name, items.reduce((map, item) => {
54
- map.set(serializeValue(item.id), item);
55
- return map;
56
- }, /* @__PURE__ */ new Map()));
57
- this.rebuildIndices(collection);
58
- }).catch((error) => {
59
- if (!this.options.onError) {
60
- console.error(`Error during data persistence operation in collection ${collection.name}`, error);
61
- return;
62
- }
63
- this.options.onError(collection.name, error instanceof Error ? error : new Error(error));
64
- });
65
- }
66
- getIndexInfo(collection, selector) {
67
- if (selector != null && Object.keys(selector).length === 1 && "id" in selector && typeof selector.id !== "object") {
68
- return {
69
- matched: true,
70
- ids: [serializeValue(selector.id)],
71
- optimizedSelector: {}
72
- };
73
- }
74
- if (selector == null) {
75
- return {
76
- matched: false,
77
- ids: [],
78
- optimizedSelector: {}
79
- };
80
- }
81
- return getIndexInfo.default((this.indices.get(collection.name) ?? []).map((i) => i.query.bind(i)), selector);
82
- }
83
- applyIndexDeltas(collection, changes) {
84
- const indices = this.indices.get(collection.name) ?? [];
85
- for (const index of indices) {
86
- if (changes.modified)
87
- index.update(changes.modified);
88
- if (changes.added && changes.added.length > 0)
89
- index.insert(changes.added);
90
- if (changes.removed && changes.removed.length > 0)
91
- index.remove(changes.removed);
92
- }
93
- }
94
- getItem(collection, selector) {
95
- const memory = this.items.get(collection.name) ?? /* @__PURE__ */ new Map();
96
- const indexInfo = this.getIndexInfo(collection, selector);
97
- const items = indexInfo.matched ? indexInfo.ids.map((id) => memory.get(serializeValue(id))).filter((i) => i != null) : [...memory.values()];
98
- const item = items.find((document) => match(document, selector));
99
- return item;
100
- }
101
- queryItems(collection, selector) {
102
- const indexInfo = this.getIndexInfo(collection, selector);
103
- const matchItems = (item) => {
104
- if (indexInfo.optimizedSelector == null)
105
- return true;
106
- if (Object.keys(indexInfo.optimizedSelector).length <= 0)
107
- return true;
108
- const matches = match(item, indexInfo.optimizedSelector);
109
- return matches;
110
- };
111
- const items = this.items.get(collection.name);
112
- if (!indexInfo.matched) {
113
- if (isEqual(selector, {}))
114
- return [...items.values()];
115
- return [...items.values()].filter(matchItems);
116
- }
117
- const foundItems = indexInfo.ids.map((ids) => items.get(serializeValue(ids))).filter((i) => i != null);
118
- if (isEqual(indexInfo.optimizedSelector, {}))
119
- return foundItems;
120
- return foundItems.filter(matchItems);
121
- }
122
- executeQuery(collection, selector, options) {
123
- const items = this.queryItems(collection, selector || {});
124
- const { sort, skip, limit, fields } = options || {};
125
- const sorted = sort ? sortItems(items, sort) : items;
126
- const skipped = skip ? sorted.slice(skip) : sorted;
127
- const limited = limit ? skipped.slice(0, limit) : skipped;
128
- const idExcluded = fields && fields.id === 0;
129
- return limited.map((item) => {
130
- if (!fields)
131
- return item;
132
- return {
133
- ...idExcluded ? {} : { id: item.id },
134
- ...project(item, fields)
135
- };
136
- });
137
- }
138
- flushQueuedQueryUpdates(collection) {
139
- if (!this.queuedQueryUpdates.get(collection.name))
140
- return;
141
- const changes = this.queuedQueryUpdates.get(collection.name);
142
- if (!changes || !hasPendingUpdates(changes))
143
- return;
144
- this.queuedQueryUpdates.set(collection.name, { added: [], modified: [], removed: [] });
145
- const flatItems = [...changes.added, ...changes.modified, ...changes.removed];
146
- const queries = [...this.activeQueries.get(collection.name)?.values() ?? []].filter(({ selector }) => flatItems.some((item) => match(item, selector)));
147
- queries.forEach(({ selector, options }) => {
148
- const emitter = this.queryEmitters.get(collection.name);
149
- if (!emitter)
150
- return;
151
- emitter.emit("change", selector, options, "complete");
152
- });
153
- }
154
- updateQueries(collection, changes) {
155
- this.queuedQueryUpdates.set(collection.name, this.queuedQueryUpdates.get(collection.name) || { added: [], modified: [], removed: [] });
156
- this.queuedQueryUpdates.get(collection.name)?.added.push(...changes.added);
157
- this.queuedQueryUpdates.get(collection.name)?.modified.push(...changes.modified);
158
- this.queuedQueryUpdates.get(collection.name)?.removed.push(...changes.removed);
159
- this.flushQueuedQueryUpdates(collection);
160
- }
161
- createCollectionBackend(collection, indices) {
162
- this.ensureStorageAdapter(collection.name);
163
- this.items.set(collection.name, this.items.get(collection.name) ?? /* @__PURE__ */ new Map());
164
- this.queryEmitters.set(collection.name, this.queryEmitters.get(collection.name) ?? new EventEmitter());
165
- this.activeQueries.set(collection.name, this.activeQueries.get(collection.name) || /* @__PURE__ */ new Map());
166
- this.indices.set(collection.name, indices.map((field) => createIndex(field)));
167
- this.rebuildIndices(collection);
168
- const persistenceReadyPromise = this.setupStorageAdapter(collection);
169
- const backend = {
170
- // CRUD operations
171
- insert: async (newItem) => {
172
- const items = this.items.get(collection.name);
173
- if (!items)
174
- throw new Error(`Items not found for collection ${collection.name}`);
175
- if (items.has(serializeValue(newItem.id))) {
176
- throw new Error(`Item with id '${newItem.id}' already exists`);
177
- }
178
- this.items.get(collection.name)?.set(serializeValue(newItem.id), newItem);
179
- await this.storageAdapters.get(collection.name)?.insert([newItem]);
180
- this.applyIndexDeltas(collection, { added: [newItem] });
181
- this.updateQueries(collection, {
182
- added: [],
183
- modified: [newItem],
184
- removed: []
185
- });
186
- return newItem;
187
- },
188
- updateOne: async (selector, modifier) => {
189
- const { $setOnInsert, ...restModifier } = modifier;
190
- const item = this.getItem(collection, selector);
191
- if (item == null)
192
- return [];
193
- const modifiedItem = modify(deepClone.default(item), restModifier);
194
- const hasItemWithSameId = item.id !== modifiedItem.id && this.getItem(collection, { id: modifiedItem.id }) != null;
195
- if (hasItemWithSameId) {
196
- throw new Error(`Item with id '${modifiedItem.id}' already exists`);
197
- }
198
- this.items.get(collection.name)?.set(serializeValue(modifiedItem.id), modifiedItem);
199
- await this.storageAdapters.get(collection.name)?.replace([modifiedItem]);
200
- this.applyIndexDeltas(collection, { modified: [{ oldItem: item, newItem: modifiedItem }] });
201
- this.updateQueries(collection, {
202
- added: [],
203
- modified: [modifiedItem],
204
- removed: []
205
- });
206
- return [modifiedItem];
207
- },
208
- updateMany: async (selector, modifier) => {
209
- const { $setOnInsert, ...restModifier } = modifier;
210
- const items = backend.getQueryResult(selector);
211
- const changedItems = items.map((item) => {
212
- const modifiedItem = modify(deepClone.default(item), restModifier);
213
- const hasItemWithSameId = item.id !== modifiedItem.id && this.getItem(collection, { id: modifiedItem.id }) != null;
214
- if (hasItemWithSameId) {
215
- throw new Error(`Item with id '${modifiedItem.id}' already exists`);
216
- }
217
- return modifiedItem;
218
- });
219
- changedItems.forEach((item) => {
220
- this.items.get(collection.name)?.set(serializeValue(item.id), item);
221
- });
222
- await this.storageAdapters.get(collection.name)?.replace(changedItems);
223
- const pairs = items.map((oldItem, index) => ({ oldItem, newItem: changedItems[index] }));
224
- this.applyIndexDeltas(collection, { modified: pairs });
225
- this.updateQueries(collection, {
226
- added: [],
227
- modified: changedItems,
228
- removed: []
229
- });
230
- return changedItems;
231
- },
232
- replaceOne: async (selector, replacement) => {
233
- const item = this.getItem(collection, selector);
234
- if (item == null)
235
- return [];
236
- const hasItemWithSameId = item.id !== replacement.id && replacement.id != null && this.getItem(collection, { id: replacement.id }) != null;
237
- if (hasItemWithSameId) {
238
- throw new Error(`Item with id '${replacement.id}' already exists`);
239
- }
240
- const modifiedItem = { id: item.id, ...replacement };
241
- this.items.get(collection.name)?.set(serializeValue(modifiedItem.id), modifiedItem);
242
- await this.storageAdapters.get(collection.name)?.replace([modifiedItem]);
243
- this.applyIndexDeltas(collection, { modified: [{ oldItem: item, newItem: modifiedItem }] });
244
- this.updateQueries(collection, {
245
- added: [],
246
- modified: [modifiedItem],
247
- removed: []
248
- });
249
- return [modifiedItem];
250
- },
251
- removeOne: async (selector) => {
252
- const item = this.getItem(collection, selector);
253
- if (item == null)
254
- return [];
255
- this.items.get(collection.name)?.delete(serializeValue(item.id));
256
- await this.storageAdapters.get(collection.name)?.remove([item]);
257
- this.applyIndexDeltas(collection, { removed: [item] });
258
- this.updateQueries(collection, {
259
- added: [],
260
- modified: [],
261
- removed: [item]
262
- });
263
- return [item];
264
- },
265
- removeMany: async (selector) => {
266
- const items = backend.getQueryResult(selector);
267
- items.forEach((item) => {
268
- this.items.get(collection.name)?.delete(serializeValue(item.id));
269
- });
270
- await this.storageAdapters.get(collection.name)?.remove(items);
271
- this.applyIndexDeltas(collection, { removed: items });
272
- this.updateQueries(collection, {
273
- added: [],
274
- modified: [],
275
- removed: items
276
- });
277
- return items;
278
- },
279
- // methods for registering and unregistering queries that will be called from the collection during find/findOne
280
- registerQuery: (selector, options) => {
281
- this.activeQueries.set(collection.name, this.activeQueries.get(collection.name) || /* @__PURE__ */ new Map());
282
- this.activeQueries.get(collection.name)?.set(queryId(selector, options), {
283
- selector,
284
- options
285
- });
286
- const emitter = this.queryEmitters.get(collection.name);
287
- if (!emitter)
288
- throw new Error(`Query emitter not found for collection ${collection.name}`);
289
- emitter.emit("change", selector, options, "complete");
290
- },
291
- unregisterQuery: (selector, options) => {
292
- if (!this.activeQueries.get(collection.name))
293
- return;
294
- this.activeQueries.get(collection.name)?.delete(queryId(selector, options));
295
- },
296
- getQueryState: () => "complete",
297
- onQueryStateChange: (selector, options, callback) => {
298
- const emitter = this.queryEmitters.get(collection.name);
299
- if (!emitter)
300
- throw new Error(`Query emitter not found for collection ${collection.name}`);
301
- const handler = (querySelector, queryOptions, state) => {
302
- if (querySelector !== selector || queryOptions !== options)
303
- return;
304
- callback(state);
305
- };
306
- emitter.on("change", handler);
307
- return () => {
308
- emitter.off("change", handler);
309
- };
310
- },
311
- getQueryError: () => null,
312
- getQueryResult: (selector, options) => {
313
- const result = this.executeQuery(collection, selector, options);
314
- const isQueryActive = this.activeQueries.get(collection.name)?.has(queryId(selector, options));
315
- if (isQueryActive) {
316
- this.cachedQueryResults.set(collection.name, this.cachedQueryResults.get(collection.name) || /* @__PURE__ */ new Map());
317
- this.cachedQueryResults.get(collection.name)?.set(queryId(selector, options), result);
318
- }
319
- return result;
320
- },
321
- // lifecycle methods
322
- dispose: async () => {
323
- const adapter = this.storageAdapters.get(collection.name);
324
- if (adapter?.teardown)
325
- await adapter.teardown();
326
- this.storageAdapters.delete(collection.name);
327
- this.items.delete(collection.name);
328
- this.indices.delete(collection.name);
329
- this.activeQueries.delete(collection.name);
330
- this.queryEmitters.delete(collection.name);
331
- this.queuedQueryUpdates.delete(collection.name);
332
- this.cachedQueryResults.delete(collection.name);
333
- },
334
- isReady: () => persistenceReadyPromise
335
- };
336
- return backend;
337
- }
338
- }
339
- module.exports = DefaultDataAdapter;