@signaldb/core 2.0.0-beta.3 → 2.0.0-beta.5

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 (54) hide show
  1. package/dist/.vite/manifest.json +24 -18
  2. package/dist/Collection/Observer.d.ts +2 -0
  3. package/dist/Collection/index.d.ts +11 -10
  4. package/dist/Collection/types.d.ts +7 -0
  5. package/dist/DefaultDataAdapter.d.ts +2 -0
  6. package/dist/index.cjs.js +8 -5
  7. package/dist/index.cjs12.js +41 -346
  8. package/dist/index.cjs13.js +308 -362
  9. package/dist/index.cjs14.js +387 -177
  10. package/dist/index.cjs15.js +182 -364
  11. package/dist/index.cjs16.js +287 -478
  12. package/dist/index.cjs17.js +563 -136
  13. package/dist/index.cjs18.js +154 -23
  14. package/dist/index.cjs19.js +23 -39
  15. package/dist/index.cjs2.js +1 -1
  16. package/dist/index.cjs20.js +39 -13
  17. package/dist/index.cjs21.js +14 -102
  18. package/dist/index.cjs22.js +93 -118
  19. package/dist/index.cjs23.js +127 -5
  20. package/dist/index.cjs24.js +5 -25
  21. package/dist/index.cjs25.js +24 -7
  22. package/dist/index.cjs26.js +8 -27
  23. package/dist/index.cjs27.js +25 -42
  24. package/dist/index.cjs28.js +44 -6
  25. package/dist/index.cjs29.js +6 -7
  26. package/dist/index.cjs3.js +9 -26
  27. package/dist/index.cjs34.js +9 -0
  28. package/dist/index.cjs7.js +1 -1
  29. package/dist/index.d.ts +2 -1
  30. package/dist/index.mjs +10 -7
  31. package/dist/index12.mjs +40 -346
  32. package/dist/index13.mjs +308 -362
  33. package/dist/index14.mjs +387 -177
  34. package/dist/index15.mjs +182 -364
  35. package/dist/index16.mjs +287 -478
  36. package/dist/index17.mjs +563 -136
  37. package/dist/index18.mjs +154 -23
  38. package/dist/index19.mjs +23 -38
  39. package/dist/index2.mjs +1 -1
  40. package/dist/index20.mjs +38 -13
  41. package/dist/index21.mjs +14 -102
  42. package/dist/index22.mjs +93 -117
  43. package/dist/index23.mjs +126 -5
  44. package/dist/index24.mjs +5 -25
  45. package/dist/index25.mjs +24 -7
  46. package/dist/index26.mjs +8 -27
  47. package/dist/index27.mjs +25 -42
  48. package/dist/index28.mjs +44 -6
  49. package/dist/index29.mjs +6 -7
  50. package/dist/index3.mjs +9 -26
  51. package/dist/index34.mjs +10 -0
  52. package/dist/index7.mjs +1 -1
  53. package/dist/utils/reactiveOrAsync.d.ts +59 -0
  54. package/package.json +1 -1
package/dist/index13.mjs CHANGED
@@ -1,215 +1,68 @@
1
- import deepClone from "./index19.mjs";
2
- import match from "./index23.mjs";
3
- import modify from "./index7.mjs";
4
- import queryId from "./index20.mjs";
1
+ import createIndex from "./index22.mjs";
2
+ import getIndexInfo from "./index23.mjs";
3
+ import deepClone from "./index20.mjs";
4
+ import EventEmitter from "./index9.mjs";
5
5
  import isEqual from "./index6.mjs";
