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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/dist/.vite/manifest.json +118 -84
  2. package/dist/AsyncDataAdapter.d.ts +1 -1
  3. package/dist/index.cjs.js +33 -34
  4. package/dist/index.mjs +17 -35
  5. package/dist/index10.cjs.js +23 -0
  6. package/dist/index10.mjs +21 -17
  7. package/dist/index11.cjs.js +45 -0
  8. package/dist/index11.mjs +44 -15
  9. package/dist/index12.cjs.js +22 -0
  10. package/dist/index12.mjs +21 -47
  11. package/dist/index13.cjs.js +45 -0
  12. package/dist/index13.mjs +44 -365
  13. package/dist/index14.cjs.js +86 -0
  14. package/dist/index14.mjs +85 -416
  15. package/dist/index15.cjs.js +15 -0
  16. package/dist/index15.mjs +14 -206
  17. package/dist/index16.cjs.js +136 -0
  18. package/dist/index16.mjs +135 -388
  19. package/dist/index17.cjs.js +47 -0
  20. package/dist/index17.mjs +45 -578
  21. package/dist/index18.cjs.js +15 -0
  22. package/dist/index18.mjs +14 -157
  23. package/dist/index19.cjs.js +23 -0
  24. package/dist/index19.mjs +22 -26
  25. package/dist/index2.cjs.js +33 -0
  26. package/dist/index2.mjs +32 -258
  27. package/dist/index20.cjs.js +37 -0
  28. package/dist/index20.mjs +36 -41
  29. package/dist/index21.cjs.js +35 -0
  30. package/dist/index21.mjs +34 -16
  31. package/dist/index22.cjs.js +25 -0
  32. package/dist/index22.mjs +24 -104
  33. package/dist/index23.cjs.js +19 -0
  34. package/dist/index23.mjs +18 -128
  35. package/dist/index24.cjs.js +342 -0
  36. package/dist/index24.mjs +340 -6
  37. package/dist/index25.cjs.js +519 -0
  38. package/dist/index25.mjs +518 -27
  39. package/dist/index26.cjs.js +11 -0
  40. package/dist/index26.mjs +10 -10
  41. package/dist/index27.cjs.js +11 -0
  42. package/dist/index27.mjs +10 -29
  43. package/dist/index28.cjs.js +90 -0
  44. package/dist/index28.mjs +88 -46
  45. package/dist/index29.cjs.js +370 -0
  46. package/dist/index29.mjs +369 -8
  47. package/dist/index3.cjs.js +19 -0
  48. package/dist/index3.mjs +18 -539
  49. package/dist/index30.cjs.js +72 -0
  50. package/dist/index30.mjs +71 -9
  51. package/dist/index31.cjs.js +191 -0
  52. package/dist/index31.mjs +190 -7
  53. package/dist/index32.cjs.js +21 -0
  54. package/dist/index32.mjs +20 -42
  55. package/dist/index33.cjs.js +336 -0
  56. package/dist/index33.mjs +335 -29
  57. package/dist/index34.cjs.js +539 -0
  58. package/dist/index34.mjs +537 -4
  59. package/dist/index4.cjs.js +150 -0
  60. package/dist/index4.mjs +149 -5
  61. package/dist/index5.cjs.js +254 -0
  62. package/dist/index5.mjs +252 -4
  63. package/dist/index6.cjs.js +125 -0
  64. package/dist/index6.mjs +124 -29
  65. package/dist/index7.cjs.js +33 -0
  66. package/dist/index7.mjs +32 -12
  67. package/dist/index8.cjs.js +12 -0
  68. package/dist/index8.mjs +10 -4
  69. package/dist/index9.cjs.js +11 -0
  70. package/dist/index9.mjs +10 -133
  71. package/package.json +1 -1
  72. package/dist/index.cjs10.js +0 -18
  73. package/dist/index.cjs11.js +0 -15
  74. package/dist/index.cjs12.js +0 -48
  75. package/dist/index.cjs13.js +0 -365
  76. package/dist/index.cjs14.js +0 -416
  77. package/dist/index.cjs15.js +0 -206
  78. package/dist/index.cjs16.js +0 -388
  79. package/dist/index.cjs17.js +0 -579
  80. package/dist/index.cjs18.js +0 -157
  81. package/dist/index.cjs19.js +0 -26
  82. package/dist/index.cjs2.js +0 -259
  83. package/dist/index.cjs20.js +0 -42
  84. package/dist/index.cjs21.js +0 -16
  85. package/dist/index.cjs22.js +0 -104
  86. package/dist/index.cjs23.js +0 -129
  87. package/dist/index.cjs24.js +0 -7
  88. package/dist/index.cjs25.js +0 -27
  89. package/dist/index.cjs26.js +0 -10
  90. package/dist/index.cjs27.js +0 -29
  91. package/dist/index.cjs28.js +0 -46
  92. package/dist/index.cjs29.js +0 -8
  93. package/dist/index.cjs3.js +0 -540
  94. package/dist/index.cjs30.js +0 -9
  95. package/dist/index.cjs31.js +0 -7
  96. package/dist/index.cjs32.js +0 -42
  97. package/dist/index.cjs33.js +0 -29
  98. package/dist/index.cjs34.js +0 -5
  99. package/dist/index.cjs4.js +0 -5
  100. package/dist/index.cjs5.js +0 -5
  101. package/dist/index.cjs6.js +0 -29
  102. package/dist/index.cjs7.js +0 -12
  103. package/dist/index.cjs8.js +0 -5
  104. package/dist/index.cjs9.js +0 -133
