@signaldb/core 2.0.0-beta.2 → 2.0.0-beta.21

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 (145) hide show
  1. package/dist/.vite/manifest.json +183 -80
  2. package/dist/AsyncDataAdapter.d.ts +53 -7
  3. package/dist/AutoFetchDataAdapter.d.ts +4 -6
  4. package/dist/Collection/Cursor.d.ts +56 -4
  5. package/dist/Collection/Observer.d.ts +33 -0
  6. package/dist/Collection/index.d.ts +66 -19
  7. package/dist/Collection/types.d.ts +9 -2
  8. package/dist/DataAdapter.d.ts +24 -6
  9. package/dist/DefaultDataAdapter.d.ts +5 -5
  10. package/dist/WorkerDataAdapter.d.ts +57 -5
  11. package/dist/WorkerDataAdapterHost.d.ts +9 -7
  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 +6 -1
  19. package/dist/index.mjs +17 -32
  20. package/dist/index10.cjs.js +11 -0
  21. package/dist/index10.mjs +10 -18
  22. package/dist/index11.cjs.js +23 -0
  23. package/dist/index11.mjs +22 -15
  24. package/dist/index12.cjs.js +45 -0
  25. package/dist/index12.mjs +44 -353
  26. package/dist/index13.cjs.js +22 -0
  27. package/dist/index13.mjs +21 -419
  28. package/dist/index14.cjs.js +45 -0
  29. package/dist/index14.mjs +44 -206
  30. package/dist/index15.cjs.js +86 -0
  31. package/dist/index15.mjs +85 -388
  32. package/dist/index16.cjs.js +15 -0
  33. package/dist/index16.mjs +14 -579
  34. package/dist/index17.cjs.js +141 -0
  35. package/dist/index17.mjs +140 -152
  36. package/dist/index18.cjs.js +47 -0
  37. package/dist/index18.mjs +46 -26
  38. package/dist/index19.cjs.js +15 -0
  39. package/dist/index19.mjs +14 -41
  40. package/dist/index2.cjs.js +33 -0
  41. package/dist/index2.mjs +32 -258
  42. package/dist/index20.cjs.js +23 -0
  43. package/dist/index20.mjs +22 -16
  44. package/dist/index21.cjs.js +37 -0
  45. package/dist/index21.mjs +36 -104
  46. package/dist/index22.cjs.js +35 -0
  47. package/dist/index22.mjs +34 -128
  48. package/dist/index23.cjs.js +21 -0
  49. package/dist/index23.mjs +20 -7
  50. package/dist/index24.cjs.js +19 -0
  51. package/dist/index24.mjs +18 -27
  52. package/dist/index25.cjs.js +157 -0
  53. package/dist/index25.mjs +156 -11
  54. package/dist/index26.cjs.js +38 -0
  55. package/dist/index26.mjs +37 -29
  56. package/dist/index27.cjs.js +42 -0
  57. package/dist/index27.mjs +41 -46
  58. package/dist/index28.cjs.js +347 -0
  59. package/dist/index28.mjs +345 -7
  60. package/dist/index29.cjs.js +602 -0
  61. package/dist/index29.mjs +601 -7
  62. package/dist/index3.cjs.js +19 -0
  63. package/dist/index3.mjs +18 -556
  64. package/dist/index30.cjs.js +11 -0
  65. package/dist/index30.mjs +10 -42
  66. package/dist/index31.cjs.js +11 -0
  67. package/dist/index31.mjs +10 -29
  68. package/dist/index32.cjs.js +90 -0
  69. package/dist/index32.mjs +89 -10
  70. package/dist/index33.cjs.js +53 -0
  71. package/dist/index33.mjs +52 -5
  72. package/dist/index34.cjs.js +453 -0
  73. package/dist/index34.mjs +453 -0
  74. package/dist/index35.cjs.js +72 -0
  75. package/dist/index35.mjs +72 -0
  76. package/dist/index36.cjs.js +580 -0
  77. package/dist/index36.mjs +580 -0
  78. package/dist/index37.cjs.js +21 -0
  79. package/dist/index37.mjs +21 -0
  80. package/dist/index38.cjs.js +363 -0
  81. package/dist/index38.mjs +363 -0
  82. package/dist/index39.cjs.js +513 -0
  83. package/dist/index39.mjs +513 -0
  84. package/dist/index4.cjs.js +209 -0
  85. package/dist/index4.mjs +204 -5
  86. package/dist/index5.cjs.js +187 -0
  87. package/dist/index5.mjs +186 -5
  88. package/dist/index6.cjs.js +303 -0
  89. package/dist/index6.mjs +301 -28
  90. package/dist/index7.cjs.js +125 -0
  91. package/dist/index7.mjs +124 -12
  92. package/dist/index8.cjs.js +33 -0
  93. package/dist/index8.mjs +32 -5
  94. package/dist/index9.cjs.js +12 -0
  95. package/dist/index9.mjs +11 -133
  96. package/dist/types/IndexProvider.d.ts +2 -2
  97. package/dist/types/Modifier.d.ts +1 -1
  98. package/dist/types/ReactivityAdapter.d.ts +1 -1
  99. package/dist/types/StorageAdapter.d.ts +9 -1
  100. package/dist/utils/applyQueryOptions.d.ts +15 -0
  101. package/dist/utils/createSignal.d.ts +2 -2
  102. package/dist/utils/getMatchingKeys.d.ts +2 -2
  103. package/dist/utils/idIndexQuery.d.ts +20 -0
  104. package/dist/utils/incrementalQueryUpdate.d.ts +62 -0
  105. package/dist/utils/isFieldExpression.d.ts +1 -1
  106. package/dist/utils/match.d.ts +1 -1
  107. package/dist/utils/modify.d.ts +1 -1
  108. package/dist/utils/projectItems.d.ts +12 -0
  109. package/dist/utils/queryDelta.d.ts +83 -0
  110. package/dist/utils/queryId.d.ts +2 -2
  111. package/dist/utils/reactiveOrAsync.d.ts +59 -0
  112. package/dist/utils/storageIndexQuery.d.ts +20 -0
  113. package/package.json +1 -1
  114. package/dist/index.cjs10.js +0 -18
  115. package/dist/index.cjs11.js +0 -15
  116. package/dist/index.cjs12.js +0 -353
  117. package/dist/index.cjs13.js +0 -419
  118. package/dist/index.cjs14.js +0 -206
  119. package/dist/index.cjs15.js +0 -388
  120. package/dist/index.cjs16.js +0 -579
  121. package/dist/index.cjs17.js +0 -152
  122. package/dist/index.cjs18.js +0 -26
  123. package/dist/index.cjs19.js +0 -42
  124. package/dist/index.cjs2.js +0 -259
  125. package/dist/index.cjs20.js +0 -16
  126. package/dist/index.cjs21.js +0 -104
  127. package/dist/index.cjs22.js +0 -129
  128. package/dist/index.cjs23.js +0 -7
  129. package/dist/index.cjs24.js +0 -27
  130. package/dist/index.cjs25.js +0 -10
  131. package/dist/index.cjs26.js +0 -29
  132. package/dist/index.cjs27.js +0 -46
  133. package/dist/index.cjs28.js +0 -8
  134. package/dist/index.cjs29.js +0 -7
  135. package/dist/index.cjs3.js +0 -557
  136. package/dist/index.cjs30.js +0 -42
  137. package/dist/index.cjs31.js +0 -29
  138. package/dist/index.cjs32.js +0 -9
  139. package/dist/index.cjs33.js +0 -5
  140. package/dist/index.cjs4.js +0 -5
  141. package/dist/index.cjs5.js +0 -5
  142. package/dist/index.cjs6.js +0 -29
  143. package/dist/index.cjs7.js +0 -12
  144. package/dist/index.cjs8.js +0 -5
  145. package/dist/index.cjs9.js +0 -133
