@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
package/dist/index4.mjs CHANGED
@@ -1,150 +1,205 @@
1
1
  import isEqual from "./index2.mjs";
2
- import uniqueBy from "./index3.mjs";
3
- //#region src/Collection/Observer.ts
2
+ //#region src/utils/queryDelta.ts
4
3
  /**
5
- * Represents an observer that tracks changes in a collection of items and triggers
6
- * callbacks for various events such as addition, removal, and modification of items.
7
- * @template T - The type of the items being observed, which must include an `id` field.
4
+ * Checks whether a delta leaves the result it is applied to unchanged.
5
+ * @param delta - The delta to inspect.
6
+ * @returns `true` when applying the delta would be a no-op.
8
7
  */
9
- var Observer = class {
10
- previousItems = [];
11
- callbacks;
12
- unbindEvents;
13
- /**
14
- * Creates a new instance of the `Observer` class.
15
- * Sets up event bindings and initializes the callbacks for tracking changes in a collection.
16
- * @param bindEvents - A function to bind external events to the observer. Must return a cleanup function to unbind those events.
17
- */
18
- constructor(bindEvents) {
19
- this.callbacks = {
20
- added: [],
21
- addedBefore: [],
22
- changed: [],
23
- changedField: [],
24
- movedBefore: [],
25
- removed: []
26
- };
27
- this.unbindEvents = bindEvents();
28
- }
29
- call(event, ...args) {
30
- this.callbacks[event].forEach(({ callback, options }) => {
31
- if (!options.skipInitial || !options.isInitial) callback(...args);
32
- });
33
- }
34
- hasCallbacks(events) {
35
- return events.some((event) => this.callbacks[event].length > 0);
36
- }
37
- /**
38
- * Determines if the observer has no active callbacks registered for any events.
39
- * @returns A boolean indicating whether the observer is empty (i.e., no callbacks are registered).
40
- */
41
- isEmpty() {
42
- return !this.hasCallbacks([
43
- "added",
44
- "addedBefore",
45
- "changed",
46
- "changedField",
47
- "movedBefore",
48
- "removed"
49
- ]);
50
- }
51
- /**
52
- * Compares the previous state of items with the new state and triggers the appropriate callbacks
53
- * for events such as added, removed, changed, or moved items.
54
- * @param getItems - A function that returns a promise resolving to the new items or the items themselves.
55
- */
56
- runChecks(getItems) {
57
- const result = getItems();
58
- if (result instanceof Promise) result.then((newItems) => this.checkItems(newItems)).catch((error) => {
59
- console.error("Error while asynchronously querying items", error);
60
- });
61
- else this.checkItems(result);
8
+ function isEmptyQueryDelta(delta) {
9
+ return delta.added.length === 0 && delta.changed.length === 0 && delta.removed.length === 0 && delta.moved.length === 0;
10
+ }
11
+ /**
12
+ * Calls a state-change callback, passing the delta only when there is one.
13
+ *
14
+ * A callback invoked as `callback(state, undefined)` has been handed two arguments, which is a
15
+ * different thing from being handed one visible to anything that inspects arity, and to any test
16
+ * that asserts on the call.
17
+ * @template T - The type of the items.
18
+ * @param callback - The callback to invoke.
19
+ * @param state - The state to report.
20
+ * @param delta - The delta to report, if there is one.
21
+ */
22
+ function callWithDelta(callback, state, delta) {
23
+ if (delta == null) {
24
+ callback(state);
25
+ return;
62
26
  }
63
- checkItems(newItems) {
64
- const oldItemsMap = new Map(this.previousItems.map((item, index) => [item.id, {
65
- item,
66
- index,
67
- beforeItem: this.previousItems[index + 1] || null
68
- }]));
69
- const newItemsMap = new Map(newItems.map((item, index) => [item.id, {
70
- item,
71
- index,
72
- beforeItem: newItems[index + 1] || null
73
- }]));
74
- if (this.hasCallbacks([
75
- "changed",
76
- "changedField",
77
- "movedBefore",
78
- "removed"
79
- ])) oldItemsMap.forEach(({ item: oldItem, index, beforeItem: oldBeforeItem }) => {
80
- const newItem = newItemsMap.get(oldItem.id);
81
- if (newItem) {
82
- if (this.hasCallbacks(["changed", "changedField"]) && !isEqual(newItem.item, oldItem)) {
83
- this.call("changed", newItem.item);
84
- if (this.hasCallbacks(["changedField"])) uniqueBy([...Object.keys(newItem.item), ...Object.keys(oldItem)], (value) => value).forEach((key) => {
85
- if (isEqual(newItem.item[key], oldItem[key])) return;
86
- this.call("changedField", newItem.item, key, oldItem[key], newItem.item[key]);
87
- });
88
- }
89
- if (newItem.index !== index && newItem.beforeItem?.id !== oldBeforeItem?.id) this.call("movedBefore", newItem.item, newItem.beforeItem);
90
- } else this.call("removed", oldItem);
91
- });
92
- if (this.hasCallbacks(["added", "addedBefore"])) newItems.forEach((newItem, index) => {
93
- if (oldItemsMap.get(newItem.id)) return;
94
- this.call("added", newItem);
95
- this.call("addedBefore", newItem, newItems[index + 1] || null);
96
- });
97
- this.previousItems = newItems;
98
- Object.keys(this.callbacks).forEach((key) => {
99
- const event = key;
100
- const callbacks = this.callbacks[event];
101
- this.callbacks[event] = callbacks.map((callback) => ({
102
- ...callback,
103
- options: {
104
- ...callback.options,
105
- isInitial: false
106
- }
107
- }));
108
- });
27
+ callback(state, delta);
28
+ }
29
+ /**
30
+ * Checks whether a delta describes a change to the given result.
31
+ *
32
+ * A delta is only meaningful against the exact result it was computed from — it names positions in
33
+ * an array and items by id alone. Applying one to anything else produces a result that looks
34
+ * plausible and is wrong, and from then on every further delta compounds the error. This is the
35
+ * cheap structural check that catches that: every id the delta expects to find is there, every id
36
+ * it expects to be new is not, and the arithmetic on the length works out. It costs the size of the
37
+ * delta, not the size of the result.
38
+ * @template T - The type of the items.
39
+ * @param previous - The result the delta would be applied to.
40
+ * @param delta - The delta to check.
41
+ * @returns `true` when the delta can be applied.
42
+ */
43
+ function canApplyQueryDelta(previous, delta) {
44
+ const present = new Set(previous.map((item) => item.id));
45
+ const seen = /* @__PURE__ */ new Set();
46
+ const claim = (id, shouldExist) => {
47
+ if (seen.has(id)) return false;
48
+ seen.add(id);
49
+ return present.has(id) === shouldExist;
50
+ };
51
+ if (previous.length - delta.removed.length + delta.added.length !== delta.resultCount) return false;
52
+ if (!delta.removed.every((id) => claim(id, true))) return false;
53
+ if (!delta.added.every(({ index, item }) => claim(item.id, false) && index >= 0 && index < delta.resultCount)) return false;
54
+ if (!delta.changed.every((item) => present.has(item.id))) return false;
55
+ return delta.moved.every(({ index, id }) => present.has(id) && !delta.removed.includes(id) && index >= 0 && index < delta.resultCount);
56
+ }
57
+ /**
58
+ * Indices of the longest strictly increasing subsequence of the given numbers.
59
+ * Used to decide which items keep their place when a result is reordered: everything outside the
60
+ * subsequence has to move, everything inside it is already in the right relative order.
61
+ * @param sequence - The numbers to inspect.
62
+ * @returns The indices into `sequence` that form the longest increasing subsequence.
63
+ */
64
+ function longestIncreasingSubsequence(sequence) {
65
+ if (sequence.length === 0) return [];
66
+ const tails = [];
67
+ const previous = Array.from({ length: sequence.length }).fill(-1);
68
+ for (let index = 0; index < sequence.length; index += 1) {
69
+ const value = sequence[index];
70
+ let low = 0;
71
+ let high = tails.length;
72
+ while (low < high) {
73
+ const middle = low + high >> 1;
74
+ if (sequence[tails[middle]] < value) low = middle + 1;
75
+ else high = middle;
76
+ }
77
+ if (low > 0) previous[index] = tails[low - 1];
78
+ tails[low] = index;
109
79
  }
110
- stopped = false;
111
- /**
112
- * Stops the observer by unbinding all events and cleaning up resources.
113
- * Safe to call multiple times - will only unbind once.
114
- */
115
- stop() {
116
- if (this.stopped) return;
117
- this.stopped = true;
118
- this.unbindEvents();
80
+ const result = [];
81
+ let cursor = tails.at(-1);
82
+ while (cursor !== -1) {
83
+ result.push(cursor);
84
+ cursor = previous[cursor];
119
85
  }
120
- /**
121
- * Registers callbacks for specific events to observe changes in the collection.
122
- * @param callbacks - An object containing the callbacks for various events (e.g., 'added', 'removed').
123
- * @param skipInitial - A boolean indicating whether to skip invoking the callbacks for the initial state of the collection.
124
- */
125
- addCallbacks(callbacks, skipInitial = false) {
126
- Object.keys(callbacks).forEach((key) => {
127
- const typedKey = key;
128
- this.callbacks[typedKey].push({
129
- callback: callbacks[typedKey],
130
- options: {
131
- skipInitial,
132
- isInitial: true
133
- }
86
+ return result.toReversed();
87
+ }
88
+ /**
89
+ * Computes the delta between two results of the same query.
90
+ *
91
+ * A fallback for the cases where the change that produced the new result is not available — a query
92
+ * that had to be re-executed in full, for instance. It costs a pass over both results, but it is
93
+ * paid once, on the side that has both of them, instead of shipping the entire new result to
94
+ * everyone who only needs to know what changed.
95
+ * @template T - The type of the items.
96
+ * @param previous - The result the delta should be relative to.
97
+ * @param next - The result the delta should produce.
98
+ * @returns The delta between the two results.
99
+ */
100
+ function diffQueryResults(previous, next) {
101
+ if (holdsTheSameItems(previous, next)) return {
102
+ added: [],
103
+ changed: [],
104
+ removed: [],
105
+ moved: [],
106
+ resultCount: next.length
107
+ };
108
+ const previousIndexById = /* @__PURE__ */ new Map();
109
+ previous.forEach((item, index) => previousIndexById.set(item.id, index));
110
+ const added = [];
111
+ const changed = [];
112
+ const survivingPreviousIndices = [];
113
+ const survivingNextIndices = [];
114
+ const survived = Array.from({ length: previous.length }).fill(false);
115
+ let orderPreserved = true;
116
+ let lastPreviousIndex = -1;
117
+ next.forEach((item, index) => {
118
+ const previousIndex = previousIndexById.get(item.id);
119
+ if (previousIndex == null) {
120
+ added.push({
121
+ index,
122
+ item
123
+ });
124
+ return;
125
+ }
126
+ survived[previousIndex] = true;
127
+ if (!isEqual(previous[previousIndex], item)) changed.push(item);
128
+ if (previousIndex < lastPreviousIndex) orderPreserved = false;
129
+ lastPreviousIndex = previousIndex;
130
+ survivingPreviousIndices.push(previousIndex);
131
+ survivingNextIndices.push(index);
132
+ });
133
+ const removed = [];
134
+ previous.forEach((item, index) => {
135
+ if (!survived[index]) removed.push(item.id);
136
+ });
137
+ const moved = [];
138
+ if (!orderPreserved) {
139
+ const stationary = new Set(longestIncreasingSubsequence(survivingPreviousIndices).map((position) => survivingNextIndices[position]));
140
+ survivingNextIndices.forEach((nextIndex) => {
141
+ if (stationary.has(nextIndex)) return;
142
+ moved.push({
143
+ index: nextIndex,
144
+ id: next[nextIndex].id
134
145
  });
135
146
  });
136
147
  }
137
- /**
138
- * Removes the specified callbacks for specific events, unregistering them from the observer.
139
- * @param callbacks - An object containing the callbacks to be removed for various events.
140
- */
141
- removeCallbacks(callbacks) {
142
- Object.keys(callbacks).forEach((key) => {
143
- const typedKey = key;
144
- const index = this.callbacks[typedKey].findIndex(({ callback }) => callback === callbacks[typedKey]);
145
- this.callbacks[typedKey].splice(index, 1);
146
- });
147
- }
148
- };
148
+ return {
149
+ added,
150
+ changed,
151
+ removed,
152
+ moved,
153
+ resultCount: next.length
154
+ };
155
+ }
156
+ /**
157
+ * Whether two results hold the same items in the same order, by identity.
158
+ *
159
+ * Items are replaced rather than mutated wherever they come from, so identity is a sound answer to
160
+ * "unchanged" — and a wrong one is impossible, only a missed shortcut.
161
+ * @template T - The type of the items.
162
+ * @param previous - One result.
163
+ * @param next - The other.
164
+ * @returns `true` when the two are element-for-element the same objects.
165
+ */
166
+ function holdsTheSameItems(previous, next) {
167
+ if (previous === next) return true;
168
+ if (previous.length !== next.length) return false;
169
+ return previous.every((item, index) => item === next[index]);
170
+ }
171
+ /**
172
+ * Applies a delta to the result it was computed against.
173
+ * @template T - The type of the items.
174
+ * @param previous - The result the delta is relative to. Not modified.
175
+ * @param delta - The delta to apply.
176
+ * @returns The resulting items.
177
+ */
178
+ function applyQueryDelta(previous, delta) {
179
+ const removed = new Set(delta.removed);
180
+ const changedById = new Map(delta.changed.map((item) => [item.id, item]));
181
+ const movedIds = new Set(delta.moved.map(({ id }) => id));
182
+ const stationary = [];
183
+ const byId = /* @__PURE__ */ new Map();
184
+ previous.forEach((item) => {
185
+ if (removed.has(item.id)) return;
186
+ const current = changedById.get(item.id) ?? item;
187
+ byId.set(current.id, current);
188
+ if (!movedIds.has(current.id)) stationary.push(current);
189
+ });
190
+ const insertions = [...delta.added.map(({ index, item }) => ({
191
+ index,
192
+ item
193
+ })), ...delta.moved.map(({ index, id }) => ({
194
+ index,
195
+ item: byId.get(id)
196
+ }))].sort((a, b) => a.index - b.index);
197
+ const result = stationary;
198
+ insertions.forEach(({ index, item }) => {
199
+ if (item == null) return;
200
+ result.splice(index, 0, item);
201
+ });
202
+ return result;
203
+ }
149
204
  //#endregion
150
- export { Observer as default };
205
+ export { applyQueryDelta, callWithDelta, canApplyQueryDelta, diffQueryResults, isEmptyQueryDelta };