@signaldb/core 2.0.0-beta.13 → 2.0.0-beta.14

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 (82) hide show
  1. package/dist/.vite/manifest.json +72 -46
  2. package/dist/AsyncDataAdapter.d.ts +11 -2
  3. package/dist/Collection/Cursor.d.ts +11 -1
  4. package/dist/Collection/Observer.d.ts +31 -0
  5. package/dist/DataAdapter.d.ts +15 -2
  6. package/dist/WorkerDataAdapter.d.ts +25 -2
  7. package/dist/WorkerDataAdapterHost.d.ts +2 -0
  8. package/dist/index.cjs.js +15 -15
  9. package/dist/index.d.ts +2 -0
  10. package/dist/index.mjs +15 -15
  11. package/dist/index10.cjs.js +7 -19
  12. package/dist/index10.mjs +7 -19
  13. package/dist/index11.cjs.js +19 -41
  14. package/dist/index11.mjs +19 -41
  15. package/dist/index12.cjs.js +41 -18
  16. package/dist/index12.mjs +41 -18
  17. package/dist/index13.cjs.js +18 -41
  18. package/dist/index13.mjs +18 -41
  19. package/dist/index14.cjs.js +39 -80
  20. package/dist/index14.mjs +39 -80
  21. package/dist/index15.cjs.js +82 -11
  22. package/dist/index15.mjs +82 -11
  23. package/dist/index16.cjs.js +11 -132
  24. package/dist/index16.mjs +11 -132
  25. package/dist/index17.cjs.js +127 -38
  26. package/dist/index17.mjs +127 -38
  27. package/dist/index18.cjs.js +43 -11
  28. package/dist/index18.mjs +43 -11
  29. package/dist/index19.cjs.js +10 -18
  30. package/dist/index19.mjs +11 -19
  31. package/dist/index20.cjs.js +19 -33
  32. package/dist/index20.mjs +19 -33
  33. package/dist/index21.cjs.js +33 -31
  34. package/dist/index21.mjs +33 -31
  35. package/dist/index22.cjs.js +31 -21
  36. package/dist/index22.mjs +31 -21
  37. package/dist/index23.cjs.js +16 -14
  38. package/dist/index23.mjs +16 -14
  39. package/dist/index24.cjs.js +15 -338
  40. package/dist/index24.mjs +15 -338
  41. package/dist/index25.cjs.js +122 -554
  42. package/dist/index25.mjs +121 -554
  43. package/dist/index26.cjs.js +34 -7
  44. package/dist/index26.mjs +34 -7
  45. package/dist/index27.cjs.js +339 -7
  46. package/dist/index27.mjs +339 -7
  47. package/dist/index28.cjs.js +550 -83
  48. package/dist/index28.mjs +550 -82
  49. package/dist/index29.cjs.js +8 -422
  50. package/dist/index29.mjs +8 -422
  51. package/dist/index30.cjs.js +7 -68
  52. package/dist/index30.mjs +7 -68
  53. package/dist/index31.cjs.js +86 -28
  54. package/dist/index31.mjs +85 -28
  55. package/dist/index32.cjs.js +446 -278
  56. package/dist/index32.mjs +446 -278
  57. package/dist/index33.cjs.js +68 -17
  58. package/dist/index33.mjs +68 -17
  59. package/dist/index34.cjs.js +460 -304
  60. package/dist/index34.mjs +460 -304
  61. package/dist/index35.cjs.js +14 -532
  62. package/dist/index35.mjs +14 -532
  63. package/dist/index36.cjs.js +389 -0
  64. package/dist/index36.mjs +389 -0
  65. package/dist/index37.cjs.js +539 -0
  66. package/dist/index37.mjs +539 -0
  67. package/dist/index4.cjs.js +199 -140
  68. package/dist/index4.mjs +195 -140
  69. package/dist/index5.cjs.js +152 -253
  70. package/dist/index5.mjs +152 -253
  71. package/dist/index6.cjs.js +267 -89
  72. package/dist/index6.mjs +267 -89
  73. package/dist/index7.cjs.js +121 -29
  74. package/dist/index7.mjs +121 -29
  75. package/dist/index8.cjs.js +29 -8
  76. package/dist/index8.mjs +29 -8
  77. package/dist/index9.cjs.js +8 -7
  78. package/dist/index9.mjs +8 -7
  79. package/dist/utils/incrementalQueryUpdate.d.ts +60 -0
  80. package/dist/utils/projectItems.d.ts +12 -0
  81. package/dist/utils/queryDelta.d.ts +83 -0
  82. package/package.json +1 -1
