@signaldb/core 1.0.0 → 1.2.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 (76) hide show
  1. package/README.md +2 -2
  2. package/dist/.vite/manifest.json +78 -64
  3. package/dist/Collection/index.d.ts +39 -16
  4. package/dist/Collection/types.d.ts +1 -1
  5. package/dist/devtools.d.ts +4 -0
  6. package/dist/index.cjs.js +19 -11
  7. package/dist/index.cjs10.js +27 -6
  8. package/dist/index.cjs11.js +6 -3
  9. package/dist/index.cjs12.js +3 -35
  10. package/dist/index.cjs13.js +141 -16
  11. package/dist/index.cjs14.js +38 -5
  12. package/dist/index.cjs15.js +2 -42
  13. package/dist/index.cjs16.js +5 -11
  14. package/dist/index.cjs17.js +40 -17
  15. package/dist/index.cjs18.js +11 -245
  16. package/dist/index.cjs19.js +16 -67
  17. package/dist/index.cjs2.js +104 -615
  18. package/dist/index.cjs20.js +251 -67
  19. package/dist/index.cjs21.js +68 -8
  20. package/dist/index.cjs22.js +83 -22
  21. package/dist/index.cjs23.js +8 -135
  22. package/dist/index.cjs24.js +25 -16
  23. package/dist/index.cjs25.js +144 -5
  24. package/dist/index.cjs26.js +5 -17
  25. package/dist/index.cjs27.js +15 -21
  26. package/dist/index.cjs28.js +21 -39
  27. package/dist/index.cjs29.js +40 -27
  28. package/dist/index.cjs3.js +669 -136
  29. package/dist/index.cjs30.js +27 -7
  30. package/dist/index.cjs31.js +9 -0
  31. package/dist/index.cjs4.js +166 -63
  32. package/dist/index.cjs5.js +66 -3
  33. package/dist/index.cjs6.js +2 -2
  34. package/dist/index.cjs7.js +2 -2
  35. package/dist/index.cjs8.js +2 -2
  36. package/dist/index.cjs9.js +3 -28
  37. package/dist/index.d.ts +2 -0
  38. package/dist/index.mjs +20 -12
  39. package/dist/index10.mjs +27 -6
  40. package/dist/index11.mjs +6 -3
  41. package/dist/index12.mjs +3 -34
  42. package/dist/index13.mjs +141 -16
  43. package/dist/index14.mjs +37 -5
  44. package/dist/index15.mjs +2 -41
  45. package/dist/index16.mjs +5 -11
  46. package/dist/index17.mjs +39 -17
  47. package/dist/index18.mjs +11 -244
  48. package/dist/index19.mjs +16 -66
  49. package/dist/index2.mjs +80 -615
  50. package/dist/index20.mjs +251 -67
  51. package/dist/index21.mjs +67 -8
  52. package/dist/index22.mjs +82 -22
  53. package/dist/index23.mjs +8 -135
  54. package/dist/index24.mjs +25 -15
  55. package/dist/index25.mjs +144 -5
  56. package/dist/index26.mjs +5 -17
  57. package/dist/index27.mjs +15 -21
  58. package/dist/index28.mjs +21 -39
  59. package/dist/index29.mjs +40 -27
  60. package/dist/index3.mjs +669 -136
  61. package/dist/index30.mjs +27 -7
  62. package/dist/index31.mjs +10 -0
  63. package/dist/index4.mjs +166 -62
  64. package/dist/index5.mjs +65 -3
  65. package/dist/index6.mjs +2 -2
  66. package/dist/index7.mjs +2 -2
  67. package/dist/index8.mjs +2 -2
  68. package/dist/index9.mjs +3 -28
  69. package/dist/persistence/combinePersistenceAdapters.d.ts +7 -7
  70. package/dist/types/MemoryAdapter.d.ts +2 -2
  71. package/dist/utils/EventEmitter.d.ts +75 -0
  72. package/dist/utils/deepClone.d.ts +2 -2
  73. package/dist/utils/set.d.ts +2 -2
  74. package/dist/utils/uniqueBy.d.ts +2 -2
  75. package/package.json +1 -1
  76. package/dist/types/EventEmitter.d.ts +0 -25
