mutts 1.0.8 → 1.0.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +77 -35
- package/dist/browser.cjs +2144 -5355
- package/dist/browser.cjs.map +1 -1
- package/dist/browser.d.ts +2 -1655
- package/dist/browser.dev.cjs +110 -0
- package/dist/browser.dev.cjs.map +1 -0
- package/dist/browser.dev.d.ts +2 -0
- package/dist/browser.dev.esm.js +5 -0
- package/dist/browser.dev.esm.js.map +1 -0
- package/dist/browser.esm.js +20 -107
- package/dist/browser.esm.js.map +1 -1
- package/dist/chunks/{async-browser-CA0jPWIi.cjs → async-browser-BU_IfxYD.cjs} +19 -107
- package/dist/chunks/async-browser-BU_IfxYD.cjs.map +1 -0
- package/dist/chunks/{async-core-UqHzvJ-S.cjs → async-core-CRLKP3l-.cjs} +8 -4
- package/dist/chunks/async-core-CRLKP3l-.cjs.map +1 -0
- package/dist/chunks/{async-node-BYHuGTni.cjs → async-node-3PrbVAbB.cjs} +7 -12
- package/dist/chunks/async-node-3PrbVAbB.cjs.map +1 -0
- package/dist/chunks/index-CaaQQlPJ.esm.js +3174 -0
- package/dist/chunks/index-CaaQQlPJ.esm.js.map +1 -0
- package/dist/chunks/node-nKJBk8iJ.esm.js +96 -0
- package/dist/chunks/node-nKJBk8iJ.esm.js.map +1 -0
- package/dist/chunks/proxy-Dtg-bJ3T.cjs +3763 -0
- package/dist/chunks/proxy-Dtg-bJ3T.cjs.map +1 -0
- package/dist/chunks/proxy-r7lARftl.esm.js +3701 -0
- package/dist/chunks/proxy-r7lARftl.esm.js.map +1 -0
- package/dist/debug.cjs +980 -0
- package/dist/debug.cjs.map +1 -0
- package/dist/debug.d.ts +208 -0
- package/dist/debug.esm.js +950 -0
- package/dist/debug.esm.js.map +1 -0
- package/dist/devtools/manifest.json +1 -1
- package/dist/devtools/panel.html +1 -1
- package/dist/devtools/panel.js +107 -94
- package/dist/devtools/panel.js.map +1 -1
- package/dist/index.d.ts +1447 -13
- package/dist/mutts.umd.js +7167 -1
- package/dist/mutts.umd.js.map +1 -1
- package/dist/mutts.umd.min.js +1 -1
- package/dist/mutts.umd.min.js.map +1 -1
- package/dist/node.cjs +70 -66
- package/dist/node.cjs.map +1 -1
- package/dist/node.d.ts +2 -1
- package/dist/node.dev.cjs +110 -0
- package/dist/node.dev.cjs.map +1 -0
- package/dist/node.dev.d.ts +2 -0
- package/dist/node.dev.esm.js +6 -0
- package/dist/node.dev.esm.js.map +1 -0
- package/dist/node.esm.js +4 -103
- package/dist/node.esm.js.map +1 -1
- package/dist/{reactive/types.d.ts → types-W5vD6m2n.d.ts} +186 -93
- package/docs/ai/api-reference.md +12 -19
- package/docs/ai/manual.md +521 -17
- package/docs/events.md +57 -2
- package/docs/flavored.md +210 -0
- package/docs/reactive/advanced.md +314 -5
- package/docs/reactive/attend.md +142 -0
- package/docs/reactive/collections.md +76 -39
- package/docs/reactive/core.md +100 -14
- package/docs/reactive/debugging.md +123 -18
- package/docs/reactive/error-handling.md +121 -0
- package/docs/reactive/resource.md +125 -0
- package/docs/reactive/scan.md +247 -1
- package/docs/reactive.md +4 -1
- package/docs/std-decorators.md +102 -51
- package/docs/utils.md +70 -0
- package/docs/zone.md +3 -7
- package/package.json +64 -30
- package/dist/async/browser.d.ts +0 -2
- package/dist/async/browser.d.ts.map +0 -1
- package/dist/async/index.d.ts +0 -18
- package/dist/async/index.d.ts.map +0 -1
- package/dist/async/node.d.ts +0 -2
- package/dist/async/node.d.ts.map +0 -1
- package/dist/chunks/async-browser-CA0jPWIi.cjs.map +0 -1
- package/dist/chunks/async-core-UqHzvJ-S.cjs.map +0 -1
- package/dist/chunks/async-node-BYHuGTni.cjs.map +0 -1
- package/dist/chunks/index-DhaOVusv.esm.js +0 -6411
- package/dist/chunks/index-DhaOVusv.esm.js.map +0 -1
- package/dist/decorator.d.ts +0 -106
- package/dist/decorator.d.ts.map +0 -1
- package/dist/destroyable.d.ts +0 -87
- package/dist/destroyable.d.ts.map +0 -1
- package/dist/entry-browser.d.ts +0 -3
- package/dist/entry-browser.d.ts.map +0 -1
- package/dist/entry-node.d.ts +0 -3
- package/dist/entry-node.d.ts.map +0 -1
- package/dist/eventful.d.ts +0 -18
- package/dist/eventful.d.ts.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/indexable.d.ts +0 -243
- package/dist/indexable.d.ts.map +0 -1
- package/dist/introspection.d.ts +0 -27
- package/dist/introspection.d.ts.map +0 -1
- package/dist/iterableWeak.d.ts +0 -53
- package/dist/iterableWeak.d.ts.map +0 -1
- package/dist/mixins.d.ts +0 -25
- package/dist/mixins.d.ts.map +0 -1
- package/dist/promiseChain.d.ts +0 -20
- package/dist/promiseChain.d.ts.map +0 -1
- package/dist/reactive/array.d.ts +0 -49
- package/dist/reactive/array.d.ts.map +0 -1
- package/dist/reactive/buffer.d.ts +0 -44
- package/dist/reactive/buffer.d.ts.map +0 -1
- package/dist/reactive/change.d.ts +0 -29
- package/dist/reactive/change.d.ts.map +0 -1
- package/dist/reactive/debug.d.ts +0 -111
- package/dist/reactive/debug.d.ts.map +0 -1
- package/dist/reactive/deep-touch.d.ts +0 -28
- package/dist/reactive/deep-touch.d.ts.map +0 -1
- package/dist/reactive/deep-watch-state.d.ts +0 -25
- package/dist/reactive/deep-watch-state.d.ts.map +0 -1
- package/dist/reactive/deep-watch.d.ts +0 -19
- package/dist/reactive/deep-watch.d.ts.map +0 -1
- package/dist/reactive/effect-context.d.ts +0 -7
- package/dist/reactive/effect-context.d.ts.map +0 -1
- package/dist/reactive/effects.d.ts +0 -151
- package/dist/reactive/effects.d.ts.map +0 -1
- package/dist/reactive/index.d.ts +0 -20
- package/dist/reactive/index.d.ts.map +0 -1
- package/dist/reactive/interface.d.ts +0 -64
- package/dist/reactive/interface.d.ts.map +0 -1
- package/dist/reactive/map.d.ts +0 -30
- package/dist/reactive/map.d.ts.map +0 -1
- package/dist/reactive/memoize.d.ts +0 -5
- package/dist/reactive/memoize.d.ts.map +0 -1
- package/dist/reactive/non-reactive-state.d.ts +0 -9
- package/dist/reactive/non-reactive-state.d.ts.map +0 -1
- package/dist/reactive/non-reactive.d.ts +0 -11
- package/dist/reactive/non-reactive.d.ts.map +0 -1
- package/dist/reactive/project.d.ts +0 -41
- package/dist/reactive/project.d.ts.map +0 -1
- package/dist/reactive/proxy-state.d.ts +0 -8
- package/dist/reactive/proxy-state.d.ts.map +0 -1
- package/dist/reactive/proxy.d.ts +0 -23
- package/dist/reactive/proxy.d.ts.map +0 -1
- package/dist/reactive/record.d.ts +0 -116
- package/dist/reactive/record.d.ts.map +0 -1
- package/dist/reactive/register.d.ts +0 -64
- package/dist/reactive/register.d.ts.map +0 -1
- package/dist/reactive/registry.d.ts +0 -20
- package/dist/reactive/registry.d.ts.map +0 -1
- package/dist/reactive/set.d.ts +0 -28
- package/dist/reactive/set.d.ts.map +0 -1
- package/dist/reactive/tracking.d.ts +0 -7
- package/dist/reactive/tracking.d.ts.map +0 -1
- package/dist/reactive/types.d.ts.map +0 -1
- package/dist/std-decorators.d.ts +0 -50
- package/dist/std-decorators.d.ts.map +0 -1
- package/dist/utils.d.ts +0 -49
- package/dist/utils.d.ts.map +0 -1
- package/dist/zone.d.ts +0 -40
- package/dist/zone.d.ts.map +0 -1
- package/docs/reactive/project.md +0 -93
- package/src/async/browser.ts +0 -319
- package/src/async/index.ts +0 -23
- package/src/async/node.ts +0 -104
- package/src/decorator.ts +0 -272
- package/src/destroyable.ts +0 -199
- package/src/entry-browser.ts +0 -5
- package/src/entry-node.ts +0 -5
- package/src/eventful.ts +0 -77
- package/src/index.d.ts +0 -12
- package/src/index.ts +0 -64
- package/src/indexable.ts +0 -526
- package/src/introspection.ts +0 -59
- package/src/iterableWeak.ts +0 -233
- package/src/mixins.ts +0 -123
- package/src/promiseChain.ts +0 -110
- package/src/reactive/array.ts +0 -507
- package/src/reactive/buffer.ts +0 -168
- package/src/reactive/change.ts +0 -138
- package/src/reactive/debug.ts +0 -517
- package/src/reactive/deep-touch.ts +0 -268
- package/src/reactive/deep-watch-state.ts +0 -82
- package/src/reactive/deep-watch.ts +0 -168
- package/src/reactive/effect-context.ts +0 -18
- package/src/reactive/effects.ts +0 -1382
- package/src/reactive/index.ts +0 -75
- package/src/reactive/interface.ts +0 -210
- package/src/reactive/map.ts +0 -158
- package/src/reactive/memoize.ts +0 -163
- package/src/reactive/non-reactive-state.ts +0 -49
- package/src/reactive/non-reactive.ts +0 -43
- package/src/reactive/project.ts +0 -453
- package/src/reactive/proxy-state.ts +0 -27
- package/src/reactive/proxy.ts +0 -264
- package/src/reactive/record.ts +0 -196
- package/src/reactive/register.ts +0 -419
- package/src/reactive/registry.ts +0 -59
- package/src/reactive/set.ts +0 -130
- package/src/reactive/tracking.ts +0 -44
- package/src/reactive/types.ts +0 -440
- package/src/std-decorators.ts +0 -217
- package/src/utils.ts +0 -301
- package/src/zone.ts +0 -138
|
@@ -0,0 +1,3701 @@
|
|
|
1
|
+
// Queue for hooks registered before the environment is ready (circular dependency fix)
|
|
2
|
+
const hooks = new Set();
|
|
3
|
+
const asyncHooks = {
|
|
4
|
+
addHook(hook) {
|
|
5
|
+
hooks.add(hook);
|
|
6
|
+
return () => hooks.delete(hook);
|
|
7
|
+
},
|
|
8
|
+
/**
|
|
9
|
+
* [Hack] Sanitize a promise (or value) to prevent context leaks.
|
|
10
|
+
* Default: Identity function.
|
|
11
|
+
* Browser: Uses Macrotask wrapping to break microtask chains.
|
|
12
|
+
*/
|
|
13
|
+
sanitizePromise(p) {
|
|
14
|
+
return p;
|
|
15
|
+
},
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* Register a hook that will be called whenever an asynchronous operation is initiated.
|
|
19
|
+
* The hook should return a restorer function which will be called just before the async callback runs.
|
|
20
|
+
* That restorer should in turn return an undoer function which will be called just after the async callback finishes.
|
|
21
|
+
*/
|
|
22
|
+
const asyncHook = (hook) => asyncHooks.addHook(hook);
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Yields tuples containing elements from each input array, stopping at the longest array length
|
|
26
|
+
* @param args - Arrays to zip together
|
|
27
|
+
* @returns Generator yielding tuples containing elements from each input array
|
|
28
|
+
*/
|
|
29
|
+
function* zip(...args) {
|
|
30
|
+
if (!args.length)
|
|
31
|
+
return [];
|
|
32
|
+
const maxLength = Math.max(...args.map((arr) => arr.length));
|
|
33
|
+
for (let i = 0; i < maxLength; i++) {
|
|
34
|
+
const tuple = args.map((arr) => arr[i]);
|
|
35
|
+
yield tuple;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Checks if two arrays are strictly equal (shallow comparison)
|
|
40
|
+
* @param a - First value
|
|
41
|
+
* @param b - Second value
|
|
42
|
+
* @returns True if arrays are equal or values are strictly equal
|
|
43
|
+
*/
|
|
44
|
+
function arrayEquals(a, b) {
|
|
45
|
+
if (!Array.isArray(a) || !Array.isArray(b))
|
|
46
|
+
return false;
|
|
47
|
+
if (a === b)
|
|
48
|
+
return true;
|
|
49
|
+
if (a.length !== b.length)
|
|
50
|
+
return false;
|
|
51
|
+
for (let i = 0; i < a.length; i++) {
|
|
52
|
+
if (a[i] !== b[i])
|
|
53
|
+
return false;
|
|
54
|
+
}
|
|
55
|
+
return true;
|
|
56
|
+
}
|
|
57
|
+
const nativeConstructors = new Set([
|
|
58
|
+
Object,
|
|
59
|
+
Array,
|
|
60
|
+
Date,
|
|
61
|
+
Function,
|
|
62
|
+
Set,
|
|
63
|
+
Map,
|
|
64
|
+
WeakMap,
|
|
65
|
+
WeakSet,
|
|
66
|
+
Promise,
|
|
67
|
+
Error,
|
|
68
|
+
TypeError,
|
|
69
|
+
ReferenceError,
|
|
70
|
+
SyntaxError,
|
|
71
|
+
RangeError,
|
|
72
|
+
URIError,
|
|
73
|
+
EvalError,
|
|
74
|
+
Reflect,
|
|
75
|
+
Proxy,
|
|
76
|
+
RegExp,
|
|
77
|
+
String,
|
|
78
|
+
Number,
|
|
79
|
+
Boolean,
|
|
80
|
+
]);
|
|
81
|
+
/**
|
|
82
|
+
* Checks if a function is a constructor (class or constructor function)
|
|
83
|
+
* @param fn - The function to check
|
|
84
|
+
* @returns True if the function is a constructor
|
|
85
|
+
*/
|
|
86
|
+
function isConstructor(fn) {
|
|
87
|
+
return (fn &&
|
|
88
|
+
typeof fn === 'function' &&
|
|
89
|
+
(nativeConstructors.has(fn) || fn.toString?.().startsWith('class ')));
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Checks if a value is an object
|
|
93
|
+
* @param value - The value to check
|
|
94
|
+
* @returns True if the value is an object
|
|
95
|
+
*/
|
|
96
|
+
function isObject(value) {
|
|
97
|
+
return (typeof value === 'object' &&
|
|
98
|
+
value !== null &&
|
|
99
|
+
!Array.isArray(value) &&
|
|
100
|
+
!(value instanceof Date ||
|
|
101
|
+
value instanceof RegExp ||
|
|
102
|
+
value instanceof Error ||
|
|
103
|
+
value instanceof Set ||
|
|
104
|
+
value instanceof Map ||
|
|
105
|
+
value instanceof WeakSet ||
|
|
106
|
+
value instanceof WeakMap ||
|
|
107
|
+
value instanceof Promise ||
|
|
108
|
+
value instanceof Function));
|
|
109
|
+
}
|
|
110
|
+
const hasNode = typeof Node !== 'undefined';
|
|
111
|
+
const FoolProof = {
|
|
112
|
+
get(obj, prop, receiver) {
|
|
113
|
+
if (hasNode && obj instanceof Node)
|
|
114
|
+
return obj[prop];
|
|
115
|
+
return Reflect.get(obj, prop, receiver);
|
|
116
|
+
},
|
|
117
|
+
set(obj, prop, value, receiver) {
|
|
118
|
+
if (hasNode && obj instanceof Node) {
|
|
119
|
+
obj[prop] = value;
|
|
120
|
+
return true;
|
|
121
|
+
}
|
|
122
|
+
if (!(obj instanceof Object) && !Reflect.has(obj, prop)) {
|
|
123
|
+
Object.defineProperty(obj, prop, {
|
|
124
|
+
value,
|
|
125
|
+
configurable: true,
|
|
126
|
+
writable: true,
|
|
127
|
+
enumerable: true,
|
|
128
|
+
});
|
|
129
|
+
return true;
|
|
130
|
+
}
|
|
131
|
+
return Reflect.set(obj, prop, value, receiver);
|
|
132
|
+
},
|
|
133
|
+
};
|
|
134
|
+
function isOwnAccessor(obj, prop) {
|
|
135
|
+
const opd = Object.getOwnPropertyDescriptor(obj, prop);
|
|
136
|
+
return !!(opd?.get || opd?.set);
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Deeply compares two values.
|
|
140
|
+
* For objects, compares prototypes with === and then own properties recursively.
|
|
141
|
+
* Uses a cache to handle circular references.
|
|
142
|
+
* @param a - First value
|
|
143
|
+
* @param b - Second value
|
|
144
|
+
* @param cache - Map for circular reference protection (internal use)
|
|
145
|
+
* @returns True if values are deeply equal
|
|
146
|
+
*/
|
|
147
|
+
function deepCompare(a, b, cache = new Map()) {
|
|
148
|
+
if (a === b)
|
|
149
|
+
return true;
|
|
150
|
+
if (typeof a !== 'object' || a === null || typeof b !== 'object' || b === null) {
|
|
151
|
+
return a === b;
|
|
152
|
+
}
|
|
153
|
+
// Prototype check
|
|
154
|
+
const protoA = Object.getPrototypeOf(a);
|
|
155
|
+
const protoB = Object.getPrototypeOf(b);
|
|
156
|
+
if (protoA !== protoB) {
|
|
157
|
+
console.warn(`[deepCompare] prototype mismatch:`, {
|
|
158
|
+
nameA: a?.constructor?.name,
|
|
159
|
+
nameB: b?.constructor?.name,
|
|
160
|
+
});
|
|
161
|
+
return false;
|
|
162
|
+
}
|
|
163
|
+
// Circular reference protection
|
|
164
|
+
let compared = cache.get(a);
|
|
165
|
+
if (compared?.has(b))
|
|
166
|
+
return true;
|
|
167
|
+
if (!compared) {
|
|
168
|
+
compared = new Set();
|
|
169
|
+
cache.set(a, compared);
|
|
170
|
+
}
|
|
171
|
+
compared.add(b);
|
|
172
|
+
// Handle specific object types
|
|
173
|
+
if (Array.isArray(a)) {
|
|
174
|
+
if (!Array.isArray(b)) {
|
|
175
|
+
console.warn(`[deepCompare] B is not an array`);
|
|
176
|
+
return false;
|
|
177
|
+
}
|
|
178
|
+
if (a.length !== b.length) {
|
|
179
|
+
console.warn(`[deepCompare] array length mismatch:`, { lenA: a.length, lenB: b.length });
|
|
180
|
+
return false;
|
|
181
|
+
}
|
|
182
|
+
for (let i = 0; i < a.length; i++) {
|
|
183
|
+
if (!deepCompare(a[i], b[i], cache)) {
|
|
184
|
+
console.warn(`[deepCompare] array element mismatch at index ${i}`);
|
|
185
|
+
return false;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
return true;
|
|
189
|
+
}
|
|
190
|
+
if (a instanceof Date) {
|
|
191
|
+
const match = b instanceof Date && a.getTime() === b.getTime();
|
|
192
|
+
if (!match)
|
|
193
|
+
console.warn(`[deepCompare] Date mismatch`);
|
|
194
|
+
return match;
|
|
195
|
+
}
|
|
196
|
+
if (a instanceof RegExp) {
|
|
197
|
+
const match = b instanceof RegExp && a.toString() === b.toString();
|
|
198
|
+
if (!match)
|
|
199
|
+
console.warn(`[deepCompare] RegExp mismatch`);
|
|
200
|
+
return match;
|
|
201
|
+
}
|
|
202
|
+
if (a instanceof Set) {
|
|
203
|
+
if (!(b instanceof Set) || a.size !== b.size) {
|
|
204
|
+
console.warn(`[deepCompare] Set size mismatch`);
|
|
205
|
+
return false;
|
|
206
|
+
}
|
|
207
|
+
for (const val of a) {
|
|
208
|
+
let found = false;
|
|
209
|
+
for (const bVal of b) {
|
|
210
|
+
if (deepCompare(val, bVal, cache)) {
|
|
211
|
+
found = true;
|
|
212
|
+
break;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
if (!found) {
|
|
216
|
+
console.warn(`[deepCompare] missing Set element`);
|
|
217
|
+
return false;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
return true;
|
|
221
|
+
}
|
|
222
|
+
if (a instanceof Map) {
|
|
223
|
+
if (!(b instanceof Map) || a.size !== b.size) {
|
|
224
|
+
console.warn(`[deepCompare] Map size mismatch`);
|
|
225
|
+
return false;
|
|
226
|
+
}
|
|
227
|
+
for (const [key, val] of a) {
|
|
228
|
+
if (!b.has(key)) {
|
|
229
|
+
let foundMatch = false;
|
|
230
|
+
for (const [bKey, bVal] of b) {
|
|
231
|
+
if (deepCompare(key, bKey, cache) && deepCompare(val, bVal, cache)) {
|
|
232
|
+
foundMatch = true;
|
|
233
|
+
break;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
if (!foundMatch) {
|
|
237
|
+
console.warn(`[deepCompare] missing Map key`);
|
|
238
|
+
return false;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
else {
|
|
242
|
+
if (!deepCompare(val, b.get(key), cache)) {
|
|
243
|
+
console.warn(`[deepCompare] Map value mismatch for key`);
|
|
244
|
+
return false;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
return true;
|
|
249
|
+
}
|
|
250
|
+
// Compare own properties
|
|
251
|
+
const keysA = Object.keys(a);
|
|
252
|
+
const keysB = Object.keys(b);
|
|
253
|
+
if (keysA.length !== keysB.length) {
|
|
254
|
+
console.warn(`[deepCompare] keys length mismatch:`, {
|
|
255
|
+
lenA: keysA.length,
|
|
256
|
+
lenB: keysB.length,
|
|
257
|
+
keysA,
|
|
258
|
+
keysB,
|
|
259
|
+
a,
|
|
260
|
+
b,
|
|
261
|
+
});
|
|
262
|
+
return false;
|
|
263
|
+
}
|
|
264
|
+
for (const key of keysA) {
|
|
265
|
+
if (!Object.hasOwn(b, key)) {
|
|
266
|
+
console.warn(`[deepCompare] missing key ${String(key)} in B`);
|
|
267
|
+
return false;
|
|
268
|
+
}
|
|
269
|
+
if (!deepCompare(a[key], b[key], cache)) {
|
|
270
|
+
console.warn(`[deepCompare] value mismatch for key ${String(key)}:`, {
|
|
271
|
+
valA: a[key],
|
|
272
|
+
valB: b[key],
|
|
273
|
+
});
|
|
274
|
+
return false;
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
return true;
|
|
278
|
+
}
|
|
279
|
+
// Internal use: Used for reactive sets/maps to differentiate between different reactive containers: `x.get('aKey')` vs. `x['aKey']`
|
|
280
|
+
const contentRefs = new WeakMap();
|
|
281
|
+
function contentRef(container) {
|
|
282
|
+
if (!contentRefs.has(container))
|
|
283
|
+
contentRefs.set(container, Object.seal(Object.create(null, {
|
|
284
|
+
contentOf: { value: container, writable: false, configurable: false },
|
|
285
|
+
})));
|
|
286
|
+
return contentRefs.get(container);
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* Tags an object with a name
|
|
290
|
+
* @param name - The name to tag the object with
|
|
291
|
+
* @param obj - The object to tag
|
|
292
|
+
* @returns The object with the tag
|
|
293
|
+
*/
|
|
294
|
+
function tag(name, obj) {
|
|
295
|
+
Object.defineProperties(obj, {
|
|
296
|
+
[Symbol.toStringTag]: {
|
|
297
|
+
value: name,
|
|
298
|
+
writable: false,
|
|
299
|
+
configurable: true,
|
|
300
|
+
},
|
|
301
|
+
toString: {
|
|
302
|
+
value: () => name,
|
|
303
|
+
writable: false,
|
|
304
|
+
configurable: true,
|
|
305
|
+
},
|
|
306
|
+
});
|
|
307
|
+
return obj;
|
|
308
|
+
}
|
|
309
|
+
/**
|
|
310
|
+
* Renames a function with a new name
|
|
311
|
+
* @param name - The new name for the function
|
|
312
|
+
* @param fn - The function to rename
|
|
313
|
+
* @returns The function with the new name
|
|
314
|
+
*/
|
|
315
|
+
function named(name, fn) {
|
|
316
|
+
Object.defineProperty(fn, 'name', {
|
|
317
|
+
value: fn.name ? `${fn.name}::${name}` : name,
|
|
318
|
+
writable: false,
|
|
319
|
+
configurable: true,
|
|
320
|
+
});
|
|
321
|
+
return fn;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
// biome-ignore-all lint/suspicious/noConfusingVoidType: We *love* voids
|
|
325
|
+
// Standardized decorator system that works with both Legacy and Modern decorators
|
|
326
|
+
/**
|
|
327
|
+
* Error thrown when decorator operations fail
|
|
328
|
+
*/
|
|
329
|
+
class DecoratorError extends Error {
|
|
330
|
+
constructor(message) {
|
|
331
|
+
super(message);
|
|
332
|
+
this.name = 'DecoratorException';
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
/**
|
|
336
|
+
* Creates a decorator that works with Legacy decorator proposals
|
|
337
|
+
* @param description - The decorator description object
|
|
338
|
+
* @returns A decorator function compatible with Legacy decorators
|
|
339
|
+
*/
|
|
340
|
+
function legacyDecorator(description) {
|
|
341
|
+
return function (target, propertyKey, descriptor, ...args) {
|
|
342
|
+
if (propertyKey === undefined) {
|
|
343
|
+
if (isConstructor(target)) {
|
|
344
|
+
if (!('class' in description))
|
|
345
|
+
throw new Error('Decorator cannot be applied to a class');
|
|
346
|
+
return description.class(target);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
else if (typeof target === 'object' && ['string', 'symbol'].includes(typeof propertyKey)) {
|
|
350
|
+
if (!descriptor)
|
|
351
|
+
throw new Error('Decorator cannot be applied to a field');
|
|
352
|
+
else if (typeof descriptor === 'object' && 'configurable' in descriptor) {
|
|
353
|
+
if ('get' in descriptor || 'set' in descriptor) {
|
|
354
|
+
if (!('getter' in description || 'setter' in description))
|
|
355
|
+
throw new Error('Decorator cannot be applied to a getter or setter');
|
|
356
|
+
if ('getter' in description) {
|
|
357
|
+
const newGetter = description.getter(descriptor.get, target, propertyKey);
|
|
358
|
+
if (newGetter)
|
|
359
|
+
descriptor.get = newGetter;
|
|
360
|
+
}
|
|
361
|
+
if ('setter' in description) {
|
|
362
|
+
const newSetter = description.setter(descriptor.set, target, propertyKey);
|
|
363
|
+
if (newSetter)
|
|
364
|
+
descriptor.set = newSetter;
|
|
365
|
+
}
|
|
366
|
+
return descriptor;
|
|
367
|
+
}
|
|
368
|
+
else if (typeof descriptor.value === 'function') {
|
|
369
|
+
if (!('method' in description))
|
|
370
|
+
throw new Error('Decorator cannot be applied to a method');
|
|
371
|
+
const newMethod = description.method(descriptor.value, target, propertyKey);
|
|
372
|
+
if (newMethod)
|
|
373
|
+
descriptor.value = newMethod;
|
|
374
|
+
return descriptor;
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
if (!('default' in description))
|
|
379
|
+
throw new Error('Decorator do not have a default implementation');
|
|
380
|
+
return description.default.call(this, target, propertyKey, descriptor, ...args);
|
|
381
|
+
};
|
|
382
|
+
}
|
|
383
|
+
/**
|
|
384
|
+
* Creates a decorator that works with Modern decorator proposals
|
|
385
|
+
* @param description - The decorator description object
|
|
386
|
+
* @returns A decorator function compatible with Modern decorators
|
|
387
|
+
*/
|
|
388
|
+
function modernDecorator(description) {
|
|
389
|
+
/*return function (target: any, context?: DecoratorContext, ...args: any[]) {*/
|
|
390
|
+
return function (target, context, ...args) {
|
|
391
|
+
if (!context?.kind || typeof context.kind !== 'string') {
|
|
392
|
+
if (!('default' in description))
|
|
393
|
+
throw new Error('Decorator do not have a default implementation');
|
|
394
|
+
return description.default.call(this, target, context, ...args);
|
|
395
|
+
}
|
|
396
|
+
switch (context.kind) {
|
|
397
|
+
case 'class':
|
|
398
|
+
if (!('class' in description))
|
|
399
|
+
throw new Error('Decorator cannot be applied to a class');
|
|
400
|
+
return description.class(target);
|
|
401
|
+
case 'field':
|
|
402
|
+
throw new Error('Decorator cannot be applied to a field');
|
|
403
|
+
case 'getter':
|
|
404
|
+
if (!('getter' in description))
|
|
405
|
+
throw new Error('Decorator cannot be applied to a getter');
|
|
406
|
+
return description.getter(target, target, context.name);
|
|
407
|
+
case 'setter':
|
|
408
|
+
if (!('setter' in description))
|
|
409
|
+
throw new Error('Decorator cannot be applied to a setter');
|
|
410
|
+
return description.setter(target, target, context.name);
|
|
411
|
+
case 'method':
|
|
412
|
+
if (!('method' in description))
|
|
413
|
+
throw new Error('Decorator cannot be applied to a method');
|
|
414
|
+
return description.method(target, target, context.name);
|
|
415
|
+
case 'accessor': {
|
|
416
|
+
if (!('getter' in description || 'setter' in description))
|
|
417
|
+
throw new Error('Decorator cannot be applied to a getter or setter');
|
|
418
|
+
const rv = {};
|
|
419
|
+
if ('getter' in description) {
|
|
420
|
+
const newGetter = description.getter(target.get, target, context.name);
|
|
421
|
+
if (newGetter)
|
|
422
|
+
rv.get = newGetter;
|
|
423
|
+
}
|
|
424
|
+
if ('setter' in description) {
|
|
425
|
+
const newSetter = description.setter(target.set, target, context.name);
|
|
426
|
+
if (newSetter)
|
|
427
|
+
rv.set = newSetter;
|
|
428
|
+
}
|
|
429
|
+
return rv;
|
|
430
|
+
}
|
|
431
|
+
//return description.accessor?.(target, context.name, target)
|
|
432
|
+
}
|
|
433
|
+
};
|
|
434
|
+
}
|
|
435
|
+
/**
|
|
436
|
+
* Detects if the decorator is being called in modern (Modern) or legacy (Legacy) mode
|
|
437
|
+
* based on the arguments passed to the decorator function
|
|
438
|
+
*/
|
|
439
|
+
function detectDecoratorMode(_target, contextOrKey, _descriptor) {
|
|
440
|
+
// Modern decorators have a context object as the second parameter
|
|
441
|
+
// Legacy decorators have a string/symbol key as the second parameter
|
|
442
|
+
if (typeof contextOrKey === 'object' &&
|
|
443
|
+
contextOrKey !== null &&
|
|
444
|
+
typeof contextOrKey.kind === 'string') {
|
|
445
|
+
return 'modern';
|
|
446
|
+
}
|
|
447
|
+
return 'legacy';
|
|
448
|
+
}
|
|
449
|
+
/**
|
|
450
|
+
* Main decorator factory that automatically detects and works with both Legacy and Modern decorator proposals
|
|
451
|
+
* @param description - The decorator description object
|
|
452
|
+
* @returns A decorator that works in both Legacy and Modern environments
|
|
453
|
+
*/
|
|
454
|
+
const decorator = (description) => {
|
|
455
|
+
const modern = modernDecorator(description);
|
|
456
|
+
const legacy = legacyDecorator(description);
|
|
457
|
+
return ((target, contextOrKey, ...args) => {
|
|
458
|
+
const mode = detectDecoratorMode(target, contextOrKey, args[0]);
|
|
459
|
+
return mode === 'modern'
|
|
460
|
+
? modern(target, contextOrKey, ...args)
|
|
461
|
+
: legacy(target, contextOrKey, ...args);
|
|
462
|
+
});
|
|
463
|
+
};
|
|
464
|
+
|
|
465
|
+
/**
|
|
466
|
+
* Creates a flavored (extensible) version of a function with chainable property modifiers.
|
|
467
|
+
*
|
|
468
|
+
* Each property defined in `flavors` returns a new flavored function that transforms
|
|
469
|
+
* how the original function is called. This enables a fluent API where properties
|
|
470
|
+
* create specialized variants of the base function.
|
|
471
|
+
*
|
|
472
|
+
* @param fn - The base function to flavor
|
|
473
|
+
* @param flavors - Object defining the flavor properties (getters or methods)
|
|
474
|
+
* @returns A proxy of the function with the flavor properties attached
|
|
475
|
+
*
|
|
476
|
+
* @example
|
|
477
|
+
* ```typescript
|
|
478
|
+
* function greet(name: string, options?: { loud?: boolean }) {
|
|
479
|
+
* const greeting = `Hello, ${name}!`
|
|
480
|
+
* return options?.loud ? greeting.toUpperCase() : greeting
|
|
481
|
+
* }
|
|
482
|
+
*
|
|
483
|
+
* const flavoredGreet = flavored(greet, {
|
|
484
|
+
* get loud() {
|
|
485
|
+
* return createFlavor(this, (name, opts) => [name, { ...opts, loud: true }])
|
|
486
|
+
* }
|
|
487
|
+
* })
|
|
488
|
+
*
|
|
489
|
+
* flavoredGreet('World') // "Hello, World!"
|
|
490
|
+
* flavoredGreet.loud('World') // "HELLO, WORLD!"
|
|
491
|
+
* ```
|
|
492
|
+
*/
|
|
493
|
+
/**
|
|
494
|
+
* Creates a flavored (extensible) version of a function with chainable property modifiers.
|
|
495
|
+
*/
|
|
496
|
+
function flavored(fn, flavors) {
|
|
497
|
+
fn.flavors = flavors;
|
|
498
|
+
return new Proxy(fn, {
|
|
499
|
+
get(target, prop, receiver) {
|
|
500
|
+
if (prop in flavors) {
|
|
501
|
+
return Reflect.get(flavors, prop, receiver);
|
|
502
|
+
}
|
|
503
|
+
return target[prop];
|
|
504
|
+
},
|
|
505
|
+
});
|
|
506
|
+
}
|
|
507
|
+
/**
|
|
508
|
+
* Creates a new flavored function that transforms arguments before calling the base.
|
|
509
|
+
*
|
|
510
|
+
* @param fn - The base flavored function
|
|
511
|
+
* @param transform - Function that receives the original arguments and returns transformed arguments
|
|
512
|
+
* @returns A new flavored function with the transformation applied
|
|
513
|
+
*
|
|
514
|
+
* @example
|
|
515
|
+
* ```typescript
|
|
516
|
+
* const loudGreet = createFlavor(greet, (name, opts) => [name, { ...opts, loud: true }])
|
|
517
|
+
* ```
|
|
518
|
+
*/
|
|
519
|
+
function createFlavor(fn, transform, name) {
|
|
520
|
+
const fct = function flavorWrapper(...args) {
|
|
521
|
+
return fn.apply(this, transform(...args));
|
|
522
|
+
};
|
|
523
|
+
if (name)
|
|
524
|
+
named(name, fct);
|
|
525
|
+
return flavored(fct, fn.flavors || {});
|
|
526
|
+
}
|
|
527
|
+
/**
|
|
528
|
+
* Creates a new flavored function that merges options objects at a specific index.
|
|
529
|
+
* By default, uses the function's arity (length) as the index for options.
|
|
530
|
+
*
|
|
531
|
+
* @param fn - The base flavored function
|
|
532
|
+
* @param defaultOptions - Options to merge
|
|
533
|
+
* @param optionsIndex - Optional explicit index for options (defaults to fn.length)
|
|
534
|
+
* @param name - Optional name for the wrapper
|
|
535
|
+
* @returns A new flavored function
|
|
536
|
+
*/
|
|
537
|
+
function flavorOptions(fn, defaultOptions, opts = {}) {
|
|
538
|
+
// If the function is already flavorOptions-wrapped, it might have an index stored
|
|
539
|
+
const targetIndex = opts.optionsIndex ?? fn.optionsIndex ?? fn.length;
|
|
540
|
+
const fct = function flavorOptionsWrapper(...args) {
|
|
541
|
+
const newArgs = [...args];
|
|
542
|
+
// Ensure we have enough arguments to reach the options index
|
|
543
|
+
while (newArgs.length <= targetIndex) {
|
|
544
|
+
newArgs.push(undefined);
|
|
545
|
+
}
|
|
546
|
+
const currentOptions = newArgs[targetIndex];
|
|
547
|
+
const isObject = currentOptions !== null &&
|
|
548
|
+
typeof currentOptions === 'object' &&
|
|
549
|
+
!Array.isArray(currentOptions);
|
|
550
|
+
newArgs[targetIndex] = isObject
|
|
551
|
+
? { ...defaultOptions, ...currentOptions }
|
|
552
|
+
: defaultOptions;
|
|
553
|
+
return fn.apply(this, newArgs);
|
|
554
|
+
};
|
|
555
|
+
if (opts.name)
|
|
556
|
+
named(`${fn.name}.${opts.name}`, fct);
|
|
557
|
+
// Preserve arity and options track
|
|
558
|
+
Object.defineProperty(fct, 'length', { value: fn.length });
|
|
559
|
+
fct.optionsIndex = targetIndex;
|
|
560
|
+
return flavored(fct, fn.flavors || {});
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
/// <reference lib="esnext.collection" />
|
|
564
|
+
var _a, _b;
|
|
565
|
+
/**
|
|
566
|
+
* Uses weak references but still may iterate through them
|
|
567
|
+
* Note: The behavior is highly dependant on the garbage collector - some entries are perhaps deemed to be collected: don't resuscitate them
|
|
568
|
+
*/
|
|
569
|
+
class IterableWeakMap {
|
|
570
|
+
constructor(entries) {
|
|
571
|
+
this.uuids = new WeakMap();
|
|
572
|
+
this.refs = {};
|
|
573
|
+
this[_a] = 'IterableWeakMap';
|
|
574
|
+
// Create a FinalizationRegistry to clean up refs when keys are garbage collected
|
|
575
|
+
this.registry = new FinalizationRegistry((uuid) => {
|
|
576
|
+
delete this.refs[uuid];
|
|
577
|
+
});
|
|
578
|
+
if (entries)
|
|
579
|
+
for (const [k, v] of entries)
|
|
580
|
+
this.set(k, v);
|
|
581
|
+
}
|
|
582
|
+
createIterator(cb) {
|
|
583
|
+
const { refs } = this;
|
|
584
|
+
return (function* () {
|
|
585
|
+
for (const uuid of Object.keys(refs)) {
|
|
586
|
+
const [keyRef, value] = refs[uuid];
|
|
587
|
+
const key = keyRef.deref();
|
|
588
|
+
if (key)
|
|
589
|
+
yield cb(key, value);
|
|
590
|
+
else
|
|
591
|
+
delete refs[uuid];
|
|
592
|
+
}
|
|
593
|
+
return undefined;
|
|
594
|
+
})();
|
|
595
|
+
}
|
|
596
|
+
clear() {
|
|
597
|
+
// Unregister all keys from the FinalizationRegistry
|
|
598
|
+
for (const uuid of Object.keys(this.refs)) {
|
|
599
|
+
const key = this.refs[uuid][0].deref();
|
|
600
|
+
if (key)
|
|
601
|
+
this.registry.unregister(key);
|
|
602
|
+
}
|
|
603
|
+
this.uuids = new WeakMap();
|
|
604
|
+
this.refs = {};
|
|
605
|
+
}
|
|
606
|
+
delete(key) {
|
|
607
|
+
const uuid = this.uuids.get(key);
|
|
608
|
+
if (!uuid)
|
|
609
|
+
return false;
|
|
610
|
+
delete this.refs[uuid];
|
|
611
|
+
this.uuids.delete(key);
|
|
612
|
+
this.registry.unregister(key);
|
|
613
|
+
return true;
|
|
614
|
+
}
|
|
615
|
+
forEach(callbackfn, thisArg) {
|
|
616
|
+
for (const [k, v] of this)
|
|
617
|
+
callbackfn.call(thisArg ?? this, v, k, thisArg ?? this);
|
|
618
|
+
}
|
|
619
|
+
get(key) {
|
|
620
|
+
const uuid = this.uuids.get(key);
|
|
621
|
+
if (!uuid)
|
|
622
|
+
return undefined;
|
|
623
|
+
return this.refs[uuid][1];
|
|
624
|
+
}
|
|
625
|
+
has(key) {
|
|
626
|
+
return this.uuids.has(key);
|
|
627
|
+
}
|
|
628
|
+
set(key, value) {
|
|
629
|
+
let uuid = this.uuids.get(key);
|
|
630
|
+
if (uuid) {
|
|
631
|
+
this.refs[uuid][1] = value;
|
|
632
|
+
}
|
|
633
|
+
else {
|
|
634
|
+
uuid = crypto.randomUUID();
|
|
635
|
+
this.uuids.set(key, uuid);
|
|
636
|
+
this.refs[uuid] = [new WeakRef(key), value];
|
|
637
|
+
// Register key for cleanup when garbage collected
|
|
638
|
+
this.registry.register(key, uuid, key);
|
|
639
|
+
}
|
|
640
|
+
return this;
|
|
641
|
+
}
|
|
642
|
+
get size() {
|
|
643
|
+
return [...this].length;
|
|
644
|
+
}
|
|
645
|
+
entries() {
|
|
646
|
+
return this.createIterator((key, value) => [key, value]);
|
|
647
|
+
}
|
|
648
|
+
keys() {
|
|
649
|
+
return this.createIterator((key, _value) => key);
|
|
650
|
+
}
|
|
651
|
+
values() {
|
|
652
|
+
return this.createIterator((_key, value) => value);
|
|
653
|
+
}
|
|
654
|
+
[Symbol.iterator]() {
|
|
655
|
+
return this.entries();
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
_a = Symbol.toStringTag;
|
|
659
|
+
/**
|
|
660
|
+
* Uses weak references but still may iterate through them
|
|
661
|
+
* Note: The behavior is highly dependant on the garbage collector - some entries are perhaps deemed to be collected: don't resuscitate them
|
|
662
|
+
*/
|
|
663
|
+
class IterableWeakSet {
|
|
664
|
+
constructor(entries) {
|
|
665
|
+
this.uuids = new WeakMap();
|
|
666
|
+
this.refs = {};
|
|
667
|
+
this[_b] = 'IterableWeakSet';
|
|
668
|
+
// Create a FinalizationRegistry to clean up refs when values are garbage collected
|
|
669
|
+
this.registry = new FinalizationRegistry((uuid) => {
|
|
670
|
+
delete this.refs[uuid];
|
|
671
|
+
});
|
|
672
|
+
if (entries)
|
|
673
|
+
for (const k of entries)
|
|
674
|
+
this.add(k);
|
|
675
|
+
}
|
|
676
|
+
createIterator(cb) {
|
|
677
|
+
const { refs } = this;
|
|
678
|
+
return (function* () {
|
|
679
|
+
for (const uuid of Object.keys(refs)) {
|
|
680
|
+
const key = refs[uuid].deref();
|
|
681
|
+
if (key)
|
|
682
|
+
yield cb(key);
|
|
683
|
+
else
|
|
684
|
+
delete refs[uuid];
|
|
685
|
+
}
|
|
686
|
+
return undefined;
|
|
687
|
+
})();
|
|
688
|
+
}
|
|
689
|
+
clear() {
|
|
690
|
+
// Unregister all values from the FinalizationRegistry
|
|
691
|
+
for (const uuid of Object.keys(this.refs)) {
|
|
692
|
+
const value = this.refs[uuid].deref();
|
|
693
|
+
if (value)
|
|
694
|
+
this.registry.unregister(value);
|
|
695
|
+
}
|
|
696
|
+
this.uuids = new WeakMap();
|
|
697
|
+
this.refs = {};
|
|
698
|
+
}
|
|
699
|
+
add(value) {
|
|
700
|
+
let uuid = this.uuids.get(value);
|
|
701
|
+
if (!uuid) {
|
|
702
|
+
uuid = crypto.randomUUID();
|
|
703
|
+
this.uuids.set(value, uuid);
|
|
704
|
+
this.refs[uuid] = new WeakRef(value);
|
|
705
|
+
// Register value for cleanup when garbage collected
|
|
706
|
+
this.registry.register(value, uuid, value);
|
|
707
|
+
}
|
|
708
|
+
return this;
|
|
709
|
+
}
|
|
710
|
+
delete(value) {
|
|
711
|
+
const uuid = this.uuids.get(value);
|
|
712
|
+
if (!uuid)
|
|
713
|
+
return false;
|
|
714
|
+
delete this.refs[uuid];
|
|
715
|
+
this.uuids.delete(value);
|
|
716
|
+
this.registry.unregister(value);
|
|
717
|
+
return true;
|
|
718
|
+
}
|
|
719
|
+
forEach(callbackfn, thisArg) {
|
|
720
|
+
for (const value of this)
|
|
721
|
+
callbackfn.call(thisArg ?? this, value, value, thisArg ?? this);
|
|
722
|
+
}
|
|
723
|
+
has(value) {
|
|
724
|
+
return this.uuids.has(value);
|
|
725
|
+
}
|
|
726
|
+
get size() {
|
|
727
|
+
return [...this].length;
|
|
728
|
+
}
|
|
729
|
+
entries() {
|
|
730
|
+
return this.createIterator((key) => [key, key]);
|
|
731
|
+
}
|
|
732
|
+
keys() {
|
|
733
|
+
return this.createIterator((key) => key);
|
|
734
|
+
}
|
|
735
|
+
values() {
|
|
736
|
+
return this.createIterator((key) => key);
|
|
737
|
+
}
|
|
738
|
+
[Symbol.iterator]() {
|
|
739
|
+
return this.keys();
|
|
740
|
+
}
|
|
741
|
+
union(other) {
|
|
742
|
+
const others = {
|
|
743
|
+
[Symbol.iterator]() {
|
|
744
|
+
return other.keys();
|
|
745
|
+
},
|
|
746
|
+
};
|
|
747
|
+
const that = this;
|
|
748
|
+
return new Set((function* () {
|
|
749
|
+
yield* that;
|
|
750
|
+
for (const value of others)
|
|
751
|
+
if (!that.has(value))
|
|
752
|
+
yield value;
|
|
753
|
+
})());
|
|
754
|
+
}
|
|
755
|
+
intersection(other) {
|
|
756
|
+
const that = this;
|
|
757
|
+
return new Set((function* () {
|
|
758
|
+
for (const value of that)
|
|
759
|
+
if (other.has(value))
|
|
760
|
+
yield value;
|
|
761
|
+
})());
|
|
762
|
+
}
|
|
763
|
+
difference(other) {
|
|
764
|
+
const that = this;
|
|
765
|
+
return new Set((function* () {
|
|
766
|
+
for (const value of that)
|
|
767
|
+
if (!other.has(value))
|
|
768
|
+
yield value;
|
|
769
|
+
})());
|
|
770
|
+
}
|
|
771
|
+
symmetricDifference(other) {
|
|
772
|
+
const others = {
|
|
773
|
+
[Symbol.iterator]() {
|
|
774
|
+
return other.keys();
|
|
775
|
+
},
|
|
776
|
+
};
|
|
777
|
+
const that = this;
|
|
778
|
+
return new Set((function* () {
|
|
779
|
+
for (const value of that)
|
|
780
|
+
if (!other.has(value))
|
|
781
|
+
yield value;
|
|
782
|
+
for (const value of others)
|
|
783
|
+
if (!that.has(value))
|
|
784
|
+
yield value;
|
|
785
|
+
})());
|
|
786
|
+
}
|
|
787
|
+
isSubsetOf(other) {
|
|
788
|
+
for (const value of this)
|
|
789
|
+
if (!other.has(value))
|
|
790
|
+
return false;
|
|
791
|
+
return true;
|
|
792
|
+
}
|
|
793
|
+
isSupersetOf(other) {
|
|
794
|
+
const others = {
|
|
795
|
+
[Symbol.iterator]() {
|
|
796
|
+
return other.keys();
|
|
797
|
+
},
|
|
798
|
+
};
|
|
799
|
+
for (const value of others)
|
|
800
|
+
if (!this.has(value))
|
|
801
|
+
return false;
|
|
802
|
+
return true;
|
|
803
|
+
}
|
|
804
|
+
isDisjointFrom(other) {
|
|
805
|
+
for (const value of this)
|
|
806
|
+
if (other.has(value))
|
|
807
|
+
return false;
|
|
808
|
+
return true;
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
_b = Symbol.toStringTag;
|
|
812
|
+
|
|
813
|
+
/**
|
|
814
|
+
* Creates a mixin that can be used both as a class (extends) and as a function (mixin)
|
|
815
|
+
*
|
|
816
|
+
* This function supports:
|
|
817
|
+
* - Using mixins as base classes: `class MyClass extends MyMixin`
|
|
818
|
+
* - Using mixins as functions: `class MyClass extends MyMixin(SomeBase)`
|
|
819
|
+
* - Composing mixins: `const Composed = MixinA(MixinB)`
|
|
820
|
+
* - Type-safe property inference for all patterns
|
|
821
|
+
*
|
|
822
|
+
* @param mixinFunction - The function that creates the mixin
|
|
823
|
+
* @param unwrapFunction - Optional function to unwrap reactive objects for method calls
|
|
824
|
+
* @returns A mixin that can be used both as a class and as a function
|
|
825
|
+
*/
|
|
826
|
+
function mixin(mixinFunction, unwrapFunction) {
|
|
827
|
+
/**
|
|
828
|
+
* Cache for mixin results to ensure the same base class always returns the same mixed class
|
|
829
|
+
*/
|
|
830
|
+
const mixinCache = new WeakMap();
|
|
831
|
+
// Apply the mixin to Object as the base class
|
|
832
|
+
const MixedBase = mixinFunction(Object);
|
|
833
|
+
mixinCache.set(Object, MixedBase);
|
|
834
|
+
// Create the proxy that handles both constructor and function calls
|
|
835
|
+
return new Proxy(MixedBase, {
|
|
836
|
+
// Handle `MixinClass(SomeBase)` - use as mixin function
|
|
837
|
+
apply(_target, _thisArg, args) {
|
|
838
|
+
if (args.length === 0) {
|
|
839
|
+
throw new Error('Mixin requires a base class');
|
|
840
|
+
}
|
|
841
|
+
const baseClass = args[0];
|
|
842
|
+
if (typeof baseClass !== 'function') {
|
|
843
|
+
throw new Error('Mixin requires a constructor function');
|
|
844
|
+
}
|
|
845
|
+
// Check if it's a valid constructor or a mixin
|
|
846
|
+
if (!isConstructor(baseClass) &&
|
|
847
|
+
!(baseClass && typeof baseClass === 'function' && baseClass.prototype)) {
|
|
848
|
+
throw new Error('Mixin requires a valid constructor');
|
|
849
|
+
}
|
|
850
|
+
// Check cache first
|
|
851
|
+
const cached = mixinCache.get(baseClass);
|
|
852
|
+
if (cached) {
|
|
853
|
+
return cached;
|
|
854
|
+
}
|
|
855
|
+
let usedBase = baseClass;
|
|
856
|
+
if (unwrapFunction) {
|
|
857
|
+
// Create a proxied base class that handles method unwrapping
|
|
858
|
+
const ProxiedBaseClass = class extends baseClass {
|
|
859
|
+
};
|
|
860
|
+
// Proxy the prototype methods to handle unwrapping
|
|
861
|
+
const originalPrototype = baseClass.prototype;
|
|
862
|
+
const proxiedPrototype = new Proxy(originalPrototype, {
|
|
863
|
+
get(target, prop, receiver) {
|
|
864
|
+
const value = FoolProof.get(target, prop, receiver);
|
|
865
|
+
// Only wrap methods that are likely to access private fields
|
|
866
|
+
// Skip symbols and special properties that the reactive system needs
|
|
867
|
+
if (typeof value === 'function' &&
|
|
868
|
+
typeof prop === 'string' &&
|
|
869
|
+
!['constructor', 'toString', 'valueOf'].includes(prop)) {
|
|
870
|
+
// Return a wrapped version that uses unwrapped context
|
|
871
|
+
return function (...args) {
|
|
872
|
+
// Use the unwrapping function if provided, otherwise use this
|
|
873
|
+
const context = unwrapFunction(this);
|
|
874
|
+
return value.apply(context, args);
|
|
875
|
+
};
|
|
876
|
+
}
|
|
877
|
+
return value;
|
|
878
|
+
},
|
|
879
|
+
});
|
|
880
|
+
// Set the proxied prototype
|
|
881
|
+
Object.setPrototypeOf(ProxiedBaseClass.prototype, proxiedPrototype);
|
|
882
|
+
usedBase = ProxiedBaseClass;
|
|
883
|
+
}
|
|
884
|
+
// Create the mixed class using the proxied base class
|
|
885
|
+
const mixedClass = mixinFunction(usedBase);
|
|
886
|
+
// Cache the result
|
|
887
|
+
mixinCache.set(baseClass, mixedClass);
|
|
888
|
+
return mixedClass;
|
|
889
|
+
},
|
|
890
|
+
});
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
/******************************************************************************
|
|
894
|
+
Copyright (c) Microsoft Corporation.
|
|
895
|
+
|
|
896
|
+
Permission to use, copy, modify, and/or distribute this software for any
|
|
897
|
+
purpose with or without fee is hereby granted.
|
|
898
|
+
|
|
899
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
|
900
|
+
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
|
901
|
+
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
|
902
|
+
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
|
903
|
+
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
904
|
+
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
905
|
+
PERFORMANCE OF THIS SOFTWARE.
|
|
906
|
+
***************************************************************************** */
|
|
907
|
+
/* global Reflect, Promise, SuppressedError, Symbol, Iterator */
|
|
908
|
+
|
|
909
|
+
|
|
910
|
+
function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
|
|
911
|
+
function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
|
|
912
|
+
var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
|
|
913
|
+
var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
|
|
914
|
+
var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
|
|
915
|
+
var _, done = false;
|
|
916
|
+
for (var i = decorators.length - 1; i >= 0; i--) {
|
|
917
|
+
var context = {};
|
|
918
|
+
for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
|
|
919
|
+
for (var p in contextIn.access) context.access[p] = contextIn.access[p];
|
|
920
|
+
context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
|
|
921
|
+
var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
|
|
922
|
+
if (kind === "accessor") {
|
|
923
|
+
if (result === void 0) continue;
|
|
924
|
+
if (result === null || typeof result !== "object") throw new TypeError("Object expected");
|
|
925
|
+
if (_ = accept(result.get)) descriptor.get = _;
|
|
926
|
+
if (_ = accept(result.set)) descriptor.set = _;
|
|
927
|
+
if (_ = accept(result.init)) initializers.unshift(_);
|
|
928
|
+
}
|
|
929
|
+
else if (_ = accept(result)) {
|
|
930
|
+
if (kind === "field") initializers.unshift(_);
|
|
931
|
+
else descriptor[key] = _;
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
if (target) Object.defineProperty(target, contextIn.name, descriptor);
|
|
935
|
+
done = true;
|
|
936
|
+
}
|
|
937
|
+
function __runInitializers(thisArg, initializers, value) {
|
|
938
|
+
var useValue = arguments.length > 2;
|
|
939
|
+
for (var i = 0; i < initializers.length; i++) {
|
|
940
|
+
value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
|
|
941
|
+
}
|
|
942
|
+
return useValue ? value : void 0;
|
|
943
|
+
}
|
|
944
|
+
function __setFunctionName(f, name, prefix) {
|
|
945
|
+
if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
|
|
946
|
+
return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
|
|
947
|
+
}
|
|
948
|
+
function __classPrivateFieldGet(receiver, state, kind, f) {
|
|
949
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
|
950
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
951
|
+
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
function __classPrivateFieldSet(receiver, state, value, kind, f) {
|
|
955
|
+
if (kind === "m") throw new TypeError("Private method is not writable");
|
|
956
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
|
|
957
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
|
958
|
+
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
|
|
962
|
+
var e = new Error(message);
|
|
963
|
+
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
|
|
964
|
+
};
|
|
965
|
+
|
|
966
|
+
const debugHooks = {
|
|
967
|
+
isDevtoolsEnabled: () => false,
|
|
968
|
+
registerEffect: () => { },
|
|
969
|
+
getTriggerChain: () => [],
|
|
970
|
+
captureStack: () => [],
|
|
971
|
+
captureLineage: () => new Error().stack,
|
|
972
|
+
formatStack: (stack) => [stack],
|
|
973
|
+
recordTriggerLink: () => { },
|
|
974
|
+
};
|
|
975
|
+
function setDebugHooks(hooks) {
|
|
976
|
+
Object.assign(debugHooks, hooks);
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
var _ZoneAggregator_zones;
|
|
980
|
+
function isu(z) {
|
|
981
|
+
return z;
|
|
982
|
+
}
|
|
983
|
+
class AZone {
|
|
984
|
+
enter(value) {
|
|
985
|
+
const prev = this.active;
|
|
986
|
+
this.active = value;
|
|
987
|
+
return prev;
|
|
988
|
+
}
|
|
989
|
+
leave(entered) {
|
|
990
|
+
this.active = entered;
|
|
991
|
+
}
|
|
992
|
+
with(value, fn) {
|
|
993
|
+
const entered = this.enter(value);
|
|
994
|
+
let res;
|
|
995
|
+
try {
|
|
996
|
+
res = fn();
|
|
997
|
+
}
|
|
998
|
+
finally {
|
|
999
|
+
this.leave(entered);
|
|
1000
|
+
}
|
|
1001
|
+
// [HACK]: Sanitization
|
|
1002
|
+
// See BROWSER_ASYNC_POLYFILL.md
|
|
1003
|
+
return asyncHooks.sanitizePromise(res);
|
|
1004
|
+
}
|
|
1005
|
+
root(fn) {
|
|
1006
|
+
const prev = this.enter();
|
|
1007
|
+
try {
|
|
1008
|
+
return fn();
|
|
1009
|
+
}
|
|
1010
|
+
finally {
|
|
1011
|
+
this.leave(prev);
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
get zoned() {
|
|
1015
|
+
const active = this.active;
|
|
1016
|
+
return named(`${this}@${active}`, (fn) => this.with(active, fn));
|
|
1017
|
+
}
|
|
1018
|
+
}
|
|
1019
|
+
class Zone extends AZone {
|
|
1020
|
+
}
|
|
1021
|
+
class ZoneHistory extends AZone {
|
|
1022
|
+
has(value) {
|
|
1023
|
+
return this.history.has(value);
|
|
1024
|
+
}
|
|
1025
|
+
some(predicate) {
|
|
1026
|
+
for (const value of this.history)
|
|
1027
|
+
if (predicate(value))
|
|
1028
|
+
return true;
|
|
1029
|
+
return false;
|
|
1030
|
+
}
|
|
1031
|
+
constructor(controlled = new Zone()) {
|
|
1032
|
+
super();
|
|
1033
|
+
this.controlled = controlled;
|
|
1034
|
+
this.history = new Set();
|
|
1035
|
+
const self = this;
|
|
1036
|
+
this.present = Object.create(controlled, Object.getOwnPropertyDescriptors({
|
|
1037
|
+
get active() {
|
|
1038
|
+
return controlled.active;
|
|
1039
|
+
},
|
|
1040
|
+
set active(value) {
|
|
1041
|
+
controlled.active = value;
|
|
1042
|
+
},
|
|
1043
|
+
enter(value) {
|
|
1044
|
+
if (value && self.history.has(value))
|
|
1045
|
+
throw new Error('ZoneHistory: re-entering historical zone');
|
|
1046
|
+
if (value !== undefined)
|
|
1047
|
+
self.history.add(value);
|
|
1048
|
+
return { added: value, entered: isu(controlled).enter(value) };
|
|
1049
|
+
},
|
|
1050
|
+
leave(entered) {
|
|
1051
|
+
if (entered.added !== undefined)
|
|
1052
|
+
self.history.delete(entered.added);
|
|
1053
|
+
return isu(controlled).leave(entered.entered);
|
|
1054
|
+
},
|
|
1055
|
+
}));
|
|
1056
|
+
}
|
|
1057
|
+
get active() {
|
|
1058
|
+
return { present: this.controlled.active, history: new Set(this.history) };
|
|
1059
|
+
}
|
|
1060
|
+
set active(value) {
|
|
1061
|
+
this.history = value?.history ? new Set(value.history) : new Set();
|
|
1062
|
+
this.controlled.active = value?.present;
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
class ZoneAggregator extends AZone {
|
|
1066
|
+
constructor(...zones) {
|
|
1067
|
+
super();
|
|
1068
|
+
_ZoneAggregator_zones.set(this, new Set());
|
|
1069
|
+
for (const z of zones)
|
|
1070
|
+
__classPrivateFieldGet(this, _ZoneAggregator_zones, "f").add(z);
|
|
1071
|
+
}
|
|
1072
|
+
get active() {
|
|
1073
|
+
const rv = new Map();
|
|
1074
|
+
for (const z of __classPrivateFieldGet(this, _ZoneAggregator_zones, "f"))
|
|
1075
|
+
if (z.active !== undefined)
|
|
1076
|
+
rv.set(z, z.active);
|
|
1077
|
+
return rv;
|
|
1078
|
+
}
|
|
1079
|
+
set active(value) {
|
|
1080
|
+
for (const z of __classPrivateFieldGet(this, _ZoneAggregator_zones, "f"))
|
|
1081
|
+
z.active = value?.get(z);
|
|
1082
|
+
}
|
|
1083
|
+
enter(value) {
|
|
1084
|
+
const entered = new Map();
|
|
1085
|
+
for (const z of __classPrivateFieldGet(this, _ZoneAggregator_zones, "f")) {
|
|
1086
|
+
const v = value?.get(z);
|
|
1087
|
+
entered.set(z, isu(z).enter(v));
|
|
1088
|
+
}
|
|
1089
|
+
return entered;
|
|
1090
|
+
}
|
|
1091
|
+
leave(entered) {
|
|
1092
|
+
for (const z of __classPrivateFieldGet(this, _ZoneAggregator_zones, "f"))
|
|
1093
|
+
isu(z).leave(entered.get(z));
|
|
1094
|
+
}
|
|
1095
|
+
add(z) {
|
|
1096
|
+
__classPrivateFieldGet(this, _ZoneAggregator_zones, "f").add(z);
|
|
1097
|
+
}
|
|
1098
|
+
delete(z) {
|
|
1099
|
+
__classPrivateFieldGet(this, _ZoneAggregator_zones, "f").delete(z);
|
|
1100
|
+
}
|
|
1101
|
+
clear() {
|
|
1102
|
+
__classPrivateFieldGet(this, _ZoneAggregator_zones, "f").clear();
|
|
1103
|
+
}
|
|
1104
|
+
}
|
|
1105
|
+
_ZoneAggregator_zones = new WeakMap();
|
|
1106
|
+
const asyncZone = tag('async', new ZoneAggregator());
|
|
1107
|
+
asyncHooks.addHook(() => {
|
|
1108
|
+
const zone = asyncZone.active;
|
|
1109
|
+
return () => {
|
|
1110
|
+
const prev = asyncZone.active;
|
|
1111
|
+
asyncZone.active = zone;
|
|
1112
|
+
return () => {
|
|
1113
|
+
asyncZone.active = prev;
|
|
1114
|
+
};
|
|
1115
|
+
};
|
|
1116
|
+
});
|
|
1117
|
+
|
|
1118
|
+
// Symbol for storing root function on the function itself
|
|
1119
|
+
const rootFunctionSymbol = Symbol('root-function');
|
|
1120
|
+
// Track which effects are watching which reactive objects for cleanup
|
|
1121
|
+
let effectToReactiveObjects = new WeakMap();
|
|
1122
|
+
// Track effects per reactive object and property
|
|
1123
|
+
let watchers = new WeakMap();
|
|
1124
|
+
// Track effect metadata and relationships
|
|
1125
|
+
let effectNodes = new WeakMap();
|
|
1126
|
+
function getEffectNode(effect) {
|
|
1127
|
+
let node = effectNodes.get(effect);
|
|
1128
|
+
if (!node) {
|
|
1129
|
+
node = {};
|
|
1130
|
+
effectNodes.set(effect, node);
|
|
1131
|
+
}
|
|
1132
|
+
return node;
|
|
1133
|
+
}
|
|
1134
|
+
// Track reverse mapping to ensure unicity: One Root -> One Function
|
|
1135
|
+
let reverseRoots = new WeakMap();
|
|
1136
|
+
function resetRegistry() {
|
|
1137
|
+
effectToReactiveObjects = new WeakMap();
|
|
1138
|
+
watchers = new WeakMap();
|
|
1139
|
+
effectNodes = new WeakMap();
|
|
1140
|
+
reverseRoots = new WeakMap();
|
|
1141
|
+
}
|
|
1142
|
+
/**
|
|
1143
|
+
* Marks a function with its root function for effect tracking
|
|
1144
|
+
* Enforces strict unicity: A root function can only identify ONE function.
|
|
1145
|
+
* @param fn - The function to mark
|
|
1146
|
+
* @param root - The root function
|
|
1147
|
+
* @returns The marked function
|
|
1148
|
+
*/
|
|
1149
|
+
function markWithRoot(fn, root) {
|
|
1150
|
+
// Check for collision
|
|
1151
|
+
const existingRef = reverseRoots.get(root);
|
|
1152
|
+
const existing = existingRef?.deref();
|
|
1153
|
+
if (existing && existing !== fn) {
|
|
1154
|
+
const rootName = root.name || 'anonymous';
|
|
1155
|
+
const existingName = existing.name || 'anonymous';
|
|
1156
|
+
const fnName = fn.name || 'anonymous';
|
|
1157
|
+
throw new Error(`[reactive] Abusive Shared Root detected: Root '${rootName}' is already identifying function '${existingName}'. ` +
|
|
1158
|
+
`Cannot reuse it for '${fnName}'. Shared roots cause lost updates and broken identity logic.`);
|
|
1159
|
+
}
|
|
1160
|
+
// Always update the map so subsequent checks find this one
|
|
1161
|
+
// (Last writer wins for the check)
|
|
1162
|
+
reverseRoots.set(root, new WeakRef(fn));
|
|
1163
|
+
// Store root mapping as symbol property on the function
|
|
1164
|
+
fn[rootFunctionSymbol] = getRoot(root);
|
|
1165
|
+
return fn;
|
|
1166
|
+
}
|
|
1167
|
+
/**
|
|
1168
|
+
* Gets the root function of a function for effect tracking
|
|
1169
|
+
* @param fn - The function to get the root of
|
|
1170
|
+
* @returns The root function
|
|
1171
|
+
*/
|
|
1172
|
+
function getRoot(fn) {
|
|
1173
|
+
while (fn) {
|
|
1174
|
+
const r = fn[rootFunctionSymbol];
|
|
1175
|
+
if (!r)
|
|
1176
|
+
break;
|
|
1177
|
+
fn = r;
|
|
1178
|
+
}
|
|
1179
|
+
return fn;
|
|
1180
|
+
}
|
|
1181
|
+
|
|
1182
|
+
const effectMarker = {
|
|
1183
|
+
enter: 'effect:enter',
|
|
1184
|
+
leave: 'effect:leave',
|
|
1185
|
+
};
|
|
1186
|
+
function formatTrigger({ obj, evolution, dependency, touch }) {
|
|
1187
|
+
const detail = evolution.type === 'bunch' ? evolution.method : String(evolution.prop);
|
|
1188
|
+
const parts = [`${evolution.type} ${detail} on`, obj];
|
|
1189
|
+
if (dependency) {
|
|
1190
|
+
parts.push('\n Dependency created at:');
|
|
1191
|
+
parts.push(...debugHooks.formatStack(dependency));
|
|
1192
|
+
}
|
|
1193
|
+
if (touch) {
|
|
1194
|
+
parts.push('\n Touched from:');
|
|
1195
|
+
parts.push(...debugHooks.formatStack(touch));
|
|
1196
|
+
}
|
|
1197
|
+
return parts;
|
|
1198
|
+
}
|
|
1199
|
+
/**
|
|
1200
|
+
* Console-friendly description of a `CleanupReason`.
|
|
1201
|
+
* Returns an array of arguments to spread into `console.log` / `console.warn`,
|
|
1202
|
+
* mixing strings and raw object references so the console can render them as inspectable values.
|
|
1203
|
+
*
|
|
1204
|
+
* @example
|
|
1205
|
+
* ```typescript
|
|
1206
|
+
* effect(({ reaction }) => {
|
|
1207
|
+
* if (reaction !== true) console.log(...formatCleanupReason(reaction))
|
|
1208
|
+
* })
|
|
1209
|
+
* ```
|
|
1210
|
+
*/
|
|
1211
|
+
function formatCleanupReason(reason, depth = 0) {
|
|
1212
|
+
const indent = depth ? ' '.repeat(depth) : '';
|
|
1213
|
+
switch (reason.type) {
|
|
1214
|
+
case 'propChange': {
|
|
1215
|
+
const parts = [`${indent}propChange:`];
|
|
1216
|
+
for (let i = 0; i < reason.triggers.length; i++) {
|
|
1217
|
+
if (i > 0)
|
|
1218
|
+
parts.push(',');
|
|
1219
|
+
parts.push(...formatTrigger(reason.triggers[i]));
|
|
1220
|
+
}
|
|
1221
|
+
return parts;
|
|
1222
|
+
}
|
|
1223
|
+
case 'stopped':
|
|
1224
|
+
return [`${indent}stopped`];
|
|
1225
|
+
case 'gc':
|
|
1226
|
+
return [`${indent}gc`];
|
|
1227
|
+
case 'error':
|
|
1228
|
+
return [`${indent}error:`, reason.error];
|
|
1229
|
+
case 'lineage':
|
|
1230
|
+
return [`${indent}lineage ←\n`, ...formatCleanupReason(reason.parent, depth + 1)];
|
|
1231
|
+
case 'invalidate':
|
|
1232
|
+
return [`${indent}invalidate ←\n`, ...formatCleanupReason(reason.cause, depth + 1)];
|
|
1233
|
+
case 'multiple': {
|
|
1234
|
+
const parts = [];
|
|
1235
|
+
for (let i = 0; i < reason.reasons.length; i++) {
|
|
1236
|
+
if (i > 0)
|
|
1237
|
+
parts.push('\n');
|
|
1238
|
+
parts.push(...formatCleanupReason(reason.reasons[i], depth));
|
|
1239
|
+
}
|
|
1240
|
+
return parts;
|
|
1241
|
+
}
|
|
1242
|
+
}
|
|
1243
|
+
}
|
|
1244
|
+
/**
|
|
1245
|
+
* Symbol representing all properties in reactive tracking
|
|
1246
|
+
*/
|
|
1247
|
+
const allProps = Symbol('all-props');
|
|
1248
|
+
/**
|
|
1249
|
+
* Symbol for structure-only tracking (triggered on key add/delete, not value changes).
|
|
1250
|
+
* Used by ownKeys proxy trap — Object.keys(), for..in, Map.keys() depend on this.
|
|
1251
|
+
*/
|
|
1252
|
+
const keysOf = Symbol('keys-of');
|
|
1253
|
+
/**
|
|
1254
|
+
* Symbol to check if an effect is stopped
|
|
1255
|
+
*/
|
|
1256
|
+
const stopped = Symbol('stopped');
|
|
1257
|
+
/**
|
|
1258
|
+
* Symbol to access effect cleanup function
|
|
1259
|
+
*/
|
|
1260
|
+
const cleanup = Symbol('cleanup');
|
|
1261
|
+
/**
|
|
1262
|
+
* Structured error codes for machine-readable diagnosis
|
|
1263
|
+
*/
|
|
1264
|
+
var ReactiveErrorCode;
|
|
1265
|
+
(function (ReactiveErrorCode) {
|
|
1266
|
+
ReactiveErrorCode["CycleDetected"] = "Cycle detected";
|
|
1267
|
+
ReactiveErrorCode["MaxDepthExceeded"] = "Max depth exceeded";
|
|
1268
|
+
ReactiveErrorCode["MaxReactionExceeded"] = "Max reaction exceeded";
|
|
1269
|
+
ReactiveErrorCode["WriteInComputed"] = "Write in computed";
|
|
1270
|
+
ReactiveErrorCode["TrackingError"] = "Tracking error";
|
|
1271
|
+
ReactiveErrorCode["BrokenEffects"] = "Broken effects";
|
|
1272
|
+
})(ReactiveErrorCode || (ReactiveErrorCode = {}));
|
|
1273
|
+
/**
|
|
1274
|
+
* Error class for reactive system errors
|
|
1275
|
+
*/
|
|
1276
|
+
class ReactiveError extends Error {
|
|
1277
|
+
constructor(message, debugInfo) {
|
|
1278
|
+
super(message);
|
|
1279
|
+
this.debugInfo = debugInfo;
|
|
1280
|
+
this.name = 'ReactiveError';
|
|
1281
|
+
}
|
|
1282
|
+
get code() {
|
|
1283
|
+
return this.debugInfo?.code;
|
|
1284
|
+
}
|
|
1285
|
+
get cause() {
|
|
1286
|
+
return this.debugInfo?.cause;
|
|
1287
|
+
}
|
|
1288
|
+
}
|
|
1289
|
+
// biome-ignore-start lint/correctness/noUnusedFunctionParameters: Interface declaration with empty defaults
|
|
1290
|
+
/**
|
|
1291
|
+
* Global options for the reactive system
|
|
1292
|
+
*/
|
|
1293
|
+
const options = {
|
|
1294
|
+
/**
|
|
1295
|
+
* Debug purpose: called when an effect is entered
|
|
1296
|
+
* @param effect - The effect that is entered
|
|
1297
|
+
*/
|
|
1298
|
+
enter: (_effect) => { },
|
|
1299
|
+
/**
|
|
1300
|
+
* Debug purpose: called when an effect is left
|
|
1301
|
+
* @param effect - The effect that is left
|
|
1302
|
+
*/
|
|
1303
|
+
leave: (_effect) => { },
|
|
1304
|
+
/**
|
|
1305
|
+
* Debug purpose: called when an effect is chained
|
|
1306
|
+
* @param target - The effect that is being triggered
|
|
1307
|
+
* @param caller - The effect that is calling the target
|
|
1308
|
+
*/
|
|
1309
|
+
chain: (_targets, _caller) => { },
|
|
1310
|
+
/**
|
|
1311
|
+
* Debug purpose: called when an effect chain is started
|
|
1312
|
+
* @param target - The effect that is being triggered
|
|
1313
|
+
*/
|
|
1314
|
+
beginChain: (_targets) => { },
|
|
1315
|
+
/**
|
|
1316
|
+
* Debug purpose: called when an effect chain is ended
|
|
1317
|
+
*/
|
|
1318
|
+
endChain: () => { },
|
|
1319
|
+
garbageCollected: (_fn) => { },
|
|
1320
|
+
/**
|
|
1321
|
+
* Debug purpose: called when an object is touched
|
|
1322
|
+
* @param obj - The object that is touched
|
|
1323
|
+
* @param evolution - The type of change
|
|
1324
|
+
* @param props - The properties that changed
|
|
1325
|
+
* @param deps - The dependencies that changed
|
|
1326
|
+
*/
|
|
1327
|
+
touched: (_obj, _evolution, _props, _deps) => { },
|
|
1328
|
+
/**
|
|
1329
|
+
* Debug purpose: called when an effect is skipped because it's already running
|
|
1330
|
+
* @param effect - The effect that is already running
|
|
1331
|
+
* @param runningChain - The array of effects from the detected one to the currently running one
|
|
1332
|
+
*/
|
|
1333
|
+
skipRunningEffect: (_effect) => { },
|
|
1334
|
+
/**
|
|
1335
|
+
* Debug purpose: maximum effect chain (like call stack max depth)
|
|
1336
|
+
* Used to prevent infinite loops
|
|
1337
|
+
* @default 100
|
|
1338
|
+
*/
|
|
1339
|
+
maxEffectChain: 100,
|
|
1340
|
+
/**
|
|
1341
|
+
* Maximum number of times an effect can be triggered by the same cause in a single batch
|
|
1342
|
+
* Used to detect aggressive re-computation or infinite loops
|
|
1343
|
+
* @default 10
|
|
1344
|
+
*/
|
|
1345
|
+
maxTriggerPerBatch: 10,
|
|
1346
|
+
/**
|
|
1347
|
+
* Debug purpose: maximum effect reaction (like call stack max depth)
|
|
1348
|
+
* Used to prevent infinite loops
|
|
1349
|
+
* @default 'throw'
|
|
1350
|
+
*/
|
|
1351
|
+
maxEffectReaction: 'throw',
|
|
1352
|
+
/**
|
|
1353
|
+
* Callback called when a memoization discrepancy is detected (debug only)
|
|
1354
|
+
* When defined, memoized functions will run a second time (untracked) to verify consistency.
|
|
1355
|
+
* If the untracked run returns a different value than the cached one, this callback is triggered.
|
|
1356
|
+
*
|
|
1357
|
+
* This is the primary tool for detecting missing reactive dependencies in computed values.
|
|
1358
|
+
*
|
|
1359
|
+
* @param cached - The value currently in the memoization cache
|
|
1360
|
+
* @param fresh - The value obtained by re-running the function untracked
|
|
1361
|
+
* @param fn - The memoized function itself
|
|
1362
|
+
* @param args - Arguments passed to the function
|
|
1363
|
+
*
|
|
1364
|
+
* @example
|
|
1365
|
+
* ```typescript
|
|
1366
|
+
* reactiveOptions.onMemoizationDiscrepancy = (cached, fresh, fn, args) => {
|
|
1367
|
+
* throw new Error(`Memoization discrepancy in ${fn.name}!`);
|
|
1368
|
+
* };
|
|
1369
|
+
* ```
|
|
1370
|
+
*/
|
|
1371
|
+
onMemoizationDiscrepancy: undefined,
|
|
1372
|
+
/**
|
|
1373
|
+
* How to handle cycles detected in effect batches.
|
|
1374
|
+
*
|
|
1375
|
+
* - `'production'` (Default): High-performance mode. Disables dependency graph maintenance and
|
|
1376
|
+
* Topological Sorting in favor of a simple FIFO queue. Use this for trustworthy, acyclic UI code.
|
|
1377
|
+
* Cycle detection is heuristic (uses maxEffectChain execution counts).
|
|
1378
|
+
*
|
|
1379
|
+
* - `'development'`: Maintains direct dependency graph for early cycle detection during edge creation.
|
|
1380
|
+
* Catches cycles before effects execute via DFS check when adding edges. Throws immediately with
|
|
1381
|
+
* basic path information. Good balance of debugging help with moderate overhead.
|
|
1382
|
+
*
|
|
1383
|
+
* - `'debug'`: Full diagnostic mode with transitive closures and topological sorting.
|
|
1384
|
+
* Provides detailed cycle path reporting. Highest overhead but most informative for bug hunting.
|
|
1385
|
+
*
|
|
1386
|
+
* @default 'production'
|
|
1387
|
+
*/
|
|
1388
|
+
cycleHandling: 'development',
|
|
1389
|
+
/**
|
|
1390
|
+
* Internal flag used by memoization discrepancy detector to avoid counting calls in tests
|
|
1391
|
+
* @warning Do not modify this flag manually, this flag is given by the engine
|
|
1392
|
+
*/
|
|
1393
|
+
isVerificationRun: false,
|
|
1394
|
+
/**
|
|
1395
|
+
* Maximum depth for deep watching traversal
|
|
1396
|
+
* Used to prevent infinite recursion in circular references
|
|
1397
|
+
* @default 100
|
|
1398
|
+
*/
|
|
1399
|
+
maxDeepWatchDepth: 100,
|
|
1400
|
+
/**
|
|
1401
|
+
* Only react on instance members modification (not inherited properties)
|
|
1402
|
+
* For instance, do not track class methods
|
|
1403
|
+
* @default true
|
|
1404
|
+
*/
|
|
1405
|
+
instanceMembers: true,
|
|
1406
|
+
/**
|
|
1407
|
+
* Ignore accessors (getters and setters) and only track direct properties
|
|
1408
|
+
* @default true
|
|
1409
|
+
*/
|
|
1410
|
+
ignoreAccessors: true,
|
|
1411
|
+
/**
|
|
1412
|
+
* Enable recursive touching when objects with the same prototype are replaced
|
|
1413
|
+
* When enabled, replacing an object with another of the same prototype triggers
|
|
1414
|
+
* recursive diffing instead of notifying parent effects
|
|
1415
|
+
* @default true
|
|
1416
|
+
*/
|
|
1417
|
+
recursiveTouching: true,
|
|
1418
|
+
/**
|
|
1419
|
+
* Default async execution mode for effects that return Promises
|
|
1420
|
+
* - 'cancel': Cancel previous async execution when dependencies change (default, enables async zone)
|
|
1421
|
+
* - 'queue': Queue next execution to run after current completes (enables async zone)
|
|
1422
|
+
* - 'ignore': Ignore new executions while async work is running (enables async zone)
|
|
1423
|
+
* - false: Disable async zone and async mode handling (effects run concurrently)
|
|
1424
|
+
*
|
|
1425
|
+
* **When truthy:** Enables async zone (Promise.prototype wrapping) for automatic context
|
|
1426
|
+
* preservation in Promise callbacks. Warning: This modifies Promise.prototype globally.
|
|
1427
|
+
* Only enable if no other library modifies Promise.prototype.
|
|
1428
|
+
*
|
|
1429
|
+
* **When false:** Async zone is disabled. Use `tracked()` manually in Promise callbacks.
|
|
1430
|
+
*
|
|
1431
|
+
* Can be overridden per-effect via EffectOptions
|
|
1432
|
+
* @default 'cancel'
|
|
1433
|
+
*/
|
|
1434
|
+
asyncMode: 'cancel',
|
|
1435
|
+
// biome-ignore lint/suspicious/noConsole: This is the whole point here
|
|
1436
|
+
warn: (...args) => console.warn(...args),
|
|
1437
|
+
/**
|
|
1438
|
+
* Introspection and debug aids. Set to `null` to disable all debug overhead in production.
|
|
1439
|
+
*
|
|
1440
|
+
* - `gatherReasons`: collect `PropTrigger[]` for `CleanupReason` on effect re-runs (default `true`)
|
|
1441
|
+
* - `lineages`: what lineages to capture in PropTrigger (default `'touch'`)
|
|
1442
|
+
* - `logErrors`: log errors with detailed context (default `true`)
|
|
1443
|
+
* - `enableHistory`: keep a history of mutations (default `true`)
|
|
1444
|
+
* - `historySize`: number of mutations to keep in history (default `50`)
|
|
1445
|
+
*
|
|
1446
|
+
* `enableDevTools()` sets `logErrors` to `true` automatically.
|
|
1447
|
+
*
|
|
1448
|
+
* @example
|
|
1449
|
+
* ```typescript
|
|
1450
|
+
* // Production: disable all introspection
|
|
1451
|
+
* reactiveOptions.introspection = null
|
|
1452
|
+
* ```
|
|
1453
|
+
*/
|
|
1454
|
+
introspection: {
|
|
1455
|
+
gatherReasons: { lineages: 'touch' },
|
|
1456
|
+
logErrors: true,
|
|
1457
|
+
enableHistory: true,
|
|
1458
|
+
historySize: 50,
|
|
1459
|
+
},
|
|
1460
|
+
/**
|
|
1461
|
+
* Configuration for zone hooks - control which async APIs are hooked
|
|
1462
|
+
* Each option controls whether the corresponding async API is wrapped to preserve effect context
|
|
1463
|
+
* Only applies when asyncMode is enabled (truthy)
|
|
1464
|
+
* @deprecated Should take all when we made sure PIXI.create, Game.create, ... are -> .root()
|
|
1465
|
+
*/
|
|
1466
|
+
zones: {
|
|
1467
|
+
/**
|
|
1468
|
+
* Hook setTimeout to preserve effect context
|
|
1469
|
+
* @default true
|
|
1470
|
+
*/
|
|
1471
|
+
setTimeout: true,
|
|
1472
|
+
/**
|
|
1473
|
+
* Hook setInterval to preserve effect context
|
|
1474
|
+
* @default true
|
|
1475
|
+
*/
|
|
1476
|
+
setInterval: true,
|
|
1477
|
+
/**
|
|
1478
|
+
* Hook requestAnimationFrame (runs in untracked context when hooked)
|
|
1479
|
+
* @default true
|
|
1480
|
+
*/
|
|
1481
|
+
requestAnimationFrame: true,
|
|
1482
|
+
/**
|
|
1483
|
+
* Hook queueMicrotask to preserve effect context
|
|
1484
|
+
* @default true
|
|
1485
|
+
*/
|
|
1486
|
+
queueMicrotask: true,
|
|
1487
|
+
},
|
|
1488
|
+
};
|
|
1489
|
+
function optionCall(name, ...args) {
|
|
1490
|
+
const fn = options[name];
|
|
1491
|
+
if (typeof fn !== 'function')
|
|
1492
|
+
return;
|
|
1493
|
+
try {
|
|
1494
|
+
;
|
|
1495
|
+
fn(...args);
|
|
1496
|
+
}
|
|
1497
|
+
catch (error) {
|
|
1498
|
+
options.warn(`options.${name} threw`, error);
|
|
1499
|
+
}
|
|
1500
|
+
}
|
|
1501
|
+
// --- Proxy State (Merged from proxy-state.ts) ---
|
|
1502
|
+
const objectToProxy = new WeakMap();
|
|
1503
|
+
const proxyToObject = new WeakMap();
|
|
1504
|
+
function storeProxyRelationship(target, proxy) {
|
|
1505
|
+
objectToProxy.set(target, proxy);
|
|
1506
|
+
proxyToObject.set(proxy, target);
|
|
1507
|
+
}
|
|
1508
|
+
function getExistingProxy(target) {
|
|
1509
|
+
return objectToProxy.get(target);
|
|
1510
|
+
}
|
|
1511
|
+
function unwrap(obj) {
|
|
1512
|
+
if (!obj || typeof obj !== 'object')
|
|
1513
|
+
return obj;
|
|
1514
|
+
return proxyToObject.get(obj) || obj;
|
|
1515
|
+
}
|
|
1516
|
+
function isReactive(obj) {
|
|
1517
|
+
return proxyToObject.has(obj);
|
|
1518
|
+
}
|
|
1519
|
+
|
|
1520
|
+
const effectHistory = tag('effectHistory', new ZoneHistory());
|
|
1521
|
+
tag('effectHistory.present', effectHistory.present);
|
|
1522
|
+
asyncZone.add(effectHistory);
|
|
1523
|
+
/**
|
|
1524
|
+
* Aggregator for zones that need to be tracked along effects.
|
|
1525
|
+
* ie. in each effect, the active zone of the given zoning will be the one active at effect's definition
|
|
1526
|
+
*/
|
|
1527
|
+
const effectAggregator = tag('effectAggregator', new ZoneAggregator(effectHistory.present));
|
|
1528
|
+
function isRunning(effect) {
|
|
1529
|
+
const root = getRoot(effect);
|
|
1530
|
+
return effectHistory.some((e) => getRoot(e) === root);
|
|
1531
|
+
}
|
|
1532
|
+
function getActiveEffect() {
|
|
1533
|
+
return effectHistory.present.active;
|
|
1534
|
+
}
|
|
1535
|
+
/**
|
|
1536
|
+
* ADD a cleanup function to an object using the cleanup symbol.
|
|
1537
|
+
* The cleanup function will be called when the object needs to be disposed.
|
|
1538
|
+
*
|
|
1539
|
+
* Note: most of the time, you don't need to use this function directly.
|
|
1540
|
+
* The main use if for the cleanup function to be stored with the object, as GC calls the cleanup function when the *function* is garbage collected.
|
|
1541
|
+
*
|
|
1542
|
+
* @param obj - The object to attach the cleanup function to
|
|
1543
|
+
* @param cleanupFn - The cleanup function to attach
|
|
1544
|
+
* @returns The object with the cleanup function attached
|
|
1545
|
+
*/
|
|
1546
|
+
function cleanedBy(obj, cleanupFn) {
|
|
1547
|
+
const oldCleanup = obj[cleanup];
|
|
1548
|
+
return Object.defineProperty(obj, cleanup, {
|
|
1549
|
+
value: oldCleanup
|
|
1550
|
+
? Object.defineProperties((reason) => {
|
|
1551
|
+
oldCleanup(reason);
|
|
1552
|
+
cleanupFn(reason);
|
|
1553
|
+
}, {
|
|
1554
|
+
[stopped]: { get: () => oldCleanup[stopped] || cleanupFn[stopped] },
|
|
1555
|
+
})
|
|
1556
|
+
: cleanupFn,
|
|
1557
|
+
writable: false,
|
|
1558
|
+
enumerable: false,
|
|
1559
|
+
configurable: true,
|
|
1560
|
+
});
|
|
1561
|
+
}
|
|
1562
|
+
|
|
1563
|
+
// Track dependency stacks per (obj, prop, effect)
|
|
1564
|
+
let dependencyStacks = new WeakMap();
|
|
1565
|
+
function resetTracking() {
|
|
1566
|
+
dependencyStacks = new WeakMap();
|
|
1567
|
+
}
|
|
1568
|
+
function getDependencyStack(effect, obj, prop) {
|
|
1569
|
+
const objStacks = dependencyStacks.get(obj);
|
|
1570
|
+
if (!objStacks)
|
|
1571
|
+
return undefined;
|
|
1572
|
+
return objStacks.get(prop)?.get(effect) ?? objStacks.get(allProps)?.get(effect);
|
|
1573
|
+
}
|
|
1574
|
+
/**
|
|
1575
|
+
* Marks a property as a dependency of the current effect
|
|
1576
|
+
* @param obj - The object containing the property
|
|
1577
|
+
* @param prop - The property name (defaults to allProps)
|
|
1578
|
+
*/
|
|
1579
|
+
function dependant(obj, prop = allProps) {
|
|
1580
|
+
obj = unwrap(obj);
|
|
1581
|
+
const currentActiveEffect = getActiveEffect();
|
|
1582
|
+
// Early return if no active effect, tracking disabled, or invalid prop
|
|
1583
|
+
if (!currentActiveEffect || (typeof prop === 'symbol' && prop !== allProps && prop !== keysOf))
|
|
1584
|
+
return;
|
|
1585
|
+
if ('dependencyHook' in currentActiveEffect) {
|
|
1586
|
+
// @ts-expect-error We declared it nowhere - it's okay as it's really internal and for edge-case debug purpose only
|
|
1587
|
+
currentActiveEffect.dependencyHook(obj, prop);
|
|
1588
|
+
}
|
|
1589
|
+
let objectWatchers = watchers.get(obj);
|
|
1590
|
+
if (!objectWatchers) {
|
|
1591
|
+
objectWatchers = new Map();
|
|
1592
|
+
watchers.set(obj, objectWatchers);
|
|
1593
|
+
}
|
|
1594
|
+
let deps = objectWatchers.get(prop);
|
|
1595
|
+
if (!deps) {
|
|
1596
|
+
deps = new Set();
|
|
1597
|
+
objectWatchers.set(prop, deps);
|
|
1598
|
+
}
|
|
1599
|
+
deps.add(currentActiveEffect);
|
|
1600
|
+
// Track which reactive objects this effect is watching
|
|
1601
|
+
const effectObjects = effectToReactiveObjects.get(currentActiveEffect);
|
|
1602
|
+
if (effectObjects) {
|
|
1603
|
+
effectObjects.add(obj);
|
|
1604
|
+
}
|
|
1605
|
+
else {
|
|
1606
|
+
effectToReactiveObjects.set(currentActiveEffect, new Set([obj]));
|
|
1607
|
+
}
|
|
1608
|
+
// Store dependency stack if introspection is enabled
|
|
1609
|
+
const gatherReasons = options.introspection?.gatherReasons;
|
|
1610
|
+
if (gatherReasons) {
|
|
1611
|
+
const lineageConfig = gatherReasons.lineages;
|
|
1612
|
+
if (lineageConfig === 'dependency' || lineageConfig === 'both') {
|
|
1613
|
+
let objStacks = dependencyStacks.get(obj);
|
|
1614
|
+
if (!objStacks) {
|
|
1615
|
+
objStacks = new Map();
|
|
1616
|
+
dependencyStacks.set(obj, objStacks);
|
|
1617
|
+
}
|
|
1618
|
+
let propStacks = objStacks.get(prop);
|
|
1619
|
+
if (!propStacks) {
|
|
1620
|
+
propStacks = new Map();
|
|
1621
|
+
objStacks.set(prop, propStacks);
|
|
1622
|
+
}
|
|
1623
|
+
propStacks.set(currentActiveEffect, debugHooks.captureLineage());
|
|
1624
|
+
}
|
|
1625
|
+
}
|
|
1626
|
+
}
|
|
1627
|
+
|
|
1628
|
+
/**
|
|
1629
|
+
* Finds a cycle in a sequence of functions by looking for the first repetition
|
|
1630
|
+
*/
|
|
1631
|
+
function findCycleInChain(roots) {
|
|
1632
|
+
const seen = new Map();
|
|
1633
|
+
for (let i = 0; i < roots.length; i++) {
|
|
1634
|
+
const root = roots[i];
|
|
1635
|
+
if (seen.has(root)) {
|
|
1636
|
+
return roots.slice(seen.get(root));
|
|
1637
|
+
}
|
|
1638
|
+
seen.set(root, i);
|
|
1639
|
+
}
|
|
1640
|
+
return null;
|
|
1641
|
+
}
|
|
1642
|
+
/**
|
|
1643
|
+
* Formats a list of function roots into a readable trace
|
|
1644
|
+
*/
|
|
1645
|
+
function formatRoots(roots, limit = 20) {
|
|
1646
|
+
const names = roots.map((r) => r.name || '<anonymous>');
|
|
1647
|
+
if (names.length <= limit)
|
|
1648
|
+
return names.join(' → ');
|
|
1649
|
+
const start = names.slice(0, 5);
|
|
1650
|
+
const end = names.slice(-10);
|
|
1651
|
+
return `${start.join(' → ')} ... (${names.length - 15} more) ... ${end.join(' → ')}`;
|
|
1652
|
+
}
|
|
1653
|
+
// Nested map structure for efficient counting and batch cleanup
|
|
1654
|
+
// batchId -> effect root -> obj -> prop -> count
|
|
1655
|
+
let activationRegistry;
|
|
1656
|
+
const activationLog = new Array(100);
|
|
1657
|
+
/**
|
|
1658
|
+
* Returns the activation log containing recent effect activations for debugging.
|
|
1659
|
+
* The log is a circular buffer of the last 100 activations.
|
|
1660
|
+
*
|
|
1661
|
+
* @returns Array of activation records
|
|
1662
|
+
*/
|
|
1663
|
+
function getActivationLog() {
|
|
1664
|
+
return activationLog;
|
|
1665
|
+
}
|
|
1666
|
+
function recordActivation(effect, obj, evolution, prop) {
|
|
1667
|
+
const root = getRoot(effect);
|
|
1668
|
+
if (!activationRegistry)
|
|
1669
|
+
return;
|
|
1670
|
+
let effectData = activationRegistry.get(root);
|
|
1671
|
+
if (!effectData) {
|
|
1672
|
+
effectData = new Map();
|
|
1673
|
+
activationRegistry.set(root, effectData);
|
|
1674
|
+
}
|
|
1675
|
+
let objData = effectData.get(obj);
|
|
1676
|
+
if (!objData) {
|
|
1677
|
+
objData = new Map();
|
|
1678
|
+
effectData.set(obj, objData);
|
|
1679
|
+
}
|
|
1680
|
+
const count = (objData.get(prop) ?? 0) + 1;
|
|
1681
|
+
objData.set(prop, count);
|
|
1682
|
+
// Keep a limited history for diagnostics
|
|
1683
|
+
activationLog.unshift({
|
|
1684
|
+
effect,
|
|
1685
|
+
obj,
|
|
1686
|
+
evolution,
|
|
1687
|
+
prop,
|
|
1688
|
+
});
|
|
1689
|
+
activationLog.pop();
|
|
1690
|
+
if (count >= options.maxTriggerPerBatch) {
|
|
1691
|
+
const effectName = root.name;
|
|
1692
|
+
const message = `Aggressive trigger detected: effect "${effectName}" triggered ${count} times in the batch by the same cause.`;
|
|
1693
|
+
if (options.maxEffectReaction === 'throw') {
|
|
1694
|
+
throw new ReactiveError(message, {
|
|
1695
|
+
code: ReactiveErrorCode.MaxReactionExceeded,
|
|
1696
|
+
count,
|
|
1697
|
+
effect: root,
|
|
1698
|
+
});
|
|
1699
|
+
}
|
|
1700
|
+
options.warn(`[reactive] ${message}`);
|
|
1701
|
+
}
|
|
1702
|
+
}
|
|
1703
|
+
function caught(onThrow, effect) {
|
|
1704
|
+
effect ?? (effect = getActiveEffect());
|
|
1705
|
+
if (!effect)
|
|
1706
|
+
throw new Error('Tracking an effect throw while not in an effect');
|
|
1707
|
+
const node = getEffectNode(effect);
|
|
1708
|
+
if (!node.catchers)
|
|
1709
|
+
node.catchers = [onThrow];
|
|
1710
|
+
else
|
|
1711
|
+
node.catchers.push(onThrow);
|
|
1712
|
+
}
|
|
1713
|
+
/** @deprecated Use `caught` instead */
|
|
1714
|
+
const onEffectThrow = caught;
|
|
1715
|
+
// Dependency graph: tracks which effects trigger which other effects
|
|
1716
|
+
// Uses roots (Function) as keys for consistency
|
|
1717
|
+
let effectTriggers = new WeakMap();
|
|
1718
|
+
let effectTriggeredBy = new WeakMap();
|
|
1719
|
+
// Transitive closures: track all indirect relationships
|
|
1720
|
+
// causesClosure: for each effect, all effects that trigger it (directly or indirectly)
|
|
1721
|
+
// consequencesClosure: for each effect, all effects that it triggers (directly or indirectly)
|
|
1722
|
+
let causesClosure = new WeakMap();
|
|
1723
|
+
let consequencesClosure = new WeakMap();
|
|
1724
|
+
let broken = false;
|
|
1725
|
+
/**
|
|
1726
|
+
* Gets or creates an IterableWeakSet for a closure map
|
|
1727
|
+
*/
|
|
1728
|
+
function getOrCreateClosure(closure, root) {
|
|
1729
|
+
let set = closure.get(root);
|
|
1730
|
+
if (!set) {
|
|
1731
|
+
set = new IterableWeakSet();
|
|
1732
|
+
closure.set(root, set);
|
|
1733
|
+
}
|
|
1734
|
+
return set;
|
|
1735
|
+
}
|
|
1736
|
+
/**
|
|
1737
|
+
* Adds an edge to the dependency graph: callerRoot → targetRoot
|
|
1738
|
+
* Also maintains transitive closures
|
|
1739
|
+
* @param callerRoot - Root function of the effect that triggers
|
|
1740
|
+
* @param targetRoot - Root function of the effect being triggered
|
|
1741
|
+
*/
|
|
1742
|
+
function addGraphEdge(callerRoot, targetRoot) {
|
|
1743
|
+
if (options.cycleHandling === 'production')
|
|
1744
|
+
return;
|
|
1745
|
+
// Add to forward graph: callerRoot → targetRoot
|
|
1746
|
+
const triggers = effectTriggers.get(callerRoot);
|
|
1747
|
+
if (!triggers) {
|
|
1748
|
+
const newTriggers = new IterableWeakSet();
|
|
1749
|
+
newTriggers.add(targetRoot);
|
|
1750
|
+
effectTriggers.set(callerRoot, newTriggers);
|
|
1751
|
+
}
|
|
1752
|
+
else {
|
|
1753
|
+
triggers.add(targetRoot);
|
|
1754
|
+
}
|
|
1755
|
+
// Add to reverse graph: targetRoot ← callerRoot
|
|
1756
|
+
let triggeredBy = effectTriggeredBy.get(targetRoot);
|
|
1757
|
+
if (!triggeredBy) {
|
|
1758
|
+
triggeredBy = new IterableWeakSet();
|
|
1759
|
+
effectTriggeredBy.set(targetRoot, triggeredBy);
|
|
1760
|
+
}
|
|
1761
|
+
triggeredBy.add(callerRoot);
|
|
1762
|
+
// Update transitive closures
|
|
1763
|
+
// When U→V is added, we need to propagate the relationship:
|
|
1764
|
+
// 1. Add U to causesClosure(V) and V to consequencesClosure(U) (direct relationship)
|
|
1765
|
+
// 2. For each X in causesClosure(U): add V to consequencesClosure(X) and X to causesClosure(V)
|
|
1766
|
+
// 3. For each Y in consequencesClosure(V): add U to causesClosure(Y) and Y to consequencesClosure(U)
|
|
1767
|
+
// Note: Self-loops (U→U) are not added to closures - if an effect appears in its own closure,
|
|
1768
|
+
// it means there's an indirect cycle that should be detected
|
|
1769
|
+
// Self-loops are explicitly ignored - an effect reading and writing the same property
|
|
1770
|
+
// (e.g., obj.prop++) should not create a dependency relationship or appear in closures
|
|
1771
|
+
if (callerRoot === targetRoot) {
|
|
1772
|
+
return;
|
|
1773
|
+
}
|
|
1774
|
+
const uConsequences = getOrCreateClosure(consequencesClosure, callerRoot);
|
|
1775
|
+
const vCauses = getOrCreateClosure(causesClosure, targetRoot);
|
|
1776
|
+
// 1. Add direct relationship
|
|
1777
|
+
uConsequences.add(targetRoot);
|
|
1778
|
+
vCauses.add(callerRoot);
|
|
1779
|
+
// 2. For each X in causesClosure(U): X→U→V means X→V
|
|
1780
|
+
const uCausesSet = causesClosure.get(callerRoot);
|
|
1781
|
+
if (uCausesSet) {
|
|
1782
|
+
for (const x of uCausesSet) {
|
|
1783
|
+
// Skip if this would create a self-loop
|
|
1784
|
+
if (x === targetRoot)
|
|
1785
|
+
continue;
|
|
1786
|
+
const xConsequences = getOrCreateClosure(consequencesClosure, x);
|
|
1787
|
+
xConsequences.add(targetRoot);
|
|
1788
|
+
vCauses.add(x);
|
|
1789
|
+
}
|
|
1790
|
+
}
|
|
1791
|
+
// 3. For each Y in consequencesClosure(V): U→V→Y means U→Y
|
|
1792
|
+
const vConsequencesSet = consequencesClosure.get(targetRoot);
|
|
1793
|
+
if (vConsequencesSet) {
|
|
1794
|
+
for (const y of vConsequencesSet) {
|
|
1795
|
+
// Skip if this would create a self-loop
|
|
1796
|
+
if (y === callerRoot)
|
|
1797
|
+
continue;
|
|
1798
|
+
const yCauses = getOrCreateClosure(causesClosure, y);
|
|
1799
|
+
yCauses.add(callerRoot);
|
|
1800
|
+
uConsequences.add(y);
|
|
1801
|
+
}
|
|
1802
|
+
}
|
|
1803
|
+
// 4. Cross-product: for each X in causesClosure(U) and Y in consequencesClosure(V): X→Y
|
|
1804
|
+
if (uCausesSet?.size && vConsequencesSet?.size) {
|
|
1805
|
+
for (const x of uCausesSet) {
|
|
1806
|
+
const xConsequences = getOrCreateClosure(consequencesClosure, x);
|
|
1807
|
+
for (const y of vConsequencesSet) {
|
|
1808
|
+
// Skip if this would create a self-loop
|
|
1809
|
+
if (x === y)
|
|
1810
|
+
continue;
|
|
1811
|
+
xConsequences.add(y);
|
|
1812
|
+
const yCauses = getOrCreateClosure(causesClosure, y);
|
|
1813
|
+
yCauses.add(x);
|
|
1814
|
+
}
|
|
1815
|
+
}
|
|
1816
|
+
}
|
|
1817
|
+
}
|
|
1818
|
+
/**
|
|
1819
|
+
* Checks if there's a path from start to end in the dependency graph, excluding a specific node
|
|
1820
|
+
* Uses BFS to find any path that doesn't go through the excluded node
|
|
1821
|
+
* @param start - Starting node
|
|
1822
|
+
* @param end - Target node
|
|
1823
|
+
* @param exclude - Node to exclude from the path
|
|
1824
|
+
* @returns true if a path exists without going through the excluded node
|
|
1825
|
+
*/
|
|
1826
|
+
function hasPathExcluding(start, end, exclude) {
|
|
1827
|
+
if (start === end)
|
|
1828
|
+
return true;
|
|
1829
|
+
if (start === exclude)
|
|
1830
|
+
return false;
|
|
1831
|
+
const visited = new Set();
|
|
1832
|
+
const queue = [start];
|
|
1833
|
+
visited.add(start);
|
|
1834
|
+
visited.add(exclude); // Pre-mark excluded node as visited to skip it
|
|
1835
|
+
while (queue.length > 0) {
|
|
1836
|
+
const current = queue.shift();
|
|
1837
|
+
const triggers = effectTriggers.get(current);
|
|
1838
|
+
if (!triggers)
|
|
1839
|
+
continue;
|
|
1840
|
+
for (const next of triggers) {
|
|
1841
|
+
if (next === end)
|
|
1842
|
+
return true;
|
|
1843
|
+
if (!visited.has(next)) {
|
|
1844
|
+
visited.add(next);
|
|
1845
|
+
queue.push(next);
|
|
1846
|
+
}
|
|
1847
|
+
}
|
|
1848
|
+
}
|
|
1849
|
+
return false;
|
|
1850
|
+
}
|
|
1851
|
+
/**
|
|
1852
|
+
* Removes all edges involving the given effect from the dependency graph
|
|
1853
|
+
* Also cleans up transitive closures by propagating cleanup to all affected effects
|
|
1854
|
+
* Called when an effect is stopped/cleaned up
|
|
1855
|
+
* @param effect - The effect being cleaned up
|
|
1856
|
+
*/
|
|
1857
|
+
function cleanupEffectFromGraph(effect) {
|
|
1858
|
+
if (options.cycleHandling === 'production')
|
|
1859
|
+
return;
|
|
1860
|
+
const root = getRoot(effect);
|
|
1861
|
+
// Get closures before removing direct edges (needed for propagation)
|
|
1862
|
+
const rootCauses = causesClosure.get(root);
|
|
1863
|
+
const rootConsequences = consequencesClosure.get(root);
|
|
1864
|
+
// Remove from effectTriggers (outgoing edges)
|
|
1865
|
+
const triggers = effectTriggers.get(root);
|
|
1866
|
+
if (triggers) {
|
|
1867
|
+
// Remove this root from all targets' effectTriggeredBy sets
|
|
1868
|
+
for (const targetRoot of triggers) {
|
|
1869
|
+
const triggeredBy = effectTriggeredBy.get(targetRoot);
|
|
1870
|
+
triggeredBy?.delete(root);
|
|
1871
|
+
}
|
|
1872
|
+
effectTriggers.delete(root);
|
|
1873
|
+
}
|
|
1874
|
+
// Remove from effectTriggeredBy (incoming edges)
|
|
1875
|
+
const triggeredBy = effectTriggeredBy.get(root);
|
|
1876
|
+
if (triggeredBy) {
|
|
1877
|
+
// Remove this root from all sources' effectTriggers sets
|
|
1878
|
+
for (const sourceRoot of triggeredBy) {
|
|
1879
|
+
const triggers = effectTriggers.get(sourceRoot);
|
|
1880
|
+
triggers?.delete(root);
|
|
1881
|
+
}
|
|
1882
|
+
effectTriggeredBy.delete(root);
|
|
1883
|
+
}
|
|
1884
|
+
// Propagate closure cleanup to all affected effects
|
|
1885
|
+
// When removing B from A → B → C:
|
|
1886
|
+
// - Remove B from causesClosure(C) and consequencesClosure(A)
|
|
1887
|
+
// - For each X in causesClosure(B): remove C from consequencesClosure(X) if B was the only path
|
|
1888
|
+
// - For each Y in consequencesClosure(B): remove A from causesClosure(Y) if B was the only path
|
|
1889
|
+
// - Remove transitive relationships that depended on B
|
|
1890
|
+
if (rootCauses) {
|
|
1891
|
+
// For each X that triggers root: remove root from X's consequences
|
|
1892
|
+
// Only remove root's consequences if no alternate path exists
|
|
1893
|
+
for (const causeRoot of rootCauses) {
|
|
1894
|
+
const causeConsequences = consequencesClosure.get(causeRoot);
|
|
1895
|
+
if (causeConsequences) {
|
|
1896
|
+
// Remove root itself (it's being cleaned up)
|
|
1897
|
+
causeConsequences.delete(root);
|
|
1898
|
+
// Only remove consequences of root if there's no alternate path from causeRoot to them
|
|
1899
|
+
if (rootConsequences) {
|
|
1900
|
+
for (const consequence of rootConsequences) {
|
|
1901
|
+
// Check if causeRoot can still reach consequence without going through root
|
|
1902
|
+
if (!hasPathExcluding(causeRoot, consequence, root)) {
|
|
1903
|
+
causeConsequences.delete(consequence);
|
|
1904
|
+
}
|
|
1905
|
+
}
|
|
1906
|
+
}
|
|
1907
|
+
}
|
|
1908
|
+
}
|
|
1909
|
+
}
|
|
1910
|
+
if (rootConsequences) {
|
|
1911
|
+
// For each Y that root triggers: remove root from Y's causes
|
|
1912
|
+
// Only remove root's causes if no alternate path exists
|
|
1913
|
+
for (const consequenceRoot of rootConsequences) {
|
|
1914
|
+
const consequenceCauses = causesClosure.get(consequenceRoot);
|
|
1915
|
+
if (consequenceCauses) {
|
|
1916
|
+
// Remove root itself (it's being cleaned up)
|
|
1917
|
+
consequenceCauses.delete(root);
|
|
1918
|
+
// Only remove causes of root if there's no alternate path from them to consequenceRoot
|
|
1919
|
+
if (rootCauses) {
|
|
1920
|
+
for (const cause of rootCauses) {
|
|
1921
|
+
// Check if cause can still reach consequenceRoot without going through root
|
|
1922
|
+
if (!hasPathExcluding(cause, consequenceRoot, root)) {
|
|
1923
|
+
consequenceCauses.delete(cause);
|
|
1924
|
+
}
|
|
1925
|
+
}
|
|
1926
|
+
}
|
|
1927
|
+
}
|
|
1928
|
+
}
|
|
1929
|
+
}
|
|
1930
|
+
// Cross-product cleanup: for each X in causesClosure(B) and Y in consequencesClosure(B),
|
|
1931
|
+
// remove X→Y if B was the only path connecting them
|
|
1932
|
+
if (rootCauses && rootConsequences) {
|
|
1933
|
+
for (const x of rootCauses) {
|
|
1934
|
+
const xConsequences = consequencesClosure.get(x);
|
|
1935
|
+
if (xConsequences) {
|
|
1936
|
+
for (const y of rootConsequences) {
|
|
1937
|
+
// Check if there's still a path from X to Y without going through root
|
|
1938
|
+
// Use BFS to find any path that doesn't include root
|
|
1939
|
+
if (!hasPathExcluding(x, y, root)) {
|
|
1940
|
+
xConsequences.delete(y);
|
|
1941
|
+
const yCauses = causesClosure.get(y);
|
|
1942
|
+
yCauses?.delete(x);
|
|
1943
|
+
}
|
|
1944
|
+
}
|
|
1945
|
+
}
|
|
1946
|
+
}
|
|
1947
|
+
}
|
|
1948
|
+
// Finally, delete the closures for this effect
|
|
1949
|
+
causesClosure.delete(root);
|
|
1950
|
+
consequencesClosure.delete(root);
|
|
1951
|
+
}
|
|
1952
|
+
// Track currently executing effects to prevent re-execution
|
|
1953
|
+
// These are all the effects triggered under `activeEffect`
|
|
1954
|
+
// Batch stack - handles nested batches by giving each its own queue
|
|
1955
|
+
const batchStack = [];
|
|
1956
|
+
function hasBatched(effect) {
|
|
1957
|
+
const root = getRoot(effect);
|
|
1958
|
+
return batchStack.some((bs) => bs.all.has(root));
|
|
1959
|
+
}
|
|
1960
|
+
// DEV: stack of currently-executing effects (push on enter, pop on leave)
|
|
1961
|
+
const executingStack = [];
|
|
1962
|
+
/**
|
|
1963
|
+
* Computes and caches in-degrees for all effects in the batch
|
|
1964
|
+
* Called once when batch starts or when new effects are added
|
|
1965
|
+
*/
|
|
1966
|
+
function computeAllInDegrees(batch) {
|
|
1967
|
+
if (options.cycleHandling === 'production')
|
|
1968
|
+
return;
|
|
1969
|
+
const activeEffect = getActiveEffect();
|
|
1970
|
+
const activeRoot = activeEffect ? getRoot(activeEffect) : null;
|
|
1971
|
+
// Reset all in-degrees
|
|
1972
|
+
batch.inDegrees.clear();
|
|
1973
|
+
for (const [root] of batch.all) {
|
|
1974
|
+
let inDegree = 0;
|
|
1975
|
+
const causes = causesClosure.get(root);
|
|
1976
|
+
if (causes) {
|
|
1977
|
+
for (const causeRoot of causes) {
|
|
1978
|
+
// Only count if it's in the batch and not the active/self effect
|
|
1979
|
+
if (batch.all.has(causeRoot) && causeRoot !== activeRoot && causeRoot !== root) {
|
|
1980
|
+
inDegree++;
|
|
1981
|
+
}
|
|
1982
|
+
}
|
|
1983
|
+
}
|
|
1984
|
+
batch.inDegrees.set(root, inDegree);
|
|
1985
|
+
}
|
|
1986
|
+
}
|
|
1987
|
+
/**
|
|
1988
|
+
* Decrements in-degrees of all effects that depend on the executed effect
|
|
1989
|
+
* Called after an effect is executed to update the cached in-degrees
|
|
1990
|
+
*/
|
|
1991
|
+
function decrementInDegreesForExecuted(batch, executedRoot) {
|
|
1992
|
+
// Get all effects that this executed effect triggers
|
|
1993
|
+
const consequences = consequencesClosure.get(executedRoot);
|
|
1994
|
+
if (!consequences)
|
|
1995
|
+
return;
|
|
1996
|
+
for (const consequenceRoot of consequences) {
|
|
1997
|
+
// Only update if it's still in the batch
|
|
1998
|
+
if (batch.all.has(consequenceRoot)) {
|
|
1999
|
+
const currentDegree = batch.inDegrees.get(consequenceRoot) ?? 0;
|
|
2000
|
+
if (currentDegree > 0) {
|
|
2001
|
+
batch.inDegrees.set(consequenceRoot, currentDegree - 1);
|
|
2002
|
+
}
|
|
2003
|
+
}
|
|
2004
|
+
}
|
|
2005
|
+
}
|
|
2006
|
+
/**
|
|
2007
|
+
* Finds a path from startRoot to endRoot in the dependency graph
|
|
2008
|
+
* Uses DFS to find the path through direct edges
|
|
2009
|
+
* @param startRoot - Starting effect root
|
|
2010
|
+
* @param endRoot - Target effect root
|
|
2011
|
+
* @param visited - Set of visited nodes (for recursion)
|
|
2012
|
+
* @param path - Current path being explored
|
|
2013
|
+
* @returns Path from startRoot to endRoot, or empty array if no path exists
|
|
2014
|
+
*/
|
|
2015
|
+
function findPath(startRoot, endRoot, visited = new Set(), path = []) {
|
|
2016
|
+
if (startRoot === endRoot) {
|
|
2017
|
+
return [...path, endRoot];
|
|
2018
|
+
}
|
|
2019
|
+
if (visited.has(startRoot)) {
|
|
2020
|
+
return [];
|
|
2021
|
+
}
|
|
2022
|
+
visited.add(startRoot);
|
|
2023
|
+
const newPath = [...path, startRoot];
|
|
2024
|
+
const triggers = effectTriggers.get(startRoot);
|
|
2025
|
+
if (triggers) {
|
|
2026
|
+
for (const targetRoot of triggers) {
|
|
2027
|
+
const result = findPath(targetRoot, endRoot, visited, newPath);
|
|
2028
|
+
if (result.length > 0) {
|
|
2029
|
+
return result;
|
|
2030
|
+
}
|
|
2031
|
+
}
|
|
2032
|
+
}
|
|
2033
|
+
return [];
|
|
2034
|
+
}
|
|
2035
|
+
/**
|
|
2036
|
+
* Gets the cycle path when adding an edge would create a cycle
|
|
2037
|
+
* @param callerRoot - Root of the effect that triggers
|
|
2038
|
+
* @param targetRoot - Root of the effect being triggered
|
|
2039
|
+
* @returns Array of effect roots forming the cycle, or empty array if no cycle
|
|
2040
|
+
*/
|
|
2041
|
+
function getCyclePathForEdge(callerRoot, targetRoot) {
|
|
2042
|
+
// Find path from targetRoot back to callerRoot (this is the existing path)
|
|
2043
|
+
// Then adding callerRoot -> targetRoot completes the cycle
|
|
2044
|
+
const path = findPath(targetRoot, callerRoot);
|
|
2045
|
+
if (path.length > 0) {
|
|
2046
|
+
// The cycle is: callerRoot -> targetRoot -> ... -> callerRoot
|
|
2047
|
+
return [callerRoot, ...path];
|
|
2048
|
+
}
|
|
2049
|
+
return [];
|
|
2050
|
+
}
|
|
2051
|
+
/**
|
|
2052
|
+
* Checks if adding an edge would create a cycle
|
|
2053
|
+
* Uses causesClosure to check if callerRoot is already a cause of targetRoot
|
|
2054
|
+
* Self-loops (callerRoot === targetRoot) are explicitly ignored and return false
|
|
2055
|
+
*
|
|
2056
|
+
* **Note**: This is the primary optimization benefit of the transitive closure system.
|
|
2057
|
+
* It allows detecting cycles in O(1) time before they are executed.
|
|
2058
|
+
*
|
|
2059
|
+
* @param callerRoot - Root of the effect that triggers
|
|
2060
|
+
* @param targetRoot - Root of the effect being triggered
|
|
2061
|
+
* @returns true if adding this edge would create a cycle
|
|
2062
|
+
*/
|
|
2063
|
+
function wouldCreateCycle(callerRoot, targetRoot) {
|
|
2064
|
+
// Self-loops are explicitly ignored - an effect reading and writing the same property
|
|
2065
|
+
// (e.g., obj.prop++) should not create a dependency relationship
|
|
2066
|
+
if (callerRoot === targetRoot) {
|
|
2067
|
+
return false;
|
|
2068
|
+
}
|
|
2069
|
+
// Check if targetRoot already triggers callerRoot (directly or indirectly)
|
|
2070
|
+
// This would create a cycle: callerRoot -> targetRoot -> ... -> callerRoot
|
|
2071
|
+
// Using consequencesClosure: if targetRoot triggers callerRoot, then callerRoot is in consequencesClosure(targetRoot)
|
|
2072
|
+
const targetConsequences = consequencesClosure.get(targetRoot);
|
|
2073
|
+
if (targetConsequences?.has(callerRoot)) {
|
|
2074
|
+
return true; // Cycle detected: targetRoot -> ... -> callerRoot, and we're adding callerRoot -> targetRoot
|
|
2075
|
+
}
|
|
2076
|
+
return false;
|
|
2077
|
+
}
|
|
2078
|
+
/**
|
|
2079
|
+
* Adds an effect to the batch queue
|
|
2080
|
+
* @param effect - The effect to add
|
|
2081
|
+
* @param caller - The active effect that triggered this one (optional)
|
|
2082
|
+
* @param immediate - If true, don't create edges in the dependency graph
|
|
2083
|
+
*/
|
|
2084
|
+
function addToBatch(effect, caller, immediate, reason) {
|
|
2085
|
+
const node = getEffectNode(effect);
|
|
2086
|
+
const currentBatch = batchStack[batchStack.length - 1];
|
|
2087
|
+
if (!currentBatch) {
|
|
2088
|
+
return;
|
|
2089
|
+
}
|
|
2090
|
+
const root = getRoot(effect);
|
|
2091
|
+
// Build reason from pending triggers if not provided
|
|
2092
|
+
if (!reason && node.pendingTriggers) {
|
|
2093
|
+
reason = { type: 'propChange', triggers: node.pendingTriggers };
|
|
2094
|
+
}
|
|
2095
|
+
node.pendingTriggers = undefined;
|
|
2096
|
+
if (reason) {
|
|
2097
|
+
const existing = node.nextReason;
|
|
2098
|
+
if (!existing) {
|
|
2099
|
+
node.nextReason = reason;
|
|
2100
|
+
}
|
|
2101
|
+
else {
|
|
2102
|
+
const mergePropChange = (into, from) => {
|
|
2103
|
+
if (into.type === 'propChange') {
|
|
2104
|
+
into.triggers.push(...from.triggers);
|
|
2105
|
+
return true;
|
|
2106
|
+
}
|
|
2107
|
+
if (into.type === 'multiple') {
|
|
2108
|
+
const target = into.reasons.find((r) => r.type === 'propChange');
|
|
2109
|
+
if (target) {
|
|
2110
|
+
target.triggers.push(...from.triggers);
|
|
2111
|
+
return true;
|
|
2112
|
+
}
|
|
2113
|
+
}
|
|
2114
|
+
return false;
|
|
2115
|
+
};
|
|
2116
|
+
if (reason.type === 'propChange') {
|
|
2117
|
+
if (!mergePropChange(existing, reason)) {
|
|
2118
|
+
if (existing.type === 'multiple') {
|
|
2119
|
+
existing.reasons.push(reason);
|
|
2120
|
+
}
|
|
2121
|
+
else {
|
|
2122
|
+
node.nextReason = { type: 'multiple', reasons: [existing, reason] };
|
|
2123
|
+
}
|
|
2124
|
+
}
|
|
2125
|
+
}
|
|
2126
|
+
else if (existing.type === 'multiple') {
|
|
2127
|
+
existing.reasons.push(reason);
|
|
2128
|
+
}
|
|
2129
|
+
else {
|
|
2130
|
+
node.nextReason = { type: 'multiple', reasons: [existing, reason] };
|
|
2131
|
+
}
|
|
2132
|
+
}
|
|
2133
|
+
}
|
|
2134
|
+
// 1. Add to batch first (needed for cycle detection)
|
|
2135
|
+
// TODO: Check if it's the correct way to do (these different behavior in function of dev/production)
|
|
2136
|
+
if (options.cycleHandling === 'production') {
|
|
2137
|
+
// Production mode: FIFO (delete and re-add to move to end)
|
|
2138
|
+
if (currentBatch.all.has(root)) {
|
|
2139
|
+
currentBatch.all.delete(root);
|
|
2140
|
+
}
|
|
2141
|
+
}
|
|
2142
|
+
else {
|
|
2143
|
+
// Dev mode: skip if already queued — the existing entry will re-run
|
|
2144
|
+
if (currentBatch.all.has(root)) {
|
|
2145
|
+
return;
|
|
2146
|
+
}
|
|
2147
|
+
}
|
|
2148
|
+
// If the effect was stopped during cleanup (e.g. lazy memoization), don't add it to the batch
|
|
2149
|
+
if (node.stopped)
|
|
2150
|
+
return;
|
|
2151
|
+
currentBatch.all.set(root, effect);
|
|
2152
|
+
if (caller && true && options.cycleHandling !== 'production') {
|
|
2153
|
+
const callerRoot = getRoot(caller);
|
|
2154
|
+
// const root = getRoot(effect) // Already have root
|
|
2155
|
+
// Check for cycle BEFORE adding edge
|
|
2156
|
+
if (wouldCreateCycle(callerRoot, root)) {
|
|
2157
|
+
const cyclePath = getCyclePathForEdge(callerRoot, root);
|
|
2158
|
+
const cycleMessage = cyclePath.length > 0
|
|
2159
|
+
? `Cycle detected: ${cyclePath.map((r) => r.name || r.toString()).join(' → ')}`
|
|
2160
|
+
: `Cycle detected: ${callerRoot.name || callerRoot.toString()} → ${root.name || root.toString()} (and back)`;
|
|
2161
|
+
currentBatch.all.delete(root);
|
|
2162
|
+
const causalChain = debugHooks.getTriggerChain(effect);
|
|
2163
|
+
const lineage = getEffectNode(effect).creationStack;
|
|
2164
|
+
throw new ReactiveError(`[reactive] ${cycleMessage}`, {
|
|
2165
|
+
code: ReactiveErrorCode.CycleDetected,
|
|
2166
|
+
cycle: cyclePath.map((r) => r.name || r.toString()),
|
|
2167
|
+
details: cycleMessage,
|
|
2168
|
+
causalChain,
|
|
2169
|
+
lineage,
|
|
2170
|
+
});
|
|
2171
|
+
}
|
|
2172
|
+
addGraphEdge(callerRoot, root);
|
|
2173
|
+
}
|
|
2174
|
+
}
|
|
2175
|
+
/**
|
|
2176
|
+
* Adds a cleanup function to be called when the current batch of effects completes
|
|
2177
|
+
* @param cleanup - The cleanup function to add
|
|
2178
|
+
*/
|
|
2179
|
+
function addBatchCleanup(cleanup) {
|
|
2180
|
+
const currentBatch = batchStack[batchStack.length - 1];
|
|
2181
|
+
if (!currentBatch)
|
|
2182
|
+
cleanup();
|
|
2183
|
+
else
|
|
2184
|
+
currentBatch.deferreds.add(cleanup);
|
|
2185
|
+
}
|
|
2186
|
+
/**
|
|
2187
|
+
* Semantic alias for `addBatchCleanup` - defers work to the end of the current reactive batch.
|
|
2188
|
+
*
|
|
2189
|
+
* Use this when an effect needs to perform an action that would modify state the effect depends on,
|
|
2190
|
+
* which would create a reactive cycle. The deferred callback runs after all effects complete.
|
|
2191
|
+
*
|
|
2192
|
+
* @param callback - The callback to defer until after the current batch completes
|
|
2193
|
+
*
|
|
2194
|
+
* @example
|
|
2195
|
+
* ```typescript
|
|
2196
|
+
* effect(() => {
|
|
2197
|
+
* processData()
|
|
2198
|
+
*
|
|
2199
|
+
* // Defer to avoid cycle (createMovement modifies state this effect reads)
|
|
2200
|
+
* defer(() => {
|
|
2201
|
+
* createMovement(data)
|
|
2202
|
+
* })
|
|
2203
|
+
* })
|
|
2204
|
+
* ```
|
|
2205
|
+
*/
|
|
2206
|
+
const defer = addBatchCleanup;
|
|
2207
|
+
/**
|
|
2208
|
+
* Gets a cycle path for debugging
|
|
2209
|
+
* Uses DFS to find cycles in the batch
|
|
2210
|
+
* @param batch - The batch queue
|
|
2211
|
+
* @returns Array of effect roots forming a cycle
|
|
2212
|
+
*/
|
|
2213
|
+
function getCyclePath(batch) {
|
|
2214
|
+
// If all effects have in-degree > 0, there must be a cycle
|
|
2215
|
+
// Use DFS to find it
|
|
2216
|
+
const visited = new Set();
|
|
2217
|
+
const recursionStack = new Set();
|
|
2218
|
+
const path = [];
|
|
2219
|
+
for (const [root] of batch.all) {
|
|
2220
|
+
if (visited.has(root))
|
|
2221
|
+
continue;
|
|
2222
|
+
const cycle = findCycle(root, visited, recursionStack, path, batch);
|
|
2223
|
+
if (cycle.length > 0) {
|
|
2224
|
+
return cycle;
|
|
2225
|
+
}
|
|
2226
|
+
}
|
|
2227
|
+
return [];
|
|
2228
|
+
}
|
|
2229
|
+
function findCycle(root, visited, recursionStack, path, batch) {
|
|
2230
|
+
if (recursionStack.has(root)) {
|
|
2231
|
+
// Found a cycle! Return the path from the cycle start to root
|
|
2232
|
+
const cycleStart = path.indexOf(root);
|
|
2233
|
+
return path.slice(cycleStart).concat([root]);
|
|
2234
|
+
}
|
|
2235
|
+
if (visited.has(root)) {
|
|
2236
|
+
return [];
|
|
2237
|
+
}
|
|
2238
|
+
visited.add(root);
|
|
2239
|
+
recursionStack.add(root);
|
|
2240
|
+
path.push(root);
|
|
2241
|
+
// Follow edges to effects in the batch
|
|
2242
|
+
// Use direct edges (effectTriggers) for cycle detection
|
|
2243
|
+
const triggers = effectTriggers.get(root);
|
|
2244
|
+
if (triggers) {
|
|
2245
|
+
for (const targetRoot of triggers) {
|
|
2246
|
+
if (batch.all.has(targetRoot)) {
|
|
2247
|
+
const cycle = findCycle(targetRoot, visited, recursionStack, path, batch);
|
|
2248
|
+
if (cycle.length > 0) {
|
|
2249
|
+
return cycle;
|
|
2250
|
+
}
|
|
2251
|
+
}
|
|
2252
|
+
}
|
|
2253
|
+
}
|
|
2254
|
+
path.pop();
|
|
2255
|
+
recursionStack.delete(root);
|
|
2256
|
+
return [];
|
|
2257
|
+
}
|
|
2258
|
+
/**
|
|
2259
|
+
* Executes the next effect in dependency order (using cached in-degrees)
|
|
2260
|
+
* Finds an effect with in-degree 0 and executes it
|
|
2261
|
+
* @returns The return value of the executed effect, or null if batch is complete
|
|
2262
|
+
*/
|
|
2263
|
+
function executeNext(effectuatedRoots) {
|
|
2264
|
+
const currentBatch = batchStack[batchStack.length - 1];
|
|
2265
|
+
if (!currentBatch)
|
|
2266
|
+
return null;
|
|
2267
|
+
// Find an effect with in-degree 0 using cached values
|
|
2268
|
+
let nextEffect = null;
|
|
2269
|
+
let nextRoot = null;
|
|
2270
|
+
if (options.cycleHandling === 'production') {
|
|
2271
|
+
// In flat mode, we just take the first effect in the queue (FIFO)
|
|
2272
|
+
const first = currentBatch.all.entries().next().value;
|
|
2273
|
+
if (first) {
|
|
2274
|
+
[nextRoot, nextEffect] = first;
|
|
2275
|
+
}
|
|
2276
|
+
}
|
|
2277
|
+
else {
|
|
2278
|
+
// Find an effect with in-degree 0 (no dependencies in batch that still need execution)
|
|
2279
|
+
// Using cached in-degrees for O(n) lookup instead of O(n²)
|
|
2280
|
+
for (const [root, effect] of currentBatch.all) {
|
|
2281
|
+
const inDegree = currentBatch.inDegrees.get(root) ?? 0;
|
|
2282
|
+
if (inDegree === 0) {
|
|
2283
|
+
nextEffect = effect;
|
|
2284
|
+
nextRoot = root;
|
|
2285
|
+
break;
|
|
2286
|
+
}
|
|
2287
|
+
}
|
|
2288
|
+
}
|
|
2289
|
+
if (!nextEffect) {
|
|
2290
|
+
// No effect with in-degree 0 - there must be a cycle
|
|
2291
|
+
// If all effects have dependencies, it means there's a circular dependency
|
|
2292
|
+
if (currentBatch.all.size > 0) {
|
|
2293
|
+
let cycle = getCyclePath(currentBatch);
|
|
2294
|
+
// If we couldn't find a cycle path using direct edges, try using closures
|
|
2295
|
+
// (transitive relationships) - if all effects have in-degree > 0, there must be a cycle
|
|
2296
|
+
if (cycle.length === 0) {
|
|
2297
|
+
// Try to find a cycle using consequencesClosure (transitive relationships)
|
|
2298
|
+
// Note: Self-loops are ignored - we only look for cycles between different effects
|
|
2299
|
+
for (const [root] of currentBatch.all) {
|
|
2300
|
+
const consequences = consequencesClosure.get(root);
|
|
2301
|
+
if (consequences) {
|
|
2302
|
+
// Check if any consequence in the batch also has root as a consequence
|
|
2303
|
+
for (const consequence of consequences) {
|
|
2304
|
+
// Skip self-loops - they are ignored
|
|
2305
|
+
if (consequence === root)
|
|
2306
|
+
continue;
|
|
2307
|
+
if (currentBatch.all.has(consequence)) {
|
|
2308
|
+
const consequenceConsequences = consequencesClosure.get(consequence);
|
|
2309
|
+
if (consequenceConsequences?.has(root)) {
|
|
2310
|
+
// Found cycle: root -> consequence -> root
|
|
2311
|
+
cycle = [root, consequence, root];
|
|
2312
|
+
break;
|
|
2313
|
+
}
|
|
2314
|
+
}
|
|
2315
|
+
}
|
|
2316
|
+
if (cycle.length > 0)
|
|
2317
|
+
break;
|
|
2318
|
+
}
|
|
2319
|
+
}
|
|
2320
|
+
}
|
|
2321
|
+
const cycleMessage = cycle.length > 0
|
|
2322
|
+
? `Cycle detected: ${cycle.map((r) => r.name || '<anonymous>').join(' → ')}`
|
|
2323
|
+
: 'Cycle detected in effect batch - all effects have dependencies that prevent execution';
|
|
2324
|
+
throw new ReactiveError(`[reactive] ${cycleMessage}`, {
|
|
2325
|
+
code: ReactiveErrorCode.CycleDetected,
|
|
2326
|
+
cycle: cycle.map((r) => r.name || r.toString()),
|
|
2327
|
+
details: cycleMessage,
|
|
2328
|
+
});
|
|
2329
|
+
}
|
|
2330
|
+
return null; // Batch complete
|
|
2331
|
+
}
|
|
2332
|
+
effectuatedRoots.push(getRoot(nextEffect));
|
|
2333
|
+
// Execute the effect
|
|
2334
|
+
executingStack.push(nextEffect);
|
|
2335
|
+
let result;
|
|
2336
|
+
try {
|
|
2337
|
+
const node = getEffectNode(nextEffect);
|
|
2338
|
+
const reason = node.nextReason;
|
|
2339
|
+
if (node.cleanup) {
|
|
2340
|
+
const cleanup = node.cleanup;
|
|
2341
|
+
node.cleanup = undefined;
|
|
2342
|
+
cleanup(reason);
|
|
2343
|
+
}
|
|
2344
|
+
result = nextEffect();
|
|
2345
|
+
}
|
|
2346
|
+
finally {
|
|
2347
|
+
executingStack.pop();
|
|
2348
|
+
}
|
|
2349
|
+
// Remove from ALL batches in the stack and update in-degrees of dependents
|
|
2350
|
+
for (let i = batchStack.length - 1; i >= 0; i--) {
|
|
2351
|
+
const batch = batchStack[i];
|
|
2352
|
+
if (batch.all.has(nextRoot)) {
|
|
2353
|
+
batch.all.delete(nextRoot);
|
|
2354
|
+
batch.inDegrees.delete(nextRoot);
|
|
2355
|
+
decrementInDegreesForExecuted(batch, nextRoot);
|
|
2356
|
+
}
|
|
2357
|
+
}
|
|
2358
|
+
return result;
|
|
2359
|
+
}
|
|
2360
|
+
// Track which sub-effects have been executed to prevent infinite loops
|
|
2361
|
+
// These are all the effects triggered under `activeEffect` and all their sub-effects
|
|
2362
|
+
function batch(effect, immediate) {
|
|
2363
|
+
if (broken) {
|
|
2364
|
+
throw new ReactiveError('[reactive] Reactive system is broken after an unrecoverable error. Call reset() to recover.', { code: ReactiveErrorCode.BrokenEffects });
|
|
2365
|
+
}
|
|
2366
|
+
if (!Array.isArray(effect))
|
|
2367
|
+
effect = [effect];
|
|
2368
|
+
const roots = effect.map(getRoot);
|
|
2369
|
+
const isNewBatch = batchStack.length === 0;
|
|
2370
|
+
if (isNewBatch) {
|
|
2371
|
+
if (!activationRegistry)
|
|
2372
|
+
activationRegistry = new Map();
|
|
2373
|
+
else
|
|
2374
|
+
throw new Error('Activation registry already exists');
|
|
2375
|
+
optionCall('beginChain', roots);
|
|
2376
|
+
}
|
|
2377
|
+
const caller = getActiveEffect();
|
|
2378
|
+
// Optimization: If nested and NOT immediate, just join the existing batch
|
|
2379
|
+
if (!isNewBatch && !immediate) {
|
|
2380
|
+
for (let i = 0; i < effect.length; i++) {
|
|
2381
|
+
addToBatch(effect[i], caller);
|
|
2382
|
+
}
|
|
2383
|
+
return;
|
|
2384
|
+
}
|
|
2385
|
+
const currentBatch = {
|
|
2386
|
+
all: new Map(),
|
|
2387
|
+
inDegrees: new Map(),
|
|
2388
|
+
deferreds: new Set(),
|
|
2389
|
+
};
|
|
2390
|
+
batchStack.push(currentBatch);
|
|
2391
|
+
let success = false;
|
|
2392
|
+
try {
|
|
2393
|
+
const effectuatedRoots = [];
|
|
2394
|
+
const firstReturn = {};
|
|
2395
|
+
if (immediate) {
|
|
2396
|
+
// Execute initial effects in providing order
|
|
2397
|
+
for (let i = 0; i < effect.length; i++) {
|
|
2398
|
+
executingStack.push(effect[i]);
|
|
2399
|
+
try {
|
|
2400
|
+
const node = getEffectNode(effect[i]);
|
|
2401
|
+
const reason = node.nextReason;
|
|
2402
|
+
if (node.cleanup) {
|
|
2403
|
+
const cleanup = node.cleanup;
|
|
2404
|
+
node.cleanup = undefined;
|
|
2405
|
+
cleanup(reason);
|
|
2406
|
+
}
|
|
2407
|
+
const rv = effect[i]();
|
|
2408
|
+
if (rv !== undefined && !('value' in firstReturn))
|
|
2409
|
+
firstReturn.value = rv;
|
|
2410
|
+
}
|
|
2411
|
+
finally {
|
|
2412
|
+
executingStack.pop();
|
|
2413
|
+
currentBatch.all.delete(getRoot(effect[i]));
|
|
2414
|
+
}
|
|
2415
|
+
}
|
|
2416
|
+
}
|
|
2417
|
+
else {
|
|
2418
|
+
// Add initial effects to batch and compute dependencies
|
|
2419
|
+
for (let i = 0; i < effect.length; i++) {
|
|
2420
|
+
addToBatch(effect[i], caller, false);
|
|
2421
|
+
}
|
|
2422
|
+
computeAllInDegrees(currentBatch);
|
|
2423
|
+
}
|
|
2424
|
+
// Process the current batch queue
|
|
2425
|
+
while (currentBatch.all.size > 0 || currentBatch.deferreds.size > 0) {
|
|
2426
|
+
if (currentBatch.all.size > 0) {
|
|
2427
|
+
if (effectuatedRoots.length > options.maxEffectChain) {
|
|
2428
|
+
const cycle = findCycleInChain(effectuatedRoots);
|
|
2429
|
+
const trace = formatRoots(effectuatedRoots);
|
|
2430
|
+
const message = cycle
|
|
2431
|
+
? `Max effect chain reached (cycle detected: ${formatRoots(cycle)})`
|
|
2432
|
+
: `Max effect chain reached (trace: ${trace})`;
|
|
2433
|
+
const queuedRoots = Array.from(currentBatch.all.keys());
|
|
2434
|
+
const queued = queuedRoots.map((r) => r.name || '<anonymous>');
|
|
2435
|
+
const debugInfo = {
|
|
2436
|
+
code: ReactiveErrorCode.MaxDepthExceeded,
|
|
2437
|
+
effectuatedRoots,
|
|
2438
|
+
cycle,
|
|
2439
|
+
trace,
|
|
2440
|
+
maxEffectChain: options.maxEffectChain,
|
|
2441
|
+
queued: queued.slice(0, 50),
|
|
2442
|
+
queuedCount: queued.length,
|
|
2443
|
+
causalChain: effectuatedRoots.length > 0
|
|
2444
|
+
? debugHooks.getTriggerChain(currentBatch.all.get(effectuatedRoots[effectuatedRoots.length - 1]))
|
|
2445
|
+
: [],
|
|
2446
|
+
};
|
|
2447
|
+
switch (options.maxEffectReaction) {
|
|
2448
|
+
case 'throw':
|
|
2449
|
+
throw new ReactiveError(`[reactive] ${message}`, debugInfo);
|
|
2450
|
+
case 'debug':
|
|
2451
|
+
// biome-ignore lint/suspicious/noDebugger: This is the whole point here
|
|
2452
|
+
debugger;
|
|
2453
|
+
throw new ReactiveError(`[reactive] ${message}`, debugInfo);
|
|
2454
|
+
case 'warn':
|
|
2455
|
+
options.warn(`[reactive] ${message} (queued: ${queued.slice(0, 10).join(', ')}${queued.length > 10 ? ', …' : ''})`);
|
|
2456
|
+
break;
|
|
2457
|
+
}
|
|
2458
|
+
}
|
|
2459
|
+
const rv = executeNext(effectuatedRoots);
|
|
2460
|
+
if (rv !== undefined && !('value' in firstReturn))
|
|
2461
|
+
firstReturn.value = rv;
|
|
2462
|
+
}
|
|
2463
|
+
else {
|
|
2464
|
+
// Process deferreds for this batch.
|
|
2465
|
+
const deferreds = Array.from(currentBatch.deferreds);
|
|
2466
|
+
currentBatch.deferreds.clear();
|
|
2467
|
+
for (const deferred of deferreds)
|
|
2468
|
+
deferred();
|
|
2469
|
+
}
|
|
2470
|
+
}
|
|
2471
|
+
success = true;
|
|
2472
|
+
return firstReturn.value;
|
|
2473
|
+
}
|
|
2474
|
+
finally {
|
|
2475
|
+
if (!success && batchStack.length === 1) {
|
|
2476
|
+
broken = true;
|
|
2477
|
+
}
|
|
2478
|
+
batchStack.pop();
|
|
2479
|
+
if (batchStack.length === 0) {
|
|
2480
|
+
activationRegistry = undefined;
|
|
2481
|
+
optionCall('endChain');
|
|
2482
|
+
}
|
|
2483
|
+
}
|
|
2484
|
+
}
|
|
2485
|
+
/**
|
|
2486
|
+
* Resets the reactive system to a consistent state.
|
|
2487
|
+
* Call this after an unrecoverable error has set the system to "broken".
|
|
2488
|
+
* This clears all batch state, effect dependency graphs, and watcher registrations.
|
|
2489
|
+
* All existing effects become orphaned and must be recreated.
|
|
2490
|
+
*/
|
|
2491
|
+
function reset() {
|
|
2492
|
+
broken = false;
|
|
2493
|
+
activationRegistry = undefined;
|
|
2494
|
+
batchStack.length = 0;
|
|
2495
|
+
effectTriggers = new WeakMap();
|
|
2496
|
+
effectTriggeredBy = new WeakMap();
|
|
2497
|
+
causesClosure = new WeakMap();
|
|
2498
|
+
consequencesClosure = new WeakMap();
|
|
2499
|
+
resetRegistry();
|
|
2500
|
+
resetTracking();
|
|
2501
|
+
effectHistory.present.active = undefined;
|
|
2502
|
+
}
|
|
2503
|
+
// Inject batch function to allow atomic game loops in requestAnimationFrame/setTimeout/...
|
|
2504
|
+
// Note: Automatic batching of async callbacks (setTimeout, Promise.then, etc.) is NOT implemented.
|
|
2505
|
+
// Rationale: (1) asyncHooks.addHook API doesn't support knowing when callbacks complete (needed for batching),
|
|
2506
|
+
// (2) hooking all callback-creating functions adds overhead without guaranteed benefit,
|
|
2507
|
+
// (3) incomplete coverage in Node (async_hooks misses user-land patterns).
|
|
2508
|
+
// Solution: Use explicit @atomic decorator or manual batch() calls where optimization is needed.
|
|
2509
|
+
/**
|
|
2510
|
+
* Decorator that makes methods atomic - batches all effects triggered within the method
|
|
2511
|
+
*/
|
|
2512
|
+
const atomic = decorator({
|
|
2513
|
+
method(original) {
|
|
2514
|
+
return function (...args) {
|
|
2515
|
+
const atomicEffect = () => original.apply(this, args);
|
|
2516
|
+
// Debug: helpful to have a name
|
|
2517
|
+
Object.defineProperty(atomicEffect, 'name', { value: `atomic(${original.name})` });
|
|
2518
|
+
return batch(atomicEffect, 'immediate');
|
|
2519
|
+
};
|
|
2520
|
+
},
|
|
2521
|
+
default(original) {
|
|
2522
|
+
return function (...args) {
|
|
2523
|
+
const atomicEffect = () => original.apply(this, args);
|
|
2524
|
+
// Debug: helpful to have a name
|
|
2525
|
+
Object.defineProperty(atomicEffect, 'name', { value: `atomic(${original.name})` });
|
|
2526
|
+
return batch(atomicEffect, 'immediate');
|
|
2527
|
+
};
|
|
2528
|
+
},
|
|
2529
|
+
});
|
|
2530
|
+
/**
|
|
2531
|
+
* Runs `fn` atomically and **always immediately**, batching all reactive effects
|
|
2532
|
+
* triggered inside it so they fire only once after `fn` completes.
|
|
2533
|
+
*
|
|
2534
|
+
* Unlike `atomic(fn)` which **wraps** a function for later invocation,
|
|
2535
|
+
* `atom(fn)` **executes** the function right away.
|
|
2536
|
+
*
|
|
2537
|
+
* @example
|
|
2538
|
+
* ```ts
|
|
2539
|
+
* const state = reactive({ a: 0, b: 0 })
|
|
2540
|
+
* effect(() => console.log(state.a, state.b)) // logs once after atom completes
|
|
2541
|
+
*
|
|
2542
|
+
* atom(() => {
|
|
2543
|
+
* state.a = 1
|
|
2544
|
+
* state.b = 2
|
|
2545
|
+
* })
|
|
2546
|
+
* ```
|
|
2547
|
+
*/
|
|
2548
|
+
function atom(fn) {
|
|
2549
|
+
return batch(fn, 'immediate');
|
|
2550
|
+
}
|
|
2551
|
+
const fr = new FinalizationRegistry((f) => f());
|
|
2552
|
+
/**
|
|
2553
|
+
* @param fn - The effect function to run - provides the cleaner
|
|
2554
|
+
* @returns The cleanup function
|
|
2555
|
+
*/
|
|
2556
|
+
/**
|
|
2557
|
+
* Creates a reactive effect that automatically re-runs when dependencies change
|
|
2558
|
+
* @param fn - The effect function that provides dependencies and may return a cleanup function or Promise
|
|
2559
|
+
* @param options - Options for effect execution
|
|
2560
|
+
* @returns A cleanup function to stop the effect
|
|
2561
|
+
*/
|
|
2562
|
+
const effect = named(effectMarker.leave, flavored(function effect(
|
|
2563
|
+
// biome-ignore lint/suspicious/noConfusingVoidType: Effect callbacks commonly return void
|
|
2564
|
+
fn, effectOptions = {}) {
|
|
2565
|
+
if (effectOptions?.name)
|
|
2566
|
+
Object.defineProperty(fn, 'name', { value: effectOptions.name });
|
|
2567
|
+
// Use per-effect asyncMode or fall back to global option
|
|
2568
|
+
const asyncMode = effectOptions?.asyncMode ?? options.asyncMode ?? 'cancel';
|
|
2569
|
+
// Create the effect function - naming it for debug
|
|
2570
|
+
const runEffect = () => {
|
|
2571
|
+
const node = getEffectNode(runEffect);
|
|
2572
|
+
// Clear previous dependencies
|
|
2573
|
+
if (node.cleanup) {
|
|
2574
|
+
const prevCleanup = node.cleanup;
|
|
2575
|
+
node.cleanup = undefined;
|
|
2576
|
+
try {
|
|
2577
|
+
untracked(() => prevCleanup(node.nextReason || { type: 'stopped' }));
|
|
2578
|
+
}
|
|
2579
|
+
catch (error) {
|
|
2580
|
+
// If we want to report them, we could use options.warn or similar
|
|
2581
|
+
options.warn('Error during effect cleanup', error);
|
|
2582
|
+
}
|
|
2583
|
+
}
|
|
2584
|
+
// Handle async modes when effect is retriggered
|
|
2585
|
+
if (runningPromise) {
|
|
2586
|
+
if (asyncMode === 'cancel' && cancelPrevious) {
|
|
2587
|
+
// Cancel previous execution
|
|
2588
|
+
cancelPrevious();
|
|
2589
|
+
cancelPrevious = null;
|
|
2590
|
+
runningPromise = null;
|
|
2591
|
+
}
|
|
2592
|
+
else if (asyncMode === 'ignore') {
|
|
2593
|
+
// Ignore new execution while async work is running
|
|
2594
|
+
return;
|
|
2595
|
+
}
|
|
2596
|
+
// Note: 'queue' mode not yet implemented
|
|
2597
|
+
}
|
|
2598
|
+
// The effect has been stopped after having been planned
|
|
2599
|
+
if (effectStopped)
|
|
2600
|
+
return;
|
|
2601
|
+
let reactionCleanup;
|
|
2602
|
+
function cleanupReaction(reason) {
|
|
2603
|
+
const toCleanup = reactionCleanup;
|
|
2604
|
+
reactionCleanup = undefined;
|
|
2605
|
+
toCleanup?.(reason);
|
|
2606
|
+
}
|
|
2607
|
+
// Set reaction reason for the upcoming run
|
|
2608
|
+
access.reaction = node.nextReason || access.reaction;
|
|
2609
|
+
node.nextReason = undefined;
|
|
2610
|
+
optionCall('enter', getRoot(fn));
|
|
2611
|
+
let result;
|
|
2612
|
+
let caught = 0;
|
|
2613
|
+
// Default thrower (self)
|
|
2614
|
+
let thrower = (error) => {
|
|
2615
|
+
throw error;
|
|
2616
|
+
};
|
|
2617
|
+
node.forwardThrow = thrower;
|
|
2618
|
+
let errorToThrow;
|
|
2619
|
+
try {
|
|
2620
|
+
result = tracked(named(effectMarker.enter, () => fn.call(null, access)));
|
|
2621
|
+
access.reaction = true;
|
|
2622
|
+
optionCall('leave', fn);
|
|
2623
|
+
if (result &&
|
|
2624
|
+
typeof result !== 'function' &&
|
|
2625
|
+
(typeof result !== 'object' || !('then' in result)))
|
|
2626
|
+
throw new ReactiveError(`[reactive] Effect returned a non-function value: ${result}`);
|
|
2627
|
+
// Check if result is a Promise (async effect)
|
|
2628
|
+
if (result && typeof result === 'object' && typeof result.then === 'function') {
|
|
2629
|
+
const originalPromise = result;
|
|
2630
|
+
// Create a cancellation promise that we can reject
|
|
2631
|
+
let cancelReject = null;
|
|
2632
|
+
const cancelPromise = new Promise((_, reject) => {
|
|
2633
|
+
cancelReject = reject;
|
|
2634
|
+
});
|
|
2635
|
+
const cancelError = new ReactiveError('[reactive] Effect canceled due to dependency change');
|
|
2636
|
+
// Race between the actual promise and cancellation
|
|
2637
|
+
// If canceled, the race rejects, which will propagate through any promise chain
|
|
2638
|
+
runningPromise = Promise.race([originalPromise, cancelPromise]);
|
|
2639
|
+
// Store the cancellation function
|
|
2640
|
+
cancelPrevious = () => {
|
|
2641
|
+
if (cancelReject) {
|
|
2642
|
+
cancelReject(cancelError);
|
|
2643
|
+
}
|
|
2644
|
+
};
|
|
2645
|
+
// Wrap the original promise chain so cancellation propagates
|
|
2646
|
+
// This ensures that when we cancel, the original promise's .catch() handlers are triggered
|
|
2647
|
+
// We do this by rejecting the race promise, which makes the original promise chain see the rejection
|
|
2648
|
+
// through the zone-wrapped .then()/.catch() handlers
|
|
2649
|
+
runningPromise = runningPromise.catch((error) => {
|
|
2650
|
+
// Propagate async errors to the effect's error handler
|
|
2651
|
+
// This ensures onEffectThrow handlers are triggered for async errors
|
|
2652
|
+
if (error !== cancelError) {
|
|
2653
|
+
thrower(error);
|
|
2654
|
+
}
|
|
2655
|
+
// If thrower didn't throw (handled), we absorb the error.
|
|
2656
|
+
// If thrower threw (unhandled), it propagates as a new unhandled rejection, which is correct.
|
|
2657
|
+
});
|
|
2658
|
+
}
|
|
2659
|
+
else {
|
|
2660
|
+
// Synchronous result - treat as cleanup function
|
|
2661
|
+
reactionCleanup = result;
|
|
2662
|
+
}
|
|
2663
|
+
}
|
|
2664
|
+
catch (error) {
|
|
2665
|
+
// catcher:self`
|
|
2666
|
+
errorToThrow = error;
|
|
2667
|
+
}
|
|
2668
|
+
// Create cleanup function for next run
|
|
2669
|
+
node.cleanup = (reason) => {
|
|
2670
|
+
node.cleanup = undefined;
|
|
2671
|
+
cleanupReaction(reason);
|
|
2672
|
+
delete node.catchers;
|
|
2673
|
+
// Remove this effect from all reactive objects it's watching
|
|
2674
|
+
const effectObjects = effectToReactiveObjects.get(runEffect);
|
|
2675
|
+
if (effectObjects) {
|
|
2676
|
+
for (const reactiveObj of effectObjects) {
|
|
2677
|
+
const objectWatchers = watchers.get(reactiveObj);
|
|
2678
|
+
if (objectWatchers) {
|
|
2679
|
+
for (const [prop, deps] of objectWatchers.entries()) {
|
|
2680
|
+
deps.delete(runEffect);
|
|
2681
|
+
if (deps.size === 0) {
|
|
2682
|
+
objectWatchers.delete(prop);
|
|
2683
|
+
}
|
|
2684
|
+
}
|
|
2685
|
+
if (objectWatchers.size === 0) {
|
|
2686
|
+
watchers.delete(reactiveObj);
|
|
2687
|
+
}
|
|
2688
|
+
}
|
|
2689
|
+
}
|
|
2690
|
+
effectToReactiveObjects.delete(runEffect);
|
|
2691
|
+
}
|
|
2692
|
+
// Invoke all child stops (recursive via subEffectCleanup calling its own mainCleanup)
|
|
2693
|
+
const children = node.children;
|
|
2694
|
+
if (children) {
|
|
2695
|
+
const childReason = reason
|
|
2696
|
+
? reason.type === 'lineage'
|
|
2697
|
+
? reason
|
|
2698
|
+
: { type: 'lineage', parent: reason }
|
|
2699
|
+
: { type: 'stopped' };
|
|
2700
|
+
for (const childCleanup of children)
|
|
2701
|
+
childCleanup(childReason);
|
|
2702
|
+
delete node.children;
|
|
2703
|
+
}
|
|
2704
|
+
};
|
|
2705
|
+
// Define bubbling thrower
|
|
2706
|
+
thrower = (error) => {
|
|
2707
|
+
const catches = node.catchers;
|
|
2708
|
+
const reason = { type: 'error', error };
|
|
2709
|
+
if (catches)
|
|
2710
|
+
while (caught < catches.length) {
|
|
2711
|
+
cleanupReaction(reason);
|
|
2712
|
+
try {
|
|
2713
|
+
reactionCleanup = catches[caught](error);
|
|
2714
|
+
return;
|
|
2715
|
+
}
|
|
2716
|
+
catch (e) {
|
|
2717
|
+
caught++;
|
|
2718
|
+
}
|
|
2719
|
+
}
|
|
2720
|
+
if (parent) {
|
|
2721
|
+
const parentNode = getEffectNode(parent);
|
|
2722
|
+
if (parentNode.forwardThrow)
|
|
2723
|
+
parentNode.forwardThrow(error);
|
|
2724
|
+
else
|
|
2725
|
+
throw error;
|
|
2726
|
+
}
|
|
2727
|
+
else
|
|
2728
|
+
throw error;
|
|
2729
|
+
};
|
|
2730
|
+
// Update the node's forwardThrow to the bubbling one
|
|
2731
|
+
node.forwardThrow = thrower;
|
|
2732
|
+
if (errorToThrow)
|
|
2733
|
+
thrower(errorToThrow);
|
|
2734
|
+
};
|
|
2735
|
+
// Initialize metadata node
|
|
2736
|
+
const node = getEffectNode(runEffect);
|
|
2737
|
+
if (debugHooks.isDevtoolsEnabled()) {
|
|
2738
|
+
const stack = debugHooks.captureStack(); // Robustly skips internal mutts frames
|
|
2739
|
+
if (Array.isArray(stack) && stack.length > 0) {
|
|
2740
|
+
node.creationStack = stack;
|
|
2741
|
+
}
|
|
2742
|
+
}
|
|
2743
|
+
const tracked = effectHistory.present.with(runEffect, () => named(effectMarker.leave, effectAggregator.zoned));
|
|
2744
|
+
const ascended = named(effectMarker.leave, effectHistory.zoned);
|
|
2745
|
+
const parent = effectHistory.present.active;
|
|
2746
|
+
// Set parent relationship in node
|
|
2747
|
+
node.parent = parent;
|
|
2748
|
+
// let thrower: CatchFunction | undefined // Moved inside runEffect
|
|
2749
|
+
let effectStopped = false;
|
|
2750
|
+
const access = {
|
|
2751
|
+
tracked,
|
|
2752
|
+
ascend: named(effectMarker.leave, (fn) => ascended(named(effectMarker.enter, () => fn.call(null)))),
|
|
2753
|
+
//named(effectMarker.enter, (fn) => ascended(fn)),
|
|
2754
|
+
reaction: false,
|
|
2755
|
+
};
|
|
2756
|
+
let runningPromise = null;
|
|
2757
|
+
let cancelPrevious = null;
|
|
2758
|
+
if (effectOptions?.dependencyHook) {
|
|
2759
|
+
node.dependencyHook = effectOptions.dependencyHook;
|
|
2760
|
+
}
|
|
2761
|
+
// Mark the runEffect callback with the original function as its root
|
|
2762
|
+
markWithRoot(runEffect, fn);
|
|
2763
|
+
function augmentedRv(rv) {
|
|
2764
|
+
return Object.defineProperties(rv, {
|
|
2765
|
+
[stopped]: {
|
|
2766
|
+
get: () => effectStopped,
|
|
2767
|
+
},
|
|
2768
|
+
});
|
|
2769
|
+
}
|
|
2770
|
+
// Register strict mode if enabled
|
|
2771
|
+
if (effectOptions?.opaque) {
|
|
2772
|
+
node.isOpaque = true;
|
|
2773
|
+
}
|
|
2774
|
+
if (debugHooks.isDevtoolsEnabled()) {
|
|
2775
|
+
debugHooks.registerEffect(runEffect);
|
|
2776
|
+
}
|
|
2777
|
+
// Store parent relationship for hierarchy traversal - ALREADY DONE ABOVE via getEffectNode
|
|
2778
|
+
batch(runEffect, 'immediate');
|
|
2779
|
+
// Only ROOT effects are registered for GC cleanup and zone tracking
|
|
2780
|
+
const isRootEffect = !parent;
|
|
2781
|
+
const stopEffect = (reason) => {
|
|
2782
|
+
if (effectStopped)
|
|
2783
|
+
return;
|
|
2784
|
+
effectStopped = true;
|
|
2785
|
+
node.stopped = true;
|
|
2786
|
+
// Cancel any running async work
|
|
2787
|
+
if (cancelPrevious) {
|
|
2788
|
+
cancelPrevious();
|
|
2789
|
+
cancelPrevious = null;
|
|
2790
|
+
runningPromise = null;
|
|
2791
|
+
}
|
|
2792
|
+
try {
|
|
2793
|
+
node.cleanup?.(reason || { type: 'stopped' });
|
|
2794
|
+
}
|
|
2795
|
+
catch (error) {
|
|
2796
|
+
// Cleanup errors should basically be ignored or at least not stop the world
|
|
2797
|
+
// If we want to report them, we could use options.warn or similar
|
|
2798
|
+
options.warn('Error during effect cleanup', error);
|
|
2799
|
+
}
|
|
2800
|
+
// Clean up dependency graph edges
|
|
2801
|
+
cleanupEffectFromGraph(runEffect);
|
|
2802
|
+
fr.unregister(stopEffect);
|
|
2803
|
+
};
|
|
2804
|
+
if (isRootEffect) {
|
|
2805
|
+
const callIfCollected = augmentedRv((reason) => stopEffect(reason));
|
|
2806
|
+
fr.register(callIfCollected, () => {
|
|
2807
|
+
stopEffect({ type: 'gc' });
|
|
2808
|
+
optionCall('garbageCollected', fn);
|
|
2809
|
+
}, stopEffect);
|
|
2810
|
+
return callIfCollected;
|
|
2811
|
+
}
|
|
2812
|
+
// Register this effect to be stopped when the parent effect is cleaned up
|
|
2813
|
+
if (parent) {
|
|
2814
|
+
const parentNode = getEffectNode(parent);
|
|
2815
|
+
if (!parentNode.children) {
|
|
2816
|
+
parentNode.children = new Set();
|
|
2817
|
+
}
|
|
2818
|
+
const children = parentNode.children;
|
|
2819
|
+
const subEffectCleanup = augmentedRv((reason) => {
|
|
2820
|
+
children.delete(subEffectCleanup);
|
|
2821
|
+
// Execute this child effect cleanup (which triggers its own mainCleanup)
|
|
2822
|
+
stopEffect(reason);
|
|
2823
|
+
});
|
|
2824
|
+
children.add(subEffectCleanup);
|
|
2825
|
+
return subEffectCleanup;
|
|
2826
|
+
}
|
|
2827
|
+
// Should not be reachable given isRootEffect check, but for type safety
|
|
2828
|
+
return augmentedRv((reason) => stopEffect(reason));
|
|
2829
|
+
}, {
|
|
2830
|
+
get opaque() {
|
|
2831
|
+
return flavorOptions(this, { opaque: true }, { name: 'opaque' });
|
|
2832
|
+
},
|
|
2833
|
+
named(name) {
|
|
2834
|
+
return flavorOptions(this, { name }, { name: 'named' });
|
|
2835
|
+
},
|
|
2836
|
+
}));
|
|
2837
|
+
/**
|
|
2838
|
+
* Executes a function without tracking dependencies but maintains parent cleanup relationship
|
|
2839
|
+
* Effects created inside will still be cleaned up when the parent effect is destroyed
|
|
2840
|
+
* @param fn - The function to execute
|
|
2841
|
+
*/
|
|
2842
|
+
function untracked(fn) {
|
|
2843
|
+
return effectHistory.present.root(fn);
|
|
2844
|
+
}
|
|
2845
|
+
/**
|
|
2846
|
+
* Executes a function from a virgin/root context - no parent effect, no tracking
|
|
2847
|
+
* Creates completely independent effects that won't be cleaned up by any parent
|
|
2848
|
+
* @param fn - The function to execute
|
|
2849
|
+
*/
|
|
2850
|
+
function root(fn) {
|
|
2851
|
+
return effectHistory.root(fn);
|
|
2852
|
+
}
|
|
2853
|
+
function biDi(received, get, set) {
|
|
2854
|
+
if (typeof get !== 'function') {
|
|
2855
|
+
set = get.set;
|
|
2856
|
+
get = get.get;
|
|
2857
|
+
}
|
|
2858
|
+
let programmaticallySetValue = Symbol();
|
|
2859
|
+
effect(markWithRoot(() => {
|
|
2860
|
+
const newValue = get();
|
|
2861
|
+
if (unwrap(newValue) !== programmaticallySetValue)
|
|
2862
|
+
received(newValue);
|
|
2863
|
+
}, received));
|
|
2864
|
+
return set
|
|
2865
|
+
? atomic((value) => {
|
|
2866
|
+
programmaticallySetValue = unwrap(value);
|
|
2867
|
+
set(value);
|
|
2868
|
+
})
|
|
2869
|
+
: () => { };
|
|
2870
|
+
}
|
|
2871
|
+
|
|
2872
|
+
// Track which objects contain which other objects (back-references)
|
|
2873
|
+
const objectParents = new WeakMap();
|
|
2874
|
+
// Track which objects have deep watchers
|
|
2875
|
+
const objectsWithDeepWatchers = new WeakSet();
|
|
2876
|
+
let deepWatcherCount = 0;
|
|
2877
|
+
function registerDeepWatcher() {
|
|
2878
|
+
deepWatcherCount++;
|
|
2879
|
+
}
|
|
2880
|
+
// Track deep watchers per object
|
|
2881
|
+
const deepWatchers = new WeakMap();
|
|
2882
|
+
// Track which effects are doing deep watching
|
|
2883
|
+
const effectToDeepWatchedObjects = new WeakMap();
|
|
2884
|
+
/**
|
|
2885
|
+
* Add a back-reference from child to parent
|
|
2886
|
+
*/
|
|
2887
|
+
function addBackReference(child, parent, prop) {
|
|
2888
|
+
let parents = objectParents.get(child);
|
|
2889
|
+
if (!parents) {
|
|
2890
|
+
parents = new Set();
|
|
2891
|
+
objectParents.set(child, parents);
|
|
2892
|
+
}
|
|
2893
|
+
parents.add({ parent, prop });
|
|
2894
|
+
}
|
|
2895
|
+
/**
|
|
2896
|
+
* Remove a back-reference from child to parent
|
|
2897
|
+
*/
|
|
2898
|
+
function removeBackReference(child, parent, prop) {
|
|
2899
|
+
const parents = objectParents.get(child);
|
|
2900
|
+
if (parents) {
|
|
2901
|
+
for (const entry of parents) {
|
|
2902
|
+
if (entry.parent === parent && entry.prop === prop) {
|
|
2903
|
+
parents.delete(entry);
|
|
2904
|
+
break;
|
|
2905
|
+
}
|
|
2906
|
+
}
|
|
2907
|
+
if (parents.size === 0) {
|
|
2908
|
+
objectParents.delete(child);
|
|
2909
|
+
}
|
|
2910
|
+
}
|
|
2911
|
+
}
|
|
2912
|
+
/**
|
|
2913
|
+
* Check if an object needs back-references (has deep watchers or parents with deep watchers)
|
|
2914
|
+
*/
|
|
2915
|
+
function needsBackReferences(obj) {
|
|
2916
|
+
// Fast path: if no deep watchers exist anywhere, skip entirely
|
|
2917
|
+
if (!deepWatcherCount)
|
|
2918
|
+
return false; // fast path: no deep watchers anywhere
|
|
2919
|
+
// Check if object itself has deep watchers
|
|
2920
|
+
if (objectsWithDeepWatchers.has(obj))
|
|
2921
|
+
return true;
|
|
2922
|
+
// Slow path: check if any parent has deep watchers (recursive)
|
|
2923
|
+
return hasParentWithDeepWatchers(obj);
|
|
2924
|
+
}
|
|
2925
|
+
/**
|
|
2926
|
+
* Bubble up changes through the back-reference chain
|
|
2927
|
+
*/
|
|
2928
|
+
function bubbleUpChange(changedObject, evolution) {
|
|
2929
|
+
const parents = objectParents.get(changedObject);
|
|
2930
|
+
if (!parents)
|
|
2931
|
+
return;
|
|
2932
|
+
for (const { parent, prop } of parents) {
|
|
2933
|
+
// Trigger deep watchers on parent
|
|
2934
|
+
const parentDeepWatchers = deepWatchers.get(parent);
|
|
2935
|
+
if (parentDeepWatchers) {
|
|
2936
|
+
if (options.introspection?.gatherReasons) {
|
|
2937
|
+
const gatherReasons = options.introspection.gatherReasons;
|
|
2938
|
+
const lineageConfig = gatherReasons.lineages;
|
|
2939
|
+
let touchStack;
|
|
2940
|
+
if (lineageConfig === 'touch' || lineageConfig === 'both') {
|
|
2941
|
+
touchStack = debugHooks.captureLineage();
|
|
2942
|
+
}
|
|
2943
|
+
for (const watcher of parentDeepWatchers) {
|
|
2944
|
+
const dependencyStack = lineageConfig === 'dependency' || lineageConfig === 'both'
|
|
2945
|
+
? getDependencyStack(watcher, parent, allProps)
|
|
2946
|
+
: undefined;
|
|
2947
|
+
const node = getEffectNode(watcher);
|
|
2948
|
+
if (!node.pendingTriggers)
|
|
2949
|
+
node.pendingTriggers = [];
|
|
2950
|
+
node.pendingTriggers.push({
|
|
2951
|
+
obj: parent,
|
|
2952
|
+
evolution,
|
|
2953
|
+
dependency: dependencyStack,
|
|
2954
|
+
touch: touchStack,
|
|
2955
|
+
});
|
|
2956
|
+
}
|
|
2957
|
+
}
|
|
2958
|
+
for (const watcher of parentDeepWatchers)
|
|
2959
|
+
batch(watcher);
|
|
2960
|
+
}
|
|
2961
|
+
// Continue bubbling up
|
|
2962
|
+
bubbleUpChange(parent, evolution);
|
|
2963
|
+
}
|
|
2964
|
+
}
|
|
2965
|
+
function hasParentWithDeepWatchers(obj) {
|
|
2966
|
+
const parents = objectParents.get(obj);
|
|
2967
|
+
if (!parents)
|
|
2968
|
+
return false;
|
|
2969
|
+
for (const { parent } of parents) {
|
|
2970
|
+
if (objectsWithDeepWatchers.has(parent))
|
|
2971
|
+
return true;
|
|
2972
|
+
if (hasParentWithDeepWatchers(parent))
|
|
2973
|
+
return true;
|
|
2974
|
+
}
|
|
2975
|
+
return false;
|
|
2976
|
+
}
|
|
2977
|
+
|
|
2978
|
+
const states = new WeakMap();
|
|
2979
|
+
function addState(obj, evolution) {
|
|
2980
|
+
obj = unwrap(obj);
|
|
2981
|
+
const next = {};
|
|
2982
|
+
const state = getState(obj);
|
|
2983
|
+
if (state)
|
|
2984
|
+
Object.assign(state, { evolution, next });
|
|
2985
|
+
states.set(obj, next);
|
|
2986
|
+
}
|
|
2987
|
+
/**
|
|
2988
|
+
* Gets the current state of a reactive object for evolution tracking
|
|
2989
|
+
* @param obj - The reactive object
|
|
2990
|
+
* @returns The current state object
|
|
2991
|
+
*/
|
|
2992
|
+
function getState(obj) {
|
|
2993
|
+
obj = unwrap(obj);
|
|
2994
|
+
let state = states.get(obj);
|
|
2995
|
+
if (!state) {
|
|
2996
|
+
state = {};
|
|
2997
|
+
states.set(obj, state);
|
|
2998
|
+
}
|
|
2999
|
+
return state;
|
|
3000
|
+
}
|
|
3001
|
+
function collectEffects(obj, evolution, effects, objectWatchers, ...keyChains) {
|
|
3002
|
+
const sourceEffect = getActiveEffect();
|
|
3003
|
+
for (const keys of keyChains)
|
|
3004
|
+
for (const key of keys) {
|
|
3005
|
+
const deps = objectWatchers.get(key);
|
|
3006
|
+
if (deps) {
|
|
3007
|
+
for (const effect of deps) {
|
|
3008
|
+
const runningChain = isRunning(effect);
|
|
3009
|
+
if (runningChain) {
|
|
3010
|
+
optionCall('skipRunningEffect', effect);
|
|
3011
|
+
continue;
|
|
3012
|
+
}
|
|
3013
|
+
if (!effects.has(effect)) {
|
|
3014
|
+
effects.set(effect, getDependencyStack(effect, obj, key));
|
|
3015
|
+
if (!hasBatched(effect))
|
|
3016
|
+
recordActivation(effect, obj, evolution, key);
|
|
3017
|
+
}
|
|
3018
|
+
debugHooks.recordTriggerLink(sourceEffect, effect, obj, key, evolution);
|
|
3019
|
+
}
|
|
3020
|
+
}
|
|
3021
|
+
}
|
|
3022
|
+
}
|
|
3023
|
+
/**
|
|
3024
|
+
* Triggers effects for a single property change
|
|
3025
|
+
* @param obj - The object that changed
|
|
3026
|
+
* @param evolution - The type of change
|
|
3027
|
+
* @param prop - The property that changed
|
|
3028
|
+
*/
|
|
3029
|
+
function touched1(obj, evolution, prop) {
|
|
3030
|
+
touched(obj, evolution, [prop]);
|
|
3031
|
+
}
|
|
3032
|
+
/**
|
|
3033
|
+
* Triggers effects for property changes
|
|
3034
|
+
* @param obj - The object that changed
|
|
3035
|
+
* @param evolution - The type of change
|
|
3036
|
+
* @param props - The properties that changed
|
|
3037
|
+
*/
|
|
3038
|
+
function touched(obj, evolution, props) {
|
|
3039
|
+
obj = unwrap(obj);
|
|
3040
|
+
addState(obj, evolution);
|
|
3041
|
+
const objectWatchers = watchers.get(obj);
|
|
3042
|
+
if (objectWatchers) {
|
|
3043
|
+
// Note: we have to collect effects to remove duplicates in the specific case when no batch is running
|
|
3044
|
+
const effects = new Map();
|
|
3045
|
+
const structural = !['set', 'invalidate'].includes(evolution.type);
|
|
3046
|
+
const broad = structural ? [allProps, keysOf] : [allProps];
|
|
3047
|
+
if (props)
|
|
3048
|
+
collectEffects(obj, evolution, effects, objectWatchers, broad, props);
|
|
3049
|
+
else
|
|
3050
|
+
collectEffects(obj, evolution, effects, objectWatchers, objectWatchers.keys());
|
|
3051
|
+
const triggers = Array.from(effects.keys());
|
|
3052
|
+
optionCall('touched', obj, evolution, props, triggers);
|
|
3053
|
+
// Store pending triggers for CleanupReason before batching
|
|
3054
|
+
if (options.introspection?.gatherReasons) {
|
|
3055
|
+
const gatherReasons = options.introspection.gatherReasons;
|
|
3056
|
+
const lineageConfig = gatherReasons.lineages;
|
|
3057
|
+
let touchStack;
|
|
3058
|
+
if (lineageConfig === 'touch' || lineageConfig === 'both') {
|
|
3059
|
+
touchStack = debugHooks.captureLineage();
|
|
3060
|
+
}
|
|
3061
|
+
for (const [effect, dependencyStack] of effects) {
|
|
3062
|
+
const node = getEffectNode(effect);
|
|
3063
|
+
if (!node.pendingTriggers)
|
|
3064
|
+
node.pendingTriggers = [];
|
|
3065
|
+
node.pendingTriggers.push({
|
|
3066
|
+
obj,
|
|
3067
|
+
evolution,
|
|
3068
|
+
dependency: dependencyStack,
|
|
3069
|
+
touch: touchStack,
|
|
3070
|
+
});
|
|
3071
|
+
}
|
|
3072
|
+
}
|
|
3073
|
+
batch(triggers);
|
|
3074
|
+
}
|
|
3075
|
+
// Bubble up changes if this object has deep watchers
|
|
3076
|
+
if (objectsWithDeepWatchers.has(obj)) {
|
|
3077
|
+
bubbleUpChange(obj, evolution);
|
|
3078
|
+
}
|
|
3079
|
+
}
|
|
3080
|
+
/**
|
|
3081
|
+
* Triggers only opaque effects for property changes
|
|
3082
|
+
* Used by deep-touch to ensure opaque listeners are notified even when deep optimization is active
|
|
3083
|
+
*/
|
|
3084
|
+
function touchedOpaque(obj, evolution, prop) {
|
|
3085
|
+
obj = unwrap(obj);
|
|
3086
|
+
const objectWatchers = watchers.get(obj);
|
|
3087
|
+
if (!objectWatchers)
|
|
3088
|
+
return;
|
|
3089
|
+
const deps = objectWatchers.get(prop);
|
|
3090
|
+
if (!deps)
|
|
3091
|
+
return;
|
|
3092
|
+
const effects = new Set();
|
|
3093
|
+
const sourceEffect = getActiveEffect();
|
|
3094
|
+
const gather = options.introspection?.gatherReasons;
|
|
3095
|
+
if (gather) {
|
|
3096
|
+
const lineageConfig = gather.lineages;
|
|
3097
|
+
for (const effect of deps) {
|
|
3098
|
+
const node = getEffectNode(effect);
|
|
3099
|
+
if (!node.isOpaque)
|
|
3100
|
+
continue;
|
|
3101
|
+
const runningChain = isRunning(effect);
|
|
3102
|
+
if (runningChain) {
|
|
3103
|
+
optionCall('skipRunningEffect', effect);
|
|
3104
|
+
continue;
|
|
3105
|
+
}
|
|
3106
|
+
effects.add(effect);
|
|
3107
|
+
if (gather) {
|
|
3108
|
+
let touchStack;
|
|
3109
|
+
let dependencyStack;
|
|
3110
|
+
if (lineageConfig === 'touch' || lineageConfig === 'both') {
|
|
3111
|
+
touchStack = debugHooks.captureLineage();
|
|
3112
|
+
}
|
|
3113
|
+
if (lineageConfig === 'dependency' || lineageConfig === 'both') {
|
|
3114
|
+
dependencyStack = getDependencyStack(effect, obj, prop);
|
|
3115
|
+
}
|
|
3116
|
+
if (!node.pendingTriggers)
|
|
3117
|
+
node.pendingTriggers = [];
|
|
3118
|
+
node.pendingTriggers.push({
|
|
3119
|
+
obj,
|
|
3120
|
+
evolution,
|
|
3121
|
+
dependency: dependencyStack,
|
|
3122
|
+
touch: touchStack,
|
|
3123
|
+
});
|
|
3124
|
+
}
|
|
3125
|
+
recordActivation(effect, obj, evolution, prop);
|
|
3126
|
+
debugHooks.recordTriggerLink(sourceEffect, effect, obj, prop, evolution);
|
|
3127
|
+
}
|
|
3128
|
+
}
|
|
3129
|
+
else {
|
|
3130
|
+
// When not gathering reasons, process effects normally
|
|
3131
|
+
for (const effect of deps) {
|
|
3132
|
+
const node = getEffectNode(effect);
|
|
3133
|
+
if (!node.isOpaque)
|
|
3134
|
+
continue;
|
|
3135
|
+
const runningChain = isRunning(effect);
|
|
3136
|
+
if (runningChain) {
|
|
3137
|
+
optionCall('skipRunningEffect', effect);
|
|
3138
|
+
continue;
|
|
3139
|
+
}
|
|
3140
|
+
effects.add(effect);
|
|
3141
|
+
recordActivation(effect, obj, evolution, prop);
|
|
3142
|
+
debugHooks.recordTriggerLink(sourceEffect, effect, obj, prop, evolution);
|
|
3143
|
+
}
|
|
3144
|
+
}
|
|
3145
|
+
if (effects.size > 0) {
|
|
3146
|
+
optionCall('touched', obj, evolution, [prop], Array.from(effects));
|
|
3147
|
+
batch(Array.from(effects));
|
|
3148
|
+
}
|
|
3149
|
+
}
|
|
3150
|
+
|
|
3151
|
+
const nonReactiveObjects = new WeakSet();
|
|
3152
|
+
const nonReactiveClasses = new WeakSet();
|
|
3153
|
+
const unreactiveProps = new WeakMap();
|
|
3154
|
+
let unreactivePropsCount = 0;
|
|
3155
|
+
function addUnreactiveProps(proto, set) {
|
|
3156
|
+
unreactiveProps.set(proto, set);
|
|
3157
|
+
unreactivePropsCount++;
|
|
3158
|
+
}
|
|
3159
|
+
/** Check if a property is marked unreactive on obj or any of its prototypes (trap-free) */
|
|
3160
|
+
function isUnreactiveProp(obj, prop) {
|
|
3161
|
+
if (!unreactivePropsCount)
|
|
3162
|
+
return false;
|
|
3163
|
+
let target = obj;
|
|
3164
|
+
while (target) {
|
|
3165
|
+
if (unreactiveProps.get(target)?.has(prop))
|
|
3166
|
+
return true;
|
|
3167
|
+
target = Object.getPrototypeOf(target);
|
|
3168
|
+
}
|
|
3169
|
+
return false;
|
|
3170
|
+
}
|
|
3171
|
+
const immutables = new Set();
|
|
3172
|
+
const absent = Symbol('absent');
|
|
3173
|
+
function markNonReactive(...obj) {
|
|
3174
|
+
for (const o of obj)
|
|
3175
|
+
nonReactiveObjects.add(o);
|
|
3176
|
+
return obj[0];
|
|
3177
|
+
}
|
|
3178
|
+
function nonReactiveClass(...cls) {
|
|
3179
|
+
for (const c of cls)
|
|
3180
|
+
if (c)
|
|
3181
|
+
nonReactiveClasses.add(c.prototype);
|
|
3182
|
+
return cls[0];
|
|
3183
|
+
}
|
|
3184
|
+
function isNonReactive(obj) {
|
|
3185
|
+
if (obj === null || typeof obj !== 'object')
|
|
3186
|
+
return true;
|
|
3187
|
+
if (nonReactiveObjects.has(obj))
|
|
3188
|
+
return true;
|
|
3189
|
+
// Walk the prototype chain on the raw object to check for non-reactive classes
|
|
3190
|
+
let proto = Object.getPrototypeOf(obj);
|
|
3191
|
+
while (proto) {
|
|
3192
|
+
if (nonReactiveClasses.has(proto))
|
|
3193
|
+
return true;
|
|
3194
|
+
proto = Object.getPrototypeOf(proto);
|
|
3195
|
+
}
|
|
3196
|
+
for (const fn of immutables)
|
|
3197
|
+
if (fn(obj))
|
|
3198
|
+
return true;
|
|
3199
|
+
return false;
|
|
3200
|
+
}
|
|
3201
|
+
nonReactiveClass(Date, RegExp, Error, Promise, Function);
|
|
3202
|
+
if (typeof window !== 'undefined') {
|
|
3203
|
+
markNonReactive(window, document);
|
|
3204
|
+
nonReactiveClass(Node, Element, HTMLElement, EventTarget, HTMLCollection, NodeList);
|
|
3205
|
+
}
|
|
3206
|
+
|
|
3207
|
+
function getPrototypeToken(value) {
|
|
3208
|
+
if (Array.isArray(value))
|
|
3209
|
+
return Array.prototype;
|
|
3210
|
+
if (typeof value !== 'object')
|
|
3211
|
+
return undefined;
|
|
3212
|
+
try {
|
|
3213
|
+
return value.constructor;
|
|
3214
|
+
}
|
|
3215
|
+
catch {
|
|
3216
|
+
return undefined;
|
|
3217
|
+
}
|
|
3218
|
+
}
|
|
3219
|
+
function shouldRecurseTouch(oldValue, newValue) {
|
|
3220
|
+
if (oldValue === newValue)
|
|
3221
|
+
return false;
|
|
3222
|
+
if ((typeof oldValue !== 'object' && !Array.isArray(oldValue)) ||
|
|
3223
|
+
(typeof newValue !== 'object' && !Array.isArray(newValue)))
|
|
3224
|
+
return false;
|
|
3225
|
+
if (isNonReactive(oldValue) || isNonReactive(newValue))
|
|
3226
|
+
return false;
|
|
3227
|
+
return getPrototypeToken(oldValue) === getPrototypeToken(newValue);
|
|
3228
|
+
}
|
|
3229
|
+
/**
|
|
3230
|
+
* Centralized function to handle property change notifications with optional recursive touch
|
|
3231
|
+
* @param targetObj - The object whose property changed
|
|
3232
|
+
* @param prop - The property that changed
|
|
3233
|
+
* @param oldValue - The old value (before change)
|
|
3234
|
+
* @param newValue - The new value (after change)
|
|
3235
|
+
* @param hadProperty - Whether the property existed before (for add vs set)
|
|
3236
|
+
*/
|
|
3237
|
+
function notifyPropertyChange(targetObj, prop, oldValue, newValue, hadProperty) {
|
|
3238
|
+
const evolution = { type: hadProperty ? 'set' : 'add', prop };
|
|
3239
|
+
if (options.recursiveTouching &&
|
|
3240
|
+
oldValue !== undefined &&
|
|
3241
|
+
shouldRecurseTouch(oldValue, newValue)) {
|
|
3242
|
+
const unwrappedObj = unwrap(targetObj);
|
|
3243
|
+
const origin = { obj: unwrappedObj, prop };
|
|
3244
|
+
// Deep touch: only notify nested property changes with origin filtering
|
|
3245
|
+
// Don't notify direct property change - the whole point is to avoid parent effects re-running
|
|
3246
|
+
dispatchNotifications(untracked(() => recursiveTouch(oldValue, newValue, new WeakMap(), [], origin)));
|
|
3247
|
+
// Notify opaque listeners (like memoize) that always want to know about identity changes
|
|
3248
|
+
touchedOpaque(targetObj, evolution, prop);
|
|
3249
|
+
}
|
|
3250
|
+
else {
|
|
3251
|
+
touched1(targetObj, evolution, prop);
|
|
3252
|
+
}
|
|
3253
|
+
}
|
|
3254
|
+
function hasVisitedPair(visited, oldObj, newObj) {
|
|
3255
|
+
let mapped = visited.get(oldObj);
|
|
3256
|
+
if (!mapped) {
|
|
3257
|
+
mapped = new WeakSet();
|
|
3258
|
+
visited.set(oldObj, mapped);
|
|
3259
|
+
}
|
|
3260
|
+
if (mapped.has(newObj))
|
|
3261
|
+
return true;
|
|
3262
|
+
mapped.add(newObj);
|
|
3263
|
+
return false;
|
|
3264
|
+
}
|
|
3265
|
+
function collectObjectKeys(obj) {
|
|
3266
|
+
const keys = new Set(Reflect.ownKeys(obj));
|
|
3267
|
+
let proto = Object.getPrototypeOf(obj);
|
|
3268
|
+
// Continue walking while prototype exists and doesn't have its own constructor
|
|
3269
|
+
// This stops at Object.prototype (has own constructor) and class prototypes (have own constructor)
|
|
3270
|
+
// but continues for data prototypes (Object.create({}), Object.create(instance), etc.)
|
|
3271
|
+
while (proto && !Object.hasOwn(proto, 'constructor')) {
|
|
3272
|
+
for (const key of Reflect.ownKeys(proto))
|
|
3273
|
+
keys.add(key);
|
|
3274
|
+
proto = Object.getPrototypeOf(proto);
|
|
3275
|
+
}
|
|
3276
|
+
return keys;
|
|
3277
|
+
}
|
|
3278
|
+
function recursiveTouch(oldValue, newValue, visited = new WeakMap(), notifications = [], origin) {
|
|
3279
|
+
if (!shouldRecurseTouch(oldValue, newValue))
|
|
3280
|
+
return notifications;
|
|
3281
|
+
if ((typeof oldValue !== 'object' && !Array.isArray(oldValue)) ||
|
|
3282
|
+
(typeof newValue !== 'object' && !Array.isArray(newValue)))
|
|
3283
|
+
return notifications;
|
|
3284
|
+
if (hasVisitedPair(visited, oldValue, newValue))
|
|
3285
|
+
return notifications;
|
|
3286
|
+
if (Array.isArray(oldValue) && Array.isArray(newValue)) {
|
|
3287
|
+
diffArrayElements(oldValue, newValue, visited, notifications, origin);
|
|
3288
|
+
return notifications;
|
|
3289
|
+
}
|
|
3290
|
+
diffObjectProperties(oldValue, newValue, visited, notifications, origin);
|
|
3291
|
+
return notifications;
|
|
3292
|
+
}
|
|
3293
|
+
function diffArrayElements(oldArray, newArray, _visited, notifications, origin) {
|
|
3294
|
+
const local = [];
|
|
3295
|
+
const oldLength = oldArray.length;
|
|
3296
|
+
const newLength = newArray.length;
|
|
3297
|
+
const max = Math.max(oldLength, newLength);
|
|
3298
|
+
for (let index = 0; index < max; index++) {
|
|
3299
|
+
const hasOld = index < oldLength;
|
|
3300
|
+
const hasNew = index < newLength;
|
|
3301
|
+
if (hasOld && !hasNew) {
|
|
3302
|
+
local.push({ target: oldArray, evolution: { type: 'del', prop: index }, prop: index, origin });
|
|
3303
|
+
continue;
|
|
3304
|
+
}
|
|
3305
|
+
if (!hasOld && hasNew) {
|
|
3306
|
+
local.push({ target: oldArray, evolution: { type: 'add', prop: index }, prop: index, origin });
|
|
3307
|
+
continue;
|
|
3308
|
+
}
|
|
3309
|
+
if (!hasOld || !hasNew)
|
|
3310
|
+
continue;
|
|
3311
|
+
const oldEntry = unwrap(oldArray[index]);
|
|
3312
|
+
const newEntry = unwrap(newArray[index]);
|
|
3313
|
+
if (!Object.is(oldEntry, newEntry)) {
|
|
3314
|
+
local.push({ target: oldArray, evolution: { type: 'set', prop: index }, prop: index, origin });
|
|
3315
|
+
}
|
|
3316
|
+
}
|
|
3317
|
+
if (oldLength !== newLength)
|
|
3318
|
+
local.push({
|
|
3319
|
+
target: oldArray,
|
|
3320
|
+
evolution: { type: 'set', prop: 'length' },
|
|
3321
|
+
prop: 'length',
|
|
3322
|
+
origin,
|
|
3323
|
+
});
|
|
3324
|
+
notifications.push(...local);
|
|
3325
|
+
}
|
|
3326
|
+
function diffObjectProperties(oldObj, newObj, visited, notifications, origin) {
|
|
3327
|
+
const oldKeys = collectObjectKeys(oldObj);
|
|
3328
|
+
const newKeys = collectObjectKeys(newObj);
|
|
3329
|
+
const local = [];
|
|
3330
|
+
for (const key of oldKeys)
|
|
3331
|
+
if (!newKeys.has(key))
|
|
3332
|
+
local.push({ target: oldObj, evolution: { type: 'del', prop: key }, prop: key, origin });
|
|
3333
|
+
for (const key of newKeys)
|
|
3334
|
+
if (!oldKeys.has(key))
|
|
3335
|
+
local.push({ target: oldObj, evolution: { type: 'add', prop: key }, prop: key, origin });
|
|
3336
|
+
for (const key of newKeys) {
|
|
3337
|
+
if (!oldKeys.has(key))
|
|
3338
|
+
continue;
|
|
3339
|
+
const oldEntry = unwrap(oldObj[key]);
|
|
3340
|
+
const newEntry = unwrap(newObj[key]);
|
|
3341
|
+
if (shouldRecurseTouch(oldEntry, newEntry)) {
|
|
3342
|
+
recursiveTouch(oldEntry, newEntry, visited, notifications, origin);
|
|
3343
|
+
}
|
|
3344
|
+
else if (!Object.is(oldEntry, newEntry)) {
|
|
3345
|
+
local.push({ target: oldObj, evolution: { type: 'set', prop: key }, prop: key, origin });
|
|
3346
|
+
}
|
|
3347
|
+
}
|
|
3348
|
+
notifications.push(...local);
|
|
3349
|
+
}
|
|
3350
|
+
/**
|
|
3351
|
+
* Checks if an effect or any of its ancestors is in the allowed set
|
|
3352
|
+
*/
|
|
3353
|
+
function hasAncestorInSet(effect, allowedSet) {
|
|
3354
|
+
let current = effect;
|
|
3355
|
+
const visited = new WeakSet();
|
|
3356
|
+
while (current && !visited.has(current)) {
|
|
3357
|
+
visited.add(current);
|
|
3358
|
+
if (allowedSet.has(current))
|
|
3359
|
+
return true;
|
|
3360
|
+
const node = getEffectNode(current);
|
|
3361
|
+
current = node.parent;
|
|
3362
|
+
}
|
|
3363
|
+
return false;
|
|
3364
|
+
}
|
|
3365
|
+
function dispatchNotifications(notifications) {
|
|
3366
|
+
if (!notifications.length)
|
|
3367
|
+
return;
|
|
3368
|
+
const combinedEffects = new Set();
|
|
3369
|
+
const effectCauses = new Map();
|
|
3370
|
+
// Extract origin from first notification (all should have the same origin from a single deep touch)
|
|
3371
|
+
const origin = notifications[0]?.origin;
|
|
3372
|
+
let allowedEffects;
|
|
3373
|
+
// If origin exists, compute allowed effects (those that depend on origin.obj[origin.prop])
|
|
3374
|
+
if (origin) {
|
|
3375
|
+
allowedEffects = new Set();
|
|
3376
|
+
const originWatchers = watchers.get(origin.obj);
|
|
3377
|
+
if (originWatchers) {
|
|
3378
|
+
const originEffects = new Map();
|
|
3379
|
+
collectEffects(origin.obj, { type: 'set', prop: origin.prop }, originEffects, originWatchers, [allProps], [origin.prop]);
|
|
3380
|
+
for (const effect of originEffects.keys())
|
|
3381
|
+
allowedEffects.add(effect);
|
|
3382
|
+
}
|
|
3383
|
+
// If no allowed effects, skip all notifications (no one should be notified)
|
|
3384
|
+
if (allowedEffects.size === 0)
|
|
3385
|
+
return;
|
|
3386
|
+
}
|
|
3387
|
+
for (const notification of notifications) {
|
|
3388
|
+
const { target, evolution, prop } = notification;
|
|
3389
|
+
if (typeof target !== 'object' && !Array.isArray(target))
|
|
3390
|
+
continue;
|
|
3391
|
+
const obj = unwrap(target);
|
|
3392
|
+
addState(obj, evolution);
|
|
3393
|
+
const objectWatchers = watchers.get(obj);
|
|
3394
|
+
let currentEffects;
|
|
3395
|
+
const propsArray = [prop];
|
|
3396
|
+
if (objectWatchers) {
|
|
3397
|
+
// console.log(`[DEBUG] dispatchNotifications: processing ${obj.constructor.name} (has watchers)`)
|
|
3398
|
+
currentEffects = new Map();
|
|
3399
|
+
const broad = evolution.type !== 'set' ? [allProps, keysOf] : [allProps];
|
|
3400
|
+
collectEffects(obj, evolution, currentEffects, objectWatchers, broad, propsArray);
|
|
3401
|
+
// Filter effects by ancestor chain if origin exists
|
|
3402
|
+
// Include effects that either directly depend on origin or have an ancestor that does
|
|
3403
|
+
if (origin && allowedEffects) {
|
|
3404
|
+
const filteredEffects = new Map();
|
|
3405
|
+
for (const [effect, associated] of currentEffects) {
|
|
3406
|
+
// Check if effect itself is allowed OR has an ancestor that is allowed
|
|
3407
|
+
if (allowedEffects.has(effect) || hasAncestorInSet(effect, allowedEffects)) {
|
|
3408
|
+
filteredEffects.set(effect, associated);
|
|
3409
|
+
}
|
|
3410
|
+
}
|
|
3411
|
+
currentEffects = filteredEffects;
|
|
3412
|
+
}
|
|
3413
|
+
for (const effect of currentEffects.keys()) {
|
|
3414
|
+
combinedEffects.add(effect);
|
|
3415
|
+
let causes = effectCauses.get(effect);
|
|
3416
|
+
if (!causes) {
|
|
3417
|
+
causes = [];
|
|
3418
|
+
effectCauses.set(effect, causes);
|
|
3419
|
+
}
|
|
3420
|
+
causes.push(notification);
|
|
3421
|
+
}
|
|
3422
|
+
}
|
|
3423
|
+
if (currentEffects) {
|
|
3424
|
+
optionCall('touched', obj, evolution, propsArray, Array.from(currentEffects.keys()));
|
|
3425
|
+
}
|
|
3426
|
+
if (objectsWithDeepWatchers.has(obj))
|
|
3427
|
+
bubbleUpChange(obj, evolution);
|
|
3428
|
+
}
|
|
3429
|
+
if (combinedEffects.size) {
|
|
3430
|
+
if (options.introspection?.gatherReasons) {
|
|
3431
|
+
const gatherReasons = options.introspection.gatherReasons;
|
|
3432
|
+
const lineageConfig = gatherReasons.lineages;
|
|
3433
|
+
let touchStack;
|
|
3434
|
+
if (lineageConfig === 'touch' || lineageConfig === 'both') {
|
|
3435
|
+
touchStack = debugHooks.captureLineage();
|
|
3436
|
+
}
|
|
3437
|
+
for (const effect of combinedEffects) {
|
|
3438
|
+
const node = getEffectNode(effect);
|
|
3439
|
+
if (!node.pendingTriggers)
|
|
3440
|
+
node.pendingTriggers = [];
|
|
3441
|
+
for (const { target, evolution, prop } of effectCauses.get(effect)) {
|
|
3442
|
+
const dependencyStack = lineageConfig === 'dependency' || lineageConfig === 'both'
|
|
3443
|
+
? getDependencyStack(effect, unwrap(target), prop ?? allProps)
|
|
3444
|
+
: undefined;
|
|
3445
|
+
node.pendingTriggers.push({
|
|
3446
|
+
obj: unwrap(target),
|
|
3447
|
+
evolution,
|
|
3448
|
+
dependency: dependencyStack,
|
|
3449
|
+
touch: touchStack,
|
|
3450
|
+
});
|
|
3451
|
+
}
|
|
3452
|
+
}
|
|
3453
|
+
}
|
|
3454
|
+
batch([...combinedEffects]);
|
|
3455
|
+
}
|
|
3456
|
+
}
|
|
3457
|
+
|
|
3458
|
+
const metaProtos = new WeakMap();
|
|
3459
|
+
const wrapProtos = new WeakMap();
|
|
3460
|
+
const arrayLengths = new WeakMap();
|
|
3461
|
+
const hasReentry = new Set();
|
|
3462
|
+
const subsRegister = new WeakMap();
|
|
3463
|
+
// Sub-proxy registration for custom reactive behaviors
|
|
3464
|
+
const reactiveHandlers = {
|
|
3465
|
+
[Symbol.toStringTag]: 'MutTs Reactive',
|
|
3466
|
+
get(obj, prop, receiver) {
|
|
3467
|
+
if (obj && typeof obj === 'object' && prop !== Symbol.toStringTag) {
|
|
3468
|
+
const metaProto = metaProtos.get(obj.constructor);
|
|
3469
|
+
if (metaProto && Object.hasOwn(metaProto, prop)) {
|
|
3470
|
+
const desc = Object.getOwnPropertyDescriptor(metaProto, prop);
|
|
3471
|
+
if (desc.get) {
|
|
3472
|
+
if (!Object.hasOwn(obj, prop))
|
|
3473
|
+
return desc.get.call(obj);
|
|
3474
|
+
// For own properties (e.g., array length): only override if writable/configurable
|
|
3475
|
+
const ownDesc = Object.getOwnPropertyDescriptor(obj, prop);
|
|
3476
|
+
if (ownDesc.configurable || ownDesc.writable || ownDesc.get)
|
|
3477
|
+
return desc.get.call(obj);
|
|
3478
|
+
}
|
|
3479
|
+
else if (!Object.hasOwn(obj, prop))
|
|
3480
|
+
return (...args) => desc.value.apply(obj, args);
|
|
3481
|
+
}
|
|
3482
|
+
const wrapProto = wrapProtos.get(obj.constructor);
|
|
3483
|
+
if (wrapProto && Object.hasOwn(wrapProto, prop))
|
|
3484
|
+
return wrapProto[prop];
|
|
3485
|
+
}
|
|
3486
|
+
// Symbols: fast-path — no reactivity tracking, no unreactive check needed
|
|
3487
|
+
if (typeof prop === 'symbol')
|
|
3488
|
+
return FoolProof.get(obj, prop, receiver);
|
|
3489
|
+
// Check if this property is marked as unreactive (WeakMap lookup — no proxy traps)
|
|
3490
|
+
if (isUnreactiveProp(obj, prop))
|
|
3491
|
+
return FoolProof.get(obj, prop, receiver);
|
|
3492
|
+
// Check if property exists using a trap-free walk to avoid triggering
|
|
3493
|
+
// the has-trap cascade on prototype chains of reactive proxies.
|
|
3494
|
+
const isOwnProp = Object.hasOwn(obj, prop);
|
|
3495
|
+
let hasProp = isOwnProp;
|
|
3496
|
+
let owner = isOwnProp ? obj : undefined;
|
|
3497
|
+
if (!isOwnProp) {
|
|
3498
|
+
let raw = Object.getPrototypeOf(obj);
|
|
3499
|
+
while (raw && raw !== Object.prototype) {
|
|
3500
|
+
if (Object.hasOwn(raw, prop)) {
|
|
3501
|
+
hasProp = true;
|
|
3502
|
+
owner = raw;
|
|
3503
|
+
break;
|
|
3504
|
+
}
|
|
3505
|
+
raw = Object.getPrototypeOf(raw);
|
|
3506
|
+
}
|
|
3507
|
+
}
|
|
3508
|
+
const isInheritedAccess = hasProp && !isOwnProp;
|
|
3509
|
+
// For accessor properties, check the unwrapped object to see if it's an accessor
|
|
3510
|
+
// This ensures ignoreAccessors works correctly even after operations like Object.setPrototypeOf
|
|
3511
|
+
// Skip for null-proto objects (pounce scopes) — they never have accessors
|
|
3512
|
+
const shouldIgnoreAccessor = options.ignoreAccessors &&
|
|
3513
|
+
isOwnProp &&
|
|
3514
|
+
Object.getPrototypeOf(obj) !== null &&
|
|
3515
|
+
(isOwnAccessor(receiver, prop) || isOwnAccessor(obj, prop));
|
|
3516
|
+
// Depend if...
|
|
3517
|
+
if (!hasProp ||
|
|
3518
|
+
(!(options.instanceMembers && isInheritedAccess && obj instanceof Object) &&
|
|
3519
|
+
!shouldIgnoreAccessor))
|
|
3520
|
+
dependant(obj, prop);
|
|
3521
|
+
// Two-Point Tracking: for inherited access on null-proto chains, only track
|
|
3522
|
+
// the owning ancestor — not every intermediate level. This relies on the
|
|
3523
|
+
// "structural stability" contract: key presence in the chain is fixed at
|
|
3524
|
+
// creation time, so intermediate levels never gain/lose shadowing properties.
|
|
3525
|
+
if (isInheritedAccess && owner && (!options.instanceMembers || !(obj instanceof Object))) {
|
|
3526
|
+
dependant(owner, prop);
|
|
3527
|
+
}
|
|
3528
|
+
// For arrays, use FoolProof.get (Indexer path) for numeric index reactivity.
|
|
3529
|
+
// For all other objects, inline Reflect.get directly (skips 3 function calls).
|
|
3530
|
+
const value = (subsRegister.get(obj)?.get || FoolProof.get)(obj, prop, receiver);
|
|
3531
|
+
if (typeof value === 'object' && value !== null) {
|
|
3532
|
+
const reactiveValue = reactiveObject(value);
|
|
3533
|
+
// Only create back-references if this object needs them
|
|
3534
|
+
if (needsBackReferences(obj)) {
|
|
3535
|
+
addBackReference(reactiveValue, obj, prop);
|
|
3536
|
+
}
|
|
3537
|
+
return reactiveValue;
|
|
3538
|
+
}
|
|
3539
|
+
return value;
|
|
3540
|
+
},
|
|
3541
|
+
set(obj, prop, value, receiver) {
|
|
3542
|
+
const unwrappedReceiver = unwrap(receiver);
|
|
3543
|
+
// Check if this property is marked as unreactive
|
|
3544
|
+
if (isUnreactiveProp(obj, prop) || obj !== unwrappedReceiver)
|
|
3545
|
+
return FoolProof.set(obj, prop, value, receiver);
|
|
3546
|
+
const newValue = unwrap(value);
|
|
3547
|
+
// metaProto setter dispatch (e.g., reactive array length)
|
|
3548
|
+
if (obj && typeof obj === 'object' && prop !== Symbol.toStringTag) {
|
|
3549
|
+
const metaProto = obj.constructor && metaProtos.get(obj.constructor);
|
|
3550
|
+
if (metaProto && Object.hasOwn(metaProto, prop)) {
|
|
3551
|
+
const desc = Object.getOwnPropertyDescriptor(metaProto, prop);
|
|
3552
|
+
if (desc.set) {
|
|
3553
|
+
desc.set.call(obj, newValue);
|
|
3554
|
+
return true;
|
|
3555
|
+
}
|
|
3556
|
+
}
|
|
3557
|
+
}
|
|
3558
|
+
// Read old value, using withEffect(undefined, ...) for getter-only accessors to avoid
|
|
3559
|
+
// breaking memoization dependency tracking during SET operations
|
|
3560
|
+
let oldVal = absent;
|
|
3561
|
+
// TODO: Pffft... Find a way to "generalize" this case?
|
|
3562
|
+
const isArrayLength = prop === 'length' && Array.isArray(obj);
|
|
3563
|
+
if (Reflect.has(unwrappedReceiver, prop)) {
|
|
3564
|
+
// We *need* to use `receiver` and not `obj` here, otherwise we break
|
|
3565
|
+
// the dependency tracking for memoized getters
|
|
3566
|
+
oldVal = isArrayLength
|
|
3567
|
+
? arrayLengths.get(obj) === newValue
|
|
3568
|
+
? newValue
|
|
3569
|
+
: absent
|
|
3570
|
+
: untracked(() => Reflect.get(obj, prop, receiver));
|
|
3571
|
+
}
|
|
3572
|
+
if (objectsWithDeepWatchers.has(obj)) {
|
|
3573
|
+
if (typeof oldVal === 'object' && oldVal !== null) {
|
|
3574
|
+
removeBackReference(oldVal, obj, prop);
|
|
3575
|
+
}
|
|
3576
|
+
if (typeof newValue === 'object' && newValue !== null) {
|
|
3577
|
+
const reactiveValue = reactiveObject(newValue);
|
|
3578
|
+
addBackReference(reactiveValue, obj, prop);
|
|
3579
|
+
}
|
|
3580
|
+
}
|
|
3581
|
+
if (oldVal !== newValue) {
|
|
3582
|
+
// For getter-only accessors, Reflect.set() may fail, but we still return true
|
|
3583
|
+
// to avoid throwing errors. Only proceed with change notifications if set succeeded.
|
|
3584
|
+
if (FoolProof.set(obj, prop, newValue, receiver)) {
|
|
3585
|
+
if (isArrayLength)
|
|
3586
|
+
arrayLengths.set(obj, newValue);
|
|
3587
|
+
notifyPropertyChange(obj, prop, oldVal, newValue, oldVal !== absent);
|
|
3588
|
+
}
|
|
3589
|
+
}
|
|
3590
|
+
return true;
|
|
3591
|
+
},
|
|
3592
|
+
has(obj, prop) {
|
|
3593
|
+
if (hasReentry.has(obj))
|
|
3594
|
+
throw new ReactiveError(`[reactive] Circular dependency detected in 'has' check for property '${String(prop)}'`, {
|
|
3595
|
+
code: ReactiveErrorCode.CycleDetected,
|
|
3596
|
+
cycle: [], // We don't have the full cycle here, but we know it involves obj
|
|
3597
|
+
});
|
|
3598
|
+
hasReentry.add(obj);
|
|
3599
|
+
dependant(obj, prop);
|
|
3600
|
+
const rv = (subsRegister.get(obj)?.has || Reflect.has)(obj, prop);
|
|
3601
|
+
hasReentry.delete(obj);
|
|
3602
|
+
return rv;
|
|
3603
|
+
},
|
|
3604
|
+
deleteProperty(obj, prop) {
|
|
3605
|
+
if (!Object.hasOwn(obj, prop))
|
|
3606
|
+
return false;
|
|
3607
|
+
const oldVal = obj[prop];
|
|
3608
|
+
// Remove back-references if this object has deep watchers
|
|
3609
|
+
if (objectsWithDeepWatchers.has(obj) && typeof oldVal === 'object' && oldVal !== null) {
|
|
3610
|
+
removeBackReference(oldVal, obj, prop);
|
|
3611
|
+
}
|
|
3612
|
+
delete obj[prop];
|
|
3613
|
+
touched1(obj, { type: 'del', prop }, prop);
|
|
3614
|
+
// Bubble up changes if this object has deep watchers
|
|
3615
|
+
if (objectsWithDeepWatchers.has(obj)) {
|
|
3616
|
+
bubbleUpChange(obj, { type: 'del', prop });
|
|
3617
|
+
}
|
|
3618
|
+
return true;
|
|
3619
|
+
},
|
|
3620
|
+
ownKeys(obj) {
|
|
3621
|
+
dependant(obj, keysOf);
|
|
3622
|
+
return subsRegister.get(obj)?.ownKeys?.(obj) || Reflect.ownKeys(obj);
|
|
3623
|
+
},
|
|
3624
|
+
getOwnPropertyDescriptor(obj, prop) {
|
|
3625
|
+
return subsRegister.get(obj)?.getOwnPropertyDescriptor?.(obj, prop) || Reflect.getOwnPropertyDescriptor(obj, prop);
|
|
3626
|
+
},
|
|
3627
|
+
};
|
|
3628
|
+
const reactiveClasses = new WeakSet();
|
|
3629
|
+
// Create the ReactiveBase mixin
|
|
3630
|
+
/**
|
|
3631
|
+
* Base mixin for reactive classes that provides proper constructor reactivity
|
|
3632
|
+
* Solves constructor reactivity issues in complex inheritance trees
|
|
3633
|
+
*/
|
|
3634
|
+
const ReactiveBase = mixin((base) => {
|
|
3635
|
+
class ReactiveMixin extends base {
|
|
3636
|
+
constructor(...args) {
|
|
3637
|
+
super(...args);
|
|
3638
|
+
// Only apply reactive transformation if the class is marked with @reactive
|
|
3639
|
+
// This allows the mixin to work properly with method inheritance
|
|
3640
|
+
// biome-ignore lint/correctness/noConstructorReturn: This is the whole point here
|
|
3641
|
+
return reactiveClasses.has(new.target) ? reactive(this) : this;
|
|
3642
|
+
}
|
|
3643
|
+
}
|
|
3644
|
+
return ReactiveMixin;
|
|
3645
|
+
});
|
|
3646
|
+
function reactiveObject(anyTarget, subProxy) {
|
|
3647
|
+
if (!anyTarget || typeof anyTarget !== 'object')
|
|
3648
|
+
return anyTarget;
|
|
3649
|
+
const target = anyTarget;
|
|
3650
|
+
// If target is already a proxy, return it
|
|
3651
|
+
if (isNonReactive(target))
|
|
3652
|
+
return target;
|
|
3653
|
+
const isProxy = proxyToObject.has(target);
|
|
3654
|
+
if (isProxy)
|
|
3655
|
+
return target;
|
|
3656
|
+
// If we already have a proxy for this object, return it (optimized: get returns undefined if not found)
|
|
3657
|
+
const existing = getExistingProxy(target);
|
|
3658
|
+
if (existing !== undefined)
|
|
3659
|
+
return existing;
|
|
3660
|
+
if (subProxy)
|
|
3661
|
+
subsRegister.set(target, subProxy);
|
|
3662
|
+
const proxy = new Proxy(target, reactiveHandlers);
|
|
3663
|
+
if (Array.isArray(target))
|
|
3664
|
+
arrayLengths.set(target, target.length);
|
|
3665
|
+
// Store the relationships
|
|
3666
|
+
storeProxyRelationship(target, proxy);
|
|
3667
|
+
return proxy;
|
|
3668
|
+
}
|
|
3669
|
+
/**
|
|
3670
|
+
* Main decorator for making classes reactive
|
|
3671
|
+
* Automatically makes class instances reactive when created
|
|
3672
|
+
*/
|
|
3673
|
+
const reactive = decorator({
|
|
3674
|
+
class(original) {
|
|
3675
|
+
if (original.prototype instanceof ReactiveBase) {
|
|
3676
|
+
reactiveClasses.add(original);
|
|
3677
|
+
return original;
|
|
3678
|
+
}
|
|
3679
|
+
class Reactive extends original {
|
|
3680
|
+
constructor(...args) {
|
|
3681
|
+
super(...args);
|
|
3682
|
+
if (new.target !== Reactive && !reactiveClasses.has(new.target))
|
|
3683
|
+
options.warn(`${original.name} has been inherited by ${this.constructor.name} that is not reactive.
|
|
3684
|
+
@reactive decorator must be applied to the leaf class OR classes have to extend ReactiveBase.`);
|
|
3685
|
+
// biome-ignore lint/correctness/noConstructorReturn: This is the whole point here
|
|
3686
|
+
return reactive(this);
|
|
3687
|
+
}
|
|
3688
|
+
}
|
|
3689
|
+
Object.defineProperty(Reactive, 'name', {
|
|
3690
|
+
value: `Reactive<${original.name}>`,
|
|
3691
|
+
});
|
|
3692
|
+
return Reactive;
|
|
3693
|
+
},
|
|
3694
|
+
get(original) {
|
|
3695
|
+
return reactiveObject(original);
|
|
3696
|
+
},
|
|
3697
|
+
default: reactiveObject,
|
|
3698
|
+
});
|
|
3699
|
+
|
|
3700
|
+
export { touched1 as $, AZone as A, getActiveEffect as B, getState as C, DecoratorError as D, hooks as E, immutables as F, isConstructor as G, isNonReactive as H, IterableWeakMap as I, isObject as J, isReactive as K, legacyDecorator as L, mixin as M, modernDecorator as N, named as O, objectToProxy as P, onEffectThrow as Q, ReactiveBase as R, proxyToObject as S, reactive as T, options as U, reset as V, root as W, stopped as X, tag as Y, Zone as Z, touched as _, IterableWeakSet as a, untracked as a0, unwrap as a1, zip as a2, markWithRoot as a3, rootFunctionSymbol as a4, getRoot as a5, dependant as a6, optionCall as a7, keysOf as a8, __runInitializers as a9, __esDecorate as aa, FoolProof as ab, objectsWithDeepWatchers as ac, effectToDeepWatchedObjects as ad, deepWatchers as ae, registerDeepWatcher as af, nonReactiveClass as ag, unreactiveProps as ah, addUnreactiveProps as ai, nonReactiveObjects as aj, __setFunctionName as ak, __classPrivateFieldGet as al, __classPrivateFieldSet as am, contentRef as an, notifyPropertyChange as ao, metaProtos as ap, wrapProtos as aq, objectParents as ar, watchers as as, effectToReactiveObjects as at, effectMarker as au, getEffectNode as av, setDebugHooks as aw, allProps as ax, ReactiveError as b, ReactiveErrorCode as c, ZoneAggregator as d, ZoneHistory as e, addBatchCleanup as f, arrayEquals as g, asyncHook as h, asyncHooks as i, asyncZone as j, atom as k, atomic as l, biDi as m, caught as n, cleanedBy as o, cleanup as p, createFlavor as q, decorator as r, deepCompare as s, defer as t, effect as u, effectAggregator as v, flavorOptions as w, flavored as x, formatCleanupReason as y, getActivationLog as z };
|
|
3701
|
+
//# sourceMappingURL=proxy-r7lARftl.esm.js.map
|