@signaldb/core 2.0.0-beta.0 → 2.0.0-beta.10

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 (128) hide show
  1. package/dist/.vite/manifest.json +128 -75
  2. package/dist/AsyncDataAdapter.d.ts +44 -7
  3. package/dist/AutoFetchDataAdapter.d.ts +5 -8
  4. package/dist/Collection/Cursor.d.ts +6 -5
  5. package/dist/Collection/Observer.d.ts +2 -0
  6. package/dist/Collection/index.d.ts +36 -25
  7. package/dist/Collection/types.d.ts +10 -2
  8. package/dist/DataAdapter.d.ts +18 -11
  9. package/dist/DefaultDataAdapter.d.ts +7 -6
  10. package/dist/WorkerDataAdapter.d.ts +7 -6
  11. package/dist/WorkerDataAdapterHost.d.ts +14 -11
  12. package/dist/createIndex.d.ts +2 -2
  13. package/dist/createIndexProvider.d.ts +2 -2
  14. package/dist/createReactivityAdapter.d.ts +2 -2
  15. package/dist/createStorageAdapter.d.ts +1 -1
  16. package/dist/getIndexInfo.d.ts +3 -4
  17. package/dist/index.cjs.js +33 -31
  18. package/dist/index.d.ts +3 -1
  19. package/dist/index.mjs +17 -32
  20. package/dist/index10.cjs.js +23 -0
  21. package/dist/index10.mjs +21 -17
  22. package/dist/index11.cjs.js +45 -0
  23. package/dist/index11.mjs +44 -15
  24. package/dist/index12.cjs.js +22 -0
  25. package/dist/index12.mjs +21 -339
  26. package/dist/index13.cjs.js +45 -0
  27. package/dist/index13.mjs +44 -407
  28. package/dist/index14.cjs.js +86 -0
  29. package/dist/index14.mjs +85 -190
  30. package/dist/index15.cjs.js +15 -0
  31. package/dist/index15.mjs +14 -341
  32. package/dist/index16.cjs.js +136 -0
  33. package/dist/index16.mjs +134 -569
  34. package/dist/index17.cjs.js +47 -0
  35. package/dist/index17.mjs +46 -150
  36. package/dist/index18.cjs.js +15 -0
  37. package/dist/index18.mjs +14 -26
  38. package/dist/index19.cjs.js +23 -0
  39. package/dist/index19.mjs +22 -42
  40. package/dist/index2.cjs.js +33 -0
  41. package/dist/index2.mjs +32 -254
  42. package/dist/index20.cjs.js +37 -0
  43. package/dist/index20.mjs +36 -104
  44. package/dist/index21.cjs.js +35 -0
  45. package/dist/index21.mjs +34 -128
  46. package/dist/index22.cjs.js +25 -0
  47. package/dist/index22.mjs +24 -7
  48. package/dist/index23.cjs.js +19 -0
  49. package/dist/index23.mjs +17 -26
  50. package/dist/index24.cjs.js +342 -0
  51. package/dist/index24.mjs +340 -6
  52. package/dist/index25.cjs.js +542 -0
  53. package/dist/index25.mjs +541 -10
  54. package/dist/index26.cjs.js +11 -0
  55. package/dist/index26.mjs +10 -29
  56. package/dist/index27.cjs.js +11 -0
  57. package/dist/index27.mjs +10 -5
  58. package/dist/index28.cjs.js +90 -0
  59. package/dist/index28.mjs +89 -8
  60. package/dist/index29.cjs.js +424 -0
  61. package/dist/index29.mjs +423 -29
  62. package/dist/index3.cjs.js +19 -0
  63. package/dist/index3.mjs +18 -537
  64. package/dist/index30.cjs.js +72 -0
  65. package/dist/index30.mjs +71 -42
  66. package/dist/index31.cjs.js +191 -0
  67. package/dist/index31.mjs +190 -9
  68. package/dist/index32.cjs.js +21 -0
  69. package/dist/index32.mjs +21 -0
  70. package/dist/index33.cjs.js +336 -0
  71. package/dist/index33.mjs +336 -0
  72. package/dist/index34.cjs.js +539 -0
  73. package/dist/index34.mjs +539 -0
  74. package/dist/index4.cjs.js +150 -0
  75. package/dist/index4.mjs +149 -5
  76. package/dist/index5.cjs.js +254 -0
  77. package/dist/index5.mjs +252 -4
  78. package/dist/index6.cjs.js +125 -0
  79. package/dist/index6.mjs +124 -29
  80. package/dist/index7.cjs.js +33 -0
  81. package/dist/index7.mjs +32 -12
  82. package/dist/index8.cjs.js +12 -0
  83. package/dist/index8.mjs +10 -4
  84. package/dist/index9.cjs.js +11 -0
  85. package/dist/index9.mjs +10 -133
  86. package/dist/types/IndexProvider.d.ts +2 -2
  87. package/dist/types/Modifier.d.ts +1 -1
  88. package/dist/types/ReactivityAdapter.d.ts +1 -1
  89. package/dist/utils/batchOnNextTick.d.ts +16 -0
  90. package/dist/utils/createSignal.d.ts +2 -2
  91. package/dist/utils/deepClone.d.ts +1 -1
  92. package/dist/utils/getMatchingKeys.d.ts +2 -2
  93. package/dist/utils/isFieldExpression.d.ts +1 -1
  94. package/dist/utils/match.d.ts +1 -1
  95. package/dist/utils/modify.d.ts +1 -1
  96. package/dist/utils/queryId.d.ts +2 -2
  97. package/dist/utils/reactiveOrAsync.d.ts +59 -0
  98. package/package.json +3 -3
  99. package/dist/index.cjs10.js +0 -18
  100. package/dist/index.cjs11.js +0 -15
  101. package/dist/index.cjs12.js +0 -339
  102. package/dist/index.cjs13.js +0 -407
  103. package/dist/index.cjs14.js +0 -190
  104. package/dist/index.cjs15.js +0 -341
  105. package/dist/index.cjs16.js +0 -570
  106. package/dist/index.cjs17.js +0 -150
  107. package/dist/index.cjs18.js +0 -26
  108. package/dist/index.cjs19.js +0 -43
  109. package/dist/index.cjs2.js +0 -255
  110. package/dist/index.cjs20.js +0 -104
  111. package/dist/index.cjs21.js +0 -129
  112. package/dist/index.cjs22.js +0 -7
  113. package/dist/index.cjs23.js +0 -27
  114. package/dist/index.cjs24.js +0 -7
  115. package/dist/index.cjs25.js +0 -10
  116. package/dist/index.cjs26.js +0 -29
  117. package/dist/index.cjs27.js +0 -5
  118. package/dist/index.cjs28.js +0 -7
  119. package/dist/index.cjs29.js +0 -29
  120. package/dist/index.cjs3.js +0 -538
  121. package/dist/index.cjs30.js +0 -42
  122. package/dist/index.cjs31.js +0 -9
  123. package/dist/index.cjs4.js +0 -5
  124. package/dist/index.cjs5.js +0 -5
  125. package/dist/index.cjs6.js +0 -29
  126. package/dist/index.cjs7.js +0 -12
  127. package/dist/index.cjs8.js +0 -5
  128. package/dist/index.cjs9.js +0 -133
