@signaldb/core 1.7.2 → 1.8.1

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