@signaldb/core 1.5.3 → 1.6.0

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 (64) hide show
  1. package/dist/.vite/manifest.json +28 -27
  2. package/dist/Collection/createIndex.d.ts +1 -1
  3. package/dist/Collection/index.d.ts +1 -0
  4. package/dist/index.cjs.js +14 -12
  5. package/dist/index.cjs10.js +27 -10
  6. package/dist/index.cjs11.js +10 -3
  7. package/dist/index.cjs12.js +3 -136
  8. package/dist/index.cjs13.js +131 -61
  9. package/dist/index.cjs14.js +72 -5
  10. package/dist/index.cjs15.js +8 -41
  11. package/dist/index.cjs16.js +25 -11
  12. package/dist/index.cjs17.js +143 -23
  13. package/dist/index.cjs18.js +5 -262
  14. package/dist/index.cjs19.js +36 -63
  15. package/dist/index.cjs2.js +210 -731
  16. package/dist/index.cjs20.js +13 -85
  17. package/dist/index.cjs21.js +24 -8
  18. package/dist/index.cjs22.js +67 -24
  19. package/dist/index.cjs23.js +72 -131
  20. package/dist/index.cjs24.js +16 -5
  21. package/dist/index.cjs25.js +22 -11
  22. package/dist/index.cjs26.js +7 -27
  23. package/dist/index.cjs27.js +5 -27
  24. package/dist/index.cjs28.js +27 -7
  25. package/dist/index.cjs3.js +757 -136
  26. package/dist/index.cjs4.js +165 -62
  27. package/dist/index.cjs5.js +67 -3
  28. package/dist/index.cjs6.js +2 -2
  29. package/dist/index.cjs7.js +2 -2
  30. package/dist/index.cjs8.js +2 -2
  31. package/dist/index.cjs9.js +3 -27
  32. package/dist/index.d.ts +1 -0
  33. package/dist/index.mjs +14 -12
  34. package/dist/index10.mjs +27 -10
  35. package/dist/index11.mjs +10 -3
  36. package/dist/index12.mjs +3 -136
  37. package/dist/index13.mjs +131 -60
  38. package/dist/index14.mjs +71 -5
  39. package/dist/index15.mjs +8 -40
  40. package/dist/index16.mjs +25 -11
  41. package/dist/index17.mjs +143 -23
  42. package/dist/index18.mjs +5 -261
  43. package/dist/index19.mjs +36 -63
  44. package/dist/index2.mjs +210 -732
  45. package/dist/index20.mjs +13 -84
  46. package/dist/index21.mjs +24 -8
  47. package/dist/index22.mjs +66 -24
  48. package/dist/index23.mjs +71 -131
  49. package/dist/index24.mjs +16 -5
  50. package/dist/index25.mjs +22 -11
  51. package/dist/index26.mjs +7 -27
  52. package/dist/index27.mjs +5 -27
  53. package/dist/index28.mjs +27 -7
  54. package/dist/index3.mjs +757 -136
  55. package/dist/index4.mjs +165 -61
  56. package/dist/index5.mjs +66 -3
  57. package/dist/index6.mjs +2 -2
  58. package/dist/index7.mjs +2 -2
  59. package/dist/index8.mjs +2 -2
  60. package/dist/index9.mjs +3 -27
  61. package/dist/types/IndexProvider.d.ts +2 -0
  62. package/dist/utils/getMatchingKeys.d.ts +2 -2
  63. package/dist/utils/serializeValue.d.ts +1 -1
  64. package/package.json +1 -1
package/dist/index3.mjs CHANGED
@@ -1,173 +1,794 @@
1
1
  var __defProp = Object.defineProperty;
2
2
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
3
  var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