package/dist/index25.mjs CHANGED
@@ -1,11 +1,542 @@
1
- import { sort } from "fast-sort";
2
- import get from "./index10.mjs";
3
- function sortItems(items, sortFields) {
4
- return sort(items).by(Object.entries(sortFields).map(([key, value]) => {
5
- const order = value === 1 ? "asc" : "desc";
6
- return { [order]: (i) => get(i, key) };
7
- }));
8
- }
9
- export {
10
- sortItems as default
1
+ import Cursor from "./index5.mjs";
2
+ import EventEmitter from "./index6.mjs";
3
+ import createSignal from "./index7.mjs";
4
+ import randomId from "./index8.mjs";
5
+ import "./index14.mjs";
6
+ import deepClone from "./index17.mjs";
7
+ import modify from "./index19.mjs";
8
+ import queryId from "./index22.mjs";
9
+ import DefaultDataAdapter from "./index24.mjs";
10
+ //#region src/Collection/index.ts
11
+ /**
12
+ * Represents a collection of data items with support for in-memory operations,
13
+ * persistence, reactivity, and event-based notifications. The collection provides
14
+ * CRUD operations, observer patterns, and batch operations.
15
+ * @template T - The type of the items stored in the collection.
16
+ * @template I - The type of the unique identifier for the items.
17
+ * @template U - The transformed item type after applying transformations (default is T).
18
+ */
19
+ var Collection = class Collection extends EventEmitter {
20
+ static collections = [];
21
+ static debugMode = false;
22
+ static batchOperationInProgress = false;
23
+ static fieldTracking = false;
24
+ static onCreationCallbacks = [];
25
+ static onDisposeCallbacks = [];
26
+ static getCollections() {
27
+ return Collection.collections;
28
+ }
29
+ static onCreation(callback) {
30
+ Collection.onCreationCallbacks.push(callback);
31
+ }
32
+ static onDispose(callback) {
33
+ Collection.onDisposeCallbacks.push(callback);
34
+ }
35
+ /**
36
+ * Enables debug mode for all collections.
37
+ */
38
+ static enableDebugMode = () => {
39
+ Collection.debugMode = true;
40
+ Collection.collections.forEach((collection) => {
41
+ collection.setDebugMode(true);
42
+ });
43
+ };
44
+ /**
45
+ * Enables field tracking for all collections.
46
+ * @param enable - A boolean indicating whether to enable field tracking.
47
+ */
48
+ static setFieldTracking = (enable) => {
49
+ Collection.fieldTracking = enable;
50
+ Collection.collections.forEach((collection) => {
51
+ collection.setFieldTracking(enable);
52
+ });
53
+ };
54
+ static batch(callback) {
55
+ Collection.batchOperationInProgress = true;
56
+ const execute = () => Collection.collections.reduce((memo, collection) => () => {
57
+ return collection.batch(memo);
58
+ }, callback)();
59
+ const afterBatch = () => {
60
+ Collection.batchOperationInProgress = false;
61
+ };
62
+ let maybePromise;
63
+ try {
64
+ maybePromise = execute();
65
+ } catch (error) {
66
+ afterBatch();
67
+ throw error;
68
+ }
69
+ if (maybePromise && typeof maybePromise.then === "function") return maybePromise.then(() => afterBatch(), (error) => {
70
+ afterBatch();
71
+ throw error;
72
+ });
73
+ else afterBatch();
74
+ }
75
+ name;
76
+ backend;
77
+ options;
78
+ isPullingSignal;
79
+ isPushingSignal;
80
+ readySignal;
81
+ debugMode;
82
+ batchOperationInProgress = false;
83
+ isDisposed = false;
84
+ postBatchCallbacks = /* @__PURE__ */ new Set();
85
+ fieldTracking = false;
86
+ queryListenersMap = /* @__PURE__ */ new Map();
87
+ constructor(nameOrOptions, maybeDataAdapter, maybeOptions) {
88
+ super();
89
+ const name = typeof nameOrOptions === "string" ? nameOrOptions : nameOrOptions?.name || `${this.constructor.name}-${randomId()}`;
90
+ const options = typeof nameOrOptions === "string" ? maybeOptions || {} : nameOrOptions || {};
91
+ const persistence = options.persistence;
92
+ const dataAdapter = maybeDataAdapter || new DefaultDataAdapter({ ...persistence ? { storage: () => persistence } : {} });
93
+ Collection.collections.push(this);
94
+ this.name = name;
95
+ this.options = { ...options };
96
+ this.fieldTracking = this.options.fieldTracking ?? Collection.fieldTracking;
97
+ this.debugMode = this.options.enableDebugMode ?? Collection.debugMode;
98
+ this.isPullingSignal = createSignal(this.options.reactivity, false);
99
+ this.isPushingSignal = createSignal(this.options.reactivity, false);
100
+ this.readySignal = createSignal(this.options.reactivity, false);
101
+ this.backend = dataAdapter.createCollectionBackend(this, this.options.indices ?? []);
102
+ this.backend.isReady().then(() => {
103
+ this.readySignal.set(true);
104
+ }).catch(() => {});
105
+ Collection.onCreationCallbacks.forEach((callback) => callback(this));
106
+ }
107
+ isBatchOperationInProgress() {
108
+ return Collection.batchOperationInProgress || this.batchOperationInProgress;
109
+ }
110
+ /**
111
+ * Checks whether the collection is currently performing a pull operation
112
+ * ⚡️ this function is reactive!
113
+ * (loading data from the persistence adapter).
114
+ * @returns A boolean indicating if the collection is in the process of pulling data.
115
+ */
116
+ isPulling() {
117
+ return this.isPullingSignal.get() ?? false;
118
+ }
119
+ /**
120
+ * Checks whether the collection is currently performing a push operation
121
+ * ⚡️ this function is reactive!
122
+ * (saving data to the persistence adapter).
123
+ * @returns A boolean indicating if the collection is in the process of pushing data.
124
+ */
125
+ isPushing() {
126
+ return this.isPushingSignal.get() ?? false;
127
+ }
128
+ /**
129
+ * Checks whether the collection is currently performing either a pull or push operation,
130
+ * ⚡️ this function is reactive!
131
+ * indicating that it is loading or saving data.
132
+ * @returns A boolean indicating if the collection is in the process of loading or saving data.
133
+ */
134
+ isLoading() {
135
+ const isPulling = this.isPulling();
136
+ const isPushing = this.isPushing();
137
+ return isPulling || isPushing;
138
+ }
139
+ /**
140
+ * Retrieves the current debug mode status of the collection.
141
+ * @returns A boolean indicating whether debug mode is enabled for the collection.
142
+ */
143
+ getDebugMode() {
144
+ return this.debugMode;
145
+ }
146
+ /**
147
+ * Enables or disables debug mode for the collection.
148
+ * When debug mode is enabled, additional debugging information and events are emitted.
149
+ * @param enable - A boolean indicating whether to enable (`true`) or disable (`false`) debug mode.
150
+ */
151
+ setDebugMode(enable) {
152
+ this.debugMode = enable;
153
+ }
154
+ /**
155
+ * Enables or disables field tracking for the collection.
156
+ * @param enable - A boolean indicating whether to enable (`true`) or disable (`false`) field tracking.
157
+ */
158
+ setFieldTracking(enable) {
159
+ this.fieldTracking = enable;
160
+ }
161
+ /**
162
+ * Resolves when the persistence adapter finished initializing
163
+ * and the collection is ready to be used.
164
+ * @returns A promise that resolves when the collection is ready.
165
+ * @example
166
+ * ```ts
167
+ * const collection = new Collection({
168
+ * persistence: // ...
169
+ * })
170
+ * await collection.isReady()
171
+ *
172
+ * collection.insert({ name: 'Item 1' })
173
+ */
174
+ async ready() {
175
+ return this.backend.isReady();
176
+ }
177
+ /**
178
+ * Checks if the collection is ready.
179
+ * ⚡️ this function is reactive!
180
+ * @returns A boolean indicating whether the collection is ready.
181
+ */
182
+ isReady() {
183
+ return this.readySignal.get() ?? false;
184
+ }
185
+ profile(fn, measureFunction) {
186
+ if (!this.debugMode) return fn();
187
+ const startTime = performance.now();
188
+ const handleProfileEnd = (result) => {
189
+ measureFunction(performance.now() - startTime);
190
+ return result;
191
+ };
192
+ const maybePromise = fn();
193
+ return maybePromise instanceof Promise ? maybePromise.then(handleProfileEnd) : handleProfileEnd(maybePromise);
194
+ }
195
+ executeInDebugMode(fn) {
196
+ if (!this.debugMode) return;
197
+ fn((/* @__PURE__ */ new Error()).stack || "");
198
+ }
199
+ transform(item) {
200
+ if (!this.options.transform) return item;
201
+ return this.options.transform(item);
202
+ }
203
+ transformAll(items, fields) {
204
+ if (!this.options.transformAll) return items;
205
+ return this.options.transformAll(deepClone(items), fields);
206
+ }
207
+ getItem(selector, options) {
208
+ const itemsOrPromise = this.getItems(selector, {
209
+ ...options,
210
+ limit: 1
211
+ });
212
+ if (itemsOrPromise instanceof Promise) return itemsOrPromise.then((items) => {
213
+ return items[0] || void 0;
214
+ });
215
+ return itemsOrPromise[0];
216
+ }
217
+ getItems(selector, options) {
218
+ this.emit("getItems", selector);
219
+ return this.profile(() => {
220
+ if (!options?.async) return this.backend.getQueryResult(selector, options);
221
+ this.isPullingSignal.set(true);
222
+ return this.backend.executeQuery(selector, options).finally(() => {
223
+ this.isPullingSignal.set(false);
224
+ });
225
+ }, (measuredTime) => this.executeInDebugMode((callstack) => this.emit("_debug.getItems", callstack, selector, measuredTime)));
226
+ }
227
+ async withPushState(asyncFunction) {
228
+ this.isPushingSignal.set(true);
229
+ try {
230
+ return await asyncFunction();
231
+ } finally {
232
+ this.isPushingSignal.set(false);
233
+ }
234
+ }
235
+ queryListeners(query, listeners) {
236
+ const id = queryId(query.selector, query.options);
237
+ if (listeners != null) return this.queryListenersMap.set(id, listeners);
238
+ return this.queryListenersMap.get(id) ?? 0;
239
+ }
240
+ /**
241
+ * Disposes the collection, unregisters persistence adapters, clears memory, and
242
+ * cleans up all resources used by the collection.
243
+ * @returns A promise that resolves when the collection is disposed.
244
+ */
245
+ async dispose() {
246
+ await this.backend.dispose();
247
+ this.isDisposed = true;
248
+ this.removeAllListeners();
249
+ Collection.collections = Collection.collections.filter((collection) => collection !== this);
250
+ Collection.onDisposeCallbacks.forEach((callback) => callback(this));
251
+ }
252
+ find(selector = {}, options) {
253
+ if (this.isDisposed) throw new Error("Collection is disposed");
254
+ if (selector !== void 0 && (!selector || typeof selector !== "object")) throw new Error("Invalid selector");
255
+ const getTransformedItems = () => {
256
+ const itemsOrPromise = this.getItems(selector, options || {});
257
+ if (itemsOrPromise instanceof Promise) return itemsOrPromise.then((items) => {
258
+ return this.transformAll(items, options?.fields);
259
+ });
260
+ const items = itemsOrPromise;
261
+ return this.transformAll(items, options?.fields);
262
+ };
263
+ const cursor = new Cursor(getTransformedItems, {
264
+ reactive: this.options.reactivity,
265
+ fieldTracking: this.fieldTracking,
266
+ ...options,
267
+ transform: this.transform.bind(this),
268
+ bindEvents: (requery) => {
269
+ const handleRequery = () => {
270
+ if (this.batchOperationInProgress) {
271
+ this.postBatchCallbacks.add(requery);
272
+ return;
273
+ }
274
+ requery();
275
+ };
276
+ const listeners = this.queryListeners({
277
+ selector,
278
+ options
279
+ });
280
+ const didRegister = listeners === 0;
281
+ if (didRegister) this.backend.registerQuery(selector, options || {});
282
+ this.queryListeners({
283
+ selector,
284
+ options
285
+ }, listeners + 1);
286
+ const queryStateChangeCleanup = this.backend.onQueryStateChange(selector, options || {}, (state) => {
287
+ if (state === "error") {
288
+ const queryError = this.backend.getQueryError(selector, options || {}) || /* @__PURE__ */ new Error(`Query on "${this.name}" failed`);
289
+ this.emit("query.error", queryError, selector, options);
290
+ return;
291
+ }
292
+ if (state !== "complete") return;
293
+ handleRequery();
294
+ });
295
+ this.emit("observer.created", selector, options);
296
+ return () => {
297
+ queueMicrotask(() => {
298
+ const newListeners = Math.max(0, this.queryListeners({
299
+ selector,
300
+ options
301
+ }) - 1);
302
+ if (newListeners === 0 && didRegister) this.backend.unregisterQuery(selector, options || {});
303
+ this.queryListeners({
304
+ selector,
305
+ options
306
+ }, newListeners);
307
+ queryStateChangeCleanup();
308
+ this.emit("observer.disposed", selector, options);
309
+ });
310
+ };
311
+ }
312
+ });
313
+ this.emit("find", selector, options, cursor);
314
+ this.executeInDebugMode((callstack) => this.emit("_debug.find", callstack, selector, options, cursor));
315
+ return cursor;
316
+ }
317
+ findOne(selector, options) {
318
+ if (this.isDisposed) throw new Error("Collection is disposed");
319
+ const cursor = this.find(selector, {
320
+ limit: 1,
321
+ ...options
322
+ });
323
+ const handleItems = (items) => {
324
+ const returnValue = items[0] || void 0;
325
+ this.emit("findOne", selector, options, returnValue);
326
+ this.executeInDebugMode((callstack) => this.emit("_debug.findOne", callstack, selector, options, returnValue));
327
+ return returnValue;
328
+ };
329
+ const maybePromise = cursor.fetch();
330
+ return maybePromise instanceof Promise ? maybePromise.then(handleItems) : handleItems(maybePromise);
331
+ }
332
+ batch(callback) {
333
+ if (this.batchOperationInProgress) return callback();
334
+ this.batchOperationInProgress = true;
335
+ const afterBatch = () => {
336
+ this.batchOperationInProgress = false;
337
+ this.postBatchCallbacks.forEach((callback_) => callback_());
338
+ this.postBatchCallbacks.clear();
339
+ };
340
+ let maybePromise;
341
+ try {
342
+ maybePromise = callback();
343
+ } catch (error) {
344
+ afterBatch();
345
+ throw error;
346
+ }
347
+ if (maybePromise && typeof maybePromise.then === "function") return maybePromise.then(() => afterBatch(), (error) => {
348
+ afterBatch();
349
+ throw error;
350
+ });
351
+ else afterBatch();
352
+ }
353
+ onPostBatch(callback) {
354
+ if (this.isDisposed) throw new Error("Collection is disposed");
355
+ if (this.batchOperationInProgress) {
356
+ this.postBatchCallbacks.add(callback);
357
+ return;
358
+ }
359
+ return callback();
360
+ }
361
+ /**
362
+ * Inserts a single item into the collection. Generates a unique ID if not provided.
363
+ * @param item - The item to insert.
364
+ * @returns The ID of the inserted item.
365
+ * @throws {Error} If the collection is disposed or the item has an invalid ID.
366
+ */
367
+ async insert(item) {
368
+ if (this.isDisposed) throw new Error("Collection is disposed");
369
+ if (!item) throw new Error("Invalid item");
370
+ const itemWithId = {
371
+ id: (this.options.primaryKeyGenerator ?? randomId)(item),
372
+ ...item
373
+ };
374
+ this.emit("validate", itemWithId);
375
+ const newItem = await this.withPushState(() => this.backend.insert(itemWithId));
376
+ this.emit("added", newItem);
377
+ this.emit("insert", newItem);
378
+ this.executeInDebugMode((callstack) => this.emit("_debug.insert", callstack, newItem));
379
+ return newItem.id;
380
+ }
381
+ /**
382
+ * Inserts multiple items into the collection. Generates unique IDs for items if not provided.
383
+ * @param items - The items to insert.
384
+ * @returns An array of IDs of the inserted items.
385
+ * @throws {Error} If the collection is disposed or the items are invalid.
386
+ */
387
+ async insertMany(items) {
388
+ if (this.isDisposed) throw new Error("Collection is disposed");
389
+ if (!items) throw new Error("Invalid items");
390
+ if (items.length === 0) return [];
391
+ const ids = [];
392
+ await this.batch(async () => {
393
+ await Promise.all(items.map(async (item) => {
394
+ ids.push(await this.insert(item));
395
+ }));
396
+ });
397
+ return ids;
398
+ }
399
+ /**
400
+ * Updates a single item in the collection that matches the given selector.
401
+ * @param selector - The criteria to select the item to update.
402
+ * @param modifier - The modifications to apply to the item.
403
+ * @param [options] - Optional settings for the update operation.
404
+ * @param [options.upsert] - If `true`, creates a new item if no item matches the selector.
405
+ * @returns The number of items updated (0 or 1).
406
+ * @throws {Error} If the collection is disposed or invalid arguments are provided.
407
+ */
408
+ async updateOne(selector, modifier, options) {
409
+ if (this.isDisposed) throw new Error("Collection is disposed");
410
+ if (!selector) throw new Error("Invalid selector");
411
+ if (!modifier) throw new Error("Invalid modifier");
412
+ const { $setOnInsert, ...restModifier } = modifier;
413
+ const item = await this.getItem(selector, { async: true });
414
+ if (item == null) {
415
+ if (options?.upsert) {
416
+ const newItem = modify({}, {
417
+ ...restModifier,
418
+ $set: {
419
+ ...$setOnInsert,
420
+ ...restModifier.$set
421
+ }
422
+ });
423
+ await this.insert(newItem);
424
+ return 1;
425
+ }
426
+ return 0;
427
+ }
428
+ const modifiedItem = modify(deepClone(item), restModifier);
429
+ this.emit("validate", modifiedItem);
430
+ const changes = await this.withPushState(() => this.backend.updateOne(selector, modifier));
431
+ this.emit("changed", modifiedItem, restModifier);
432
+ this.emit("updateOne", selector, modifier);
433
+ this.executeInDebugMode((callstack) => this.emit("_debug.updateOne", callstack, selector, modifier));
434
+ return changes.length;
435
+ }
436
+ /**
437
+ * Updates multiple items in the collection that match the given selector.
438
+ * @param selector - The criteria to select the items to update.
439
+ * @param modifier - The modifications to apply to the items.
440
+ * @param [options] - Optional settings for the update operation.
441
+ * @param [options.upsert] - If `true`, creates new items if no items match the selector.
442
+ * @returns The number of items updated.
443
+ * @throws {Error} If the collection is disposed or invalid arguments are provided.
444
+ */
445
+ async updateMany(selector, modifier, options) {
446
+ if (this.isDisposed) throw new Error("Collection is disposed");
447
+ if (!selector) throw new Error("Invalid selector");
448
+ if (!modifier) throw new Error("Invalid modifier");
449
+ const { $setOnInsert, ...restModifier } = modifier;
450
+ const items = await this.getItems(selector, { async: true });
451
+ if (items.length === 0) {
452
+ if (options?.upsert) {
453
+ const newItem = modify({}, {
454
+ ...restModifier,
455
+ $set: {
456
+ ...$setOnInsert,
457
+ ...restModifier.$set
458
+ }
459
+ });
460
+ await this.insert(newItem);
461
+ return 1;
462
+ }
463
+ return 0;
464
+ }
465
+ items.forEach((item) => {
466
+ const modifiedItem = modify(deepClone(item), restModifier);
467
+ this.emit("validate", modifiedItem);
468
+ });
469
+ const changes = await this.withPushState(() => this.backend.updateMany(selector, modifier));
470
+ changes.forEach((item) => {
471
+ this.emit("changed", item, restModifier);
472
+ });
473
+ this.emit("updateMany", selector, modifier);
474
+ this.executeInDebugMode((callstack) => this.emit("_debug.updateMany", callstack, selector, modifier));
475
+ return changes.length;
476
+ }
477
+ /**
478
+ * Replaces a single item in the collection that matches the given selector.
479
+ * @param selector - The criteria to select the item to replace.
480
+ * @param replacement - The item to replace the selected item with.
481
+ * @param [options] - Optional settings for the replace operation.
482
+ * @param [options.upsert] - If `true`, creates a new item if no item matches the selector.
483
+ * @returns The number of items replaced (0 or 1).
484
+ * @throws {Error} If the collection is disposed or invalid arguments are provided.
485
+ */
486
+ async replaceOne(selector, replacement, options) {
487
+ if (this.isDisposed) throw new Error("Collection is disposed");
488
+ if (!selector) throw new Error("Invalid selector");
489
+ const item = await this.getItem(selector, { async: true });
490
+ if (item == null) {
491
+ if (options?.upsert) {
492
+ await this.insert(replacement);
493
+ return 1;
494
+ }
495
+ return 0;
496
+ }
497
+ const modifiedItem = {
498
+ id: item.id,
499
+ ...replacement
500
+ };
501
+ this.emit("validate", modifiedItem);
502
+ const changes = await this.withPushState(() => this.backend.replaceOne(selector, replacement));
503
+ this.emit("changed", modifiedItem, replacement);
504
+ this.emit("replaceOne", selector, replacement);
505
+ this.executeInDebugMode((callstack) => this.emit("_debug.replaceOne", callstack, selector, replacement));
506
+ return changes.length;
507
+ }
508
+ /**
509
+ * Removes a single item from the collection that matches the given selector.
510
+ * @param selector - The criteria to select the item to remove.
511
+ * @returns The number of items removed (0 or 1).
512
+ * @throws {Error} If the collection is disposed or invalid arguments are provided.
513
+ */
514
+ async removeOne(selector) {
515
+ if (this.isDisposed) throw new Error("Collection is disposed");
516
+ if (!selector) throw new Error("Invalid selector");
517
+ const removedItems = await this.withPushState(() => this.backend.removeOne(selector));
518
+ this.emit("removed", removedItems[0]);
519
+ this.emit("removeOne", selector);
520
+ this.executeInDebugMode((callstack) => this.emit("_debug.removeOne", callstack, selector));
521
+ return removedItems.length;
522
+ }
523
+ /**
524
+ * Removes multiple items from the collection that match the given selector.
525
+ * @param selector - The criteria to select the items to remove.
526
+ * @returns The number of items removed.
527
+ * @throws {Error} If the collection is disposed or invalid arguments are provided.
528
+ */
529
+ async removeMany(selector) {
530
+ if (this.isDisposed) throw new Error("Collection is disposed");
531
+ if (!selector) throw new Error("Invalid selector");
532
+ const removedItems = await this.withPushState(() => this.backend.removeMany(selector));
533
+ removedItems.forEach((item) => {
534
+ this.emit("removed", item);
535
+ });
536
+ this.emit("removeMany", selector);
537
+ this.executeInDebugMode((callstack) => this.emit("_debug.removeMany", callstack, selector));
538
+ return removedItems.length;
539
+ }
11
540
  };
541
+ //#endregion
542
+ export { Collection as default };
@@ -0,0 +1,11 @@
1
+ //#region src/createStorageAdapter.ts
2
+ /**
3
+ * Creates an StorageAdapter based on the given definition.
4
+ * @param definition - The definition of the StorageAdapter.
5
+ * @returns The created StorageAdapter.
6
+ */
7
+ function createStorageAdapter(definition) {
8
+ return definition;
9
+ }
10
+ //#endregion
11
+ exports.default = createStorageAdapter;
package/dist/index26.mjs CHANGED
@@ -1,30 +1,11 @@
1
- import isFieldExpression from "./index30.mjs";
2
- import serializeValue from "./index11.mjs";
3
- function getMatchingKeys(field, selector) {
4
- const result = { include: null, exclude: null };
5
- const fieldSelector = selector[field];
6
- if (fieldSelector instanceof RegExp)
7
- return result;
8
- if (fieldSelector == null)
9
- return result;
10
- if (isFieldExpression(fieldSelector)) {
11
- if (fieldSelector.$ne != null) {
12
- result.exclude = [serializeValue(fieldSelector.$ne)];
13
- return result;
14
- }
15
- if (Array.isArray(fieldSelector.$in) && fieldSelector.$in.length > 0) {
16
- result.include = fieldSelector.$in.map(serializeValue);
17
- return result;
18
- }
19
- if (Array.isArray(fieldSelector.$nin) && fieldSelector.$nin.length > 0) {
20
- result.exclude = fieldSelector.$nin.map(serializeValue);
21
- return result;
22
- }
23
- return { include: null, exclude: null };
24
- }
25
- result.include = [serializeValue(fieldSelector)];
26
- return result;
1
+ //#region src/createStorageAdapter.ts
2
+ /**
3
+ * Creates an StorageAdapter based on the given definition.
4
+ * @param definition - The definition of the StorageAdapter.
5
+ * @returns The created StorageAdapter.
6
+ */
7
+ function createStorageAdapter(definition) {
8
+ return definition;
27
9
  }
28
- export {
29
- getMatchingKeys as default
30
- };
10
+ //#endregion
11
+ export { createStorageAdapter as default };
@@ -0,0 +1,11 @@
1
+ //#region src/createReactivityAdapter.ts
2
+ /**
3
+ * Creates an ReactivityAdapter based on the given definition.
4
+ * @param definition - The definition of the ReactivityAdapter.
5
+ * @returns The created ReactivityAdapter.
6
+ */
7
+ function createReactivityAdapter(definition) {
8
+ return definition;
9
+ }
10
+ //#endregion
11
+ exports.default = createReactivityAdapter;
package/dist/index27.mjs CHANGED
@@ -1,6 +1,11 @@
1
- function createIndexProvider(definition) {
2
- return definition;
1
+ //#region src/createReactivityAdapter.ts
2
+ /**
3
+ * Creates an ReactivityAdapter based on the given definition.
4
+ * @param definition - The definition of the ReactivityAdapter.
5
+ * @returns The created ReactivityAdapter.
6
+ */
7
+ function createReactivityAdapter(definition) {
8
+ return definition;
3
9
  }
4
- export {
5
- createIndexProvider as default
6
- };
10
+ //#endregion
11
+ export { createReactivityAdapter as default };