@@ -1,80 +1,264 @@
1
1
  "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
2
5
  Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
3
- const index = require("./index.cjs2.js");
4
- const combinePersistenceAdapters = require("./index.cjs4.js");
5
- const createPersistenceAdapter = require("./index.cjs7.js");
6
- const createSignal = require("./index.cjs17.js");
7
- function createReplicationAdapter(options) {
8
- return createPersistenceAdapter({
9
- async register(onChange) {
10
- if (!options.registerRemoteChange)
11
- return;
12
- await options.registerRemoteChange(onChange);
13
- },
14
- load: () => options.pull(),
15
- save: (items, changes) => {
16
- if (!options.push)
17
- throw new Error("Pushing is not configured for this collection. Try to pass a `push` function to the collection options.");
18
- return options.push(changes, items);
19
- }
20
- });
6
+ const sortItems = require("./index.cjs23.js");
7
+ const project = require("./index.cjs24.js");
8
+ const Observer = require("./index.cjs25.js");
9
+ function isInReactiveScope(reactivity) {
10
+ if (!reactivity)
11
+ return false;
12
+ if (!reactivity.isInScope)
13
+ return true;
14
+ return reactivity.isInScope();
21
15
  }
22
- class ReplicatedCollection extends index.default {
16
+ class Cursor {
23
17
  /**
24
- * Creates a new instance of the `ReplicatedCollection` class.
25
- * Sets up the replication adapter, combining it with an optional persistence adapter, and
26
- * initializes signals for tracking remote pull and push operations.
27
- * @param options - The configuration options for the replicated collection.
28
- * @param options.pull - A function to fetch data from the remote source.
29
- * @param options.push - An optional function to send changes and items to the remote source.
30
- * @param options.registerRemoteChange - An optional function to register a listener for remote changes.
31
- * @param options.persistence - An optional persistence adapter to combine with replication.
32
- * @param options.reactivity - A reactivity adapter for observing changes in the collection.
33
- * @param options.transform - A transformation function to apply to items when retrieving them.
34
- * @param options.indices - An array of index providers for optimized querying.
35
- * @param options.enableDebugMode - A boolean to enable or disable debug mode.
18
+ * Creates a new instance of the `Cursor` class.
19
+ * Provides utilities for querying, observing, and transforming items from a collection.
20
+ * @template T - The type of the items in the collection.
21
+ * @template U - The transformed item type after applying transformations (default is T).
22
+ * @param getItems - A function that retrieves the filtered list of items.
23
+ * @param options - Optional configuration for the cursor.
24
+ * @param options.transform - A transformation function to apply to each item when retrieving them.
25
+ * @param options.bindEvents - A function to bind reactivity events for the cursor, which should return a cleanup function.
26
+ * @param options.fields - A projection object defining which fields of the item should be included or excluded.
27
+ * @param options.sort - A sort specifier to determine the order of the items.
28
+ * @param options.skip - The number of items to skip from the beginning of the result set.
29
+ * @param options.limit - The maximum number of items to return in the result set.
30
+ * @param options.reactive - A reactivity adapter to enable observing changes in the cursor's result set.
31
+ * @param options.fieldTracking - A boolean to enable fine-grained field tracking for reactivity.
36
32
  */
37
- constructor(options) {
38
- var _a, _b;
39
- const replicationAdapter = createReplicationAdapter({
40
- registerRemoteChange: options.registerRemoteChange,
41
- pull: async () => {
42
- this.isPullingRemoteSignal.set(true);
43
- try {
44
- return await options.pull();
45
- } finally {
46
- this.isPullingRemoteSignal.set(false);
47
- }
48
- },
49
- push: options.push ? async (changes, items) => {
50
- if (!options.push)
51
- throw new Error("Pushing is not configured for this collection. Try to pass a `push` function to the collection options.");
52
- this.isPushingRemoteSignal.set(true);
53
- try {
54
- await options.push(changes, items);
55
- } finally {
56
- this.isPushingRemoteSignal.set(false);
33
+ constructor(getItems, options) {
34
+ __publicField(this, "observer");
35
+ __publicField(this, "getFilteredItems");
36
+ __publicField(this, "options");
37
+ __publicField(this, "onCleanupCallbacks", []);
38
+ this.getFilteredItems = getItems;
39
+ this.options = options || {};
40
+ }
41
+ addGetters(item) {
42
+ if (!isInReactiveScope(this.options.reactive))
43
+ return item;
44
+ const depend = this.depend.bind(this);
45
+ return Object.entries(item).reduce((memo, [key, value]) => {
46
+ Object.defineProperty(memo, key, {
47
+ get() {
48
+ depend({
49
+ changedField: (notify) => (changedItem, changedFieldName) => {
50
+ if (changedFieldName !== key || changedItem.id !== item.id)
51
+ return;
52
+ notify();
53
+ }
54
+ });
55
+ return value;
56
+ },
57
+ enumerable: true,
58
+ configurable: true
59
+ });
60
+ return memo;
61
+ }, {});
62
+ }
63
+ transform(rawItem) {
64
+ const item = this.options.fieldTracking ? this.addGetters(rawItem) : rawItem;
65
+ if (!this.options.transform)
66
+ return item;
67
+ return this.options.transform(item);
68
+ }
69
+ getItems() {
70
+ const items = this.getFilteredItems();
71
+ const { sort, skip, limit } = this.options;
72
+ const sorted = sort ? sortItems(items, sort) : items;
73
+ const skipped = skip ? sorted.slice(skip) : sorted;
74
+ const limited = limit ? skipped.slice(0, limit) : skipped;
75
+ const idExcluded = this.options.fields && this.options.fields.id === 0;
76
+ return limited.map((item) => {
77
+ if (!this.options.fields)
78
+ return item;
79
+ return {
80
+ ...idExcluded ? {} : { id: item.id },
81
+ ...project(item, this.options.fields)
82
+ };
83
+ });
84
+ }
85
+ depend(changeEvents) {
86
+ if (!this.options.reactive)
87
+ return;
88
+ if (!isInReactiveScope(this.options.reactive))
89
+ return;
90
+ const signal = this.options.reactive.create();
91
+ signal.depend();
92
+ const notify = () => signal.notify();
93
+ function buildNotifier(event) {
94
+ const eventHandler = changeEvents[event];
95
+ return (...args) => {
96
+ if (eventHandler === true) {
97
+ notify();
98
+ return;
57
99
  }
58
- } : void 0
100
+ if (typeof eventHandler !== "function")
101
+ return;
102
+ eventHandler(notify)(...args);
103
+ };
104
+ }
105
+ const stop = this.observeRawChanges({
106
+ added: buildNotifier("added"),
107
+ addedBefore: buildNotifier("addedBefore"),
108
+ changed: buildNotifier("changed"),
109
+ changedField: buildNotifier("changedField"),
110
+ movedBefore: buildNotifier("movedBefore"),
111
+ removed: buildNotifier("removed")
112
+ }, true);
113
+ if (this.options.reactive.onDispose) {
114
+ this.options.reactive.onDispose(() => stop(), signal);
115
+ }
116
+ this.onCleanup(stop);
117
+ }
118
+ ensureObserver() {
119
+ if (!this.observer) {
120
+ const observer = new Observer(() => {
121
+ const requery = () => {
122
+ observer.runChecks(this.getItems());
123
+ };
124
+ const cleanup = this.options.bindEvents && this.options.bindEvents(requery);
125
+ return () => {
126
+ if (cleanup)
127
+ cleanup();
128
+ };
129
+ });
130
+ this.onCleanup(() => observer.stop());
131
+ this.observer = observer;
132
+ }
133
+ return this.observer;
134
+ }
135
+ observeRawChanges(callbacks, skipInitial = false) {
136
+ const observer = this.ensureObserver();
137
+ observer.addCallbacks(callbacks, skipInitial);
138
+ observer.runChecks(this.getItems());
139
+ return () => {
140
+ observer.removeCallbacks(callbacks);
141
+ if (!observer.isEmpty())
142
+ return;
143
+ observer.stop();
144
+ this.observer = void 0;
145
+ };
146
+ }
147
+ /**
148
+ * Cleans up all resources associated with the cursor, such as reactive bindings
149
+ * and event listeners. This method should be called when the cursor is no longer needed
150
+ * to prevent memory leaks.
151
+ */
152
+ cleanup() {
153
+ this.onCleanupCallbacks.forEach((callback) => {
154
+ callback();
59
155
  });
60
- const persistenceAdapter = (options === null || options === void 0 ? void 0 : options.persistence) ? combinePersistenceAdapters.default(replicationAdapter, options.persistence) : replicationAdapter;
61
- super(Object.assign(Object.assign({}, options), { persistence: persistenceAdapter }));
62
- this.isPullingRemoteSignal = createSignal((_a = options.reactivity) === null || _a === void 0 ? void 0 : _a.create(), false);
63
- this.isPushingRemoteSignal = createSignal((_b = options.reactivity) === null || _b === void 0 ? void 0 : _b.create(), false);
156
+ this.onCleanupCallbacks = [];
64
157
  }
65
158
  /**
66
- * Checks whether the collection is currently performing any loading operation,
67
- * including pulling or pushing data from/to the remote source, or standard
68
- * persistence adapter operations.
159
+ * Registers a cleanup callback to be executed when the `cleanup` method is called.
160
+ * Useful for managing resources and ensuring proper cleanup of bindings or listeners.
161
+ * @param callback - A function to be executed during cleanup.
162
+ */
163
+ onCleanup(callback) {
164
+ this.onCleanupCallbacks.push(callback);
165
+ }
166
+ /**
167
+ * Iterates over each item in the cursor's result set, applying the provided callback
168
+ * function to each transformed item.
69
169
  * ⚡️ this function is reactive!
70
- * @returns A boolean indicating if the collection is currently loading or synchronizing.
170
+ * @param callback - A function to execute for each item in the result set.
171
+ * @param callback.item - The transformed item.
172
+ */
173
+ forEach(callback) {
174
+ const items = this.getItems();
175
+ this.depend({
176
+ addedBefore: true,
177
+ removed: true,
178
+ movedBefore: true,
179
+ ...this.options.fieldTracking ? {} : { changed: true }
180
+ });
181
+ items.forEach((item) => {
182
+ callback(this.transform(item));
183
+ });
184
+ }
185
+ /**
186
+ * Creates a new array populated with the results of applying the provided callback
187
+ * function to each transformed item in the cursor's result set.
188
+ * ⚡️ this function is reactive!
189
+ * @template V - The type of the items in the resulting array.
190
+ * @param callback - A function to execute for each item in the result set.
191
+ * @param callback.item - The transformed item.
192
+ * @returns An array of results after applying the callback to each item.
193
+ */
194
+ map(callback) {
195
+ const results = [];
196
+ this.forEach((item) => {
197
+ results.push(callback(item));
198
+ });
199
+ return results;
200
+ }
201
+ /**
202
+ * Fetches all transformed items from the cursor's result set as an array.
203
+ * Automatically applies filtering, sorting, and limiting as per the cursor's options.
204
+ * ⚡️ this function is reactive!
205
+ * @returns An array of transformed items in the result set.
206
+ */
207
+ fetch() {
208
+ return this.map((item) => item);
209
+ }
210
+ /**
211
+ * Counts the total number of items in the cursor's result set after applying
212
+ * filtering and other criteria.
213
+ * ⚡️ this function is reactive!
214
+ * @returns The total number of items in the result set.
215
+ */
216
+ count() {
217
+ const items = this.getItems();
218
+ this.depend({
219
+ added: true,
220
+ removed: true
221
+ });
222
+ return items.length;
223
+ }
224
+ /**
225
+ * Observes changes to the cursor's result set and triggers the specified callbacks
226
+ * when items are added, removed, or updated. Supports reactivity and transformation.
227
+ * @param callbacks - An object containing the callback functions to handle different change events.
228
+ * @param callbacks.added - Triggered when an item is added to the result set.
229
+ * @param callbacks.removed - Triggered when an item is removed from the result set.
230
+ * @param callbacks.changed - Triggered when an item in the result set is modified.
231
+ * @param callbacks.addedBefore - Triggered when an item is added before another item in the result set.
232
+ * @param callbacks.movedBefore - Triggered when an item is moved before another item in the result set.
233
+ * @param callbacks.changedField - Triggered when a specific field of an item changes.
234
+ * @param skipInitial - A boolean indicating whether to skip the initial notification of the current result set.
235
+ * @returns A function to stop observing changes.
236
+ */
237
+ observeChanges(callbacks, skipInitial = false) {
238
+ return this.observeRawChanges(Object.entries(callbacks).reduce((memo, [callbackName, callback]) => {
239
+ if (!callback)
240
+ return memo;
241
+ return {
242
+ ...memo,
243
+ [callbackName]: (item, before) => {
244
+ const transformedValue = this.transform(item);
245
+ const hasBeforeParameter = before !== void 0;
246
+ const transformedBeforeValue = hasBeforeParameter && before ? this.transform(before) : null;
247
+ return callback(transformedValue, ...hasBeforeParameter ? [transformedBeforeValue] : []);
248
+ }
249
+ };
250
+ }, {}), skipInitial);
251
+ }
252
+ /**
253
+ * Forces the cursor to re-evaluate its result set by re-fetching items
254
+ * from the collection. This is useful when the underlying data or query
255
+ * criteria have changed, and you want to ensure the cursor reflects the latest state.
71
256
  */
72
- isLoading() {
73
- const isPullingRemote = this.isPullingRemoteSignal.get();
74
- const isPushingRemote = this.isPushingRemoteSignal.get();
75
- const isLoading = super.isLoading();
76
- return isPullingRemote || isPushingRemote || isLoading;
257
+ requery() {
258
+ if (!this.observer)
259
+ return;
260
+ this.observer.runChecks(this.getItems());
77
261
  }
78
262
  }
79
- exports.createReplicationAdapter = createReplicationAdapter;
80
- exports.default = ReplicatedCollection;
263
+ exports.default = Cursor;
264
+ exports.isInReactiveScope = isInReactiveScope;
@@ -1,10 +1,70 @@
1
1
  "use strict";
2
- const fastSort = require("fast-sort");
3
- const get = require("./index.cjs26.js");
4
- function sortItems(items, sortFields) {
5
- return fastSort.sort(items).by(Object.entries(sortFields).map(([key, value]) => {
6
- const order = value === 1 ? "asc" : "desc";
7
- return { [order]: (i) => get(i, key) };
8
- }));
2
+ Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
3
+ const intersection = require("./index.cjs26.js");
4
+ function getMergedIndexInfo(indexProviders, selector) {
5
+ return indexProviders.reduce((memo, indexProvider) => {
6
+ const info = indexProvider.query(selector);
7
+ if (!info.matched)
8
+ return memo;
9
+ const optimizedSelector = Object.fromEntries(Object.entries(memo.optimizedSelector).filter(([key]) => !info.fields.includes(key)));
10
+ return {
11
+ matched: true,
12
+ positions: [...new Set(memo.matched ? intersection(memo.positions, info.positions) : info.positions)],
13
+ optimizedSelector
14
+ };
15
+ }, {
16
+ matched: false,
17
+ positions: [],
18
+ optimizedSelector: { ...selector }
19
+ });
9
20
  }
10
- module.exports = sortItems;
21
+ function getIndexInfo(indexProviders, selector) {
22
+ if (selector == null || Object.keys(selector).length <= 0) {
23
+ return { matched: false, positions: [], optimizedSelector: selector };
24
+ }
25
+ const { $and, $or, ...rest } = selector;
26
+ const flatInfo = getMergedIndexInfo(indexProviders, rest);
27
+ let { matched, positions } = flatInfo;
28
+ const newSelector = flatInfo.optimizedSelector;
29
+ if (Array.isArray($and)) {
30
+ const $andNew = [];
31
+ for (const sel of $and) {
32
+ const { matched: selMatched, positions: selPositions, optimizedSelector } = getIndexInfo(indexProviders, sel);
33
+ if (selMatched) {
34
+ positions = matched ? intersection(positions, selPositions) : selPositions;
35
+ matched = true;
36
+ if (Object.keys(optimizedSelector).length > 0) {
37
+ $andNew.push(optimizedSelector);
38
+ }
39
+ } else {
40
+ $andNew.push(sel);
41
+ }
42
+ }
43
+ if ($andNew.length > 0)
44
+ newSelector.$and = $andNew;
45
+ }
46
+ if (Array.isArray($or)) {
47
+ const $orNew = [];
48
+ for (const sel of $or) {
49
+ const { matched: selMatched, positions: selPositions, optimizedSelector } = getIndexInfo(indexProviders, sel);
50
+ if (selMatched) {
51
+ positions = [.../* @__PURE__ */ new Set([...positions, ...selPositions])];
52
+ matched = true;
53
+ if (Object.keys(optimizedSelector).length > 0) {
54
+ $orNew.push(optimizedSelector);
55
+ }
56
+ } else {
57
+ $orNew.push(sel);
58
+ }
59
+ }
60
+ if ($orNew.length > 0)
61
+ newSelector.$or = $orNew;
62
+ }
63
+ return {
64
+ matched,
65
+ positions: positions || [],
66
+ optimizedSelector: newSelector
67
+ };
68
+ }
69
+ exports.default = getIndexInfo;
70
+ exports.getMergedIndexInfo = getMergedIndexInfo;
@@ -1,27 +1,88 @@
1
1
  "use strict";
2
- const get = require("./index.cjs26.js");
3
- const set = require("./index.cjs29.js");
4
- function project(item, fields) {
5
- const allFieldsDeactivated = Object.values(fields).every((value) => value === 0);
6
- if (allFieldsDeactivated) {
7
- const result2 = Object.assign({}, item);
8
- Object.keys(fields).forEach((key) => {
9
- const fieldValue = get(item, key);
10
- if (fieldValue === void 0)
2
+ var __defProp = Object.defineProperty;
3
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
4
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
5
+ Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
6
+ const index = require("./index.cjs3.js");
7
+ const combinePersistenceAdapters = require("./index.cjs5.js");
8
+ const createPersistenceAdapter = require("./index.cjs8.js");
9
+ const createSignal = require("./index.cjs19.js");
10
+ function createReplicationAdapter(options) {
11
+ return createPersistenceAdapter({
12
+ async register(onChange) {
13
+ if (!options.registerRemoteChange)
11
14
  return;
12
- set(result2, key, void 0, true);
15
+ await options.registerRemoteChange(onChange);
16
+ },
17
+ load: () => options.pull(),
18
+ save: (items, changes) => {
19
+ if (!options.push)
20
+ throw new Error("Pushing is not configured for this collection. Try to pass a `push` function to the collection options.");
21
+ return options.push(changes, items);
22
+ }
23
+ });
24
+ }
25
+ class ReplicatedCollection extends index.default {
26
+ /**
27
+ * Creates a new instance of the `ReplicatedCollection` class.
28
+ * Sets up the replication adapter, combining it with an optional persistence adapter, and
29
+ * initializes signals for tracking remote pull and push operations.
30
+ * @param options - The configuration options for the replicated collection.
31
+ * @param options.pull - A function to fetch data from the remote source.
32
+ * @param options.push - An optional function to send changes and items to the remote source.
33
+ * @param options.registerRemoteChange - An optional function to register a listener for remote changes.
34
+ * @param options.persistence - An optional persistence adapter to combine with replication.
35
+ * @param options.reactivity - A reactivity adapter for observing changes in the collection.
36
+ * @param options.transform - A transformation function to apply to items when retrieving them.
37
+ * @param options.indices - An array of index providers for optimized querying.
38
+ * @param options.enableDebugMode - A boolean to enable or disable debug mode.
39
+ */
40
+ constructor(options) {
41
+ var _a, _b;
42
+ const replicationAdapter = createReplicationAdapter({
43
+ registerRemoteChange: options.registerRemoteChange,
44
+ pull: async () => {
45
+ this.isPullingRemoteSignal.set(true);
46
+ try {
47
+ return await options.pull();
48
+ } finally {
49
+ this.isPullingRemoteSignal.set(false);
50
+ }
51
+ },
52
+ push: options.push ? async (changes, items) => {
53
+ if (!options.push)
54
+ throw new Error("Pushing is not configured for this collection. Try to pass a `push` function to the collection options.");
55
+ this.isPushingRemoteSignal.set(true);
56
+ try {
57
+ await options.push(changes, items);
58
+ } finally {
59
+ this.isPushingRemoteSignal.set(false);
60
+ }
61
+ } : void 0
62
+ });
63
+ const persistenceAdapter = (options == null ? void 0 : options.persistence) ? combinePersistenceAdapters.default(replicationAdapter, options.persistence) : replicationAdapter;
64
+ super({
65
+ ...options,
66
+ persistence: persistenceAdapter
13
67
  });
14
- return result2;
68
+ __publicField(this, "isPullingRemoteSignal");
69
+ __publicField(this, "isPushingRemoteSignal");
70
+ this.isPullingRemoteSignal = createSignal((_a = options.reactivity) == null ? void 0 : _a.create(), false);
71
+ this.isPushingRemoteSignal = createSignal((_b = options.reactivity) == null ? void 0 : _b.create(), false);
72
+ }
73
+ /**
74
+ * Checks whether the collection is currently performing any loading operation,
75
+ * including pulling or pushing data from/to the remote source, or standard
76
+ * persistence adapter operations.
77
+ * ⚡️ this function is reactive!
78
+ * @returns A boolean indicating if the collection is currently loading or synchronizing.
79
+ */
80
+ isLoading() {
81
+ const isPullingRemote = this.isPullingRemoteSignal.get();
82
+ const isPushingRemote = this.isPushingRemoteSignal.get();
83
+ const isLoading = super.isLoading();
84
+ return isPullingRemote || isPushingRemote || isLoading;
15
85
  }
16
- const result = {};
17
- Object.entries(fields).forEach(([key, value]) => {
18
- const fieldValue = get(item, key);
19
- if (fieldValue === void 0)
20
- return;
21
- if (fieldValue == null && value !== 1)
22
- return;
23
- set(result, key, value === 1 ? fieldValue : void 0);
24
- });
25
- return result;
26
86
  }
27
- module.exports = project;
87
+ exports.createReplicationAdapter = createReplicationAdapter;
88
+ exports.default = ReplicatedCollection;
@@ -1,137 +1,10 @@
1
1
  "use strict";
2
- const isEqual = require("./index.cjs9.js");
3
- const uniqueBy = require("./index.cjs30.js");
4
- class Observer {
5
- /**
6
- * Creates a new instance of the `Observer` class.
7
- * Sets up event bindings and initializes the callbacks for tracking changes in a collection.
8
- * @param bindEvents - A function to bind external events to the observer. Must return a cleanup function to unbind those events.
9
- */
10
- constructor(bindEvents) {
11
- this.previousItems = [];
12
- this.callbacks = {
13
- added: [],
14
- addedBefore: [],
15
- changed: [],
16
- changedField: [],
17
- movedBefore: [],
18
- removed: []
19
- };
20
- this.unbindEvents = bindEvents();
21
- }
22
- call(event, ...args) {
23
- this.callbacks[event].forEach(({ callback, options }) => {
24
- if (!options.skipInitial || !options.isInitial) {
25
- callback(...args);
26
- }
27
- });
28
- }
29
- hasCallbacks(events) {
30
- return events.some((event) => this.callbacks[event].length > 0);
31
- }
32
- /**
33
- * Determines if the observer has no active callbacks registered for any events.
34
- * @returns A boolean indicating whether the observer is empty (i.e., no callbacks are registered).
35
- */
36
- isEmpty() {
37
- return !this.hasCallbacks([
38
- "added",
39
- "addedBefore",
40
- "changed",
41
- "changedField",
42
- "movedBefore",
43
- "removed"
44
- ]);
45
- }
46
- /**
47
- * Compares the previous state of items with the new state and triggers the appropriate callbacks
48
- * for events such as added, removed, changed, or moved items.
49
- * @param newItems - The new list of items to compare against the previous state.
50
- */
51
- runChecks(newItems) {
52
- const oldItemsMap = new Map(this.previousItems.map((item, index) => [
53
- item.id,
54
- { item, index, beforeItem: this.previousItems[index + 1] || null }
55
- ]));
56
- const newItemsMap = new Map(newItems.map((item, index) => [
57
- item.id,
58
- { item, index, beforeItem: newItems[index + 1] || null }
59
- ]));
60
- if (this.hasCallbacks(["changed", "changedField", "movedBefore", "removed"])) {
61
- oldItemsMap.forEach(({ item: oldItem, index, beforeItem: oldBeforeItem }) => {
62
- var _a;
63
- const newItem = newItemsMap.get(oldItem.id);
64
- if (newItem) {
65
- if (this.hasCallbacks(["changed", "changedField"])) {
66
- if (!isEqual(newItem.item, oldItem)) {
67
- this.call("changed", newItem.item);
68
- if (this.hasCallbacks(["changedField"])) {
69
- const keys = uniqueBy([
70
- ...Object.keys(newItem.item),
71
- ...Object.keys(oldItem)
72
- ], (value) => value);
73
- keys.forEach((key) => {
74
- if (isEqual(newItem.item[key], oldItem[key]))
75
- return;
76
- this.call("changedField", newItem.item, key, oldItem[key], newItem.item[key]);
77
- });
78
- }
79
- }
80
- }
81
- if (newItem.index !== index && ((_a = newItem.beforeItem) === null || _a === void 0 ? void 0 : _a.id) !== (oldBeforeItem === null || oldBeforeItem === void 0 ? void 0 : oldBeforeItem.id)) {
82
- this.call("movedBefore", newItem.item, newItem.beforeItem);
83
- }
84
- } else {
85
- this.call("removed", oldItem);
86
- }
87
- });
88
- }
89
- if (this.hasCallbacks(["added", "addedBefore"])) {
90
- newItems.forEach((newItem, index) => {
91
- const oldItem = oldItemsMap.get(newItem.id);
92
- if (oldItem)
93
- return;
94
- this.call("added", newItem);
95
- this.call("addedBefore", newItem, newItems[index + 1] || null);
96
- });
97
- }
98
- this.previousItems = newItems;
99
- Object.keys(this.callbacks).forEach((key) => {
100
- const event = key;
101
- const callbacks = this.callbacks[event];
102
- this.callbacks[event] = callbacks.map((callback) => Object.assign(Object.assign({}, callback), { options: Object.assign(Object.assign({}, callback.options), { isInitial: false }) }));
103
- });
104
- }
105
- /**
106
- * Stops the observer by unbinding all events and cleaning up resources.
107
- */
108
- stop() {
109
- this.unbindEvents();
110
- }
111
- /**
112
- * Registers callbacks for specific events to observe changes in the collection.
113
- * @param callbacks - An object containing the callbacks for various events (e.g., 'added', 'removed').
114
- * @param skipInitial - A boolean indicating whether to skip invoking the callbacks for the initial state of the collection.
115
- */
116
- addCallbacks(callbacks, skipInitial = false) {
117
- Object.keys(callbacks).forEach((key) => {
118
- const typedKey = key;
119
- this.callbacks[typedKey].push({
120
- callback: callbacks[typedKey],
121
- options: { skipInitial, isInitial: true }
122
- });
123
- });
124
- }
125
- /**
126
- * Removes the specified callbacks for specific events, unregistering them from the observer.
127
- * @param callbacks - An object containing the callbacks to be removed for various events.
128
- */
129
- removeCallbacks(callbacks) {
130
- Object.keys(callbacks).forEach((key) => {
131
- const typedKey = key;
132
- const index = this.callbacks[typedKey].findIndex(({ callback }) => callback === callbacks[typedKey]);
133
- this.callbacks[typedKey].splice(index, 1);
134
- });
135
- }
2
+ const fastSort = require("fast-sort");
3
+ const get = require("./index.cjs27.js");
4
+ function sortItems(items, sortFields) {
5
+ return fastSort.sort(items).by(Object.entries(sortFields).map(([key, value]) => {
6
+ const order = value === 1 ? "asc" : "desc";
7
+ return { [order]: (i) => get(i, key) };
8
+ }));
136
9
  }
137
- module.exports = Observer;
10
+ module.exports = sortItems;