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