@signaldb/svelte 1.1.1 → 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 (95) hide show
  1. package/dist/base/core/src/AsyncDataAdapter.d.ts +103 -0
  2. package/dist/base/core/src/AsyncDataAdapter.js +518 -0
  3. package/dist/base/core/src/AutoFetchDataAdapter.d.ts +112 -0
  4. package/dist/base/core/src/AutoFetchDataAdapter.js +652 -0
  5. package/dist/base/core/src/Collection/Cursor.d.ts +113 -0
  6. package/dist/base/core/src/Collection/Cursor.js +293 -0
  7. package/dist/base/core/src/Collection/Observer.d.ts +64 -0
  8. package/dist/base/core/src/Collection/Observer.js +181 -0
  9. package/dist/base/core/src/Collection/index.d.ts +300 -0
  10. package/dist/base/core/src/Collection/index.js +625 -0
  11. package/dist/base/core/src/Collection/types.d.ts +28 -0
  12. package/dist/base/core/src/Collection/types.js +2 -0
  13. package/dist/base/core/src/DataAdapter.d.ts +41 -0
  14. package/dist/base/core/src/DataAdapter.js +2 -0
  15. package/dist/base/core/src/DefaultDataAdapter.d.ts +35 -0
  16. package/dist/base/core/src/DefaultDataAdapter.js +398 -0
  17. package/dist/base/core/src/WorkerDataAdapter.d.ts +25 -0
  18. package/dist/base/core/src/WorkerDataAdapter.js +211 -0
  19. package/dist/base/core/src/WorkerDataAdapterHost.d.ts +62 -0
  20. package/dist/base/core/src/WorkerDataAdapterHost.js +409 -0
  21. package/dist/base/core/src/createIndex.d.ts +7 -0
  22. package/dist/base/core/src/createIndex.js +120 -0
  23. package/dist/base/core/src/createIndexProvider.d.ts +8 -0
  24. package/dist/base/core/src/createIndexProvider.js +11 -0
  25. package/dist/base/core/src/createReactivityAdapter.d.ts +8 -0
  26. package/dist/base/core/src/createReactivityAdapter.js +11 -0
  27. package/dist/base/core/src/createStorageAdapter.d.ts +9 -0
  28. package/dist/base/core/src/createStorageAdapter.js +11 -0
  29. package/dist/base/core/src/getIndexInfo.d.ts +39 -0
  30. package/dist/base/core/src/getIndexInfo.js +176 -0
  31. package/dist/base/core/src/index.d.ts +22 -0
  32. package/dist/base/core/src/index.js +39 -0
  33. package/dist/base/core/src/types/Dependency.d.ts +4 -0
  34. package/dist/base/core/src/types/Dependency.js +2 -0
  35. package/dist/base/core/src/types/IndexProvider.d.ts +26 -0
  36. package/dist/base/core/src/types/IndexProvider.js +2 -0
  37. package/dist/base/core/src/types/Modifier.d.ts +46 -0
  38. package/dist/base/core/src/types/Modifier.js +3 -0
  39. package/dist/base/core/src/types/ReactivityAdapter.d.ts +6 -0
  40. package/dist/base/core/src/types/ReactivityAdapter.js +2 -0
  41. package/dist/base/core/src/types/Selector.d.ts +46 -0
  42. package/dist/base/core/src/types/Selector.js +3 -0
  43. package/dist/base/core/src/types/Signal.d.ts +4 -0
  44. package/dist/base/core/src/types/Signal.js +2 -0
  45. package/dist/base/core/src/types/StorageAdapter.d.ts +20 -0
  46. package/dist/base/core/src/types/StorageAdapter.js +2 -0
  47. package/dist/base/core/src/utils/EventEmitter.d.ts +71 -0
  48. package/dist/base/core/src/utils/EventEmitter.js +144 -0
  49. package/dist/base/core/src/utils/batchOnNextTick.d.ts +16 -0
  50. package/dist/base/core/src/utils/batchOnNextTick.js +72 -0
  51. package/dist/base/core/src/utils/compact.d.ts +9 -0
  52. package/dist/base/core/src/utils/compact.js +21 -0
  53. package/dist/base/core/src/utils/createSignal.d.ts +14 -0
  54. package/dist/base/core/src/utils/createSignal.js +38 -0
  55. package/dist/base/core/src/utils/deepClone.d.ts +17 -0
  56. package/dist/base/core/src/utils/deepClone.js +68 -0
  57. package/dist/base/core/src/utils/get.d.ts +9 -0
  58. package/dist/base/core/src/utils/get.js +27 -0
  59. package/dist/base/core/src/utils/getMatchingKeys.d.ts +19 -0
  60. package/dist/base/core/src/utils/getMatchingKeys.js +49 -0
  61. package/dist/base/core/src/utils/intersection.d.ts +9 -0
  62. package/dist/base/core/src/utils/intersection.js +16 -0
  63. package/dist/base/core/src/utils/isEqual.d.ts +14 -0
  64. package/dist/base/core/src/utils/isEqual.js +43 -0
  65. package/dist/base/core/src/utils/isFieldExpression.d.ts +11 -0
  66. package/dist/base/core/src/utils/isFieldExpression.js +52 -0
  67. package/dist/base/core/src/utils/match.d.ts +12 -0
  68. package/dist/base/core/src/utils/match.js +16 -0
  69. package/dist/base/core/src/utils/modify.d.ts +14 -0
  70. package/dist/base/core/src/utils/modify.js +29 -0
  71. package/dist/base/core/src/utils/project.d.ts +15 -0
  72. package/dist/base/core/src/utils/project.js +43 -0
  73. package/dist/base/core/src/utils/queryId.d.ts +9 -0
  74. package/dist/base/core/src/utils/queryId.js +30 -0
  75. package/dist/base/core/src/utils/randomId.d.ts +7 -0
  76. package/dist/base/core/src/utils/randomId.js +12 -0
  77. package/dist/base/core/src/utils/reactiveOrAsync.d.ts +59 -0
  78. package/dist/base/core/src/utils/reactiveOrAsync.js +93 -0
  79. package/dist/base/core/src/utils/serializeValue.d.ts +12 -0
  80. package/dist/base/core/src/utils/serializeValue.js +27 -0
  81. package/dist/base/core/src/utils/set.d.ts +13 -0
  82. package/dist/base/core/src/utils/set.js +43 -0
  83. package/dist/base/core/src/utils/sortItems.d.ts +12 -0
  84. package/dist/base/core/src/utils/sortItems.js +23 -0
  85. package/dist/base/core/src/utils/uniqueBy.d.ts +10 -0
  86. package/dist/base/core/src/utils/uniqueBy.js +19 -0
  87. package/dist/index.cjs +38 -0
  88. package/dist/index.cjs.map +1 -0
  89. package/dist/index.mjs +38 -0
  90. package/dist/index.mjs.map +1 -0
  91. package/dist/index.svelte.d.ts +7 -3
  92. package/dist/index.svelte.js +30 -28
  93. package/dist/reactivity-adapters/svelte/index.svelte.d.ts +10 -0
  94. package/dist/reactivity-adapters/svelte/index.svelte.js +36 -0
  95. package/package.json +4 -4