- import ReplicatedCollection from "./index20.mjs";
5
- import createSignal from "./index17.mjs";
6
- class AutoFetchCollection extends ReplicatedCollection {
4
+ import EventEmitter from "./index13.mjs";
5
+ import match from "./index18.mjs";
6
+ import modify from "./index11.mjs";
7
+ import isEqual from "./index10.mjs";
8
+ import randomId from "./index12.mjs";
9
+ import deepClone from "./index19.mjs";
10
+ import serializeValue from "./index20.mjs";
11
+ import createSignal from "./index21.mjs";
12
+ import Cursor from "./index2.mjs";
13
+ import getIndexInfo from "./index22.mjs";
14
+ import { createExternalIndex } from "./index14.mjs";
15
+ import { default as default2 } from "./index14.mjs";
16
+ function hasPendingUpdates(pendingUpdates) {
17
+ return pendingUpdates.added.length > 0 || pendingUpdates.modified.length > 0 || pendingUpdates.removed.length > 0;
18
+ }
19
+ function applyUpdates(currentItems, { added, modified, removed }) {
20
+ const items = [...currentItems];
21
+ added.forEach((item) => {
22
+ items.push(item);
23
+ });
24
+ modified.forEach((item) => {
25
+ const index = items.findIndex(({ id }) => id === item.id);
26
+ if (index === -1)
27
+ return;
28
+ items[index] = item;
29
+ });
30
+ removed.forEach((item) => {
31
+ const index = items.findIndex(({ id }) => id === item.id);
32
+ if (index === -1)
33
+ return;
34
+ items.splice(index, 1);
35
+ });
36
+ return items;
37
+ }
38
+ const _Collection = class _Collection extends EventEmitter {
7
39
  /**
8
- * @param options {Object} - Options for the collection.
9
- * @param options.fetchQueryItems {Function} - A function that fetches items from the server. It takes the selector as an argument and returns a promise that resolves to an object with an `items` property.
10
- * @param options.purgeDelay {Number} - The delay in milliseconds before purging an item from the cache.
40
+ * Initializes a new instance of the `Collection` class with optional configuration.
41
+ * Sets up memory, persistence, reactivity, and indices as specified in the options.
42
+ * @template T - The type of the items stored in the collection.
43
+ * @template I - The type of the unique identifier for the items.
44
+ * @template U - The transformed item type after applying transformations (default is T).
45
+ * @param options - Optional configuration for the collection.
46
+ * @param options.name - An optional name for the collection.
47
+ * @param options.memory - The in-memory adapter for storing items.
48
+ * @param options.reactivity - The reactivity adapter for observing changes in the collection.
49
+ * @param options.transform - A transformation function to apply to items when retrieving them.
50
+ * @param options.persistence - The persistence adapter for saving and loading items.
51
+ * @param options.indices - An array of index providers for optimized querying.
52
+ * @param options.enableDebugMode - A boolean to enable or disable debug mode.
53
+ * @param options.fieldTracking - A boolean to enable or disable field tracking by default.
11
54
  */
12
55
  constructor(options) {
13
- let triggerRemoteChange;
14
- super({
15
- ...options,
16
- pull: () => Promise.resolve({
17
- items: [...this.itemsCache.values()].reduce((memo, items) => {
18
- const newItems = [...memo];
19
- items.forEach((item) => {
20
- const index = newItems.findIndex((i) => i.id === item.id);
21
- if (index === -1) {
22
- newItems.push(item);
56
+ super();
57
+ __publicField(this, "name");
58
+ __publicField(this, "options");
59
+ __publicField(this, "persistenceAdapter", null);
60
+ __publicField(this, "isPullingSignal");
61
+ __publicField(this, "isPushingSignal");
62
+ __publicField(this, "indexProviders", []);
63
+ __publicField(this, "indicesOutdated", false);
64
+ __publicField(this, "idIndex", /* @__PURE__ */ new Map());
65
+ __publicField(this, "debugMode");
66
+ __publicField(this, "batchOperationInProgress", false);
67
+ __publicField(this, "isDisposed", false);
68
+ __publicField(this, "postBatchCallbacks", /* @__PURE__ */ new Set());
69
+ __publicField(this, "fieldTracking", false);
70
+ __publicField(this, "persistenceReadyPromise");
71
+ _Collection.collections.push(this);
72
+ this.name = (options == null ? void 0 : options.name) ?? `${this.constructor.name}-${randomId()}`;
73
+ this.options = {
74
+ memory: [],
75
+ ...options
76
+ };
77
+ this.fieldTracking = this.options.fieldTracking ?? _Collection.fieldTracking;
78
+ this.debugMode = this.options.enableDebugMode ?? _Collection.debugMode;
79
+ this.indexProviders = [
80
+ createExternalIndex("id", this.idIndex),
81
+ ...this.options.indices || []
82
+ ];
83
+ this.rebuildIndices();
84
+ this.isPullingSignal = createSignal(this.options.reactivity, !!(options == null ? void 0 : options.persistence));
85
+ this.isPushingSignal = createSignal(this.options.reactivity, false);
86
+ this.on("persistence.pullStarted", () => {
87
+ this.isPullingSignal.set(true);
88
+ });
89
+ this.on("persistence.pullCompleted", () => {
90
+ this.isPullingSignal.set(false);
91
+ });
92
+ this.on("persistence.pushStarted", () => {
93
+ this.isPushingSignal.set(true);
94
+ });
95
+ this.on("persistence.pushCompleted", () => {
96
+ this.isPushingSignal.set(false);
97
+ });
98
+ this.persistenceAdapter = this.options.persistence ?? null;
99
+ if (this.persistenceAdapter) {
100
+ let ongoingSaves = 0;
101
+ let isInitialized = false;
102
+ const pendingUpdates = { added: [], modified: [], removed: [] };
103
+ const loadPersistentData = async (data) => {
104
+ if (!this.persistenceAdapter)
105
+ throw new Error("Persistence adapter not found");
106
+ this.emit("persistence.pullStarted");
107
+ const { items, changes } = data ?? await this.persistenceAdapter.load();
108
+ if (items) {
109
+ if (ongoingSaves > 0)
110
+ return;
111
+ this.memory().splice(0, this.memoryArray().length, ...items);
112
+ this.idIndex.clear();
113
+ this.memory().map((item, index) => {
114
+ this.idIndex.set(serializeValue(item.id), /* @__PURE__ */ new Set([index]));
115
+ });
116
+ } else if (changes) {
117
+ changes.added.forEach((item) => {
118
+ const index = this.memory().findIndex((document) => document.id === item.id);
119
+ if (index !== -1) {
120
+ this.memory().splice(index, 1, item);
23
121
  return;
24
122
  }
25
- newItems[index] = this.mergeItems(newItems[index], item);
123
+ this.memory().push(item);
124
+ const itemIndex = this.memory().findIndex((document) => document === item);
125
+ this.idIndex.set(serializeValue(item.id), /* @__PURE__ */ new Set([itemIndex]));
26
126
  });
27
- return newItems;
28
- }, [])
29
- }),
30
- registerRemoteChange: async (onChange) => {
31
- triggerRemoteChange = onChange;
32
- }
33
- });
34
- __publicField(this, "activeObservers", /* @__PURE__ */ new Map());
35
- __publicField(this, "observerTimeouts", /* @__PURE__ */ new Map());
36
- __publicField(this, "purgeDelay");
37
- __publicField(this, "idQueryCache", /* @__PURE__ */ new Map());
38
- __publicField(this, "itemsCache", /* @__PURE__ */ new Map());
39
- __publicField(this, "fetchQueryItems");
40
- __publicField(this, "triggerReload", null);
41
- __publicField(this, "reactivityAdapter", null);
42
- __publicField(this, "loadingSignals", /* @__PURE__ */ new Map());
43
- __publicField(this, "isFetchingSignal");
44
- __publicField(this, "mergeItems");
45
- this.mergeItems = options.mergeItems ?? ((itemA, itemB) => ({ ...itemA, ...itemB }));
46
- this.purgeDelay = options.purgeDelay ?? 1e4;
47
- this.isFetchingSignal = createSignal(options.reactivity, false);
48
- if (!triggerRemoteChange)
49
- throw new Error("No triggerRemoteChange method found. Looks like your persistence adapter was not registered");
50
- this.triggerReload = triggerRemoteChange;
51
- this.reactivityAdapter = options.reactivity ?? null;
52
- this.fetchQueryItems = options.fetchQueryItems;
53
- this.on("observer.created", (selector) => this.handleObserverCreation(selector ?? {}));
54
- this.on("observer.disposed", (selector) => setTimeout(() => this.handleObserverDisposal(selector ?? {}), 100));
55
- if (options.registerRemoteChange) {
56
- void options.registerRemoteChange(() => this.forceRefetch());
127
+ changes.modified.forEach((item) => {
128
+ const index = this.memory().findIndex((document) => document.id === item.id);
129
+ if (index === -1)
130
+ throw new Error("Cannot resolve index for item");
131
+ this.memory().splice(index, 1, item);
132
+ });
133
+ changes.removed.forEach((item) => {
134
+ const index = this.memory().findIndex((document) => document.id === item.id);
135
+ if (index === -1)
136
+ throw new Error("Cannot resolve index for item");
137
+ this.memory().splice(index, 1);
138
+ });
139
+ }
140
+ this.rebuildIndices();
141
+ this.emit("persistence.received");
142
+ setTimeout(() => this.emit("persistence.pullCompleted"), 0);
143
+ };
144
+ const saveQueue = {
145
+ added: [],
146
+ modified: [],
147
+ removed: []
148
+ };
149
+ let isFlushing = false;
150
+ const flushQueue = () => {
151
+ if (!this.persistenceAdapter)
152
+ throw new Error("Persistence adapter not found");
153
+ if (ongoingSaves <= 0)
154
+ this.emit("persistence.pushStarted");
155
+ if (isFlushing)
156
+ return;
157
+ if (!hasPendingUpdates(saveQueue))
158
+ return;
159
+ isFlushing = true;
160
+ ongoingSaves += 1;
161
+ const currentItems = this.memoryArray();
162
+ const changes = { ...saveQueue };
163
+ saveQueue.added = [];
164
+ saveQueue.modified = [];
165
+ saveQueue.removed = [];
166
+ this.persistenceAdapter.save(currentItems, changes).then(() => {
167
+ this.emit("persistence.transmitted");
168
+ }).catch((error) => {
169
+ this.emit("persistence.error", error instanceof Error ? error : new Error(error));
170
+ }).finally(() => {
171
+ ongoingSaves -= 1;
172
+ isFlushing = false;
173
+ flushQueue();
174
+ if (ongoingSaves <= 0)
175
+ this.emit("persistence.pushCompleted");
176
+ });
177
+ };
178
+ this.on("added", (item) => {
179
+ if (!isInitialized) {
180
+ pendingUpdates.added.push(item);
181
+ return;
182
+ }
183
+ saveQueue.added.push(item);
184
+ flushQueue();
185
+ });
186
+ this.on("changed", (item) => {
187
+ if (!isInitialized) {
188
+ pendingUpdates.modified.push(item);
189
+ return;
190
+ }
191
+ saveQueue.modified.push(item);
192
+ flushQueue();
193
+ });
194
+ this.on("removed", (item) => {
195
+ if (!isInitialized) {
196
+ pendingUpdates.removed.push(item);
197
+ return;
198
+ }
199
+ saveQueue.removed.push(item);
200
+ flushQueue();
201
+ });
202
+ this.persistenceAdapter.register((data) => loadPersistentData(data)).then(async () => {
203
+ if (!this.persistenceAdapter)
204
+ throw new Error("Persistence adapter not found");
205
+ let currentItems = this.memoryArray();
206
+ await loadPersistentData();
207
+ while (hasPendingUpdates(pendingUpdates)) {
208
+ const added = pendingUpdates.added.splice(0);
209
+ const modified = pendingUpdates.modified.splice(0);
210
+ const removed = pendingUpdates.removed.splice(0);
211
+ currentItems = applyUpdates(this.memoryArray(), { added, modified, removed });
212
+ await this.persistenceAdapter.save(currentItems, { added, modified, removed }).then(() => {
213
+ this.emit("persistence.transmitted");
214
+ });
215
+ }
216
+ await loadPersistentData();
217
+ isInitialized = true;
218
+ setTimeout(() => this.emit("persistence.init"), 0);
219
+ }).catch((error) => {
220
+ this.emit("persistence.error", error instanceof Error ? error : new Error(error));
221
+ });
57
222
  }
223
+ this.persistenceReadyPromise = new Promise((resolve, reject) => {
224
+ if (!this.persistenceAdapter)
225
+ return resolve();
226
+ this.once("persistence.init", resolve);
227
+ this.once("persistence.error", reject);
228
+ });
229
+ _Collection.onCreationCallbacks.forEach((callback) => callback(this));
230
+ }
231
+ static getCollections() {
232
+ return _Collection.collections;
233
+ }
234
+ static onCreation(callback) {
235
+ _Collection.onCreationCallbacks.push(callback);
236
+ }
237
+ static onDispose(callback) {
238
+ _Collection.onDisposeCallbacks.push(callback);
58
239
  }
59
240
  /**
60
- * Registers a query manually that items should be fetched for it
61
- * @param selector {Object} Selector of the query
241
+ * Executes a batch operation, allowing multiple modifications to the collection
242
+ * while deferring index rebuilding until all operations in the batch are completed.
243
+ * This improves performance by avoiding repetitive index recalculations and
244
+ * provides atomicity for the batch of operations.
245
+ * @param callback - The batch operation to execute.
62
246
  */
63
- registerQuery(selector) {
64
- this.handleObserverCreation(selector);
247
+ static batch(callback) {
248
+ _Collection.batchOperationInProgress = true;
249
+ _Collection.collections.reduce((memo, collection) => () => collection.batch(() => memo()), callback)();
250
+ _Collection.batchOperationInProgress = false;
65
251
  }
66
252
  /**
67
- * Unregisters a query manually that items are not fetched anymore for it
68
- * @param selector {Object} Selector of the query
253
+ * Checks whether the collection is currently performing a pull operation
254
+ * ⚡️ this function is reactive!
255
+ * (loading data from the persistence adapter).
256
+ * @returns A boolean indicating if the collection is in the process of pulling data.
69
257
  */
70
- unregisterQuery(selector) {
71
- this.handleObserverDisposal(selector);
258
+ isPulling() {
259
+ return this.isPullingSignal.get() ?? false;
72
260
  }
73
- getKeyForSelector(selector) {
74
- return JSON.stringify(selector);
261
+ /**
262
+ * Checks whether the collection is currently performing a push operation
263
+ * ⚡️ this function is reactive!
264
+ * (saving data to the persistence adapter).
265
+ * @returns A boolean indicating if the collection is in the process of pushing data.
266
+ */
267
+ isPushing() {
268
+ return this.isPushingSignal.get() ?? false;
75
269
  }
76
- async forceRefetch() {
77
- return Promise.all([...this.activeObservers.values()].map(({ selector }) => this.fetchSelector(selector))).then(() => {
270
+ /**
271
+ * Checks whether the collection is currently performing either a pull or push operation,
272
+ * ⚡️ this function is reactive!
273
+ * indicating that it is loading or saving data.
274
+ * @returns A boolean indicating if the collection is in the process of loading or saving data.
275
+ */
276
+ isLoading() {
277
+ const isPulling = this.isPulling();
278
+ const isPushing = this.isPushing();
279
+ return isPulling || isPushing;
280
+ }
281
+ /**
282
+ * Retrieves the current debug mode status of the collection.
283
+ * @returns A boolean indicating whether debug mode is enabled for the collection.
284
+ */
285
+ getDebugMode() {
286
+ return this.debugMode;
287
+ }
288
+ /**
289
+ * Enables or disables debug mode for the collection.
290
+ * When debug mode is enabled, additional debugging information and events are emitted.
291
+ * @param enable - A boolean indicating whether to enable (`true`) or disable (`false`) debug mode.
292
+ */
293
+ setDebugMode(enable) {
294
+ this.debugMode = enable;
295
+ }
296
+ /**
297
+ * Enables or disables field tracking for the collection.
298
+ * @param enable - A boolean indicating whether to enable (`true`) or disable (`false`) field tracking.
299
+ */
300
+ setFieldTracking(enable) {
301
+ this.fieldTracking = enable;
302
+ }
303
+ /**
304
+ * Resolves when the persistence adapter finished initializing
305
+ * and the collection is ready to be used.
306
+ * @returns A promise that resolves when the collection is ready.
307
+ * @example
308
+ * ```ts
309
+ * const collection = new Collection({
310
+ * persistence: // ...
311
+ * })
312
+ * await collection.isReady()
313
+ *
314
+ * collection.insert({ name: 'Item 1' })
315
+ */
316
+ async isReady() {
317
+ return this.persistenceReadyPromise;
318
+ }
319
+ profile(fn, measureFunction) {
320
+ if (!this.debugMode)
321
+ return fn();
322
+ const startTime = performance.now();
323
+ const result = fn();
324
+ const endTime = performance.now();
325
+ measureFunction(endTime - startTime);
326
+ return result;
327
+ }
328
+ executeInDebugMode(fn) {
329
+ if (!this.debugMode)
330
+ return;
331
+ const callstack = new Error().stack || "";
332
+ fn(callstack);
333
+ }
334
+ rebuildIndices() {
335
+ this.indicesOutdated = true;
336
+ if (this.batchOperationInProgress)
337
+ return;
338
+ this.rebuildAllIndices();
339
+ }
340
+ rebuildAllIndices() {
341
+ this.idIndex.clear();
342
+ this.memory().map((item, index) => {
343
+ this.idIndex.set(serializeValue(item.id), /* @__PURE__ */ new Set([index]));
78
344
  });
345
+ this.indexProviders.forEach((index) => index.rebuild(this.memoryArray()));
346
+ this.indicesOutdated = false;
79
347
  }
80
- fetchSelector(selector) {
81
- this.isFetchingSignal.set(true);
82
- return this.fetchQueryItems(selector).then((response) => {
83
- if (!response.items)
84
- throw new Error("AutoFetchCollection currently only works with a full item response");
85
- this.itemsCache.set(this.getKeyForSelector(selector), response.items);
86
- response.items.forEach((item) => {
87
- const queries = this.idQueryCache.get(item.id) ?? [];
88
- queries.push(selector);
89
- this.idQueryCache.set(item.id, queries);
90
- });
91
- this.setLoading(selector, true);
92
- this.once("persistence.received", () => {
93
- this.setLoading(selector, false);
94
- });
95
- if (!this.triggerReload)
96
- throw new Error("No triggerReload method found. Looks like your persistence adapter was not registered");
97
- void this.triggerReload();
98
- }).catch((error) => {
99
- this.emit("persistence.error", error);
100
- }).finally(() => {
101
- this.isFetchingSignal.set(false);
348
+ getIndexInfo(selector) {
349
+ if (selector != null && Object.keys(selector).length === 1 && "id" in selector && typeof selector.id !== "object") {
350
+ return {
351
+ matched: true,
352
+ positions: [...this.idIndex.get(serializeValue(selector.id)) || []],
353
+ optimizedSelector: {}
354
+ };
355
+ }
356
+ if (selector == null) {
357
+ return {
358
+ matched: false,
359
+ positions: [],
360
+ optimizedSelector: {}
361
+ };
362
+ }
363
+ if (this.indicesOutdated) {
364
+ return {
365
+ matched: false,
366
+ positions: [],
367
+ optimizedSelector: selector
368
+ };
369
+ }
370
+ return getIndexInfo(this.indexProviders, selector);
371
+ }
372
+ getItemAndIndex(selector) {
373
+ const memory = this.memoryArray();
374
+ const indexInfo = this.getIndexInfo(selector);
375
+ const items = indexInfo.matched ? indexInfo.positions.map((index2) => memory[index2]) : memory;
376
+ const item = items.find((document) => match(document, selector));
377
+ const foundInIndex = indexInfo.matched && indexInfo.positions.find((itemIndex) => memory[itemIndex] === item);
378
+ const index = foundInIndex || memory.findIndex((document) => document === item);
379
+ if (item == null)
380
+ return { item: null, index: -1 };
381
+ if (index === -1)
382
+ throw new Error("Cannot resolve index for item");
383
+ return { item, index };
384
+ }
385
+ deleteFromIdIndex(id, index) {
386
+ this.idIndex.delete(serializeValue(id));
387
+ if (!this.batchOperationInProgress)
388
+ return;
389
+ this.idIndex.forEach(([currenIndex], key) => {
390
+ if (currenIndex > index) {
391
+ this.idIndex.set(key, /* @__PURE__ */ new Set([currenIndex - 1]));
392
+ }
102
393
  });
103
394
  }
104
- handleObserverCreation(selector) {
395
+ memory() {
396
+ return this.options.memory;
397
+ }
398
+ memoryArray() {
399
+ return this.memory().map((item) => item);
400
+ }
401
+ transform(item) {
402
+ if (!this.options.transform)
403
+ return item;
404
+ return this.options.transform(item);
405
+ }
406
+ getItems(selector) {
407
+ return this.profile(() => {
408
+ const indexInfo = this.getIndexInfo(selector);
409
+ const matchItems = (item) => {
410
+ if (indexInfo.optimizedSelector == null)
411
+ return true;
412
+ if (Object.keys(indexInfo.optimizedSelector).length <= 0)
413
+ return true;
414
+ const matches = match(item, indexInfo.optimizedSelector);
415
+ return matches;
416
+ };
417
+ this.emit("getItems", selector);
418
+ const memory = this.memoryArray();
419
+ if (!indexInfo.matched) {
420
+ if (isEqual(selector, {}))
421
+ return memory;
422
+ return memory.filter(matchItems);
423
+ }
424
+ const items = indexInfo.positions.map((index) => memory[index]);
425
+ if (isEqual(indexInfo.optimizedSelector, {}))
426
+ return items;
427
+ return items.filter(matchItems);
428
+ }, (measuredTime) => this.executeInDebugMode((callstack) => this.emit("_debug.getItems", callstack, selector, measuredTime)));
429
+ }
430
+ /**
431
+ * Disposes the collection, unregisters persistence adapters, clears memory, and
432
+ * cleans up all resources used by the collection.
433
+ * @returns A promise that resolves when the collection is disposed.
434
+ */
435
+ async dispose() {
105
436
  var _a;
106
- const activeObservers = ((_a = this.activeObservers.get(this.getKeyForSelector(selector))) == null ? void 0 : _a.count) ?? 0;
107
- this.activeObservers.set(this.getKeyForSelector(selector), {
108
- selector,
109
- count: activeObservers + 1
437
+ if ((_a = this.persistenceAdapter) == null ? void 0 : _a.unregister)
438
+ await this.persistenceAdapter.unregister();
439
+ this.persistenceAdapter = null;
440
+ this.memory().map(() => this.memory().pop());
441
+ this.idIndex.clear();
442
+ this.indexProviders = [];
443
+ this.isDisposed = true;
444
+ this.removeAllListeners();
445
+ _Collection.collections = _Collection.collections.filter((collection) => collection !== this);
446
+ _Collection.onDisposeCallbacks.forEach((callback) => callback(this));
447
+ }
448
+ /**
449
+ * Finds multiple items in the collection based on a selector and optional options.
450
+ * Returns a cursor for reactive data queries.
451
+ * @template O - The options type for the find operation.
452
+ * @param [selector] - The criteria to select items.
453
+ * @param [options] - Options for the find operation, such as limit and sort.
454
+ * @returns A cursor to fetch and observe the matching items.
455
+ */
456
+ find(selector, options) {
457
+ if (this.isDisposed)
458
+ throw new Error("Collection is disposed");
459
+ if (selector !== void 0 && (!selector || typeof selector !== "object"))
460
+ throw new Error("Invalid selector");
461
+ const cursor = new Cursor(() => this.getItems(selector), {
462
+ reactive: this.options.reactivity,
463
+ fieldTracking: this.fieldTracking,
464
+ ...options,
465
+ transform: this.transform.bind(this),
466
+ bindEvents: (requery) => {
467
+ const handleRequery = () => {
468
+ if (this.batchOperationInProgress) {
469
+ this.postBatchCallbacks.add(requery);
470
+ return;
471
+ }
472
+ requery();
473
+ };
474
+ this.addListener("persistence.received", handleRequery);
475
+ this.addListener("added", handleRequery);
476
+ this.addListener("changed", handleRequery);
477
+ this.addListener("removed", handleRequery);
478
+ this.emit("observer.created", selector, options);
479
+ return () => {
480
+ this.removeListener("persistence.received", handleRequery);
481
+ this.removeListener("added", handleRequery);
482
+ this.removeListener("changed", handleRequery);
483
+ this.removeListener("removed", handleRequery);
484
+ this.emit("observer.disposed", selector, options);
485
+ };
486
+ }
110
487
  });
111
- const timeout = this.observerTimeouts.get(this.getKeyForSelector(selector));
112
- if (timeout)
113
- clearTimeout(timeout);
114
- if (activeObservers === 0)
115
- void this.fetchSelector(selector);
488
+ this.emit("find", selector, options, cursor);
489
+ this.executeInDebugMode((callstack) => this.emit("_debug.find", callstack, selector, options, cursor));
490
+ return cursor;
116
491
  }
117
- handleObserverDisposal(selector) {
118
- var _a;
119
- const currentObservers = ((_a = this.activeObservers.get(this.getKeyForSelector(selector))) == null ? void 0 : _a.count) ?? 0;
120
- const activeObservers = currentObservers - 1;
121
- if (activeObservers > 0) {
122
- this.activeObservers.set(this.getKeyForSelector(selector), {
123
- selector,
124
- count: activeObservers
125
- });
126
- return;
492
+ /**
493
+ * Finds a single item in the collection based on a selector and optional options.
494
+ * ⚡️ this function is reactive!
495
+ * Returns the found item or undefined if no item matches.
496
+ * @template O - The options type for the find operation.
497
+ * @param selector - The criteria to select the item.
498
+ * @param [options] - Options for the find operation, such as projection.
499
+ * @returns The found item or `undefined`.
500
+ */
501
+ findOne(selector, options) {
502
+ if (this.isDisposed)
503
+ throw new Error("Collection is disposed");
504
+ const cursor = this.find(selector, {
505
+ limit: 1,
506
+ ...options
507
+ });
508
+ const returnValue = cursor.fetch()[0] || void 0;
509
+ this.emit("findOne", selector, options, returnValue);
510
+ this.executeInDebugMode((callstack) => this.emit("_debug.findOne", callstack, selector, options, returnValue));
511
+ return returnValue;
512
+ }
513
+ /**
514
+ * Performs a batch operation, deferring index rebuilds and allowing multiple
515
+ * modifications to be made atomically. Executes any post-batch callbacks afterwards.
516
+ * @param callback - The batch operation to execute.
517
+ */
518
+ batch(callback) {
519
+ this.batchOperationInProgress = true;
520
+ callback();
521
+ this.batchOperationInProgress = false;
522
+ this.rebuildAllIndices();
523
+ this.postBatchCallbacks.forEach((callback_) => callback_());
524
+ this.postBatchCallbacks.clear();
525
+ }
526
+ /**
527
+ * Inserts a single item into the collection. Generates a unique ID if not provided.
528
+ * @param item - The item to insert.
529
+ * @returns The ID of the inserted item.
530
+ * @throws {Error} If the collection is disposed or the item has an invalid ID.
531
+ */
532
+ insert(item) {
533
+ if (this.isDisposed)
534
+ throw new Error("Collection is disposed");
535
+ if (!item)
536
+ throw new Error("Invalid item");
537
+ const primaryKeyGenerator = this.options.primaryKeyGenerator ?? randomId;
538
+ const newItem = { id: primaryKeyGenerator(item), ...item };
539
+ this.emit("validate", newItem);
540
+ if (this.idIndex.has(serializeValue(newItem.id)))
541
+ throw new Error("Item with same id already exists");
542
+ this.memory().push(newItem);
543
+ const itemIndex = this.memory().findIndex((document) => document === newItem);
544
+ this.idIndex.set(serializeValue(newItem.id), /* @__PURE__ */ new Set([itemIndex]));
545
+ this.rebuildIndices();
546
+ this.emit("added", newItem);
547
+ this.emit("insert", newItem);
548
+ this.executeInDebugMode((callstack) => this.emit("_debug.insert", callstack, newItem));
549
+ return newItem.id;
550
+ }
551
+ /**
552
+ * Inserts multiple items into the collection. Generates unique IDs for items if not provided.
553
+ * @param items - The items to insert.
554
+ * @returns An array of IDs of the inserted items.
555
+ * @throws {Error} If the collection is disposed or the items are invalid.
556
+ */
557
+ insertMany(items) {
558
+ if (this.isDisposed)
559
+ throw new Error("Collection is disposed");
560
+ if (!items)
561
+ throw new Error("Invalid items");
562
+ if (items.length === 0) {
563
+ return [];
127
564
  }
128
- const timeout = this.observerTimeouts.get(this.getKeyForSelector(selector));
129
- if (timeout)
130
- clearTimeout(timeout);
131
- const removeObserver = () => {
132
- this.activeObservers.delete(this.getKeyForSelector(selector));
133
- this.itemsCache.delete(this.getKeyForSelector(selector));
134
- if (!this.triggerReload)
135
- throw new Error("No triggerReload method found. Looks like your persistence adapter was not registered");
136
- void this.triggerReload();
137
- };
138
- if (this.purgeDelay === 0) {
139
- removeObserver();
140
- return;
565
+ const ids = [];
566
+ this.batch(() => {
567
+ items.forEach((item) => {
568
+ ids.push(this.insert(item));
569
+ });
570
+ });
571
+ return ids;
572
+ }
573
+ /**
574
+ * Updates a single item in the collection that matches the given selector.
575
+ * @param selector - The criteria to select the item to update.
576
+ * @param modifier - The modifications to apply to the item.
577
+ * @param [options] - Optional settings for the update operation.
578
+ * @param [options.upsert] - If `true`, creates a new item if no item matches the selector.
579
+ * @returns The number of items updated (0 or 1).
580
+ * @throws {Error} If the collection is disposed or invalid arguments are provided.
581
+ */
582
+ updateOne(selector, modifier, options) {
583
+ if (this.isDisposed)
584
+ throw new Error("Collection is disposed");
585
+ if (!selector)
586
+ throw new Error("Invalid selector");
587
+ if (!modifier)
588
+ throw new Error("Invalid modifier");
589
+ const { $setOnInsert, ...restModifier } = modifier;
590
+ const { item, index } = this.getItemAndIndex(selector);
591
+ if (item == null) {
592
+ if (options == null ? void 0 : options.upsert) {
593
+ const newItem = modify({}, {
594
+ ...restModifier,
595
+ $set: {
596
+ ...$setOnInsert,
597
+ ...restModifier.$set
598
+ }
599
+ });
600
+ if (newItem.id != null && this.getItemAndIndex({ id: newItem.id }).item != null) {
601
+ throw new Error("Item with same id already exists");
602
+ }
603
+ this.insert(newItem);
604
+ }
605
+ } else {
606
+ const modifiedItem = modify(deepClone(item), restModifier);
607
+ if (item.id !== modifiedItem.id && this.getItemAndIndex({ id: modifiedItem.id }).item != null) {
608
+ throw new Error("Item with same id already exists");
609
+ }
610
+ this.emit("validate", modifiedItem);
611
+ this.memory().splice(index, 1, modifiedItem);
612
+ this.rebuildIndices();
613
+ this.emit("changed", modifiedItem, restModifier);
141
614
  }
142
- this.observerTimeouts.set(this.getKeyForSelector(selector), setTimeout(removeObserver, this.purgeDelay));
615
+ this.emit("updateOne", selector, modifier);
616
+ this.executeInDebugMode((callstack) => this.emit("_debug.updateOne", callstack, selector, modifier));
617
+ if (item == null && !(options == null ? void 0 : options.upsert))
618
+ return 0;
619
+ return 1;
143
620
  }
144
- ensureSignal(selector) {
145
- if (!this.reactivityAdapter)
146
- throw new Error("No reactivity adapter found");
147
- if (!this.loadingSignals.has(this.getKeyForSelector(selector))) {
148
- this.loadingSignals.set(this.getKeyForSelector(selector), createSignal(this.reactivityAdapter, false));
621
+ /**
622
+ * Updates multiple items in the collection that match the given selector.
623
+ * @param selector - The criteria to select the items to update.
624
+ * @param modifier - The modifications to apply to the items.
625
+ * @param [options] - Optional settings for the update operation.
626
+ * @param [options.upsert] - If `true`, creates new items if no items match the selector.
627
+ * @returns The number of items updated.
628
+ * @throws {Error} If the collection is disposed or invalid arguments are provided.
629
+ */
630
+ updateMany(selector, modifier, options) {
631
+ if (this.isDisposed)
632
+ throw new Error("Collection is disposed");
633
+ if (!selector)
634
+ throw new Error("Invalid selector");
635
+ if (!modifier)
636
+ throw new Error("Invalid modifier");
637
+ const { $setOnInsert, ...restModifier } = modifier;
638
+ const items = this.getItems(selector);
639
+ if (items.length === 0 && (options == null ? void 0 : options.upsert)) {
640
+ const newItem = modify({}, {
641
+ ...restModifier,
642
+ $set: {
643
+ ...$setOnInsert,
644
+ ...restModifier.$set
645
+ }
646
+ });
647
+ if (newItem.id != null && this.getItemAndIndex({ id: newItem.id }).item != null) {
648
+ throw new Error("Item with same id already exists");
649
+ }
650
+ this.insert(newItem);
149
651
  }
150
- return this.loadingSignals.get(this.getKeyForSelector(selector));
652
+ const changes = items.map((item) => {
653
+ const { index } = this.getItemAndIndex({ id: item.id });
654
+ if (index === -1)
655
+ throw new Error(`Cannot resolve index for item with id '${item.id}'`);
656
+ const modifiedItem = modify(deepClone(item), restModifier);
657
+ if (item.id !== modifiedItem.id && this.getItemAndIndex({ id: modifiedItem.id }).item != null) {
658
+ throw new Error(`Item with same id '${modifiedItem.id}' already exists`);
659
+ }
660
+ this.emit("validate", modifiedItem);
661
+ return {
662
+ item: modifiedItem,
663
+ index
664
+ };
665
+ });
666
+ changes.forEach(({ item, index }) => {
667
+ this.memory().splice(index, 1, item);
668
+ });
669
+ this.rebuildIndices();
670
+ changes.forEach(({ item }) => {
671
+ this.emit("changed", item, restModifier);
672
+ });
673
+ this.emit("updateMany", selector, modifier);
674
+ this.executeInDebugMode((callstack) => this.emit("_debug.updateMany", callstack, selector, modifier));
675
+ return changes.length === 0 && (options == null ? void 0 : options.upsert) ? 1 : changes.length;
151
676
  }
152
- setLoading(selector, value) {
153
- const signal = this.ensureSignal(selector);
154
- signal.set(value);
677
+ /**
678
+ * Replaces a single item in the collection that matches the given selector.
679
+ * @param selector - The criteria to select the item to replace.
680
+ * @param replacement - The item to replace the selected item with.
681
+ * @param [options] - Optional settings for the replace operation.
682
+ * @param [options.upsert] - If `true`, creates a new item if no item matches the selector.
683
+ * @returns The number of items replaced (0 or 1).
684
+ * @throws {Error} If the collection is disposed or invalid arguments are provided.
685
+ */
686
+ replaceOne(selector, replacement, options) {
687
+ if (this.isDisposed)
688
+ throw new Error("Collection is disposed");
689
+ if (!selector)
690
+ throw new Error("Invalid selector");
691
+ const { item, index } = this.getItemAndIndex(selector);
692
+ if (item == null) {
693
+ if (options == null ? void 0 : options.upsert) {
694
+ if (replacement.id != null && this.getItemAndIndex({ id: replacement.id }).item != null) {
695
+ throw new Error("Item with same id already exists");
696
+ }
697
+ this.insert(replacement);
698
+ }
699
+ } else {
700
+ if (item.id !== replacement.id && this.getItemAndIndex({ id: replacement.id }).item != null) {
701
+ throw new Error("Item with same id already exists");
702
+ }
703
+ const modifiedItem = { id: item.id, ...replacement };
704
+ this.emit("validate", modifiedItem);
705
+ this.memory().splice(index, 1, modifiedItem);
706
+ this.rebuildIndices();
707
+ this.emit("changed", modifiedItem, replacement);
708
+ }
709
+ this.emit("replaceOne", selector, replacement);
710
+ this.executeInDebugMode((callstack) => this.emit("_debug.replaceOne", callstack, selector, replacement));
711
+ if (item == null && !(options == null ? void 0 : options.upsert))
712
+ return 0;
713
+ return 1;
155
714
  }
156
715
  /**
157
- * Indicates wether a query is currently been loaded
158
- * ⚡️ this function is reactive!
159
- * @param selector {Object} Selector of the query
160
- * @returns The loading state
716
+ * Removes a single item from the collection that matches the given selector.
717
+ * @param selector - The criteria to select the item to remove.
718
+ * @returns The number of items removed (0 or 1).
719
+ * @throws {Error} If the collection is disposed or invalid arguments are provided.
161
720
  */
162
- isLoading(selector) {
163
- const isPushing = this.isPushing();
164
- if (!selector) {
165
- return this.isFetchingSignal.get() || isPushing;
721
+ removeOne(selector) {
722
+ if (this.isDisposed)
723
+ throw new Error("Collection is disposed");
724
+ if (!selector)
725
+ throw new Error("Invalid selector");
726
+ const { item, index } = this.getItemAndIndex(selector);
727
+ if (item != null) {
728
+ this.memory().splice(index, 1);
729
+ this.deleteFromIdIndex(item.id, index);
730
+ this.rebuildIndices();
731
+ this.emit("removed", item);
166
732
  }
167
- const signal = this.ensureSignal(selector);
168
- return signal.get() || isPushing;
733
+ this.emit("removeOne", selector);
734
+ this.executeInDebugMode((callstack) => this.emit("_debug.removeOne", callstack, selector));
735
+ return item == null ? 0 : 1;
169
736
  }
170
- }
737
+ /**
738
+ * Removes multiple items from the collection that match the given selector.
739
+ * @param selector - The criteria to select the items to remove.
740
+ * @returns The number of items removed.
741
+ * @throws {Error} If the collection is disposed or invalid arguments are provided.
742
+ */
743
+ removeMany(selector) {
744
+ if (this.isDisposed)
745
+ throw new Error("Collection is disposed");
746
+ if (!selector)
747
+ throw new Error("Invalid selector");
748
+ const items = this.getItems(selector);
749
+ items.forEach((item) => {
750
+ const index = this.memory().findIndex((document) => document === item);
751
+ if (index === -1)
752
+ throw new Error("Cannot resolve index for item");
753
+ this.memory().splice(index, 1);
754
+ this.deleteFromIdIndex(item.id, index);
755
+ this.rebuildIndices();
756
+ });
757
+ items.forEach((item) => {
758
+ this.emit("removed", item);
759
+ });
760
+ this.emit("removeMany", selector);
761
+ this.executeInDebugMode((callstack) => this.emit("_debug.removeMany", callstack, selector));
762
+ return items.length;
763
+ }
764
+ };
765
+ __publicField(_Collection, "collections", []);
766
+ __publicField(_Collection, "debugMode", false);
767
+ __publicField(_Collection, "batchOperationInProgress", false);
768
+ __publicField(_Collection, "fieldTracking", false);
769
+ __publicField(_Collection, "onCreationCallbacks", []);
770
+ __publicField(_Collection, "onDisposeCallbacks", []);
771
+ /**
772
+ * Enables debug mode for all collections.
773
+ */
774
+ __publicField(_Collection, "enableDebugMode", () => {
775
+ _Collection.debugMode = true;
776
+ _Collection.collections.forEach((collection) => {
777
+ collection.setDebugMode(true);
778
+ });
779
+ });
780
+ /**
781
+ * Enables field tracking for all collections.
782
+ * @param enable - A boolean indicating whether to enable field tracking.
783
+ */
784
+ __publicField(_Collection, "setFieldTracking", (enable) => {
785
+ _Collection.fieldTracking = enable;
786
+ _Collection.collections.forEach((collection) => {
787
+ collection.setFieldTracking(enable);
788
+ });
789
+ });
790
+ let Collection = _Collection;
171
791
  export {
172
- AutoFetchCollection as default
792
+ default2 as createIndex,
793
+ Collection as default
173
794
  };