package/dist/index34.mjs CHANGED
@@ -1,6 +1,539 @@
1
- function createIndexProvider(definition) {
2
- return definition;
1
+ import isEqual from "./index2.mjs";
2
+ import getMatchingKeys from "./index13.mjs";
3
+ import getIndexInfo from "./index16.mjs";
4
+ import deepClone from "./index17.mjs";
5
+ import match from "./index18.mjs";
6
+ import modify from "./index19.mjs";
7
+ import project from "./index21.mjs";
8
+ import queryId from "./index22.mjs";
9
+ import sortItems from "./index23.mjs";
10
+ //#region src/AutoFetchDataAdapter.ts
11
+ /**
12
+ * Default merge strategy: shallow spread (right wins)
13
+ * @param a first item
14
+ * @param b second item
15
+ * @returns merged item
16
+ */
17
+ function defaultMergeItems(a, b) {
18
+ return {
19
+ ...a,
20
+ ...b
21
+ };
3
22
  }
4
- export {
5
- createIndexProvider as default
23
+ /**
24
+ * Generates a stable key for a selector
25
+ * @param selector - the selector
26
+ * @returns the key
27
+ */
28
+ function selectorId(selector) {
29
+ return JSON.stringify(selector ?? {});
30
+ }
31
+ /**
32
+ * AutoFetchDataAdapter
33
+ *
34
+ * A DataAdapter that:
35
+ * - Mirrors the CollectionBackend surface (CRUD + query registry + lifecycle)
36
+ * - Executes queries against a provided StorageAdapter (local cache)
37
+ * - On first registration of a selector, auto-fetches from a remote source and
38
+ * ingests the result into storage (upsert), then pushes query result updates
39
+ * - Optionally purges auto-fetched items for a selector once no observers remain
40
+ * - Can subscribe to remote change notifications to re-fetch active selectors
41
+ *
42
+ * IMPORTANT: Purging only ever deletes items that were introduced via the
43
+ * auto-fetch path and are no longer referenced by any active selector. Items
44
+ * inserted through CRUD calls are never purged.
45
+ */
46
+ var AutoFetchDataAdapter = class {
47
+ options;
48
+ id;
49
+ onError;
50
+ fetchQueryItems;
51
+ mergeItems;
52
+ purgeDelay;
53
+ storageAdapters = /* @__PURE__ */ new Map();
54
+ storageAdapterReady = /* @__PURE__ */ new Map();
55
+ collectionIndices = /* @__PURE__ */ new Map();
56
+ queries = /* @__PURE__ */ new Map();
57
+ activeObservers = /* @__PURE__ */ new Map();
58
+ observerTimeouts = /* @__PURE__ */ new Map();
59
+ selectorIds = /* @__PURE__ */ new Map();
60
+ idRefCounts = /* @__PURE__ */ new Map();
61
+ autoloadIds = /* @__PURE__ */ new Map();
62
+ constructor(options) {
63
+ this.options = options;
64
+ this.id = options.id || "autofetch-data-adapter";
65
+ this.onError = options.onError ?? ((error) => {
66
+ console.error(error);
67
+ });
68
+ this.fetchQueryItems = options.fetchQueryItems;
69
+ this.mergeItems = options.mergeItems ?? defaultMergeItems;
70
+ this.purgeDelay = options.purgeDelay ?? 1e4;
71
+ if (options.registerRemoteChange) options.registerRemoteChange(async () => {
72
+ await this.forceRefetchAll();
73
+ });
74
+ }
75
+ createCollectionBackend(collection, indices) {
76
+ this.collectionIndices.set(collection.name, indices);
77
+ this.queries.set(collection.name, /* @__PURE__ */ new Map());
78
+ this.ensureStorageAdapter(collection.name);
79
+ this.activeObservers.set(collection.name, /* @__PURE__ */ new Map());
80
+ this.observerTimeouts.set(collection.name, /* @__PURE__ */ new Map());
81
+ this.selectorIds.set(collection.name, /* @__PURE__ */ new Map());
82
+ this.idRefCounts.set(collection.name, /* @__PURE__ */ new Map());
83
+ this.autoloadIds.set(collection.name, /* @__PURE__ */ new Set());
84
+ const ready = this.setupStorage(collection.name, indices);
85
+ this.storageAdapterReady.set(collection.name, ready);
86
+ const registerQuery = (selector, options) => {
87
+ const qid = queryId(selector, options);
88
+ const registry = this.queries.get(collection.name);
89
+ if (!registry) throw new Error(`Collection ${collection.name} not initialized!`);
90
+ registry.set(qid, {
91
+ selector,
92
+ options,
93
+ items: [],
94
+ listeners: /* @__PURE__ */ new Set(),
95
+ ...registry.get(qid),
96
+ state: "active",
97
+ error: null
98
+ });
99
+ const key = selectorId(selector);
100
+ const perColObservers = this.activeObservers.get(collection.name);
101
+ const current = perColObservers?.get(key)?.count ?? 0;
102
+ perColObservers?.set(key, {
103
+ selector,
104
+ count: current + 1
105
+ });
106
+ const t = this.observerTimeouts.get(collection.name)?.get(key);
107
+ if (t) clearTimeout(t);
108
+ if (current === 0) this.fetchAndIngest(collection.name, selector).catch(this.onError);
109
+ this.fulfillQuery(collection.name, selector, options).catch(this.onError);
110
+ };
111
+ const unregisterQuery = (selector, options) => {
112
+ const qid = queryId(selector, options);
113
+ this.queries.get(collection.name)?.delete(qid);
114
+ const key = selectorId(selector);
115
+ const perColObservers = this.activeObservers.get(collection.name);
116
+ const current = perColObservers?.get(key)?.count ?? 0;
117
+ const remaining = Math.max(0, current - 1);
118
+ if (remaining > 0) {
119
+ perColObservers?.set(key, {
120
+ selector,
121
+ count: remaining
122
+ });
123
+ return;
124
+ }
125
+ const doPurge = () => {
126
+ perColObservers?.delete(key);
127
+ this.purgeSelector(collection.name, selector).catch(this.onError);
128
+ };
129
+ if (this.purgeDelay === 0) doPurge();
130
+ else {
131
+ const timeouts = this.observerTimeouts.get(collection.name);
132
+ const t = timeouts?.get(key);
133
+ if (t) clearTimeout(t);
134
+ timeouts?.set(key, setTimeout(doPurge, this.purgeDelay));
135
+ }
136
+ };
137
+ const getQueryState = (selector, options) => {
138
+ return (this.queries.get(collection.name)?.get(queryId(selector, options)))?.state ?? "active";
139
+ };
140
+ const getQueryError = (selector, options) => {
141
+ return (this.queries.get(collection.name)?.get(queryId(selector, options)))?.error ?? null;
142
+ };
143
+ const getQueryResult = (selector, options) => {
144
+ return (this.queries.get(collection.name)?.get(queryId(selector, options)))?.items ?? [];
145
+ };
146
+ const onQueryStateChange = (selector, options, callback) => {
147
+ const qid = queryId(selector, options);
148
+ const registry = this.queries.get(collection.name);
149
+ if (!registry) throw new Error(`Collection ${collection.name} not initialized!`);
150
+ if (!registry.has(qid)) registry.set(qid, {
151
+ selector,
152
+ options,
153
+ state: "active",
154
+ error: null,
155
+ items: [],
156
+ listeners: /* @__PURE__ */ new Set()
157
+ });
158
+ registry.get(qid)?.listeners.add(callback);
159
+ return () => {
160
+ registry.get(qid)?.listeners.delete(callback);
161
+ };
162
+ };
163
+ return {
164
+ insert: async (item) => {
165
+ await ready;
166
+ return await this.insert(collection.name, item);
167
+ },
168
+ updateOne: async (selector, modifier) => {
169
+ await ready;
170
+ return this.updateOne(collection.name, selector, modifier);
171
+ },
172
+ updateMany: async (selector, modifier) => {
173
+ await ready;
174
+ return this.updateMany(collection.name, selector, modifier);
175
+ },
176
+ replaceOne: async (selector, replacement) => {
177
+ await ready;
178
+ return this.replaceOne(collection.name, selector, replacement);
179
+ },
180
+ removeOne: async (selector) => {
181
+ await ready;
182
+ return this.removeOne(collection.name, selector);
183
+ },
184
+ removeMany: async (selector) => {
185
+ await ready;
186
+ return this.removeMany(collection.name, selector);
187
+ },
188
+ registerQuery,
189
+ unregisterQuery,
190
+ getQueryState,
191
+ getQueryError,
192
+ getQueryResult,
193
+ onQueryStateChange,
194
+ executeQuery: async (selector, options) => {
195
+ await ready;
196
+ registerQuery(selector, options);
197
+ await new Promise((resolve) => {
198
+ let stop = () => {};
199
+ stop = onQueryStateChange(selector, options, (state) => {
200
+ if (state === "active") return;
201
+ resolve();
202
+ stop();
203
+ });
204
+ });
205
+ const result = getQueryResult(selector, options);
206
+ unregisterQuery(selector, options);
207
+ return result;
208
+ },
209
+ dispose: async () => {
210
+ this.storageAdapters.delete(collection.name);
211
+ this.queries.delete(collection.name);
212
+ this.collectionIndices.delete(collection.name);
213
+ this.storageAdapterReady.delete(collection.name);
214
+ this.activeObservers.delete(collection.name);
215
+ this.observerTimeouts.delete(collection.name);
216
+ this.selectorIds.delete(collection.name);
217
+ this.idRefCounts.delete(collection.name);
218
+ this.autoloadIds.delete(collection.name);
219
+ },
220
+ isReady: async () => {
221
+ await ready;
222
+ }
223
+ };
224
+ }
225
+ async forceRefetchAll() {
226
+ const tasks = [];
227
+ for (const [collectionName, observers] of this.activeObservers.entries()) for (const { selector, count } of observers.values()) if (count > 0) tasks.push(this.fetchAndIngest(collectionName, selector));
228
+ await Promise.all(tasks);
229
+ }
230
+ async fetchAndIngest(collectionName, selector) {
231
+ this.publishForSelector(collectionName, selector, "active", null);
232
+ try {
233
+ const items = await this.fetchQueryItems(collectionName, selector);
234
+ if (!items || !Array.isArray(items)) throw new Error("AutoFetchDataAdapter: fetchQueryItems must resolve to { items: T[] }");
235
+ const ids = items.map((i) => i.id);
236
+ const selectorKey = selectorId(selector);
237
+ const selMap = this.selectorIds.get(collectionName);
238
+ const previous = selMap?.get(selectorKey) ?? /* @__PURE__ */ new Set();
239
+ ids.forEach((id) => previous.add(id));
240
+ selMap?.set(selectorKey, previous);
241
+ await this.upsertMerged(collectionName, items);
242
+ await this.checkQueryUpdates(collectionName, items);
243
+ } catch (error) {
244
+ this.publishForSelector(collectionName, selector, "error", error);
245
+ this.onError(error);
246
+ }
247
+ }
248
+ async purgeSelector(collectionName, selector) {
249
+ const selectorKey = selectorId(selector);
250
+ const selMap = this.selectorIds.get(collectionName);
251
+ const ids = selMap?.get(selectorKey);
252
+ selMap?.delete(selectorKey);
253
+ if (!ids || ids.size === 0) return;
254
+ const referenceMap = this.idRefCounts.get(collectionName);
255
+ const autoload = this.autoloadIds.get(collectionName);
256
+ const toRemove = [];
257
+ for (const id of ids) {
258
+ const current = referenceMap?.get(id) ?? 0;
259
+ const next = Math.max(0, current - 1);
260
+ if (next === 0) {
261
+ referenceMap?.delete(id);
262
+ if (autoload?.has(id)) toRemove.push(id);
263
+ } else referenceMap?.set(id, next);
264
+ }
265
+ if (toRemove.length === 0) return;
266
+ const storage = this.storageAdapters.get(collectionName);
267
+ if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
268
+ const items = await storage.readIds(toRemove);
269
+ if (items.length > 0) {
270
+ await storage.remove(items);
271
+ await this.checkQueryUpdates(collectionName, items);
272
+ }
273
+ toRemove.forEach((id) => autoload?.delete(id));
274
+ }
275
+ async setupStorage(collectionName, indices) {
276
+ const storage = this.storageAdapters.get(collectionName);
277
+ if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
278
+ await storage.setup();
279
+ await Promise.all(indices.map((field) => storage.createIndex(field)));
280
+ }
281
+ ensureStorageAdapter(name) {
282
+ if (this.storageAdapters.has(name)) return;
283
+ const adapter = this.options.storage && this.options.storage(name);
284
+ if (!adapter) return;
285
+ this.storageAdapters.set(name, adapter);
286
+ }
287
+ publishForSelector(collectionName, selector, state, error) {
288
+ const registry = this.queries.get(collectionName);
289
+ if (!registry) return;
290
+ for (const query of registry.values()) {
291
+ if (!isEqual(query.selector, selector)) continue;
292
+ this.publishState(collectionName, queryId(query.selector, query.options), state, error);
293
+ }
294
+ }
295
+ publishState(collectionName, qid, state, error) {
296
+ const query = this.queries.get(collectionName)?.get(qid);
297
+ if (!query) return;
298
+ query.state = state;
299
+ query.error = error;
300
+ for (const callback of query.listeners) try {
301
+ callback(state);
302
+ } catch (error_) {
303
+ this.onError(error_);
304
+ }
305
+ }
306
+ publishResult(collectionName, qid, items) {
307
+ const query = this.queries.get(collectionName)?.get(qid);
308
+ if (!query) return;
309
+ query.items = items;
310
+ this.queries.get(collectionName)?.set(qid, query);
311
+ }
312
+ async fulfillQuery(collectionName, selector, options) {
313
+ const qid = queryId(selector, options);
314
+ const registry = this.queries.get(collectionName);
315
+ if (!registry) throw new Error(`Collection ${collectionName} not initialized!`);
316
+ if (!registry.get(qid)) return;
317
+ this.publishState(collectionName, qid, "active", null);
318
+ try {
319
+ const items = await this.executeQuery(collectionName, selector, options);
320
+ this.publishResult(collectionName, qid, items);
321
+ this.publishState(collectionName, qid, "complete", null);
322
+ } catch (error) {
323
+ this.publishState(collectionName, qid, "error", error);
324
+ }
325
+ }
326
+ async getIndexInfo(collectionName, selector) {
327
+ const storage = this.storageAdapters.get(collectionName);
328
+ if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
329
+ if (selector != null && Object.keys(selector).length === 1 && "id" in selector && typeof selector.id !== "object") return {
330
+ matched: true,
331
+ ids: [selector.id],
332
+ optimizedSelector: {}
333
+ };
334
+ if (selector == null) return {
335
+ matched: false,
336
+ ids: [],
337
+ optimizedSelector: {}
338
+ };
339
+ return getIndexInfo((this.collectionIndices.get(collectionName) ?? []).map((field) => async (flatSelector) => {
340
+ if (!Object.hasOwnProperty.call(flatSelector, field)) return { matched: false };
341
+ const index = await storage.readIndex(field);
342
+ const fieldSelector = flatSelector[field];
343
+ const filtersForNull = fieldSelector == null || fieldSelector.$exists === false;
344
+ const keys = filtersForNull ? {
345
+ include: null,
346
+ exclude: [...index.keys()].filter((key) => key != null)
347
+ } : getMatchingKeys(field, flatSelector);
348
+ if (keys.include == null && keys.exclude == null) return { matched: false };
349
+ let includedIds = [];
350
+ if (keys.include == null) for (const set of index.values()) for (const pos of set) includedIds.push(pos);
351
+ else for (const key of keys.include) {
352
+ const idSet = index.get(key);
353
+ if (idSet) for (const id of idSet) includedIds.push(id);
354
+ }
355
+ if (keys.exclude != null) {
356
+ const excludeIds = /* @__PURE__ */ new Set();
357
+ for (const key of keys.exclude) {
358
+ const idSet = index.get(key);
359
+ if (idSet) for (const id of idSet) excludeIds.add(id);
360
+ }
361
+ includedIds = includedIds.filter((pos) => !excludeIds.has(pos));
362
+ }
363
+ return {
364
+ matched: true,
365
+ ids: includedIds,
366
+ fields: [field],
367
+ keepSelector: filtersForNull
368
+ };
369
+ }), selector);
370
+ }
371
+ async queryItems(collectionName, selector) {
372
+ const storage = this.storageAdapters.get(collectionName);
373
+ if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
374
+ const index = await this.getIndexInfo(collectionName, selector);
375
+ const matchItems = (item) => {
376
+ if (index.optimizedSelector == null) return true;
377
+ if (Object.keys(index.optimizedSelector).length <= 0) return true;
378
+ return match(item, index.optimizedSelector);
379
+ };
380
+ if (index.matched) {
381
+ const items = await storage.readIds(index.ids);
382
+ if (isEqual(index.optimizedSelector, {})) return items;
383
+ return items.filter(matchItems);
384
+ } else {
385
+ const allItems = await storage.readAll();
386
+ if (isEqual(selector, {})) return allItems;
387
+ return allItems.filter(matchItems);
388
+ }
389
+ }
390
+ async executeQuery(collectionName, selector, options) {
391
+ const items = await this.queryItems(collectionName, selector || {});
392
+ const { sort, skip, limit, fields } = options || {};
393
+ const sorted = sort ? sortItems(items, sort) : items;
394
+ const skipped = skip ? sorted.slice(skip) : sorted;
395
+ const limited = limit ? skipped.slice(0, limit) : skipped;
396
+ const idExcluded = fields && fields.id === 0;
397
+ return limited.map((item) => {
398
+ if (!fields) return item;
399
+ return {
400
+ ...idExcluded ? {} : { id: item.id },
401
+ ...project(item, fields)
402
+ };
403
+ });
404
+ }
405
+ async checkQueryUpdates(collectionName, changedItems) {
406
+ const registry = this.queries.get(collectionName);
407
+ if (!registry) throw new Error(`Collection ${collectionName} not initialized!`);
408
+ if (registry.size === 0) return;
409
+ const affected = [...registry.values()].filter(({ selector }) => changedItems.some((item) => match(item, selector)));
410
+ if (affected.length === 0) return;
411
+ for (const { selector, options } of affected) {
412
+ const qid = queryId(selector, options);
413
+ this.publishState(collectionName, qid, "active", null);
414
+ }
415
+ await Promise.all(affected.map(async ({ selector, options }) => {
416
+ const qid = queryId(selector, options);
417
+ try {
418
+ const items = await this.executeQuery(collectionName, selector, options);
419
+ this.publishResult(collectionName, qid, items);
420
+ this.publishState(collectionName, qid, "complete", null);
421
+ } catch (error) {
422
+ this.publishState(collectionName, qid, "error", error);
423
+ }
424
+ }));
425
+ }
426
+ async insert(collectionName, newItem) {
427
+ const storage = this.storageAdapters.get(collectionName);
428
+ if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
429
+ if ((await this.executeQuery(collectionName, { id: newItem.id }, { limit: 1 })).length > 0) throw new Error(`Item with id ${String(newItem.id)} already exists`);
430
+ await storage.insert([newItem]);
431
+ await this.checkQueryUpdates(collectionName, [newItem]);
432
+ return newItem;
433
+ }
434
+ async updateOne(collectionName, selector, modifier) {
435
+ const storage = this.storageAdapters.get(collectionName);
436
+ if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
437
+ const [item] = await this.executeQuery(collectionName, selector, { limit: 1 });
438
+ const { $setOnInsert, ...rest } = modifier;
439
+ if (item == null) return [];
440
+ const modified = modify(deepClone(item), rest);
441
+ if (item.id !== modified.id) {
442
+ if ((await this.executeQuery(collectionName, { id: modified.id }, { limit: 1 })).length > 0) throw new Error(`Item with id ${String(modified.id)} already exists`);
443
+ }
444
+ await storage.replace([modified]);
445
+ await this.checkQueryUpdates(collectionName, [item, modified]);
446
+ return [modified];
447
+ }
448
+ async updateMany(collectionName, selector, modifier) {
449
+ const storage = this.storageAdapters.get(collectionName);
450
+ if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
451
+ const items = await this.executeQuery(collectionName, selector);
452
+ if (items.length === 0) return [];
453
+ const { $setOnInsert, ...rest } = modifier;
454
+ const changed = await Promise.all(items.map(async (item) => {
455
+ const modified = modify(deepClone(item), rest);
456
+ if (item.id !== modified.id) {
457
+ if ((await this.executeQuery(collectionName, { id: modified.id }, { limit: 1 })).length > 0) throw new Error(`Item with id ${String(modified.id)} already exists`);
458
+ }
459
+ return modified;
460
+ }));
461
+ await storage.replace(changed);
462
+ await this.checkQueryUpdates(collectionName, [...items, ...changed]);
463
+ return changed;
464
+ }
465
+ async replaceOne(collectionName, selector, replacement) {
466
+ const storage = this.storageAdapters.get(collectionName);
467
+ if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
468
+ const [item] = await this.executeQuery(collectionName, selector, { limit: 1 });
469
+ if (item == null) return [];
470
+ const modified = {
471
+ ...replacement,
472
+ id: replacement.id ?? item.id
473
+ };
474
+ if (item.id !== modified.id) {
475
+ if ((await this.executeQuery(collectionName, { id: modified.id }, { limit: 1 })).length > 0) throw new Error(`Item with id ${String(modified.id)} already exists`);
476
+ }
477
+ await storage.replace([modified]);
478
+ await this.checkQueryUpdates(collectionName, [item, modified]);
479
+ return [modified];
480
+ }
481
+ async removeOne(collectionName, selector) {
482
+ const storage = this.storageAdapters.get(collectionName);
483
+ if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
484
+ const [item] = await this.executeQuery(collectionName, selector, { limit: 1 });
485
+ if (item == null) return [];
486
+ await storage.remove([item]);
487
+ await this.checkQueryUpdates(collectionName, [item]);
488
+ return [item];
489
+ }
490
+ async removeMany(collectionName, selector) {
491
+ const storage = this.storageAdapters.get(collectionName);
492
+ if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
493
+ const items = await this.executeQuery(collectionName, selector);
494
+ if (items.length === 0) return [];
495
+ await storage.remove(items);
496
+ await this.checkQueryUpdates(collectionName, items);
497
+ return items;
498
+ }
499
+ async upsertMerged(collectionName, incoming) {
500
+ if (incoming.length === 0) return;
501
+ const storage = this.storageAdapters.get(collectionName);
502
+ if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
503
+ const ids = incoming.map((i) => i.id);
504
+ const existing = await storage.readIds(ids);
505
+ const existingById = new Map(existing.map((it) => [it.id, it]));
506
+ const toInsert = [];
507
+ const toReplace = [];
508
+ const referenceMap = this.idRefCounts.get(collectionName);
509
+ const autoload = this.autoloadIds.get(collectionName);
510
+ for (const item of incoming) {
511
+ const previous = existingById.get(item.id);
512
+ if (previous) toReplace.push(this.mergeItems(previous, item));
513
+ else toInsert.push(item);
514
+ autoload?.add(item.id);
515
+ referenceMap?.set(item.id, (referenceMap?.get(item.id) ?? 0) + 1);
516
+ }
517
+ if (toInsert.length > 0) await storage.insert(toInsert);
518
+ if (toReplace.length > 0) await storage.replace(toReplace);
519
+ }
6
520
  };
521
+ /**
522
+ * Usage (example):
523
+ *
524
+ * const adapter = new AutoFetchDataAdapter({
525
+ * storage: (name) => new IndexedDBStorage(name),
526
+ * fetchQueryItems: async (collectionName, selector) => {
527
+ * const res = await fetch(`/api/${collectionName}?q=${encodeURIComponent(JSON.stringify(selector||{}))}`)
528
+ * const items = await res.json()
529
+ * return { items }
530
+ * },
531
+ * registerRemoteChange: (onChange) => subscribeToWS(onChange),
532
+ * mergeItems: (a, b) => ({ ...a, ...b }),
533
+ * purgeDelay: 10_000,
534
+ * })
535
+ *
536
+ * const backend = adapter.createCollectionBackend(myCollection, ['status', 'projectId'])
537
+ */
538
+ //#endregion
539
+ export { AutoFetchDataAdapter as default };
@@ -0,0 +1,150 @@
1
+ const require_isEqual = require("./index2.cjs.js");
2
+ const require_uniqueBy = require("./index3.cjs.js");
3
+ //#region src/Collection/Observer.ts
4
+ /**
5
+ * Represents an observer that tracks changes in a collection of items and triggers
6
+ * callbacks for various events such as addition, removal, and modification of items.
7
+ * @template T - The type of the items being observed, which must include an `id` field.
8
+ */
9
+ var Observer = class {
10
+ previousItems = [];
11
+ callbacks;
12
+ unbindEvents;
13
+ /**
14
+ * Creates a new instance of the `Observer` class.
15
+ * Sets up event bindings and initializes the callbacks for tracking changes in a collection.
16
+ * @param bindEvents - A function to bind external events to the observer. Must return a cleanup function to unbind those events.
17
+ */
18
+ constructor(bindEvents) {
19
+ this.callbacks = {
20
+ added: [],
21
+ addedBefore: [],
22
+ changed: [],
23
+ changedField: [],
24
+ movedBefore: [],
25
+ removed: []
26
+ };
27
+ this.unbindEvents = bindEvents();
28
+ }
29
+ call(event, ...args) {
30
+ this.callbacks[event].forEach(({ callback, options }) => {
31
+ if (!options.skipInitial || !options.isInitial) callback(...args);
32
+ });
33
+ }
34
+ hasCallbacks(events) {
35
+ return events.some((event) => this.callbacks[event].length > 0);
36
+ }
37
+ /**
38
+ * Determines if the observer has no active callbacks registered for any events.
39
+ * @returns A boolean indicating whether the observer is empty (i.e., no callbacks are registered).
40
+ */
41
+ isEmpty() {
42
+ return !this.hasCallbacks([
43
+ "added",
44
+ "addedBefore",
45
+ "changed",
46
+ "changedField",
47
+ "movedBefore",
48
+ "removed"
49
+ ]);
50
+ }
51
+ /**
52
+ * Compares the previous state of items with the new state and triggers the appropriate callbacks
53
+ * for events such as added, removed, changed, or moved items.
54
+ * @param getItems - A function that returns a promise resolving to the new items or the items themselves.
55
+ */
56
+ runChecks(getItems) {
57
+ const result = getItems();
58
+ if (result instanceof Promise) result.then((newItems) => this.checkItems(newItems)).catch((error) => {
59
+ console.error("Error while asynchronously querying items", error);
60
+ });
61
+ else this.checkItems(result);
62
+ }
63
+ checkItems(newItems) {
64
+ const oldItemsMap = new Map(this.previousItems.map((item, index) => [item.id, {
65
+ item,
66
+ index,
67
+ beforeItem: this.previousItems[index + 1] || null
68
+ }]));
69
+ const newItemsMap = new Map(newItems.map((item, index) => [item.id, {
70
+ item,
71
+ index,
72
+ beforeItem: newItems[index + 1] || null
73
+ }]));
74
+ if (this.hasCallbacks([
75
+ "changed",
76
+ "changedField",
77
+ "movedBefore",
78
+ "removed"
79
+ ])) oldItemsMap.forEach(({ item: oldItem, index, beforeItem: oldBeforeItem }) => {
80
+ const newItem = newItemsMap.get(oldItem.id);
81
+ if (newItem) {
82
+ if (this.hasCallbacks(["changed", "changedField"]) && !require_isEqual.default(newItem.item, oldItem)) {
83
+ this.call("changed", newItem.item);
84
+ if (this.hasCallbacks(["changedField"])) require_uniqueBy.default([...Object.keys(newItem.item), ...Object.keys(oldItem)], (value) => value).forEach((key) => {
85
+ if (require_isEqual.default(newItem.item[key], oldItem[key])) return;
86
+ this.call("changedField", newItem.item, key, oldItem[key], newItem.item[key]);
87
+ });
88
+ }
89
+ if (newItem.index !== index && newItem.beforeItem?.id !== oldBeforeItem?.id) this.call("movedBefore", newItem.item, newItem.beforeItem);
90
+ } else this.call("removed", oldItem);
91
+ });
92
+ if (this.hasCallbacks(["added", "addedBefore"])) newItems.forEach((newItem, index) => {
93
+ if (oldItemsMap.get(newItem.id)) return;
94
+ this.call("added", newItem);
95
+ this.call("addedBefore", newItem, newItems[index + 1] || null);
96
+ });
97
+ this.previousItems = newItems;
98
+ Object.keys(this.callbacks).forEach((key) => {
99
+ const event = key;
100
+ const callbacks = this.callbacks[event];
101
+ this.callbacks[event] = callbacks.map((callback) => ({
102
+ ...callback,
103
+ options: {
104
+ ...callback.options,
105
+ isInitial: false
106
+ }
107
+ }));
108
+ });
109
+ }
110
+ stopped = false;
111
+ /**
112
+ * Stops the observer by unbinding all events and cleaning up resources.
113
+ * Safe to call multiple times - will only unbind once.
114
+ */
115
+ stop() {
116
+ if (this.stopped) return;
117
+ this.stopped = true;
118
+ this.unbindEvents();
119
+ }
120
+ /**
121
+ * Registers callbacks for specific events to observe changes in the collection.
122
+ * @param callbacks - An object containing the callbacks for various events (e.g., 'added', 'removed').
123
+ * @param skipInitial - A boolean indicating whether to skip invoking the callbacks for the initial state of the collection.
124
+ */
125
+ addCallbacks(callbacks, skipInitial = false) {
126
+ Object.keys(callbacks).forEach((key) => {
127
+ const typedKey = key;
128
+ this.callbacks[typedKey].push({
129
+ callback: callbacks[typedKey],
130
+ options: {
131
+ skipInitial,
132
+ isInitial: true
133
+ }
134
+ });
135
+ });
136
+ }
137
+ /**
138
+ * Removes the specified callbacks for specific events, unregistering them from the observer.
139
+ * @param callbacks - An object containing the callbacks to be removed for various events.
140
+ */
141
+ removeCallbacks(callbacks) {
142
+ Object.keys(callbacks).forEach((key) => {
143
+ const typedKey = key;
144
+ const index = this.callbacks[typedKey].findIndex(({ callback }) => callback === callbacks[typedKey]);
145
+ this.callbacks[typedKey].splice(index, 1);
146
+ });
147
+ }
148
+ };
149
+ //#endregion
150
+ exports.default = Observer;