@@ -0,0 +1,103 @@
1
+ import type { BaseItem } from './Collection';
2
+ import type Collection from './Collection';
3
+ import type DataAdapter from './DataAdapter';
4
+ import type { CollectionBackend } from './DataAdapter';
5
+ import type StorageAdapter from './types/StorageAdapter';
6
+ export interface AsyncDataAdapterOptions {
7
+ /** Factory to obtain a StorageAdapter per collection name */
8
+ storage: (name: string) => StorageAdapter<any, any>;
9
+ /** Optional logical id (handy if you run multiple adapters side-by-side) */
10
+ id?: string;
11
+ /** Optional error hook (mirrors WorkerDataAdapterHost) */
12
+ onError?: (error: Error) => void;
13
+ /**
14
+ * How often a failing query is retried before it is published as `'error'`.
15
+ * A query that fails is otherwise a dead end for the rest of the session —
16
+ * cursors only requery on `'complete'`, so they keep serving their neutral
17
+ * empty value, which consumers cannot tell apart from "there is no data".
18
+ */
19
+ retry?: {
20
+ /** Total attempts including the first one. Default 3. */
21
+ attempts?: number;
22
+ /** Delay in ms before attempt N+1. Default 100 * 4 ** (attempt - 1). */
23
+ delay?: (attempt: number) => number;
24
+ };
25
+ }
26
+ /**
27
+ * Carries the context needed to act on a failed query. The bare storage error
28
+ * on its own does not say which collection or selector produced it, which made
29
+ * the default `console.error` hook close to useless.
30
+ */
31
+ export declare class QueryError extends Error {
32
+ readonly collectionName: string;
33
+ readonly selector: unknown;
34
+ readonly options: unknown;
35
+ readonly attempts: number;
36
+ constructor(collectionName: string, selector: unknown, options: unknown, attempts: number, cause: unknown);
37
+ }
38
+ /**
39
+ * AsyncDataAdapter
40
+ * Combines WorkerDataAdapter + WorkerDataAdapterHost into a single, transport-free adapter.
41
+ * - Keeps the DataAdapter/CollectionBackend surface identical to the Worker version.
42
+ * - Executes queries and mutations directly against the provided StorageAdapter.
43
+ * - Preserves index-aware query optimization and push-style query updates to listeners.
44
+ */
45
+ export default class AsyncDataAdapter implements DataAdapter {
46
+ private options;
47
+ private id;
48
+ private onError;
49
+ private retryAttempts;
50
+ private retryDelay;
51
+ private storageAdapters;
52
+ private storageAdapterReady;
53
+ private collectionIndices;
54
+ private queries;
55
+ constructor(options: AsyncDataAdapterOptions);
56
+ createCollectionBackend<T extends BaseItem<I>, I = any, E extends BaseItem = T, U = E>(collection: Collection<T, I, E, U>, indices: string[]): CollectionBackend<T, I>;
57
+ private setupStorage;
58
+ private ensureStorageAdapter;
59
+ /**
60
+ * Compute and publish the result for a specific query
61
+ * @param collectionName - name of the collection
62
+ * @param selector - query selector
63
+ * @param options - query options
64
+ */
65
+ private fulfillQuery;
66
+ /**
67
+ * Executes a query, retrying transient failures before giving up. The state
68
+ * stays `'active'` across retries — consumers should see "still loading",
69
+ * not "failed", until we actually stop trying. Only the final failure is
70
+ * published as `'error'` and reported through `onError`; previously that
71
+ * error was swallowed entirely (`fulfillQuery` caught it internally, so the
72
+ * `.catch(this.onError)` on its call site was unreachable) and the query
73
+ * stayed dead for the rest of the session.
74
+ * @param collectionName - name of the collection
75
+ * @param selector - query selector
76
+ * @param options - query options
77
+ */
78
+ private runQuery;
79
+ /**
80
+ * Notify listeners about state changes and keep the cache updated
81
+ * @param collectionName - name of the collection
82
+ * @param qid - query id
83
+ * @param state - new state
84
+ * @param error - error if state is 'error', null otherwise
85
+ */
86
+ private publishState;
87
+ private publishResult;
88
+ private getIndexInfo;
89
+ private queryItems;
90
+ private executeQuery;
91
+ /**
92
+ * After mutations, recompute and push updates for affected active queries
93
+ * @param collectionName - name of the collection
94
+ * @param affectedItems - item states before and/or after the mutation
95
+ */
96
+ private checkQueryUpdates;
97
+ private insert;
98
+ private updateOne;
99
+ private updateMany;
100
+ private replaceOne;
101
+ private removeOne;
102
+ private removeMany;
103
+ }
@@ -0,0 +1,518 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.QueryError = void 0;
7
+ const deepClone_1 = __importDefault(require("./utils/deepClone"));
8
+ const match_1 = __importDefault(require("./utils/match"));
9
+ const modify_1 = __importDefault(require("./utils/modify"));
10
+ const queryId_1 = __importDefault(require("./utils/queryId"));
11
+ const isEqual_1 = __importDefault(require("./utils/isEqual"));
12
+ const getIndexInfo_1 = __importDefault(require("./getIndexInfo"));
13
+ const getMatchingKeys_1 = __importDefault(require("./utils/getMatchingKeys"));
14
+ const sortItems_1 = __importDefault(require("./utils/sortItems"));
15
+ const project_1 = __importDefault(require("./utils/project"));
16
+ /**
17
+ * Carries the context needed to act on a failed query. The bare storage error
18
+ * on its own does not say which collection or selector produced it, which made
19
+ * the default `console.error` hook close to useless.
20
+ */
21
+ class QueryError extends Error {
22
+ collectionName;
23
+ selector;
24
+ options;
25
+ attempts;
26
+ constructor(collectionName, selector, options, attempts, cause) {
27
+ const reason = cause instanceof Error ? cause.message : String(cause);
28
+ super(`Query on "${collectionName}" failed after ${attempts} attempt(s): ${reason}`);
29
+ this.name = 'QueryError';
30
+ this.collectionName = collectionName;
31
+ this.selector = selector;
32
+ this.options = options;
33
+ this.attempts = attempts;
34
+ this.cause = cause;
35
+ }
36
+ }
37
+ exports.QueryError = QueryError;
38
+ const DEFAULT_RETRY_ATTEMPTS = 3;
39
+ const defaultRetryDelay = (attempt) => 100 * (4 ** (attempt - 1));
40
+ const wait = (ms) => new Promise((resolve) => {
41
+ setTimeout(resolve, ms);
42
+ });
43
+ /**
44
+ * AsyncDataAdapter
45
+ * Combines WorkerDataAdapter + WorkerDataAdapterHost into a single, transport-free adapter.
46
+ * - Keeps the DataAdapter/CollectionBackend surface identical to the Worker version.
47
+ * - Executes queries and mutations directly against the provided StorageAdapter.
48
+ * - Preserves index-aware query optimization and push-style query updates to listeners.
49
+ */
50
+ class AsyncDataAdapter {
51
+ options;
52
+ id;
53
+ onError;
54
+ retryAttempts;
55
+ retryDelay;
56
+ // Per-collection resources
57
+ storageAdapters = new Map();
58
+ storageAdapterReady = new Map();
59
+ collectionIndices = new Map();
60
+ // Per-collection query registries
61
+ queries = new Map();
62
+ constructor(options) {
63
+ this.options = options;
64
+ this.id = options.id || 'async-data-adapter';
65
+ this.onError = options.onError ?? ((error) => {
66
+ /* eslint-disable no-console */ console.error(error);
67
+ });
68
+ this.retryAttempts = Math.max(1, options.retry?.attempts ?? DEFAULT_RETRY_ATTEMPTS);
69
+ this.retryDelay = options.retry?.delay ?? defaultRetryDelay;
70
+ }
71
+ createCollectionBackend(collection, indices) {
72
+ // init per-collection state
73
+ this.collectionIndices.set(collection.name, indices);
74
+ this.queries.set(collection.name, new Map());
75
+ this.ensureStorageAdapter(collection.name);
76
+ const ready = (async () => {
77
+ try {
78
+ await this.setupStorage(collection.name, indices);
79
+ }
80
+ catch (error) {
81
+ // Handle inside the same async task to avoid unhandled rejections
82
+ this.onError(error);
83
+ throw error;
84
+ }
85
+ })();
86
+ this.storageAdapterReady.set(collection.name, ready);
87
+ // don't block createCollectionBackend; callers can await isReady()
88
+ const registerQuery = (selector, options) => {
89
+ const qid = (0, queryId_1.default)(selector, options);
90
+ const registry = this.queries.get(collection.name);
91
+ if (!registry)
92
+ throw new Error(`Collection ${collection.name} not initialized!`);
93
+ registry.set(qid, {
94
+ selector,
95
+ options,
96
+ items: [],
97
+ listeners: new Set(),
98
+ ...registry.get(qid),
99
+ state: 'active',
100
+ error: null,
101
+ });
102
+ // kick async execution
103
+ void this.fulfillQuery(collection.name, selector, options).catch(this.onError);
104
+ };
105
+ const unregisterQuery = (selector, options) => {
106
+ const qid = (0, queryId_1.default)(selector, options);
107
+ this.queries.get(collection.name)?.delete(qid);
108
+ };
109
+ const getQueryState = (selector, options) => {
110
+ const q = this.queries.get(collection.name)?.get((0, queryId_1.default)(selector, options));
111
+ return q?.state ?? 'active';
112
+ };
113
+ const getQueryError = (selector, options) => {
114
+ const q = this.queries.get(collection.name)?.get((0, queryId_1.default)(selector, options));
115
+ return q?.error ?? null;
116
+ };
117
+ const getQueryResult = (selector, options) => {
118
+ const q = this.queries.get(collection.name)?.get((0, queryId_1.default)(selector, options));
119
+ return q?.items ?? [];
120
+ };
121
+ const retryQuery = (selector, options) => {
122
+ const qid = (0, queryId_1.default)(selector, options);
123
+ const rec = this.queries.get(collection.name)?.get(qid);
124
+ if (!rec)
125
+ return;
126
+ this.publishState(collection.name, qid, 'active', null);
127
+ void this.runQuery(collection.name, selector, options);
128
+ };
129
+ const onQueryStateChange = (selector, options, callback) => {
130
+ const qid = (0, queryId_1.default)(selector, options);
131
+ const registry = this.queries.get(collection.name);
132
+ if (!registry)
133
+ throw new Error(`Collection ${collection.name} not initialized!`);
134
+ // ensure the record exists so we have a listener bucket
135
+ if (!registry.has(qid)) {
136
+ registry.set(qid, {
137
+ selector,
138
+ options,
139
+ state: 'active',
140
+ error: null,
141
+ items: [],
142
+ listeners: new Set(),
143
+ });
144
+ }
145
+ registry.get(qid)?.listeners.add(callback);
146
+ // A query that has already failed would otherwise stay failed forever:
147
+ // `registerQuery` only runs for the *first* cursor on a selector, so
148
+ // every later observer inherited the dead state without anything ever
149
+ // retrying it. A new observer is a natural moment to try again.
150
+ if (registry.get(qid)?.state === 'error')
151
+ retryQuery(selector, options);
152
+ return () => registry.get(qid)?.listeners.delete(callback);
153
+ };
154
+ return {
155
+ insert: async (item) => {
156
+ await ready;
157
+ const inserted = await this.insert(collection.name, item);
158
+ return inserted;
159
+ },
160
+ updateOne: async (selector, modifier) => {
161
+ await ready;
162
+ return this.updateOne(collection.name, selector, modifier);
163
+ },
164
+ updateMany: async (selector, modifier) => {
165
+ await ready;
166
+ return this.updateMany(collection.name, selector, modifier);
167
+ },
168
+ replaceOne: async (selector, replacement) => {
169
+ await ready;
170
+ return this.replaceOne(collection.name, selector, replacement);
171
+ },
172
+ removeOne: async (selector) => {
173
+ await ready;
174
+ return this.removeOne(collection.name, selector);
175
+ },
176
+ removeMany: async (selector) => {
177
+ await ready;
178
+ return this.removeMany(collection.name, selector);
179
+ },
180
+ registerQuery,
181
+ unregisterQuery,
182
+ retryQuery,
183
+ getQueryState,
184
+ getQueryError,
185
+ getQueryResult,
186
+ onQueryStateChange,
187
+ executeQuery: async (selector, options) => {
188
+ await ready;
189
+ return this.executeQuery(collection.name, selector, options);
190
+ },
191
+ dispose: async () => {
192
+ // mirror host.unregisterCollection semantics
193
+ this.storageAdapters.delete(collection.name);
194
+ this.queries.delete(collection.name);
195
+ this.collectionIndices.delete(collection.name);
196
+ this.storageAdapterReady.delete(collection.name);
197
+ },
198
+ isReady: async () => {
199
+ await ready;
200
+ },
201
+ };
202
+ }
203
+ async setupStorage(collectionName, indices) {
204
+ const storage = this.storageAdapters.get(collectionName);
205
+ if (!storage)
206
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
207
+ await storage.setup();
208
+ await Promise.all(indices.map(index => storage.createIndex(index)));
209
+ }
210
+ ensureStorageAdapter(name) {
211
+ if (this.storageAdapters.has(name))
212
+ return;
213
+ const adapter = this.options.storage(name);
214
+ if (!adapter)
215
+ return;
216
+ this.storageAdapters.set(name, adapter);
217
+ }
218
+ /**
219
+ * Compute and publish the result for a specific query
220
+ * @param collectionName - name of the collection
221
+ * @param selector - query selector
222
+ * @param options - query options
223
+ */
224
+ async fulfillQuery(collectionName, selector, options) {
225
+ const qid = (0, queryId_1.default)(selector, options);
226
+ const registry = this.queries.get(collectionName);
227
+ if (!registry)
228
+ throw new Error(`Collection ${collectionName} not initialized!`);
229
+ const rec = registry.get(qid);
230
+ if (!rec)
231
+ return;
232
+ this.publishState(collectionName, qid, 'active', null);
233
+ await this.runQuery(collectionName, selector, options);
234
+ }
235
+ /**
236
+ * Executes a query, retrying transient failures before giving up. The state
237
+ * stays `'active'` across retries — consumers should see "still loading",
238
+ * not "failed", until we actually stop trying. Only the final failure is
239
+ * published as `'error'` and reported through `onError`; previously that
240
+ * error was swallowed entirely (`fulfillQuery` caught it internally, so the
241
+ * `.catch(this.onError)` on its call site was unreachable) and the query
242
+ * stayed dead for the rest of the session.
243
+ * @param collectionName - name of the collection
244
+ * @param selector - query selector
245
+ * @param options - query options
246
+ */
247
+ async runQuery(collectionName, selector, options) {
248
+ const qid = (0, queryId_1.default)(selector, options);
249
+ let lastError;
250
+ for (let attempt = 1; attempt <= this.retryAttempts; attempt += 1) {
251
+ // The query can be unregistered while a retry is waiting — dropping out
252
+ // here keeps a disposed cursor from resurrecting its record.
253
+ if (!this.queries.get(collectionName)?.has(qid))
254
+ return;
255
+ try {
256
+ const items = await this.executeQuery(collectionName, selector, options);
257
+ this.publishResult(collectionName, qid, items);
258
+ this.publishState(collectionName, qid, 'complete', null);
259
+ return;
260
+ }
261
+ catch (error) {
262
+ lastError = error;
263
+ if (attempt < this.retryAttempts)
264
+ await wait(this.retryDelay(attempt));
265
+ }
266
+ }
267
+ const queryError = new QueryError(collectionName, selector, options, this.retryAttempts, lastError);
268
+ this.publishState(collectionName, qid, 'error', queryError);
269
+ this.onError(queryError);
270
+ }
271
+ /**
272
+ * Notify listeners about state changes and keep the cache updated
273
+ * @param collectionName - name of the collection
274
+ * @param qid - query id
275
+ * @param state - new state
276
+ * @param error - error if state is 'error', null otherwise
277
+ */
278
+ publishState(collectionName, qid, state, error) {
279
+ const rec = this.queries.get(collectionName)?.get(qid);
280
+ if (!rec)
281
+ return;
282
+ rec.state = state;
283
+ rec.error = error;
284
+ // notify subscribers
285
+ for (const callback of rec.listeners) {
286
+ try {
287
+ callback(state);
288
+ }
289
+ catch (error_) {
290
+ this.onError(error_);
291
+ }
292
+ }
293
+ }
294
+ publishResult(collectionName, qid, items) {
295
+ const rec = this.queries.get(collectionName)?.get(qid);
296
+ if (!rec)
297
+ return;
298
+ rec.items = items;
299
+ }
300
+ async getIndexInfo(collectionName, selector) {
301
+ const storageAdapter = this.storageAdapters.get(collectionName);
302
+ if (!storageAdapter)
303
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
304
+ if (selector != null
305
+ && Object.keys(selector).length === 1
306
+ && 'id' in selector
307
+ && typeof selector.id !== 'object') {
308
+ return {
309
+ matched: true,
310
+ ids: [selector.id].filter(Boolean),
311
+ optimizedSelector: {},
312
+ };
313
+ }
314
+ if (selector == null) {
315
+ return {
316
+ matched: false,
317
+ ids: [],
318
+ optimizedSelector: {},
319
+ };
320
+ }
321
+ const indices = this.collectionIndices.get(collectionName) ?? [];
322
+ return (0, getIndexInfo_1.default)(indices.map(field => async (flatSelector) => {
323
+ if (!Object.hasOwnProperty.call(flatSelector, field))
324
+ return { matched: false };
325
+ const index = await storageAdapter.readIndex(field);
326
+ const fieldSelector = flatSelector[field];
327
+ const filtersForNull = fieldSelector == null || fieldSelector.$exists === false;
328
+ const keys = filtersForNull
329
+ ? { include: null, exclude: [...index.keys()].filter(key => key != null) }
330
+ : (0, getMatchingKeys_1.default)(field, flatSelector);
331
+ if (keys.include == null && keys.exclude == null)
332
+ return { matched: false };
333
+ // Build included ids
334
+ let includedIds = [];
335
+ if (keys.include == null) {
336
+ for (const set of index.values())
337
+ for (const pos of set)
338
+ includedIds.push(pos);
339
+ }
340
+ else {
341
+ for (const key of keys.include) {
342
+ const idSet = index.get(key);
343
+ if (idSet)
344
+ for (const id of idSet)
345
+ includedIds.push(id);
346
+ }
347
+ }
348
+ // Apply exclusions
349
+ if (keys.exclude != null) {
350
+ const excludeIds = new Set();
351
+ for (const key of keys.exclude) {
352
+ const idSet = index.get(key);
353
+ if (idSet)
354
+ for (const id of idSet)
355
+ excludeIds.add(id);
356
+ }
357
+ includedIds = includedIds.filter(pos => !excludeIds.has(pos));
358
+ }
359
+ return { matched: true, ids: includedIds, fields: [field], keepSelector: filtersForNull };
360
+ }), selector);
361
+ }
362
+ async queryItems(collectionName, selector) {
363
+ const storage = this.storageAdapters.get(collectionName);
364
+ if (!storage)
365
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
366
+ const index = await this.getIndexInfo(collectionName, selector);
367
+ const matchItems = (item) => {
368
+ if (index.optimizedSelector == null)
369
+ return true;
370
+ if (Object.keys(index.optimizedSelector).length <= 0)
371
+ return true;
372
+ return (0, match_1.default)(item, index.optimizedSelector);
373
+ };
374
+ if (index.matched) {
375
+ const items = await storage.readIds(index.ids);
376
+ if ((0, isEqual_1.default)(index.optimizedSelector, {}))
377
+ return items;
378
+ return items.filter(matchItems);
379
+ }
380
+ else {
381
+ const allItems = await storage.readAll();
382
+ if ((0, isEqual_1.default)(selector, {}))
383
+ return allItems;
384
+ return allItems.filter(matchItems);
385
+ }
386
+ }
387
+ async executeQuery(collectionName, selector, options) {
388
+ const items = await this.queryItems(collectionName, selector || {});
389
+ const { sort, skip, limit, fields } = options || {};
390
+ const sorted = sort ? (0, sortItems_1.default)(items, sort) : items;
391
+ const skipped = skip ? sorted.slice(skip) : sorted;
392
+ const limited = limit ? skipped.slice(0, limit) : skipped;
393
+ const idExcluded = fields && fields.id === 0;
394
+ return limited.map((item) => {
395
+ if (!fields)
396
+ return item;
397
+ return { ...(idExcluded ? {} : { id: item.id }), ...(0, project_1.default)(item, fields) };
398
+ });
399
+ }
400
+ /**
401
+ * After mutations, recompute and push updates for affected active queries
402
+ * @param collectionName - name of the collection
403
+ * @param affectedItems - item states before and/or after the mutation
404
+ */
405
+ async checkQueryUpdates(collectionName, affectedItems) {
406
+ const registry = this.queries.get(collectionName);
407
+ if (!registry)
408
+ throw new Error(`Collection ${collectionName} not initialized!`);
409
+ if (registry.size === 0)
410
+ return;
411
+ // Find active queries matching an item state before or after the mutation
412
+ const affected = [...registry.values()].filter(({ selector }) => affectedItems.some(item => (0, match_1.default)(item, selector)));
413
+ if (affected.length === 0)
414
+ return;
415
+ // Mark active and notify…
416
+ for (const { selector, options } of affected) {
417
+ const qid = (0, queryId_1.default)(selector, options);
418
+ this.publishState(collectionName, qid, 'active', null);
419
+ }
420
+ // …then recompute and complete, with the same retry/report behaviour a
421
+ // freshly registered query gets — a mutation-triggered refresh that fails
422
+ // silently leaves exactly the same dead cursor.
423
+ await Promise.all(affected.map(({ selector, options }) => this.runQuery(collectionName, selector, options)));
424
+ }
425
+ async insert(collectionName, newItem) {
426
+ const storage = this.storageAdapters.get(collectionName);
427
+ if (!storage)
428
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
429
+ const existingItems = await storage.readIds([newItem.id]);
430
+ if (existingItems.length > 0)
431
+ throw new Error(`Item with id ${String(newItem.id)} already exists`);
432
+ await storage.insert([newItem]);
433
+ await this.checkQueryUpdates(collectionName, [newItem]);
434
+ return newItem;
435
+ }
436
+ async updateOne(collectionName, selector, modifier) {
437
+ const storage = this.storageAdapters.get(collectionName);
438
+ if (!storage)
439
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
440
+ const items = await this.executeQuery(collectionName, selector, { limit: 1 });
441
+ const [item] = items;
442
+ const { $setOnInsert, ...rest } = modifier;
443
+ if (item == null)
444
+ return [];
445
+ const modified = (0, modify_1.default)((0, deepClone_1.default)(item), rest);
446
+ if (item.id !== modified.id) {
447
+ const existing = await storage.readIds([modified.id]);
448
+ if (existing.length > 0)
449
+ throw new Error(`Item with id ${String(modified.id)} already exists`);
450
+ }
451
+ await storage.replace([modified]);
452
+ await this.checkQueryUpdates(collectionName, [item, modified]);
453
+ return [modified];
454
+ }
455
+ async updateMany(collectionName, selector, modifier) {
456
+ const storage = this.storageAdapters.get(collectionName);
457
+ if (!storage)
458
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
459
+ const items = await this.executeQuery(collectionName, selector);
460
+ if (items.length === 0)
461
+ return [];
462
+ const { $setOnInsert, ...rest } = modifier;
463
+ const changed = await Promise.all(items.map(async (item) => {
464
+ const modified = (0, modify_1.default)((0, deepClone_1.default)(item), rest);
465
+ if (item.id !== modified.id) {
466
+ const existing = await storage.readIds([modified.id]);
467
+ if (existing.length > 0)
468
+ throw new Error(`Item with id ${String(modified.id)} already exists`);
469
+ }
470
+ return modified;
471
+ }));
472
+ await storage.replace(changed);
473
+ await this.checkQueryUpdates(collectionName, [...items, ...changed]);
474
+ return changed;
475
+ }
476
+ async replaceOne(collectionName, selector, replacement) {
477
+ const storage = this.storageAdapters.get(collectionName);
478
+ if (!storage)
479
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
480
+ const items = await this.executeQuery(collectionName, selector, { limit: 1 });
481
+ const [item] = items;
482
+ if (item == null)
483
+ return [];
484
+ const modified = { ...replacement, id: replacement.id ?? item.id };
485
+ if (item.id !== modified.id) {
486
+ const existing = await storage.readIds([modified.id]);
487
+ if (existing.length > 0)
488
+ throw new Error(`Item with id ${String(modified.id)} already exists`);
489
+ }
490
+ await storage.replace([modified]);
491
+ await this.checkQueryUpdates(collectionName, [item, modified]);
492
+ return [modified];
493
+ }
494
+ async removeOne(collectionName, selector) {
495
+ const storage = this.storageAdapters.get(collectionName);
496
+ if (!storage)
497
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
498
+ const items = await this.executeQuery(collectionName, selector, { limit: 1 });
499
+ const [item] = items;
500
+ if (item == null)
501
+ return [];
502
+ await storage.remove([item]);
503
+ await this.checkQueryUpdates(collectionName, [item]);
504
+ return [item];
505
+ }
506
+ async removeMany(collectionName, selector) {
507
+ const storage = this.storageAdapters.get(collectionName);
508
+ if (!storage)
509
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
510
+ const items = await this.executeQuery(collectionName, selector);
511
+ if (items.length === 0)
512
+ return [];
513
+ await storage.remove(items);
514
+ await this.checkQueryUpdates(collectionName, items);
515
+ return items;
516
+ }
517
+ }
518
+ exports.default = AsyncDataAdapter;