@@ -1,288 +1,187 @@
1
- const require_Observer = require("./index4.cjs.js");
2
- //#region src/Collection/Cursor.ts
1
+ const require_isEqual = require("./index2.cjs.js");
2
+ const require_uniqueBy = require("./index3.cjs.js");
3
+ const require_queryDelta = require("./index4.cjs.js");
4
+ //#region src/Collection/Observer.ts
3
5
  /**
4
- * Checks if the current scope is reactive, considering the provided reactivity adapter.
5
- * @param reactivity - The reactivity adapter or a boolean indicating whether reactivity is enabled.
6
- * @returns A boolean indicating if the current scope is reactive.
6
+ * Represents an observer that tracks changes in a collection of items and triggers
7
+ * callbacks for various events such as addition, removal, and modification of items.
8
+ * @template T - The type of the items being observed, which must include an `id` field.
7
9
  */
8
- function isInReactiveScope(reactivity) {
9
- if (!reactivity) return false;
10
- if (!reactivity.isInScope) return true;
11
- return reactivity.isInScope();
12
- }
13
- /**
14
- * Represents a cursor for querying and observing a filtered, sorted, and transformed
15
- * subset of items from a collection. Supports reactivity and field tracking.
16
- * @template T - The type of the items in the collection.
17
- * @template U - The transformed item type after applying transform (default is T).
18
- */
19
- var Cursor = class {
20
- observer;
21
- getItems;
22
- options;
23
- onCleanupCallbacks = [];
10
+ var Observer = class {
11
+ previousItems = [];
12
+ callbacks;
13
+ unbindEvents;
24
14
  /**
25
- * Creates a new instance of the `Cursor` class.
26
- * Provides utilities for querying, observing, and transforming items from a collection.
27
- * @template T - The type of the items in the collection.
28
- * @template U - The transformed item type after applying transformations (default is T).
29
- * @param getItems - A function that retrieves the filtered list of items.
30
- * @param options - Optional configuration for the cursor.
31
- * @param options.transform - A transformation function to apply to each item when retrieving them.
32
- * @param options.bindEvents - A function to bind reactivity events for the cursor, which should return a cleanup function.
33
- * @param options.fields - A projection object defining which fields of the item should be included or excluded.
34
- * @param options.sort - A sort specifier to determine the order of the items.
35
- * @param options.skip - The number of items to skip from the beginning of the result set.
36
- * @param options.limit - The maximum number of items to return in the result set.
37
- * @param options.reactive - A reactivity adapter to enable observing changes in the cursor's result set.
38
- * @param options.fieldTracking - A boolean to enable fine-grained field tracking for reactivity.
39
- * @param options.transformAll - A function that will be able to solve the n+1 problem
15
+ * Creates a new instance of the `Observer` class.
16
+ * Sets up event bindings and initializes the callbacks for tracking changes in a collection.
17
+ * @param bindEvents - A function to bind external events to the observer. Must return a cleanup function to unbind those events.
40
18
  */
41
- constructor(getItems, options) {
42
- this.getItems = getItems;
43
- this.options = options || {};
44
- }
45
- addGetters(item) {
46
- if (!isInReactiveScope(this.options.reactive)) return item;
47
- const depend = this.depend.bind(this);
48
- return Object.entries(item).reduce((memo, [key, value]) => {
49
- Object.defineProperty(memo, key, {
50
- get() {
51
- depend({ changedField: (notify) => (changedItem, changedFieldName) => {
52
- if (changedFieldName !== key || changedItem.id !== item.id) return;
53
- notify();
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) return item;
66
- return this.options.transform(item);
67
- }
68
- depend(changeEvents, bindExtraNotifier) {
69
- if (this.options?.async) return;
70
- if (!isInReactiveScope(this.options.reactive)) console.warn("Cursor.depend() called outside of a reactive scope without async option; consider using { async: true } or wrapping in a reactive scope");
71
- if (!this.options.reactive) return;
72
- const signal = this.options.reactive.create();
73
- signal.depend();
74
- const notify = () => signal.notify();
75
- /**
76
- * Builds a notifier function for the specified event.
77
- * @template Event - The type of the event.
78
- * @param event - The event for which to build the notifier.
79
- * @returns A function that handles the event and triggers the appropriate notifications.
80
- */
81
- function buildNotifier(event) {
82
- const eventHandler = changeEvents[event];
83
- return (...args) => {
84
- if (eventHandler === true) {
85
- notify();
86
- return;
87
- }
88
- if (typeof eventHandler !== "function") return;
89
- eventHandler(notify)(...args);
90
- };
91
- }
92
- const stop = this.observeRawChanges({
93
- added: buildNotifier("added"),
94
- addedBefore: buildNotifier("addedBefore"),
95
- changed: buildNotifier("changed"),
96
- changedField: buildNotifier("changedField"),
97
- movedBefore: buildNotifier("movedBefore"),
98
- removed: buildNotifier("removed")
99
- }, true);
100
- if (this.options.reactive.onDispose) this.options.reactive.onDispose(() => stop(), signal);
101
- this.onCleanup(stop);
102
- if (!bindExtraNotifier) return;
103
- const stopExtraNotifier = bindExtraNotifier(notify);
104
- if (this.options.reactive.onDispose) this.options.reactive.onDispose(() => stopExtraNotifier(), signal);
105
- this.onCleanup(stopExtraNotifier);
106
- }
107
- ensureObserver() {
108
- if (!this.observer) {
109
- const observer = new require_Observer.default(() => {
110
- const requery = () => {
111
- observer.runChecks(this.getItems);
112
- };
113
- const cleanup = this.options.bindEvents && this.options.bindEvents(requery);
114
- return () => {
115
- if (cleanup) cleanup();
116
- };
117
- });
118
- this.onCleanup(() => observer.stop());
119
- this.observer = observer;
120
- }
121
- return this.observer;
122
- }
123
- observeRawChanges(callbacks, skipInitial = false) {
124
- const observer = this.ensureObserver();
125
- observer.addCallbacks(callbacks, skipInitial);
126
- observer.runChecks(this.getItems);
127
- return () => {
128
- observer.removeCallbacks(callbacks);
129
- if (!observer.isEmpty()) return;
130
- observer.stop();
131
- this.observer = void 0;
19
+ constructor(bindEvents) {
20
+ this.callbacks = {
21
+ added: [],
22
+ addedBefore: [],
23
+ changed: [],
24
+ changedField: [],
25
+ movedBefore: [],
26
+ removed: []
132
27
  };
28
+ this.unbindEvents = bindEvents();
133
29
  }
134
- /**
135
- * Cleans up all resources associated with the cursor, such as reactive bindings
136
- * and event listeners. This method should be called when the cursor is no longer needed
137
- * to prevent memory leaks.
138
- */
139
- cleanup() {
140
- this.onCleanupCallbacks.forEach((callback) => {
141
- callback();
30
+ call(event, ...args) {
31
+ this.callbacks[event].forEach(({ callback, options }) => {
32
+ if (!options.skipInitial || !options.isInitial) callback(...args);
142
33
  });
143
- this.onCleanupCallbacks = [];
144
34
  }
145
- /**
146
- * Registers a cleanup callback to be executed when the `cleanup` method is called.
147
- * Useful for managing resources and ensuring proper cleanup of bindings or listeners.
148
- * @param callback - A function to be executed during cleanup.
149
- */
150
- onCleanup(callback) {
151
- this.onCleanupCallbacks.push(callback);
35
+ hasCallbacks(events) {
36
+ return events.some((event) => this.callbacks[event].length > 0);
152
37
  }
153
38
  /**
154
- * Iterates over each item in the cursor's result set, applying the provided callback
155
- * function to each transformed item.
156
- * ⚡️ this function is reactive!
157
- * @param callback - A function to execute for each item in the result set.
158
- * @param callback.item - The transformed item.
159
- * @returns A promise that resolves when all items have been processed, or void if not in async mode.
39
+ * Determines if the observer has no active callbacks registered for any events.
40
+ * @returns A boolean indicating whether the observer is empty (i.e., no callbacks are registered).
160
41
  */
161
- forEach(callback) {
162
- this.depend({
163
- addedBefore: true,
164
- removed: true,
165
- movedBefore: true,
166
- ...this.options.fieldTracking ? {} : { changed: true }
167
- });
168
- const executeForEach = (items) => {
169
- items.forEach((item) => {
170
- callback(this.transform(item));
171
- });
172
- };
173
- const result = this.getItems();
174
- if (result instanceof Promise) return result.then(executeForEach);
175
- else {
176
- executeForEach(result);
177
- return;
178
- }
42
+ isEmpty() {
43
+ return !this.hasCallbacks([
44
+ "added",
45
+ "addedBefore",
46
+ "changed",
47
+ "changedField",
48
+ "movedBefore",
49
+ "removed"
50
+ ]);
179
51
  }
180
52
  /**
181
- * Creates a new array populated with the results of applying the provided callback
182
- * function to each transformed item in the cursor's result set.
183
- * ⚡️ this function is reactive!
184
- * @template V - The type of the items in the resulting array.
185
- * @param callback - A function to execute for each item in the result set.
186
- * @param callback.item - The transformed item.
187
- * @returns An array of results after applying the callback to each item.
53
+ * Compares the previous state of items with the new state and triggers the appropriate callbacks
54
+ * for events such as added, removed, changed, or moved items.
55
+ * @param getItems - A function that returns a promise resolving to the new items or the items themselves.
188
56
  */
189
- map(callback) {
190
- const results = [];
191
- const maybePromise = this.forEach((item) => {
192
- results.push(callback(item));
57
+ runChecks(getItems) {
58
+ const result = getItems();
59
+ if (result instanceof Promise) result.then((newItems) => this.checkItems(newItems)).catch((error) => {
60
+ console.error("Error while asynchronously querying items", error);
193
61
  });
194
- if (maybePromise instanceof Promise) return maybePromise.then(() => results);
195
- return results;
62
+ else this.checkItems(result);
196
63
  }
197
64
  /**
198
- * Fetches all transformed items from the cursor's result set as an array.
199
- * Automatically applies filtering, sorting, and limiting as per the cursor's options.
200
- * ⚡️ this function is reactive!
201
- * @returns An array of transformed items in the result set.
65
+ * Brings the observer up to date from a description of what changed, instead of from the new
66
+ * result.
67
+ *
68
+ * `runChecks` has to rediscover the change by comparing the whole new result against the whole
69
+ * old one — a cost proportional to the result, paid on every write, to find out that one row
70
+ * moved. When the change is already known it can simply be reported, and the cost becomes
71
+ * proportional to the change.
72
+ *
73
+ * The delta must have been computed against exactly the result this observer holds. If it was
74
+ * not, this reports nothing, falls back to `runChecks`, and returns `false`.
75
+ *
76
+ * Note that the reported moves are minimal, where a comparison reports every item whose
77
+ * neighbour changed. Applying them yields the same order either way — there are simply fewer of
78
+ * them.
79
+ * @param delta - The change to report.
80
+ * @param getItems - Used to fall back to a comparison when the delta cannot be applied.
81
+ * @returns Whether the delta was applied.
202
82
  */
203
- fetch() {
204
- return this.map((item) => item);
83
+ applyDelta(delta, getItems) {
84
+ if (!require_queryDelta.canApplyQueryDelta(this.previousItems, delta)) {
85
+ this.runChecks(getItems);
86
+ return false;
87
+ }
88
+ if (require_queryDelta.isEmptyQueryDelta(delta)) return true;
89
+ this.emitDelta(delta, require_queryDelta.applyQueryDelta(this.previousItems, delta));
90
+ return true;
205
91
  }
206
92
  /**
207
- * Counts the total number of items in the cursor's result set after applying
208
- * filtering and other criteria.
209
- * ⚡️ this function is reactive!
210
- * @returns The total number of items in the result set.
93
+ * Reports a delta and adopts the result it produces.
94
+ *
95
+ * The single place the callbacks are fired from, whether the change arrived as a delta or was
96
+ * found by comparing two results so the two can never disagree about what a consumer is told.
97
+ * @param delta - The change to report.
98
+ * @param nextItems - The result the delta produces.
211
99
  */
212
- count() {
213
- this.depend({
214
- added: true,
215
- removed: true
100
+ emitDelta(delta, nextItems) {
101
+ if (this.isEmpty()) {
102
+ this.finishCheck(nextItems);
103
+ return;
104
+ }
105
+ const beforeOf = (index) => nextItems[index + 1] || null;
106
+ const previousById = delta.removed.length > 0 && this.hasCallbacks(["removed"]) || delta.changed.length > 0 && this.hasCallbacks(["changedField"]) ? new Map(this.previousItems.map((item) => [item.id, item])) : null;
107
+ if (this.hasCallbacks(["changed", "changedField"])) delta.changed.forEach((item) => {
108
+ this.call("changed", item);
109
+ if (!this.hasCallbacks(["changedField"])) return;
110
+ const oldItem = previousById?.get(item.id);
111
+ if (!oldItem) return;
112
+ require_uniqueBy.default([...Object.keys(item), ...Object.keys(oldItem)], (value) => value).forEach((key) => {
113
+ if (require_isEqual.default(item[key], oldItem[key])) return;
114
+ this.call("changedField", item, key, oldItem[key], item[key]);
115
+ });
116
+ });
117
+ if (this.hasCallbacks(["removed"])) delta.removed.forEach((id) => {
118
+ const oldItem = previousById?.get(id);
119
+ if (oldItem) this.call("removed", oldItem);
120
+ });
121
+ if (this.hasCallbacks(["added", "addedBefore"])) delta.added.forEach(({ index, item }) => {
122
+ this.call("added", item);
123
+ this.call("addedBefore", item, beforeOf(index));
124
+ });
125
+ if (this.hasCallbacks(["movedBefore"])) delta.moved.forEach(({ index }) => {
126
+ this.call("movedBefore", nextItems[index], beforeOf(index));
216
127
  });
217
- const maybePromise = this.getItems();
218
- return maybePromise instanceof Promise ? maybePromise.then((items) => items.length) : maybePromise.length;
128
+ this.finishCheck(nextItems);
219
129
  }
130
+ finishCheck(newItems) {
131
+ this.previousItems = newItems;
132
+ Object.keys(this.callbacks).forEach((key) => {
133
+ const event = key;
134
+ const callbacks = this.callbacks[event];
135
+ this.callbacks[event] = callbacks.map((callback) => ({
136
+ ...callback,
137
+ options: {
138
+ ...callback.options,
139
+ isInitial: false
140
+ }
141
+ }));
142
+ });
143
+ }
144
+ checkItems(newItems) {
145
+ this.emitDelta(require_queryDelta.diffQueryResults(this.previousItems, newItems), newItems);
146
+ }
147
+ stopped = false;
220
148
  /**
221
- * Whether this cursor's query has yet to deliver a first result.
222
- * ⚡️ this function is reactive!
223
- *
224
- * An asynchronous data adapter answers a newly registered query only after a
225
- * round trip, and serves a neutral empty result until it does — which a
226
- * consumer cannot otherwise tell apart from "there is nothing to show". This
227
- * is that distinction, per query rather than per collection, so one screen
228
- * waiting on its own data says nothing about any other query.
229
- *
230
- * Follows the usual `isLoading`/`isFetching` split: it reports "no result
231
- * yet", not "an execution is in flight". A write that re-runs an
232
- * already-settled query drives it through `'active'` again while this stays
233
- * `false`, so a list does not fall back to a loading state every time one of
234
- * its rows changes.
235
- *
236
- * A query that fails counts as settled — the `query.error` event on the
237
- * collection is what surfaces the failure, and a loading state that never
238
- * ends is the worse answer. Reading this registers the query if nothing else
239
- * has, so it cannot wait on something nobody asked for. It is always `false`
240
- * for an `{ async: true }` cursor, whose `fetch()` awaits the real result
241
- * anyway, and for a data adapter that answers synchronously.
242
- * @returns A boolean indicating whether the first result is still pending.
149
+ * Stops the observer by unbinding all events and cleaning up resources.
150
+ * Safe to call multiple times - will only unbind once.
243
151
  */
244
- isLoading() {
245
- const queryState = this.options.queryState;
246
- if (!queryState || this.options.async) return false;
247
- this.depend({}, (notify) => queryState.onSettled(notify));
248
- return !queryState.hasSettled();
152
+ stop() {
153
+ if (this.stopped) return;
154
+ this.stopped = true;
155
+ this.unbindEvents();
249
156
  }
250
157
  /**
251
- * Observes changes to the cursor's result set and triggers the specified callbacks
252
- * when items are added, removed, or updated. Supports reactivity and transformation.
253
- * @param callbacks - An object containing the callback functions to handle different change events.
254
- * @param callbacks.added - Triggered when an item is added to the result set.
255
- * @param callbacks.removed - Triggered when an item is removed from the result set.
256
- * @param callbacks.changed - Triggered when an item in the result set is modified.
257
- * @param callbacks.addedBefore - Triggered when an item is added before another item in the result set.
258
- * @param callbacks.movedBefore - Triggered when an item is moved before another item in the result set.
259
- * @param callbacks.changedField - Triggered when a specific field of an item changes.
260
- * @param skipInitial - A boolean indicating whether to skip the initial notification of the current result set.
261
- * @returns A function to stop observing changes.
158
+ * Registers callbacks for specific events to observe changes in the collection.
159
+ * @param callbacks - An object containing the callbacks for various events (e.g., 'added', 'removed').
160
+ * @param skipInitial - A boolean indicating whether to skip invoking the callbacks for the initial state of the collection.
262
161
  */
263
- observeChanges(callbacks, skipInitial = false) {
264
- return this.observeRawChanges(Object.entries(callbacks).reduce((memo, [callbackName, callback]) => {
265
- if (!callback) return memo;
266
- return {
267
- ...memo,
268
- [callbackName]: (item, before) => {
269
- const transformedValue = this.transform(item);
270
- const hasBeforeParameter = before !== void 0;
271
- const transformedBeforeValue = hasBeforeParameter && before ? this.transform(before) : null;
272
- return callback(transformedValue, ...hasBeforeParameter ? [transformedBeforeValue] : []);
162
+ addCallbacks(callbacks, skipInitial = false) {
163
+ Object.keys(callbacks).forEach((key) => {
164
+ const typedKey = key;
165
+ this.callbacks[typedKey].push({
166
+ callback: callbacks[typedKey],
167
+ options: {
168
+ skipInitial,
169
+ isInitial: true
273
170
  }
274
- };
275
- }, {}), skipInitial);
171
+ });
172
+ });
276
173
  }
277
174
  /**
278
- * Forces the cursor to re-evaluate its result set by re-fetching items
279
- * from the collection. This is useful when the underlying data or query
280
- * criteria have changed, and you want to ensure the cursor reflects the latest state.
175
+ * Removes the specified callbacks for specific events, unregistering them from the observer.
176
+ * @param callbacks - An object containing the callbacks to be removed for various events.
281
177
  */
282
- requery() {
283
- if (!this.observer) return;
284
- this.observer.runChecks(this.getItems);
178
+ removeCallbacks(callbacks) {
179
+ Object.keys(callbacks).forEach((key) => {
180
+ const typedKey = key;
181
+ const index = this.callbacks[typedKey].findIndex(({ callback }) => callback === callbacks[typedKey]);
182
+ this.callbacks[typedKey].splice(index, 1);
183
+ });
285
184
  }
286
185
  };
287
186
  //#endregion
288
- exports.default = Cursor;
187
+ exports.default = Observer;