@signaldb/svelte 2.0.0-beta.6 → 2.0.0-beta.8

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 (89) hide show
  1. package/dist/base/core/src/AsyncDataAdapter.d.ts +64 -0
  2. package/dist/base/core/src/AsyncDataAdapter.js +450 -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 +294 -0
  10. package/dist/base/core/src/Collection/index.js +580 -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 +35 -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/reactivity-adapters/svelte/index.svelte.d.ts +10 -0
  88. package/dist/reactivity-adapters/svelte/index.svelte.js +36 -0
  89. package/package.json +3 -3
@@ -0,0 +1,64 @@
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
+ /**
15
+ * AsyncDataAdapter
16
+ * Combines WorkerDataAdapter + WorkerDataAdapterHost into a single, transport-free adapter.
17
+ * - Keeps the DataAdapter/CollectionBackend surface identical to the Worker version.
18
+ * - Executes queries and mutations directly against the provided StorageAdapter.
19
+ * - Preserves index-aware query optimization and push-style query updates to listeners.
20
+ */
21
+ export default class AsyncDataAdapter implements DataAdapter {
22
+ private options;
23
+ private id;
24
+ private onError;
25
+ private storageAdapters;
26
+ private storageAdapterReady;
27
+ private collectionIndices;
28
+ private queries;
29
+ constructor(options: AsyncDataAdapterOptions);
30
+ createCollectionBackend<T extends BaseItem<I>, I = any, E extends BaseItem = T, U = E>(collection: Collection<T, I, E, U>, indices: string[]): CollectionBackend<T, I>;
31
+ private setupStorage;
32
+ private ensureStorageAdapter;
33
+ /**
34
+ * Compute and publish the result for a specific query
35
+ * @param collectionName - name of the collection
36
+ * @param selector - query selector
37
+ * @param options - query options
38
+ */
39
+ private fulfillQuery;
40
+ /**
41
+ * Notify listeners about state changes and keep the cache updated
42
+ * @param collectionName - name of the collection
43
+ * @param qid - query id
44
+ * @param state - new state
45
+ * @param error - error if state is 'error', null otherwise
46
+ */
47
+ private publishState;
48
+ private publishResult;
49
+ private getIndexInfo;
50
+ private queryItems;
51
+ private executeQuery;
52
+ /**
53
+ * After mutations, recompute and push updates for affected active queries
54
+ * @param collectionName - name of the collection
55
+ * @param affectedItems - item states before and/or after the mutation
56
+ */
57
+ private checkQueryUpdates;
58
+ private insert;
59
+ private updateOne;
60
+ private updateMany;
61
+ private replaceOne;
62
+ private removeOne;
63
+ private removeMany;
64
+ }
@@ -0,0 +1,450 @@
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
+ const deepClone_1 = __importDefault(require("./utils/deepClone"));
7
+ const match_1 = __importDefault(require("./utils/match"));
8
+ const modify_1 = __importDefault(require("./utils/modify"));
9
+ const queryId_1 = __importDefault(require("./utils/queryId"));
10
+ const isEqual_1 = __importDefault(require("./utils/isEqual"));
11
+ const getIndexInfo_1 = __importDefault(require("./getIndexInfo"));
12
+ const getMatchingKeys_1 = __importDefault(require("./utils/getMatchingKeys"));
13
+ const sortItems_1 = __importDefault(require("./utils/sortItems"));
14
+ const project_1 = __importDefault(require("./utils/project"));
15
+ /**
16
+ * AsyncDataAdapter
17
+ * Combines WorkerDataAdapter + WorkerDataAdapterHost into a single, transport-free adapter.
18
+ * - Keeps the DataAdapter/CollectionBackend surface identical to the Worker version.
19
+ * - Executes queries and mutations directly against the provided StorageAdapter.
20
+ * - Preserves index-aware query optimization and push-style query updates to listeners.
21
+ */
22
+ class AsyncDataAdapter {
23
+ options;
24
+ id;
25
+ onError;
26
+ // Per-collection resources
27
+ storageAdapters = new Map();
28
+ storageAdapterReady = new Map();
29
+ collectionIndices = new Map();
30
+ // Per-collection query registries
31
+ queries = new Map();
32
+ constructor(options) {
33
+ this.options = options;
34
+ this.id = options.id || 'async-data-adapter';
35
+ this.onError = options.onError ?? ((error) => {
36
+ /* eslint-disable no-console */ console.error(error);
37
+ });
38
+ }
39
+ createCollectionBackend(collection, indices) {
40
+ // init per-collection state
41
+ this.collectionIndices.set(collection.name, indices);
42
+ this.queries.set(collection.name, new Map());
43
+ this.ensureStorageAdapter(collection.name);
44
+ const ready = (async () => {
45
+ try {
46
+ await this.setupStorage(collection.name, indices);
47
+ }
48
+ catch (error) {
49
+ // Handle inside the same async task to avoid unhandled rejections
50
+ this.onError(error);
51
+ throw error;
52
+ }
53
+ })();
54
+ this.storageAdapterReady.set(collection.name, ready);
55
+ // don't block createCollectionBackend; callers can await isReady()
56
+ const registerQuery = (selector, options) => {
57
+ const qid = (0, queryId_1.default)(selector, options);
58
+ const registry = this.queries.get(collection.name);
59
+ if (!registry)
60
+ throw new Error(`Collection ${collection.name} not initialized!`);
61
+ registry.set(qid, {
62
+ selector,
63
+ options,
64
+ items: [],
65
+ listeners: new Set(),
66
+ ...registry.get(qid),
67
+ state: 'active',
68
+ error: null,
69
+ });
70
+ // kick async execution
71
+ void this.fulfillQuery(collection.name, selector, options).catch(this.onError);
72
+ };
73
+ const unregisterQuery = (selector, options) => {
74
+ const qid = (0, queryId_1.default)(selector, options);
75
+ this.queries.get(collection.name)?.delete(qid);
76
+ };
77
+ const getQueryState = (selector, options) => {
78
+ const q = this.queries.get(collection.name)?.get((0, queryId_1.default)(selector, options));
79
+ return q?.state ?? 'active';
80
+ };
81
+ const getQueryError = (selector, options) => {
82
+ const q = this.queries.get(collection.name)?.get((0, queryId_1.default)(selector, options));
83
+ return q?.error ?? null;
84
+ };
85
+ const getQueryResult = (selector, options) => {
86
+ const q = this.queries.get(collection.name)?.get((0, queryId_1.default)(selector, options));
87
+ return q?.items ?? [];
88
+ };
89
+ const onQueryStateChange = (selector, options, callback) => {
90
+ const qid = (0, queryId_1.default)(selector, options);
91
+ const registry = this.queries.get(collection.name);
92
+ if (!registry)
93
+ throw new Error(`Collection ${collection.name} not initialized!`);
94
+ // ensure the record exists so we have a listener bucket
95
+ if (!registry.has(qid)) {
96
+ registry.set(qid, {
97
+ selector,
98
+ options,
99
+ state: 'active',
100
+ error: null,
101
+ items: [],
102
+ listeners: new Set(),
103
+ });
104
+ }
105
+ registry.get(qid)?.listeners.add(callback);
106
+ return () => registry.get(qid)?.listeners.delete(callback);
107
+ };
108
+ return {
109
+ insert: async (item) => {
110
+ await ready;
111
+ const inserted = await this.insert(collection.name, item);
112
+ return inserted;
113
+ },
114
+ updateOne: async (selector, modifier) => {
115
+ await ready;
116
+ return this.updateOne(collection.name, selector, modifier);
117
+ },
118
+ updateMany: async (selector, modifier) => {
119
+ await ready;
120
+ return this.updateMany(collection.name, selector, modifier);
121
+ },
122
+ replaceOne: async (selector, replacement) => {
123
+ await ready;
124
+ return this.replaceOne(collection.name, selector, replacement);
125
+ },
126
+ removeOne: async (selector) => {
127
+ await ready;
128
+ return this.removeOne(collection.name, selector);
129
+ },
130
+ removeMany: async (selector) => {
131
+ await ready;
132
+ return this.removeMany(collection.name, selector);
133
+ },
134
+ registerQuery,
135
+ unregisterQuery,
136
+ getQueryState,
137
+ getQueryError,
138
+ getQueryResult,
139
+ onQueryStateChange,
140
+ executeQuery: async (selector, options) => {
141
+ await ready;
142
+ return this.executeQuery(collection.name, selector, options);
143
+ },
144
+ dispose: async () => {
145
+ // mirror host.unregisterCollection semantics
146
+ this.storageAdapters.delete(collection.name);
147
+ this.queries.delete(collection.name);
148
+ this.collectionIndices.delete(collection.name);
149
+ this.storageAdapterReady.delete(collection.name);
150
+ },
151
+ isReady: async () => {
152
+ await ready;
153
+ },
154
+ };
155
+ }
156
+ async setupStorage(collectionName, indices) {
157
+ const storage = this.storageAdapters.get(collectionName);
158
+ if (!storage)
159
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
160
+ await storage.setup();
161
+ await Promise.all(indices.map(index => storage.createIndex(index)));
162
+ }
163
+ ensureStorageAdapter(name) {
164
+ if (this.storageAdapters.has(name))
165
+ return;
166
+ const adapter = this.options.storage(name);
167
+ if (!adapter)
168
+ return;
169
+ this.storageAdapters.set(name, adapter);
170
+ }
171
+ /**
172
+ * Compute and publish the result for a specific query
173
+ * @param collectionName - name of the collection
174
+ * @param selector - query selector
175
+ * @param options - query options
176
+ */
177
+ async fulfillQuery(collectionName, selector, options) {
178
+ const qid = (0, queryId_1.default)(selector, options);
179
+ const registry = this.queries.get(collectionName);
180
+ if (!registry)
181
+ throw new Error(`Collection ${collectionName} not initialized!`);
182
+ const rec = registry.get(qid);
183
+ if (!rec)
184
+ return;
185
+ this.publishState(collectionName, qid, 'active', null);
186
+ try {
187
+ const items = await this.executeQuery(collectionName, selector, options);
188
+ this.publishResult(collectionName, qid, items);
189
+ this.publishState(collectionName, qid, 'complete', null);
190
+ }
191
+ catch (error) {
192
+ this.publishState(collectionName, qid, 'error', error);
193
+ }
194
+ }
195
+ /**
196
+ * Notify listeners about state changes and keep the cache updated
197
+ * @param collectionName - name of the collection
198
+ * @param qid - query id
199
+ * @param state - new state
200
+ * @param error - error if state is 'error', null otherwise
201
+ */
202
+ publishState(collectionName, qid, state, error) {
203
+ const rec = this.queries.get(collectionName)?.get(qid);
204
+ if (!rec)
205
+ return;
206
+ rec.state = state;
207
+ rec.error = error;
208
+ // notify subscribers
209
+ for (const callback of rec.listeners) {
210
+ try {
211
+ callback(state);
212
+ }
213
+ catch (error_) {
214
+ this.onError(error_);
215
+ }
216
+ }
217
+ }
218
+ publishResult(collectionName, qid, items) {
219
+ const rec = this.queries.get(collectionName)?.get(qid);
220
+ if (!rec)
221
+ return;
222
+ rec.items = items;
223
+ }
224
+ async getIndexInfo(collectionName, selector) {
225
+ const storageAdapter = this.storageAdapters.get(collectionName);
226
+ if (!storageAdapter)
227
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
228
+ if (selector != null
229
+ && Object.keys(selector).length === 1
230
+ && 'id' in selector
231
+ && typeof selector.id !== 'object') {
232
+ return {
233
+ matched: true,
234
+ ids: [selector.id].filter(Boolean),
235
+ optimizedSelector: {},
236
+ };
237
+ }
238
+ if (selector == null) {
239
+ return {
240
+ matched: false,
241
+ ids: [],
242
+ optimizedSelector: {},
243
+ };
244
+ }
245
+ const indices = this.collectionIndices.get(collectionName) ?? [];
246
+ return (0, getIndexInfo_1.default)(indices.map(field => async (flatSelector) => {
247
+ if (!Object.hasOwnProperty.call(flatSelector, field))
248
+ return { matched: false };
249
+ const index = await storageAdapter.readIndex(field);
250
+ const fieldSelector = flatSelector[field];
251
+ const filtersForNull = fieldSelector == null || fieldSelector.$exists === false;
252
+ const keys = filtersForNull
253
+ ? { include: null, exclude: [...index.keys()].filter(key => key != null) }
254
+ : (0, getMatchingKeys_1.default)(field, flatSelector);
255
+ if (keys.include == null && keys.exclude == null)
256
+ return { matched: false };
257
+ // Build included ids
258
+ let includedIds = [];
259
+ if (keys.include == null) {
260
+ for (const set of index.values())
261
+ for (const pos of set)
262
+ includedIds.push(pos);
263
+ }
264
+ else {
265
+ for (const key of keys.include) {
266
+ const idSet = index.get(key);
267
+ if (idSet)
268
+ for (const id of idSet)
269
+ includedIds.push(id);
270
+ }
271
+ }
272
+ // Apply exclusions
273
+ if (keys.exclude != null) {
274
+ const excludeIds = new Set();
275
+ for (const key of keys.exclude) {
276
+ const idSet = index.get(key);
277
+ if (idSet)
278
+ for (const id of idSet)
279
+ excludeIds.add(id);
280
+ }
281
+ includedIds = includedIds.filter(pos => !excludeIds.has(pos));
282
+ }
283
+ return { matched: true, ids: includedIds, fields: [field], keepSelector: filtersForNull };
284
+ }), selector);
285
+ }
286
+ async queryItems(collectionName, selector) {
287
+ const storage = this.storageAdapters.get(collectionName);
288
+ if (!storage)
289
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
290
+ const index = await this.getIndexInfo(collectionName, selector);
291
+ const matchItems = (item) => {
292
+ if (index.optimizedSelector == null)
293
+ return true;
294
+ if (Object.keys(index.optimizedSelector).length <= 0)
295
+ return true;
296
+ return (0, match_1.default)(item, index.optimizedSelector);
297
+ };
298
+ if (index.matched) {
299
+ const items = await storage.readIds(index.ids);
300
+ if ((0, isEqual_1.default)(index.optimizedSelector, {}))
301
+ return items;
302
+ return items.filter(matchItems);
303
+ }
304
+ else {
305
+ const allItems = await storage.readAll();
306
+ if ((0, isEqual_1.default)(selector, {}))
307
+ return allItems;
308
+ return allItems.filter(matchItems);
309
+ }
310
+ }
311
+ async executeQuery(collectionName, selector, options) {
312
+ const items = await this.queryItems(collectionName, selector || {});
313
+ const { sort, skip, limit, fields } = options || {};
314
+ const sorted = sort ? (0, sortItems_1.default)(items, sort) : items;
315
+ const skipped = skip ? sorted.slice(skip) : sorted;
316
+ const limited = limit ? skipped.slice(0, limit) : skipped;
317
+ const idExcluded = fields && fields.id === 0;
318
+ return limited.map((item) => {
319
+ if (!fields)
320
+ return item;
321
+ return { ...(idExcluded ? {} : { id: item.id }), ...(0, project_1.default)(item, fields) };
322
+ });
323
+ }
324
+ /**
325
+ * After mutations, recompute and push updates for affected active queries
326
+ * @param collectionName - name of the collection
327
+ * @param affectedItems - item states before and/or after the mutation
328
+ */
329
+ async checkQueryUpdates(collectionName, affectedItems) {
330
+ const registry = this.queries.get(collectionName);
331
+ if (!registry)
332
+ throw new Error(`Collection ${collectionName} not initialized!`);
333
+ if (registry.size === 0)
334
+ return;
335
+ // Find active queries matching an item state before or after the mutation
336
+ const affected = [...registry.values()].filter(({ selector }) => affectedItems.some(item => (0, match_1.default)(item, selector)));
337
+ if (affected.length === 0)
338
+ return;
339
+ // Mark active and notify…
340
+ for (const { selector, options } of affected) {
341
+ const qid = (0, queryId_1.default)(selector, options);
342
+ this.publishState(collectionName, qid, 'active', null);
343
+ }
344
+ // …then recompute and complete
345
+ await Promise.all(affected.map(async ({ selector, options }) => {
346
+ const qid = (0, queryId_1.default)(selector, options);
347
+ try {
348
+ const items = await this.executeQuery(collectionName, selector, options);
349
+ this.publishResult(collectionName, qid, items);
350
+ this.publishState(collectionName, qid, 'complete', null);
351
+ }
352
+ catch (error) {
353
+ this.publishState(collectionName, qid, 'error', error);
354
+ }
355
+ }));
356
+ }
357
+ async insert(collectionName, newItem) {
358
+ const storage = this.storageAdapters.get(collectionName);
359
+ if (!storage)
360
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
361
+ const existingItems = await storage.readIds([newItem.id]);
362
+ if (existingItems.length > 0)
363
+ throw new Error(`Item with id ${String(newItem.id)} already exists`);
364
+ await storage.insert([newItem]);
365
+ await this.checkQueryUpdates(collectionName, [newItem]);
366
+ return newItem;
367
+ }
368
+ async updateOne(collectionName, selector, modifier) {
369
+ const storage = this.storageAdapters.get(collectionName);
370
+ if (!storage)
371
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
372
+ const items = await this.executeQuery(collectionName, selector, { limit: 1 });
373
+ const [item] = items;
374
+ const { $setOnInsert, ...rest } = modifier;
375
+ if (item == null)
376
+ return [];
377
+ const modified = (0, modify_1.default)((0, deepClone_1.default)(item), rest);
378
+ if (item.id !== modified.id) {
379
+ const existing = await storage.readIds([modified.id]);
380
+ if (existing.length > 0)
381
+ throw new Error(`Item with id ${String(modified.id)} already exists`);
382
+ }
383
+ await storage.replace([modified]);
384
+ await this.checkQueryUpdates(collectionName, [item, modified]);
385
+ return [modified];
386
+ }
387
+ async updateMany(collectionName, selector, modifier) {
388
+ const storage = this.storageAdapters.get(collectionName);
389
+ if (!storage)
390
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
391
+ const items = await this.executeQuery(collectionName, selector);
392
+ if (items.length === 0)
393
+ return [];
394
+ const { $setOnInsert, ...rest } = modifier;
395
+ const changed = await Promise.all(items.map(async (item) => {
396
+ const modified = (0, modify_1.default)((0, deepClone_1.default)(item), rest);
397
+ if (item.id !== modified.id) {
398
+ const existing = await storage.readIds([modified.id]);
399
+ if (existing.length > 0)
400
+ throw new Error(`Item with id ${String(modified.id)} already exists`);
401
+ }
402
+ return modified;
403
+ }));
404
+ await storage.replace(changed);
405
+ await this.checkQueryUpdates(collectionName, [...items, ...changed]);
406
+ return changed;
407
+ }
408
+ async replaceOne(collectionName, selector, replacement) {
409
+ const storage = this.storageAdapters.get(collectionName);
410
+ if (!storage)
411
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
412
+ const items = await this.executeQuery(collectionName, selector, { limit: 1 });
413
+ const [item] = items;
414
+ if (item == null)
415
+ return [];
416
+ const modified = { ...replacement, id: replacement.id ?? item.id };
417
+ if (item.id !== modified.id) {
418
+ const existing = await storage.readIds([modified.id]);
419
+ if (existing.length > 0)
420
+ throw new Error(`Item with id ${String(modified.id)} already exists`);
421
+ }
422
+ await storage.replace([modified]);
423
+ await this.checkQueryUpdates(collectionName, [item, modified]);
424
+ return [modified];
425
+ }
426
+ async removeOne(collectionName, selector) {
427
+ const storage = this.storageAdapters.get(collectionName);
428
+ if (!storage)
429
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
430
+ const items = await this.executeQuery(collectionName, selector, { limit: 1 });
431
+ const [item] = items;
432
+ if (item == null)
433
+ return [];
434
+ await storage.remove([item]);
435
+ await this.checkQueryUpdates(collectionName, [item]);
436
+ return [item];
437
+ }
438
+ async removeMany(collectionName, selector) {
439
+ const storage = this.storageAdapters.get(collectionName);
440
+ if (!storage)
441
+ throw new Error(`No persistence adapter for collection ${collectionName}`);
442
+ const items = await this.executeQuery(collectionName, selector);
443
+ if (items.length === 0)
444
+ return [];
445
+ await storage.remove(items);
446
+ await this.checkQueryUpdates(collectionName, items);
447
+ return items;
448
+ }
449
+ }
450
+ exports.default = AsyncDataAdapter;
@@ -0,0 +1,112 @@
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
+ import type Selector from './types/Selector';
7
+ /**
8
+ * AutoFetchDataAdapterOptions
9
+ *
10
+ * Merges the core options required to talk to a per-collection StorageAdapter with
11
+ * the auto-fetch behavior inspired by AutoFetchCollection.
12
+ */
13
+ export interface AutoFetchDataAdapterOptions {
14
+ /** Factory to obtain a StorageAdapter per collection name */
15
+ storage?: (name: string) => StorageAdapter<any, any>;
16
+ /** Optional logical id (handy if you run multiple adapters side-by-side) */
17
+ id?: string;
18
+ /** Optional error hook */
19
+ onError?: (error: Error) => void;
20
+ /**
21
+ * Fetch hook: given a selector, retrieve items from a remote source.
22
+ * Must resolve to an object with an `items` array. Items MUST include an `id`.
23
+ */
24
+ fetchQueryItems: (collectionName: string, selector: Selector<BaseItem>) => Promise<BaseItem[] | undefined>;
25
+ /**
26
+ * Optional: called once at adapter construction to subscribe to remote changes.
27
+ * When invoked, call the provided callback whenever the remote source changed
28
+ * and all active queries should be re-fetched.
29
+ */
30
+ registerRemoteChange?: (onChange: () => Promise<void>) => Promise<void>;
31
+ /**
32
+ * Merge strategy for ingesting freshly fetched items with existing ones.
33
+ * Default is shallow spread (right wins).
34
+ */
35
+ mergeItems?: <T extends BaseItem<any>>(a: T, b: T) => T;
36
+ /**
37
+ * Delay (ms) before purging auto-fetched items for a query after the query
38
+ * becomes inactive. Set to 0 to purge immediately. Default: 10s.
39
+ */
40
+ purgeDelay?: number;
41
+ }
42
+ /**
43
+ * AutoFetchDataAdapter
44
+ *
45
+ * A DataAdapter that:
46
+ * - Mirrors the CollectionBackend surface (CRUD + query registry + lifecycle)
47
+ * - Executes queries against a provided StorageAdapter (local cache)
48
+ * - On first registration of a selector, auto-fetches from a remote source and
49
+ * ingests the result into storage (upsert), then pushes query result updates
50
+ * - Optionally purges auto-fetched items for a selector once no observers remain
51
+ * - Can subscribe to remote change notifications to re-fetch active selectors
52
+ *
53
+ * IMPORTANT: Purging only ever deletes items that were introduced via the
54
+ * auto-fetch path and are no longer referenced by any active selector. Items
55
+ * inserted through CRUD calls are never purged.
56
+ */
57
+ export default class AutoFetchDataAdapter implements DataAdapter {
58
+ private options;
59
+ private id;
60
+ private onError;
61
+ private fetchQueryItems;
62
+ private mergeItems;
63
+ private purgeDelay;
64
+ private storageAdapters;
65
+ private storageAdapterReady;
66
+ private collectionIndices;
67
+ private queries;
68
+ private activeObservers;
69
+ private observerTimeouts;
70
+ private selectorIds;
71
+ private idRefCounts;
72
+ private autoloadIds;
73
+ constructor(options: AutoFetchDataAdapterOptions);
74
+ createCollectionBackend<T extends BaseItem<I>, I = any, E extends BaseItem = T, U = E>(collection: Collection<T, I, E, U>, indices: string[]): CollectionBackend<T, I>;
75
+ private forceRefetchAll;
76
+ private fetchAndIngest;
77
+ private purgeSelector;
78
+ private setupStorage;
79
+ private ensureStorageAdapter;
80
+ private publishForSelector;
81
+ private publishState;
82
+ private publishResult;
83
+ private fulfillQuery;
84
+ private getIndexInfo;
85
+ private queryItems;
86
+ private executeQuery;
87
+ private checkQueryUpdates;
88
+ private insert;
89
+ private updateOne;
90
+ private updateMany;
91
+ private replaceOne;
92
+ private removeOne;
93
+ private removeMany;
94
+ private upsertMerged;
95
+ }
96
+ /**
97
+ * Usage (example):
98
+ *
99
+ * const adapter = new AutoFetchDataAdapter({
100
+ * storage: (name) => new IndexedDBStorage(name),
101
+ * fetchQueryItems: async (collectionName, selector) => {
102
+ * const res = await fetch(`/api/${collectionName}?q=${encodeURIComponent(JSON.stringify(selector||{}))}`)
103
+ * const items = await res.json()
104
+ * return { items }
105
+ * },
106
+ * registerRemoteChange: (onChange) => subscribeToWS(onChange),
107
+ * mergeItems: (a, b) => ({ ...a, ...b }),
108
+ * purgeDelay: 10_000,
109
+ * })
110
+ *
111
+ * const backend = adapter.createCollectionBackend(myCollection, ['status', 'projectId'])
112
+ */