package/dist/index5.mjs CHANGED
@@ -1,6 +1,187 @@
1
- function createReactivityAdapter(definition) {
2
- return definition;
3
- }
4
- export {
5
- createReactivityAdapter as default
1
+ import isEqual from "./index2.mjs";
2
+ import uniqueBy from "./index3.mjs";
3
+ import { applyQueryDelta, canApplyQueryDelta, diffQueryResults, isEmptyQueryDelta } from "./index4.mjs";
4
+ //#region src/Collection/Observer.ts
5
+ /**
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.
9
+ */
10
+ var Observer = class {
11
+ previousItems = [];
12
+ callbacks;
13
+ unbindEvents;
14
+ /**
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.
18
+ */
19
+ constructor(bindEvents) {
20
+ this.callbacks = {
21
+ added: [],
22
+ addedBefore: [],
23
+ changed: [],
24
+ changedField: [],
25
+ movedBefore: [],
26
+ removed: []
27
+ };
28
+ this.unbindEvents = bindEvents();
29
+ }
30
+ call(event, ...args) {
31
+ this.callbacks[event].forEach(({ callback, options }) => {
32
+ if (!options.skipInitial || !options.isInitial) callback(...args);
33
+ });
34
+ }
35
+ hasCallbacks(events) {
36
+ return events.some((event) => this.callbacks[event].length > 0);
37
+ }
38
+ /**
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).
41
+ */
42
+ isEmpty() {
43
+ return !this.hasCallbacks([
44
+ "added",
45
+ "addedBefore",
46
+ "changed",
47
+ "changedField",
48
+ "movedBefore",
49
+ "removed"
50
+ ]);
51
+ }
52
+ /**
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.
56
+ */
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);
61
+ });
62
+ else this.checkItems(result);
63
+ }
64
+ /**
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.
82
+ */
83
+ applyDelta(delta, getItems) {
84
+ if (!canApplyQueryDelta(this.previousItems, delta)) {
85
+ this.runChecks(getItems);
86
+ return false;
87
+ }
88
+ if (isEmptyQueryDelta(delta)) return true;
89
+ this.emitDelta(delta, applyQueryDelta(this.previousItems, delta));
90
+ return true;
91
+ }
92
+ /**
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.
99
+ */
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
+ uniqueBy([...Object.keys(item), ...Object.keys(oldItem)], (value) => value).forEach((key) => {
113
+ if (isEqual(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));
127
+ });
128
+ this.finishCheck(nextItems);
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(diffQueryResults(this.previousItems, newItems), newItems);
146
+ }
147
+ stopped = false;
148
+ /**
149
+ * Stops the observer by unbinding all events and cleaning up resources.
150
+ * Safe to call multiple times - will only unbind once.
151
+ */
152
+ stop() {
153
+ if (this.stopped) return;
154
+ this.stopped = true;
155
+ this.unbindEvents();
156
+ }
157
+ /**
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.
161
+ */
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
170
+ }
171
+ });
172
+ });
173
+ }
174
+ /**
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.
177
+ */
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
+ });
184
+ }
6
185
  };