6
- import getIndexInfo from "./index22.mjs";
7
- import getMatchingKeys from "./index26.mjs";
8
- import sortItems from "./index25.mjs";
9
- import project from "./index24.mjs";
10
- class AsyncDataAdapter {
6
+ import match from "./index24.mjs";
7
+ import modify from "./index7.mjs";
8
+ import project from "./index25.mjs";
9
+ import queryId from "./index21.mjs";
10
+ import serializeValue from "./index11.mjs";
11
+ import sortItems from "./index26.mjs";
12
+ function hasPendingUpdates(pendingUpdates) {
13
+ return pendingUpdates.added.length > 0 || pendingUpdates.modified.length > 0 || pendingUpdates.removed.length > 0;
14
+ }
15
+ class DefaultDataAdapter {
16
+ items = /* @__PURE__ */ new Map();
11
17
  options;
12
- id;
13
- onError;
14
- // Per-collection resources
15
18
  storageAdapters = /* @__PURE__ */ new Map();
16
- storageAdapterReady = /* @__PURE__ */ new Map();
17
- collectionIndices = /* @__PURE__ */ new Map();
18
- // Per-collection query registries
19
- queries = /* @__PURE__ */ new Map();
19
+ collections = /* @__PURE__ */ new Set();
20
+ indices = /* @__PURE__ */ new Map();
21
+ activeQueries = /* @__PURE__ */ new Map();
22
+ queryEmitters = /* @__PURE__ */ new Map();
23
+ queuedQueryUpdates = /* @__PURE__ */ new Map();
24
+ cachedQueryResults = /* @__PURE__ */ new Map();
20
25
  constructor(options) {
21
- this.options = options;
22
- this.id = options.id || "async-data-adapter";
23
- this.onError = options.onError ?? ((error) => {
24
- console.error(error);
25
- });
26
- }
27
- createCollectionBackend(collection, indices) {
28
- this.collectionIndices.set(collection.name, indices);
29
- this.queries.set(collection.name, /* @__PURE__ */ new Map());
30
- this.ensureStorageAdapter(collection.name);
31
- const ready = (async () => {
32
- try {
33
- await this.setupStorage(collection.name, indices);
34
- } catch (error) {
35
- this.onError(error);
36
- throw error;
37
- }
38
- })();
39
- this.storageAdapterReady.set(collection.name, ready);
40
- const registerQuery = (selector, options) => {
41
- const qid = queryId(selector, options);
42
- const registry = this.queries.get(collection.name);
43
- if (!registry)
44
- throw new Error(`Collection ${collection.name} not initialized!`);
45
- registry.set(qid, {
46
- selector,
47
- options,
48
- items: [],
49
- listeners: /* @__PURE__ */ new Set(),
50
- ...registry.get(qid),
51
- state: "active",
52
- error: null
53
- });
54
- void this.fulfillQuery(collection.name, selector, options).catch(this.onError);
55
- };
56
- const unregisterQuery = (selector, options) => {
57
- const qid = queryId(selector, options);
58
- this.queries.get(collection.name)?.delete(qid);
59
- };
60
- const getQueryState = (selector, options) => {
61
- const q = this.queries.get(collection.name)?.get(queryId(selector, options));
62
- return q?.state ?? "active";
63
- };
64
- const getQueryError = (selector, options) => {
65
- const q = this.queries.get(collection.name)?.get(queryId(selector, options));
66
- return q?.error ?? null;
67
- };
68
- const getQueryResult = (selector, options) => {
69
- const q = this.queries.get(collection.name)?.get(queryId(selector, options));
70
- return q?.items ?? [];
71
- };
72
- const onQueryStateChange = (selector, options, callback) => {
73
- const qid = queryId(selector, options);
74
- const registry = this.queries.get(collection.name);
75
- if (!registry)
76
- throw new Error(`Collection ${collection.name} not initialized!`);
77
- if (!registry.has(qid)) {
78
- registry.set(qid, {
79
- selector,
80
- options,
81
- state: "active",
82
- error: null,
83
- items: [],
84
- listeners: /* @__PURE__ */ new Set()
85
- });
86
- }
87
- registry.get(qid)?.listeners.add(callback);
88
- return () => registry.get(qid)?.listeners.delete(callback);
89
- };
90
- return {
91
- insert: async (item) => {
92
- await ready;
93
- const inserted = await this.insert(collection.name, item);
94
- return inserted;
95
- },
96
- updateOne: async (selector, modifier) => {
97
- await ready;
98
- return this.updateOne(collection.name, selector, modifier);
99
- },
100
- updateMany: async (selector, modifier) => {
101
- await ready;
102
- return this.updateMany(collection.name, selector, modifier);
103
- },
104
- replaceOne: async (selector, replacement) => {
105
- await ready;
106
- return this.replaceOne(collection.name, selector, replacement);
107
- },
108
- removeOne: async (selector) => {
109
- await ready;
110
- return this.removeOne(collection.name, selector);
111
- },
112
- removeMany: async (selector) => {
113
- await ready;
114
- return this.removeMany(collection.name, selector);
115
- },
116
- registerQuery,
117
- unregisterQuery,
118
- getQueryState,
119
- getQueryError,
120
- getQueryResult,
121
- onQueryStateChange,
122
- executeQuery: async (selector, options) => {
123
- await ready;
124
- registerQuery(selector, options);
125
- const result = getQueryResult(selector, options);
126
- unregisterQuery(selector, options);
127
- return result;
128
- },
129
- dispose: async () => {
130
- this.storageAdapters.delete(collection.name);
131
- this.queries.delete(collection.name);
132
- this.collectionIndices.delete(collection.name);
133
- this.storageAdapterReady.delete(collection.name);
134
- },
135
- isReady: async () => {
136
- await ready;
137
- }
138
- };
139
- }
140
- async setupStorage(collectionName, indices) {
141
- const storage = this.storageAdapters.get(collectionName);
142
- if (!storage)
143
- throw new Error(`No persistence adapter for collection ${collectionName}`);
144
- await storage.setup();
145
- await Promise.all(indices.map((index) => storage.createIndex(index)));
26
+ this.options = options || {};
146
27
  }
147
28
  ensureStorageAdapter(name) {
148
- if (this.storageAdapters.has(name))
29
+ if (this.storageAdapters.get(name))
30
+ return;
31
+ if (!this.options.storage)
149
32
  return;
150
33
  const adapter = this.options.storage(name);
151
34
  if (!adapter)
152
35
  return;
153
36
  this.storageAdapters.set(name, adapter);
154
37
  }
155
- /**
156
- * Compute and publish the result for a specific query
157
- * @param collectionName - name of the collection
158
- * @param selector - query selector
159
- * @param options - query options
160
- */
161
- async fulfillQuery(collectionName, selector, options) {
162
- const qid = queryId(selector, options);
163
- const registry = this.queries.get(collectionName);
164
- if (!registry)
165
- throw new Error(`Collection ${collectionName} not initialized!`);
166
- const rec = registry.get(qid);
167
- if (!rec)
168
- return;
169
- this.publishState(collectionName, qid, "active", null);
170
- try {
171
- const items = await this.executeQuery(collectionName, selector, options);
172
- this.publishResult(collectionName, qid, items);
173
- this.publishState(collectionName, qid, "complete", null);
174
- } catch (error) {
175
- this.publishState(collectionName, qid, "error", error);
176
- }
38
+ rebuildIndices(collection) {
39
+ const items = this.items.get(collection.name);
40
+ if (!items)
41
+ throw new Error(`Items not found for collection ${collection.name}`);
42
+ const indices = this.indices.get(collection.name);
43
+ if (!indices)
44
+ throw new Error(`Indices not found for collection ${collection.name}`);
45
+ indices.forEach((index) => index.rebuild([...items.values()]));
177
46
  }
178
- /**
179
- * Notify listeners about state changes and keep the cache updated
180
- * @param collectionName - name of the collection
181
- * @param qid - query id
182
- * @param state - new state
183
- * @param error - error if state is 'error', null otherwise
184
- */
185
- publishState(collectionName, qid, state, error) {
186
- const rec = this.queries.get(collectionName)?.get(qid);
187
- if (!rec)
47
+ async setupStorageAdapter(collection) {
48
+ const storageAdapter = this.storageAdapters.get(collection.name);
49
+ if (!storageAdapter)
188
50
  return;
189
- rec.state = state;
190
- rec.error = error;
191
- for (const callback of rec.listeners) {
192
- try {
193
- callback(state);
194
- } catch (error_) {
195
- this.onError(error_);
51
+ return storageAdapter.setup().then(async () => {
52
+ await this.fetchItemsFromStorage(collection);
53
+ }).catch((error) => {
54
+ if (!this.options.onError) {
55
+ console.error(`Error during data persistence operation in collection ${collection.name}`, error);
56
+ return;
196
57
  }
197
- }
198
- }
199
- publishResult(collectionName, qid, items) {
200
- const rec = this.queries.get(collectionName)?.get(qid);
201
- if (!rec)
202
- return;
203
- rec.items = items;
58
+ this.options.onError(collection.name, error instanceof Error ? error : new Error(error));
59
+ });
204
60
  }
205
- async getIndexInfo(collectionName, selector) {
206
- const storageAdapter = this.storageAdapters.get(collectionName);
207
- if (!storageAdapter)
208
- throw new Error(`No persistence adapter for collection ${collectionName}`);
61
+ getIndexInfo(collection, selector) {
209
62
  if (selector != null && Object.keys(selector).length === 1 && "id" in selector && typeof selector.id !== "object") {
210
63
  return {
211
64
  matched: true,
212
- ids: [selector.id].filter(Boolean),
65
+ ids: [serializeValue(selector.id)],
213
66
  optimizedSelector: {}
214
67
  };
215
68
  }
@@ -220,68 +73,49 @@ class AsyncDataAdapter {
220
73
  optimizedSelector: {}
221
74
  };
222
75
  }
223
- const indices = this.collectionIndices.get(collectionName) ?? [];
224
- return getIndexInfo(indices.map((field) => async (flatSelector) => {
225
- if (!Object.hasOwnProperty.call(flatSelector, field))
226
- return { matched: false };
227
- const index = await storageAdapter.readIndex(field);
228
- const fieldSelector = flatSelector[field];
229
- const filtersForNull = fieldSelector == null || fieldSelector.$exists === false;
230
- const keys = filtersForNull ? { include: null, exclude: [...index.keys()].filter((key) => key != null) } : getMatchingKeys(field, flatSelector);
231
- if (keys.include == null && keys.exclude == null)
232
- return { matched: false };
233
- let includedIds = [];
234
- if (keys.include == null) {
235
- for (const set of index.values())
236
- for (const pos of set)
237
- includedIds.push(pos);
238
- } else {
239
- for (const key of keys.include) {
240
- const idSet = index.get(key);
241
- if (idSet)
242
- for (const id of idSet)
243
- includedIds.push(id);
244
- }
245
- }
246
- if (keys.exclude != null) {
247
- const excludeIds = /* @__PURE__ */ new Set();
248
- for (const key of keys.exclude) {
249
- const idSet = index.get(key);
250
- if (idSet)
251
- for (const id of idSet)
252
- excludeIds.add(id);
253
- }
254
- includedIds = includedIds.filter((pos) => !excludeIds.has(pos));
255
- }
256
- return { matched: true, ids: includedIds, fields: [field], keepSelector: filtersForNull };
257
- }), selector);
76
+ return getIndexInfo((this.indices.get(collection.name) ?? []).map((i) => i.query.bind(i)), selector);
77
+ }
78
+ applyIndexDeltas(collection, changes) {
79
+ const indices = this.indices.get(collection.name) ?? [];
80
+ for (const index of indices) {
81
+ if (changes.modified)
82
+ index.update(changes.modified);
83
+ if (changes.added && changes.added.length > 0)
84
+ index.insert(changes.added);
85
+ if (changes.removed && changes.removed.length > 0)
86
+ index.remove(changes.removed);
87
+ }
88
+ }
89
+ getItem(collection, selector) {
90
+ const memory = this.items.get(collection.name) ?? /* @__PURE__ */ new Map();
91
+ const indexInfo = this.getIndexInfo(collection, selector);
92
+ const items = indexInfo.matched ? indexInfo.ids.map((id) => memory.get(serializeValue(id))).filter((i) => i != null) : [...memory.values()];
93
+ const item = items.find((document) => match(document, selector));
94
+ return item;
258
95
  }
259
- async queryItems(collectionName, selector) {
260
- const storage = this.storageAdapters.get(collectionName);
261
- if (!storage)
262
- throw new Error(`No persistence adapter for collection ${collectionName}`);
263
- const index = await this.getIndexInfo(collectionName, selector);
96
+ queryItems(collection, selector) {
97
+ const indexInfo = this.getIndexInfo(collection, selector);
264
98
  const matchItems = (item) => {
265
- if (index.optimizedSelector == null)
99
+ if (indexInfo.optimizedSelector == null)
266
100
  return true;
267
- if (Object.keys(index.optimizedSelector).length <= 0)
101
+ if (Object.keys(indexInfo.optimizedSelector).length <= 0)
268
102
  return true;
269
- return match(item, index.optimizedSelector);
103
+ const matches = match(item, indexInfo.optimizedSelector);
104
+ return matches;
270
105
  };
271
- if (index.matched) {
272
- const items = await storage.readIds(index.ids);
273
- if (isEqual(index.optimizedSelector, {}))
274
- return items;
275
- return items.filter(matchItems);
276
- } else {
277
- const allItems = await storage.readAll();
106
+ const items = this.items.get(collection.name);
107
+ if (!indexInfo.matched) {
278
108
  if (isEqual(selector, {}))
279
- return allItems;
280
- return allItems.filter(matchItems);
109
+ return [...items.values()];
110
+ return [...items.values()].filter(matchItems);
281
111
  }
112
+ const foundItems = indexInfo.ids.map((ids) => items.get(serializeValue(ids))).filter((i) => i != null);
113
+ if (isEqual(indexInfo.optimizedSelector, {}))
114
+ return foundItems;
115
+ return foundItems.filter(matchItems);
282
116
  }
283
- async executeQuery(collectionName, selector, options) {
284
- const items = await this.queryItems(collectionName, selector || {});
117
+ executeQuery(collection, selector, options) {
118
+ const items = this.queryItems(collection, selector || {});
285
119
  const { sort, skip, limit, fields } = options || {};
286
120
  const sorted = sort ? sortItems(items, sort) : items;
287
121
  const skipped = skip ? sorted.slice(skip) : sorted;
@@ -290,131 +124,243 @@ class AsyncDataAdapter {
290
124
  return limited.map((item) => {
291
125
  if (!fields)
292
126
  return item;
293
- return { ...idExcluded ? {} : { id: item.id }, ...project(item, fields) };
127
+ return {
128
+ ...idExcluded ? {} : { id: item.id },
129
+ ...project(item, fields)
130
+ };
294
131
  });
295
132
  }
296
- /**
297
- * After mutations, recompute and push updates for affected active queries
298
- * @param collectionName - name of the collection
299
- * @param changedItems - items that were inserted/updated/replaced/removed
300
- */
301
- async checkQueryUpdates(collectionName, changedItems) {
302
- const registry = this.queries.get(collectionName);
303
- if (!registry)
304
- throw new Error(`Collection ${collectionName} not initialized!`);
305
- if (registry.size === 0)
133
+ flushQueuedQueryUpdates(collection) {
134
+ if (!this.queuedQueryUpdates.get(collection.name))
306
135
  return;
307
- const affected = [...registry.values()].filter(({ selector }) => changedItems.some((item) => match(item, selector)));
308
- if (affected.length === 0)
136
+ const changes = this.queuedQueryUpdates.get(collection.name);
137
+ if (!changes || !hasPendingUpdates(changes))
309
138
  return;
310
- for (const { selector, options } of affected) {
311
- const qid = queryId(selector, options);
312
- this.publishState(collectionName, qid, "active", null);
313
- }
314
- await Promise.all(affected.map(async ({ selector, options }) => {
315
- const qid = queryId(selector, options);
316
- try {
317
- const items = await this.executeQuery(collectionName, selector, options);
318
- this.publishResult(collectionName, qid, items);
319
- this.publishState(collectionName, qid, "complete", null);
320
- } catch (error) {
321
- this.publishState(collectionName, qid, "error", error);
322
- }
323
- }));
139
+ this.queuedQueryUpdates.set(collection.name, { added: [], modified: [], removed: [] });
140
+ const flatItems = [...changes.added, ...changes.modified, ...changes.removed];
141
+ const itemIds = new Set(flatItems.map((i) => i.id));
142
+ const queries = [
143
+ ...this.activeQueries.get(collection.name)?.values() ?? []
144
+ ].filter(({ selector, options }) => {
145
+ const idsInQuery = this.cachedQueryResults.get(collection.name)?.get(queryId(selector, options))?.map((i) => i.id) ?? [];
146
+ if (idsInQuery.some((id) => itemIds.has(id)))
147
+ return true;
148
+ return flatItems.some((item) => match(item, selector));
149
+ });
150
+ queries.forEach(({ selector, options }) => {
151
+ this.executeAndCacheQuery(collection, selector, options);
152
+ });
324
153
  }
325
- async insert(collectionName, newItem) {
326
- const storage = this.storageAdapters.get(collectionName);
327
- if (!storage)
328
- throw new Error(`No persistence adapter for collection ${collectionName}`);
329
- const existingItems = await storage.readIds([newItem.id]);
330
- if (existingItems.length > 0)
331
- throw new Error(`Item with id ${String(newItem.id)} already exists`);
332
- await storage.insert([newItem]);
333
- await this.checkQueryUpdates(collectionName, [newItem]);
334
- return newItem;
154
+ executeAndCacheQuery(collection, selector, options) {
155
+ const result = this.executeQuery(collection, selector, options);
156
+ this.cachedQueryResults.set(collection.name, this.cachedQueryResults.get(collection.name) || /* @__PURE__ */ new Map());
157
+ this.cachedQueryResults.get(collection.name)?.set(queryId(selector, options), result);
158
+ const emitter = this.queryEmitters.get(collection.name);
159
+ if (!emitter)
160
+ return;
161
+ emitter.emit("change", selector, options, "complete");
335
162
  }
336
- async updateOne(collectionName, selector, modifier) {
337
- const storage = this.storageAdapters.get(collectionName);
338
- if (!storage)
339
- throw new Error(`No persistence adapter for collection ${collectionName}`);
340
- const items = await this.executeQuery(collectionName, selector, { limit: 1 });
341
- const [item] = items;
342
- const { $setOnInsert, ...rest } = modifier;
343
- if (item == null)
344
- return [];
345
- const modified = modify(deepClone(item), rest);
346
- if (item.id !== modified.id) {
347
- const existing = await this.executeQuery(collectionName, { id: modified.id }, { limit: 1 });
348
- if (existing.length > 0)
349
- throw new Error(`Item with id ${String(modified.id)} already exists`);
350
- }
351
- await storage.replace([modified]);
352
- await this.checkQueryUpdates(collectionName, [modified]);
353
- return [modified];
163
+ updateQueries(collection, changes) {
164
+ this.queuedQueryUpdates.set(collection.name, this.queuedQueryUpdates.get(collection.name) || { added: [], modified: [], removed: [] });
165
+ this.queuedQueryUpdates.get(collection.name)?.added.push(...changes.added);
166
+ this.queuedQueryUpdates.get(collection.name)?.modified.push(...changes.modified);
167
+ this.queuedQueryUpdates.get(collection.name)?.removed.push(...changes.removed);
168
+ this.flushQueuedQueryUpdates(collection);
354
169
  }
355
- async updateMany(collectionName, selector, modifier) {
356
- const storage = this.storageAdapters.get(collectionName);
357
- if (!storage)
358
- throw new Error(`No persistence adapter for collection ${collectionName}`);
359
- const items = await this.executeQuery(collectionName, selector);
360
- if (items.length === 0)
361
- return [];
362
- const { $setOnInsert, ...rest } = modifier;
363
- const changed = await Promise.all(items.map(async (item) => {
364
- const modified = modify(deepClone(item), rest);
365
- if (item.id !== modified.id) {
366
- const existing = await this.executeQuery(collectionName, { id: modified.id }, { limit: 1 });
367
- if (existing.length > 0)
368
- throw new Error(`Item with id ${String(modified.id)} already exists`);
369
- }
370
- return modified;
371
- }));
372
- await storage.replace(changed);
373
- await this.checkQueryUpdates(collectionName, changed);
374
- return changed;
170
+ createCollectionBackend(collection, indices) {
171
+ this.collections.add(collection);
172
+ this.ensureStorageAdapter(collection.name);
173
+ this.items.set(collection.name, this.items.get(collection.name) ?? /* @__PURE__ */ new Map());
174
+ this.queryEmitters.set(collection.name, this.queryEmitters.get(collection.name) ?? new EventEmitter());
175
+ this.queryEmitters.get(collection.name)?.setMaxListeners(Infinity);
176
+ this.activeQueries.set(collection.name, this.activeQueries.get(collection.name) || /* @__PURE__ */ new Map());
177
+ this.indices.set(collection.name, indices.map((field) => createIndex(field)));
178
+ this.rebuildIndices(collection);
179
+ const persistenceReadyPromise = this.setupStorageAdapter(collection);
180
+ const backend = {
181
+ // CRUD operations
182
+ insert: async (newItem) => {
183
+ const items = this.items.get(collection.name);
184
+ if (!items)
185
+ throw new Error(`Items not found for collection ${collection.name}`);
186
+ if (items.has(serializeValue(newItem.id))) {
187
+ throw new Error(`Item with id '${newItem.id}' already exists`);
188
+ }
189
+ this.items.get(collection.name)?.set(serializeValue(newItem.id), newItem);
190
+ await this.storageAdapters.get(collection.name)?.insert([newItem]);
191
+ this.applyIndexDeltas(collection, { added: [newItem] });
192
+ this.updateQueries(collection, {
193
+ added: [],
194
+ modified: [newItem],
195
+ removed: []
196
+ });
197
+ return newItem;
198
+ },
199
+ updateOne: async (selector, modifier) => {
200
+ const { $setOnInsert, ...restModifier } = modifier;
201
+ const item = this.getItem(collection, selector);
202
+ if (item == null)
203
+ return [];
204
+ const modifiedItem = modify(deepClone(item), restModifier);
205
+ const hasItemWithSameId = item.id !== modifiedItem.id && this.getItem(collection, { id: modifiedItem.id }) != null;
206
+ if (hasItemWithSameId) {
207
+ throw new Error(`Item with id '${modifiedItem.id}' already exists`);
208
+ }
209
+ this.items.get(collection.name)?.set(serializeValue(modifiedItem.id), modifiedItem);
210
+ await this.storageAdapters.get(collection.name)?.replace([modifiedItem]);
211
+ this.applyIndexDeltas(collection, { modified: [{ oldItem: item, newItem: modifiedItem }] });
212
+ this.updateQueries(collection, {
213
+ added: [],
214
+ modified: [modifiedItem],
215
+ removed: []
216
+ });
217
+ return [modifiedItem];
218
+ },
219
+ updateMany: async (selector, modifier) => {
220
+ const { $setOnInsert, ...restModifier } = modifier;
221
+ const items = this.executeQuery(collection, selector, {});
222
+ const changedItems = items.map((item) => {
223
+ const modifiedItem = modify(deepClone(item), restModifier);
224
+ const hasItemWithSameId = item.id !== modifiedItem.id && this.getItem(collection, { id: modifiedItem.id }) != null;
225
+ if (hasItemWithSameId) {
226
+ throw new Error(`Item with id '${modifiedItem.id}' already exists`);
227
+ }
228
+ return modifiedItem;
229
+ });
230
+ changedItems.forEach((item) => {
231
+ this.items.get(collection.name)?.set(serializeValue(item.id), item);
232
+ });
233
+ await this.storageAdapters.get(collection.name)?.replace(changedItems);
234
+ const pairs = items.map((oldItem, index) => ({ oldItem, newItem: changedItems[index] }));
235
+ this.applyIndexDeltas(collection, { modified: pairs });
236
+ this.updateQueries(collection, {
237
+ added: [],
238
+ modified: changedItems,
239
+ removed: []
240
+ });
241
+ return changedItems;
242
+ },
243
+ replaceOne: async (selector, replacement) => {
244
+ const item = this.getItem(collection, selector);
245
+ if (item == null)
246
+ return [];
247
+ const hasItemWithSameId = item.id !== replacement.id && replacement.id != null && this.getItem(collection, { id: replacement.id }) != null;
248
+ if (hasItemWithSameId) {
249
+ throw new Error(`Item with id '${replacement.id}' already exists`);
250
+ }
251
+ const modifiedItem = { id: item.id, ...replacement };
252
+ this.items.get(collection.name)?.set(serializeValue(modifiedItem.id), modifiedItem);
253
+ await this.storageAdapters.get(collection.name)?.replace([modifiedItem]);
254
+ this.applyIndexDeltas(collection, { modified: [{ oldItem: item, newItem: modifiedItem }] });
255
+ this.updateQueries(collection, {
256
+ added: [],
257
+ modified: [modifiedItem],
258
+ removed: []
259
+ });
260
+ return [modifiedItem];
261
+ },
262
+ removeOne: async (selector) => {
263
+ const item = this.getItem(collection, selector);
264
+ if (item == null)
265
+ return [];
266
+ this.items.get(collection.name)?.delete(serializeValue(item.id));
267
+ await this.storageAdapters.get(collection.name)?.remove([item]);
268
+ this.applyIndexDeltas(collection, { removed: [item] });
269
+ this.updateQueries(collection, {
270
+ added: [],
271
+ modified: [],
272
+ removed: [item]
273
+ });
274
+ return [item];
275
+ },
276
+ removeMany: async (selector) => {
277
+ const items = backend.getQueryResult(selector, {});
278
+ items.forEach((item) => {
279
+ this.items.get(collection.name)?.delete(serializeValue(item.id));
280
+ });
281
+ await this.storageAdapters.get(collection.name)?.remove(items);
282
+ this.applyIndexDeltas(collection, { removed: items });
283
+ this.updateQueries(collection, {
284
+ added: [],
285
+ modified: [],
286
+ removed: items
287
+ });
288
+ return items;
289
+ },
290
+ // methods for registering and unregistering queries that will be called from the collection during find/findOne
291
+ registerQuery: (selector, options) => {
292
+ this.activeQueries.set(collection.name, this.activeQueries.get(collection.name) || /* @__PURE__ */ new Map());
293
+ this.activeQueries.get(collection.name)?.set(queryId(selector, options), {
294
+ selector,
295
+ options
296
+ });
297
+ this.executeAndCacheQuery(collection, selector, options);
298
+ },
299
+ unregisterQuery: (selector, options) => {
300
+ if (!this.activeQueries.get(collection.name))
301
+ return;
302
+ this.activeQueries.get(collection.name)?.delete(queryId(selector, options));
303
+ },
304
+ getQueryState: () => "complete",
305
+ onQueryStateChange: (selector, options, callback) => {
306
+ const emitter = this.queryEmitters.get(collection.name);
307
+ if (!emitter)
308
+ throw new Error(`Query emitter not found for collection ${collection.name}`);
309
+ const handler = (querySelector, queryOptions, state) => {
310
+ if (queryId(querySelector, queryOptions) !== queryId(selector, options))
311
+ return;
312
+ callback(state);
313
+ };
314
+ emitter.on("change", handler);
315
+ return () => {
316
+ emitter.off("change", handler);
317
+ };
318
+ },
319
+ getQueryError: () => null,
320
+ getQueryResult: (selector, options) => {
321
+ const isQueryActive = this.activeQueries.get(collection.name)?.has(queryId(selector, options));
322
+ if (isQueryActive) {
323
+ const results = this.cachedQueryResults.get(collection.name)?.get(queryId(selector, options));
324
+ if (!results)
325
+ throw new Error("Cached query results are not defined!");
326
+ return results;
327
+ }
328
+ return this.executeQuery(collection, selector, options);
329
+ },
330
+ executeQuery: (selector, options) => Promise.resolve(this.executeQuery(collection, selector, options)),
331
+ // lifecycle methods
332
+ dispose: async () => {
333
+ const adapter = this.storageAdapters.get(collection.name);
334
+ if (adapter?.teardown)
335
+ await adapter.teardown();
336
+ this.storageAdapters.delete(collection.name);
337
+ this.items.delete(collection.name);
338
+ this.indices.delete(collection.name);
339
+ this.activeQueries.delete(collection.name);
340
+ this.queryEmitters.delete(collection.name);
341
+ this.queuedQueryUpdates.delete(collection.name);
342
+ this.cachedQueryResults.delete(collection.name);
343
+ },
344
+ isReady: () => persistenceReadyPromise
345
+ };
346
+ return backend;
375
347
  }
376
- async replaceOne(collectionName, selector, replacement) {
377
- const storage = this.storageAdapters.get(collectionName);
378
- if (!storage)
379
- throw new Error(`No persistence adapter for collection ${collectionName}`);
380
- const items = await this.executeQuery(collectionName, selector, { limit: 1 });
381
- const [item] = items;
382
- if (item == null)
383
- return [];
384
- const modified = { ...replacement, id: replacement.id ?? item.id };
385
- if (item.id !== modified.id) {
386
- const existing = await this.executeQuery(collectionName, { id: modified.id }, { limit: 1 });
387
- if (existing.length > 0)
388
- throw new Error(`Item with id ${String(modified.id)} already exists`);
348
+ async fetchItemsFromStorage(collection) {
349
+ if (!collection) {
350
+ await Promise.all([...this.collections].map((currentCollection) => this.fetchItemsFromStorage(currentCollection)));
351
+ return;
389
352
  }
390
- await storage.replace([modified]);
391
- await this.checkQueryUpdates(collectionName, [modified]);
392
- return [modified];
393
- }
394
- async removeOne(collectionName, selector) {
395
- const storage = this.storageAdapters.get(collectionName);
396
- if (!storage)
397
- throw new Error(`No persistence adapter for collection ${collectionName}`);
398
- const items = await this.executeQuery(collectionName, selector, { limit: 1 });
399
- const [item] = items;
400
- if (item == null)
401
- return [];
402
- await storage.remove([item]);
403
- await this.checkQueryUpdates(collectionName, [item]);
404
- return [item];
405
- }
406
- async removeMany(collectionName, selector) {
407
- const storage = this.storageAdapters.get(collectionName);
408
- if (!storage)
409
- throw new Error(`No persistence adapter for collection ${collectionName}`);
410
- const items = await this.executeQuery(collectionName, selector);
411
- if (items.length === 0)
412
- return [];
413
- await storage.remove(items);
414
- await this.checkQueryUpdates(collectionName, items);
415
- return items;
353
+ const storageAdapter = this.storageAdapters.get(collection.name);
354
+ if (!storageAdapter)
355
+ return;
356
+ const items = await storageAdapter.readAll();
357
+ this.items.set(collection.name, items.reduce((map, item) => {
358
+ map.set(serializeValue(item.id), item);
359
+ return map;
360
+ }, /* @__PURE__ */ new Map()));
361
+ this.rebuildIndices(collection);
416
362
  }
417
363
  }
418
364
  export {
419
- AsyncDataAdapter as default
365
+ DefaultDataAdapter as default
420
366
  };