186
+ //#endregion
187
+ export { Observer as default };
@@ -0,0 +1,303 @@
1
+ const require_Observer = require("./index5.cjs.js");
2
+ //#region src/Collection/Cursor.ts
3
+ /**
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.
7
+ */
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 = [];
24
+ /**
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
40
+ */
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 applyDelta = (delta) => {
114
+ observer.applyDelta(delta, this.getItems);
115
+ };
116
+ const cleanup = this.options.bindEvents && this.options.bindEvents(requery, applyDelta);
117
+ return () => {
118
+ if (cleanup) cleanup();
119
+ };
120
+ });
121
+ this.onCleanup(() => observer.stop());
122
+ this.observer = observer;
123
+ }
124
+ return this.observer;
125
+ }
126
+ observeRawChanges(callbacks, skipInitial = false) {
127
+ const observer = this.ensureObserver();
128
+ observer.addCallbacks(callbacks, skipInitial);
129
+ observer.runChecks(this.getItems);
130
+ return () => {
131
+ observer.removeCallbacks(callbacks);
132
+ if (!observer.isEmpty()) return;
133
+ observer.stop();
134
+ this.observer = void 0;
135
+ };
136
+ }
137
+ /**
138
+ * Cleans up all resources associated with the cursor, such as reactive bindings
139
+ * and event listeners. This method should be called when the cursor is no longer needed
140
+ * to prevent memory leaks.
141
+ */
142
+ cleanup() {
143
+ this.onCleanupCallbacks.forEach((callback) => {
144
+ callback();
145
+ });
146
+ this.onCleanupCallbacks = [];
147
+ }
148
+ /**
149
+ * Registers a cleanup callback to be executed when the `cleanup` method is called.
150
+ * Useful for managing resources and ensuring proper cleanup of bindings or listeners.
151
+ * @param callback - A function to be executed during cleanup.
152
+ */
153
+ onCleanup(callback) {
154
+ this.onCleanupCallbacks.push(callback);
155
+ }
156
+ /**
157
+ * Iterates over each item in the cursor's result set, applying the provided callback
158
+ * function to each transformed item.
159
+ * ⚡️ this function is reactive!
160
+ * @param callback - A function to execute for each item in the result set.
161
+ * @param callback.item - The transformed item.
162
+ * @returns A promise that resolves when all items have been processed, or void if not in async mode.
163
+ */
164
+ forEach(callback) {
165
+ this.depend({
166
+ addedBefore: true,
167
+ removed: true,
168
+ movedBefore: true,
169
+ ...this.options.fieldTracking ? {} : { changed: true }
170
+ });
171
+ const executeForEach = (items) => {
172
+ items.forEach((item) => {
173
+ callback(this.transform(item));
174
+ });
175
+ };
176
+ const result = this.getItems();
177
+ if (result instanceof Promise) return result.then(executeForEach);
178
+ else {
179
+ executeForEach(result);
180
+ return;
181
+ }
182
+ }
183
+ /**
184
+ * Creates a new array populated with the results of applying the provided callback
185
+ * function to each transformed item in the cursor's result set.
186
+ * ⚡️ this function is reactive!
187
+ * @template V - The type of the items in the resulting array.
188
+ * @param callback - A function to execute for each item in the result set.
189
+ * @param callback.item - The transformed item.
190
+ * @returns An array of results after applying the callback to each item.
191
+ */
192
+ map(callback) {
193
+ const results = [];
194
+ const maybePromise = this.forEach((item) => {
195
+ results.push(callback(item));
196
+ });
197
+ if (maybePromise instanceof Promise) return maybePromise.then(() => results);
198
+ return results;
199
+ }
200
+ /**
201
+ * Fetches all transformed items from the cursor's result set as an array.
202
+ * Automatically applies filtering, sorting, and limiting as per the cursor's options.
203
+ * ⚡️ this function is reactive!
204
+ * @returns An array of transformed items in the result set.
205
+ */
206
+ fetch() {
207
+ return this.map((item) => item);
208
+ }
209
+ /**
210
+ * Counts the total number of items in the cursor's result set after applying
211
+ * filtering and other criteria.
212
+ * ⚡️ this function is reactive!
213
+ * @returns The total number of items in the result set.
214
+ */
215
+ count() {
216
+ this.depend({
217
+ added: true,
218
+ removed: true
219
+ });
220
+ const maybePromise = this.getItems();
221
+ return maybePromise instanceof Promise ? maybePromise.then((items) => items.length) : maybePromise.length;
222
+ }
223
+ /**
224
+ * Whether this cursor's query has yet to deliver a first result.
225
+ * ⚡️ this function is reactive!
226
+ *
227
+ * An asynchronous data adapter answers a newly registered query only after a
228
+ * round trip, and serves a neutral empty result until it does — which a
229
+ * consumer cannot otherwise tell apart from "there is nothing to show". This
230
+ * is that distinction, per query rather than per collection, so one screen
231
+ * waiting on its own data says nothing about any other query.
232
+ *
233
+ * Follows the usual `isLoading`/`isFetching` split: it reports "no result
234
+ * yet", not "an execution is in flight". A write that re-runs an
235
+ * already-settled query drives it through `'active'` again while this stays
236
+ * `false`, so a list does not fall back to a loading state every time one of
237
+ * its rows changes.
238
+ *
239
+ * A query that fails counts as settled — the `query.error` event on the
240
+ * collection is what surfaces the failure, and a loading state that never
241
+ * ends is the worse answer. Reading this registers the query if nothing else
242
+ * has, so it cannot wait on something nobody asked for. It is always `false`
243
+ * for an `{ async: true }` cursor, whose `fetch()` awaits the real result
244
+ * anyway, and for a data adapter that answers synchronously.
245
+ * @returns A boolean indicating whether the first result is still pending.
246
+ */
247
+ isLoading() {
248
+ const queryState = this.options.queryState;
249
+ if (!queryState || this.options.async) return false;
250
+ this.depend({}, (notify) => queryState.onSettled(notify));
251
+ return !queryState.hasSettled();
252
+ }
253
+ /**
254
+ * Observes changes to the cursor's result set and triggers the specified callbacks
255
+ * when items are added, removed, or updated. Supports reactivity and transformation.
256
+ * @param callbacks - An object containing the callback functions to handle different change events.
257
+ * @param callbacks.added - Triggered when an item is added to the result set.
258
+ * @param callbacks.removed - Triggered when an item is removed from the result set.
259
+ * @param callbacks.changed - Triggered when an item in the result set is modified.
260
+ * @param callbacks.addedBefore - Triggered when an item is added before another item in the result set.
261
+ * @param callbacks.movedBefore - Triggered when an item is moved before another item in the result set.
262
+ * @param callbacks.changedField - Triggered when a specific field of an item changes.
263
+ * @param skipInitial - A boolean indicating whether to skip the initial notification of the current result set.
264
+ * @returns A function to stop observing changes.
265
+ */
266
+ observeChanges(callbacks, skipInitial = false) {
267
+ return this.observeRawChanges(Object.entries(callbacks).reduce((memo, [callbackName, callback]) => {
268
+ if (!callback) return memo;
269
+ return {
270
+ ...memo,
271
+ [callbackName]: (item, before) => {
272
+ const transformedValue = this.transform(item);
273
+ const hasBeforeParameter = before !== void 0;
274
+ const transformedBeforeValue = hasBeforeParameter && before ? this.transform(before) : null;
275
+ return callback(transformedValue, ...hasBeforeParameter ? [transformedBeforeValue] : []);
276
+ }
277
+ };
278
+ }, {}), skipInitial);
279
+ }
280
+ /**
281
+ * Forces the cursor to re-evaluate its result set by re-fetching items
282
+ * from the collection. This is useful when the underlying data or query
283
+ * criteria have changed, and you want to ensure the cursor reflects the latest state.
284
+ */
285
+ requery() {
286
+ if (!this.observer) return;
287
+ this.observer.runChecks(this.getItems);
288
+ }
289
+ /**
290
+ * Brings the cursor up to date from a description of what changed, rather than by re-running the
291
+ * query and comparing the result with the previous one.
292
+ *
293
+ * Falls back to `requery` when the delta does not fit the result the cursor currently holds, so
294
+ * a caller never has to decide which of the two is safe.
295
+ * @param delta - The change to apply.
296
+ */
297
+ applyDelta(delta) {
298
+ if (!this.observer) return;
299
+ this.observer.applyDelta(delta, this.getItems);
300
+ }
301
+ };
302
+ //#endregion
303
+ exports.default = Cursor;