mutts 1.0.8 → 1.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (226) hide show
  1. package/README.md +19 -2
  2. package/dist/browser.cjs +1030 -4406
  3. package/dist/browser.cjs.map +1 -1
  4. package/dist/browser.d.ts +310 -573
  5. package/dist/browser.esm.js +18 -24
  6. package/dist/browser.esm.js.map +1 -1
  7. package/dist/chunks/{async-browser-CA0jPWIi.cjs → async-browser-lvzLOCgk.cjs} +17 -24
  8. package/dist/chunks/async-browser-lvzLOCgk.cjs.map +1 -0
  9. package/dist/chunks/{async-core-UqHzvJ-S.cjs → async-core-CRLKP3l-.cjs} +8 -4
  10. package/dist/chunks/async-core-CRLKP3l-.cjs.map +1 -0
  11. package/dist/chunks/{async-node-BYHuGTni.cjs → async-node-C3DeIb0y.cjs} +5 -12
  12. package/dist/chunks/async-node-C3DeIb0y.cjs.map +1 -0
  13. package/dist/chunks/index-2vea86wD.esm.js +3011 -0
  14. package/dist/chunks/index-2vea86wD.esm.js.map +1 -0
  15. package/dist/chunks/index-CtA2AWl3.esm.js +4376 -0
  16. package/dist/chunks/index-CtA2AWl3.esm.js.map +1 -0
  17. package/dist/chunks/index-VTO-b2vR.cjs +4461 -0
  18. package/dist/chunks/index-VTO-b2vR.cjs.map +1 -0
  19. package/dist/{reactive → debug}/debug.d.ts +19 -8
  20. package/dist/debug/debug.d.ts.map +1 -0
  21. package/dist/debug/index.d.ts +4 -0
  22. package/dist/debug/index.d.ts.map +1 -0
  23. package/dist/debug/lineage-panel.d.ts +5 -0
  24. package/dist/debug/lineage-panel.d.ts.map +1 -0
  25. package/dist/debug/lineage.d.ts +79 -0
  26. package/dist/debug/lineage.d.ts.map +1 -0
  27. package/dist/debug.cjs +35 -0
  28. package/dist/debug.cjs.map +1 -0
  29. package/dist/debug.d.ts +209 -0
  30. package/dist/debug.esm.js +2 -0
  31. package/dist/debug.esm.js.map +1 -0
  32. package/dist/index.d.ts +1 -13
  33. package/dist/mutts.umd.js +1 -1
  34. package/dist/mutts.umd.js.map +1 -1
  35. package/dist/mutts.umd.min.js +1 -1
  36. package/dist/mutts.umd.min.js.map +1 -1
  37. package/dist/node.cjs +65 -63
  38. package/dist/node.cjs.map +1 -1
  39. package/dist/node.d.ts +2 -1
  40. package/dist/node.esm.js +5 -11
  41. package/dist/node.esm.js.map +1 -1
  42. package/dist/{async → src/async}/browser.d.ts.map +1 -1
  43. package/dist/{async → src/async}/index.d.ts +2 -1
  44. package/dist/src/async/index.d.ts.map +1 -0
  45. package/dist/{async → src/async}/node.d.ts.map +1 -1
  46. package/dist/src/decorator.d.ts.map +1 -0
  47. package/dist/src/destroyable.d.ts.map +1 -0
  48. package/dist/src/entry-browser.d.ts.map +1 -0
  49. package/dist/src/entry-node.d.ts.map +1 -0
  50. package/dist/src/eventful.d.ts +20 -0
  51. package/dist/src/eventful.d.ts.map +1 -0
  52. package/dist/src/flavored.d.ts +33 -0
  53. package/dist/src/flavored.d.ts.map +1 -0
  54. package/dist/src/index.d.ts +14 -0
  55. package/dist/src/index.d.ts.map +1 -0
  56. package/dist/src/indexable.d.ts.map +1 -0
  57. package/dist/{introspection.d.ts → src/introspection.d.ts} +1 -1
  58. package/dist/src/introspection.d.ts.map +1 -0
  59. package/dist/src/iterableWeak.d.ts.map +1 -0
  60. package/dist/src/mixins.d.ts.map +1 -0
  61. package/dist/src/promiseChain.d.ts.map +1 -0
  62. package/dist/{reactive → src/reactive}/array.d.ts +9 -10
  63. package/dist/src/reactive/array.d.ts.map +1 -0
  64. package/dist/src/reactive/buffer.d.ts +120 -0
  65. package/dist/src/reactive/buffer.d.ts.map +1 -0
  66. package/dist/{reactive → src/reactive}/change.d.ts +2 -2
  67. package/dist/src/reactive/change.d.ts.map +1 -0
  68. package/dist/src/reactive/deep-touch.d.ts.map +1 -0
  69. package/dist/{reactive → src/reactive}/deep-watch-state.d.ts +3 -3
  70. package/dist/src/reactive/deep-watch-state.d.ts.map +1 -0
  71. package/dist/{reactive → src/reactive}/deep-watch.d.ts +2 -1
  72. package/dist/src/reactive/deep-watch.d.ts.map +1 -0
  73. package/dist/src/reactive/describe.d.ts +12 -0
  74. package/dist/src/reactive/describe.d.ts.map +1 -0
  75. package/dist/src/reactive/effect-context.d.ts +34 -0
  76. package/dist/src/reactive/effect-context.d.ts.map +1 -0
  77. package/dist/{reactive → src/reactive}/effects.d.ts +31 -18
  78. package/dist/src/reactive/effects.d.ts.map +1 -0
  79. package/dist/src/reactive/index.d.ts +19 -0
  80. package/dist/src/reactive/index.d.ts.map +1 -0
  81. package/dist/{reactive → src/reactive}/map.d.ts +0 -2
  82. package/dist/src/reactive/map.d.ts.map +1 -0
  83. package/dist/src/reactive/memoize.d.ts +28 -0
  84. package/dist/src/reactive/memoize.d.ts.map +1 -0
  85. package/dist/src/reactive/non-reactive-state.d.ts.map +1 -0
  86. package/dist/src/reactive/non-reactive.d.ts.map +1 -0
  87. package/dist/{reactive → src/reactive}/project.d.ts +1 -2
  88. package/dist/src/reactive/project.d.ts.map +1 -0
  89. package/dist/src/reactive/proxy-state.d.ts.map +1 -0
  90. package/dist/src/reactive/proxy.d.ts.map +1 -0
  91. package/dist/{reactive → src/reactive}/record.d.ts +2 -3
  92. package/dist/src/reactive/record.d.ts.map +1 -0
  93. package/dist/{reactive → src/reactive}/register.d.ts +61 -0
  94. package/dist/src/reactive/register.d.ts.map +1 -0
  95. package/dist/{reactive → src/reactive}/registry.d.ts +6 -5
  96. package/dist/src/reactive/registry.d.ts.map +1 -0
  97. package/dist/{reactive → src/reactive}/set.d.ts +0 -2
  98. package/dist/src/reactive/set.d.ts.map +1 -0
  99. package/dist/src/reactive/tracking.d.ts.map +1 -0
  100. package/dist/{reactive → src/reactive}/types.d.ts +69 -21
  101. package/dist/src/reactive/types.d.ts.map +1 -0
  102. package/dist/{reactive/interface.d.ts → src/reactive/watch.d.ts} +7 -23
  103. package/dist/src/reactive/watch.d.ts.map +1 -0
  104. package/dist/{std-decorators.d.ts → src/std-decorators.d.ts} +1 -6
  105. package/dist/src/std-decorators.d.ts.map +1 -0
  106. package/dist/src/utils.d.ts.map +1 -0
  107. package/dist/{zone.d.ts → src/zone.d.ts} +2 -2
  108. package/dist/src/zone.d.ts.map +1 -0
  109. package/dist/types-DaHFfhlN.d.ts +414 -0
  110. package/docs/ai/api-reference.md +1 -1
  111. package/docs/ai/manual.md +443 -17
  112. package/docs/events.md +57 -2
  113. package/docs/flavored.md +210 -0
  114. package/docs/reactive/advanced.md +2 -3
  115. package/docs/reactive/attend.md +143 -0
  116. package/docs/reactive/collections.md +55 -0
  117. package/docs/reactive/core.md +120 -4
  118. package/docs/reactive/debugging.md +8 -10
  119. package/docs/reactive/describe.md +85 -0
  120. package/docs/reactive/error-handling.md +121 -0
  121. package/docs/reactive/project.md +1 -1
  122. package/docs/reactive/scan.md +215 -0
  123. package/docs/reactive.md +2 -0
  124. package/docs/std-decorators.md +102 -51
  125. package/docs/zone.md +3 -7
  126. package/package.json +6 -1
  127. package/src/async/browser.ts +110 -106
  128. package/src/async/index.ts +15 -11
  129. package/src/async/node.ts +5 -17
  130. package/src/eventful.ts +82 -49
  131. package/src/flavored.ts +106 -0
  132. package/src/index.d.ts +12 -12
  133. package/src/index.ts +2 -2
  134. package/src/introspection.ts +1 -1
  135. package/src/reactive/array.ts +29 -36
  136. package/src/reactive/buffer.ts +187 -27
  137. package/src/reactive/change.ts +16 -23
  138. package/src/reactive/deep-touch.ts +19 -14
  139. package/src/reactive/deep-watch-state.ts +3 -3
  140. package/src/reactive/deep-watch.ts +7 -4
  141. package/src/reactive/describe.ts +39 -0
  142. package/src/reactive/effect-context.ts +69 -4
  143. package/src/reactive/effects.ts +445 -393
  144. package/src/reactive/index.ts +12 -15
  145. package/src/reactive/map.ts +9 -25
  146. package/src/reactive/memoize.ts +26 -3
  147. package/src/reactive/project.md +107 -0
  148. package/src/reactive/project.ts +48 -71
  149. package/src/reactive/proxy.ts +21 -3
  150. package/src/reactive/record.ts +30 -45
  151. package/src/reactive/register.ts +138 -19
  152. package/src/reactive/registry.ts +22 -9
  153. package/src/reactive/set.ts +8 -21
  154. package/src/reactive/tracking.ts +9 -12
  155. package/src/reactive/types.ts +104 -24
  156. package/src/reactive/{interface.ts → watch.ts} +29 -59
  157. package/src/std-decorators.ts +56 -17
  158. package/src/utils.ts +2 -3
  159. package/src/zone.ts +28 -24
  160. package/dist/async/index.d.ts.map +0 -1
  161. package/dist/chunks/async-browser-CA0jPWIi.cjs.map +0 -1
  162. package/dist/chunks/async-core-UqHzvJ-S.cjs.map +0 -1
  163. package/dist/chunks/async-node-BYHuGTni.cjs.map +0 -1
  164. package/dist/chunks/index-DhaOVusv.esm.js +0 -6411
  165. package/dist/chunks/index-DhaOVusv.esm.js.map +0 -1
  166. package/dist/decorator.d.ts.map +0 -1
  167. package/dist/destroyable.d.ts.map +0 -1
  168. package/dist/entry-browser.d.ts.map +0 -1
  169. package/dist/entry-node.d.ts.map +0 -1
  170. package/dist/eventful.d.ts +0 -18
  171. package/dist/eventful.d.ts.map +0 -1
  172. package/dist/index.d.ts.map +0 -1
  173. package/dist/indexable.d.ts.map +0 -1
  174. package/dist/introspection.d.ts.map +0 -1
  175. package/dist/iterableWeak.d.ts.map +0 -1
  176. package/dist/mixins.d.ts.map +0 -1
  177. package/dist/promiseChain.d.ts.map +0 -1
  178. package/dist/reactive/array.d.ts.map +0 -1
  179. package/dist/reactive/buffer.d.ts +0 -44
  180. package/dist/reactive/buffer.d.ts.map +0 -1
  181. package/dist/reactive/change.d.ts.map +0 -1
  182. package/dist/reactive/debug.d.ts.map +0 -1
  183. package/dist/reactive/deep-touch.d.ts.map +0 -1
  184. package/dist/reactive/deep-watch-state.d.ts.map +0 -1
  185. package/dist/reactive/deep-watch.d.ts.map +0 -1
  186. package/dist/reactive/effect-context.d.ts +0 -7
  187. package/dist/reactive/effect-context.d.ts.map +0 -1
  188. package/dist/reactive/effects.d.ts.map +0 -1
  189. package/dist/reactive/index.d.ts +0 -20
  190. package/dist/reactive/index.d.ts.map +0 -1
  191. package/dist/reactive/interface.d.ts.map +0 -1
  192. package/dist/reactive/map.d.ts.map +0 -1
  193. package/dist/reactive/memoize.d.ts +0 -5
  194. package/dist/reactive/memoize.d.ts.map +0 -1
  195. package/dist/reactive/non-reactive-state.d.ts.map +0 -1
  196. package/dist/reactive/non-reactive.d.ts.map +0 -1
  197. package/dist/reactive/project.d.ts.map +0 -1
  198. package/dist/reactive/proxy-state.d.ts.map +0 -1
  199. package/dist/reactive/proxy.d.ts.map +0 -1
  200. package/dist/reactive/record.d.ts.map +0 -1
  201. package/dist/reactive/register.d.ts.map +0 -1
  202. package/dist/reactive/registry.d.ts.map +0 -1
  203. package/dist/reactive/set.d.ts.map +0 -1
  204. package/dist/reactive/tracking.d.ts.map +0 -1
  205. package/dist/reactive/types.d.ts.map +0 -1
  206. package/dist/std-decorators.d.ts.map +0 -1
  207. package/dist/utils.d.ts.map +0 -1
  208. package/dist/zone.d.ts.map +0 -1
  209. package/src/reactive/debug.ts +0 -517
  210. /package/dist/{async → src/async}/browser.d.ts +0 -0
  211. /package/dist/{async → src/async}/node.d.ts +0 -0
  212. /package/dist/{decorator.d.ts → src/decorator.d.ts} +0 -0
  213. /package/dist/{destroyable.d.ts → src/destroyable.d.ts} +0 -0
  214. /package/dist/{entry-browser.d.ts → src/entry-browser.d.ts} +0 -0
  215. /package/dist/{entry-node.d.ts → src/entry-node.d.ts} +0 -0
  216. /package/dist/{indexable.d.ts → src/indexable.d.ts} +0 -0
  217. /package/dist/{iterableWeak.d.ts → src/iterableWeak.d.ts} +0 -0
  218. /package/dist/{mixins.d.ts → src/mixins.d.ts} +0 -0
  219. /package/dist/{promiseChain.d.ts → src/promiseChain.d.ts} +0 -0
  220. /package/dist/{reactive → src/reactive}/deep-touch.d.ts +0 -0
  221. /package/dist/{reactive → src/reactive}/non-reactive-state.d.ts +0 -0
  222. /package/dist/{reactive → src/reactive}/non-reactive.d.ts +0 -0
  223. /package/dist/{reactive → src/reactive}/proxy-state.d.ts +0 -0
  224. /package/dist/{reactive → src/reactive}/proxy.d.ts +0 -0
  225. /package/dist/{reactive → src/reactive}/tracking.d.ts +0 -0
  226. /package/dist/{utils.d.ts → src/utils.d.ts} +0 -0
@@ -0,0 +1,4461 @@
1
+ 'use strict';
2
+
3
+ var asyncCore = require('./async-core-CRLKP3l-.cjs');
4
+
5
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
6
+ /**
7
+ * Combines multiple arrays into an array of tuples, stopping at the shortest array length
8
+ * @param args - Arrays to zip together
9
+ * @returns Array of tuples containing elements from each input array
10
+ */
11
+ function zip(...args) {
12
+ if (!args.length)
13
+ return [];
14
+ const minLength = Math.min(...args.map((arr) => arr.length));
15
+ const result = [];
16
+ for (let i = 0; i < minLength; i++) {
17
+ const tuple = args.map((arr) => arr[i]);
18
+ result.push(tuple);
19
+ }
20
+ return result;
21
+ }
22
+ /**
23
+ * Checks if two arrays are strictly equal (shallow comparison)
24
+ * @param a - First value
25
+ * @param b - Second value
26
+ * @returns True if arrays are equal or values are strictly equal
27
+ */
28
+ function arrayEquals(a, b) {
29
+ if (a === b)
30
+ return true;
31
+ if (!Array.isArray(a) || !Array.isArray(b))
32
+ return false;
33
+ if (a.length !== b.length)
34
+ return false;
35
+ for (let i = 0; i < a.length; i++) {
36
+ if (a[i] !== b[i])
37
+ return false;
38
+ }
39
+ return true;
40
+ }
41
+ const nativeConstructors = new Set([
42
+ Object,
43
+ Array,
44
+ Date,
45
+ Function,
46
+ Set,
47
+ Map,
48
+ WeakMap,
49
+ WeakSet,
50
+ Promise,
51
+ Error,
52
+ TypeError,
53
+ ReferenceError,
54
+ SyntaxError,
55
+ RangeError,
56
+ URIError,
57
+ EvalError,
58
+ Reflect,
59
+ Proxy,
60
+ RegExp,
61
+ String,
62
+ Number,
63
+ Boolean,
64
+ ]);
65
+ /**
66
+ * Checks if a function is a constructor (class or constructor function)
67
+ * @param fn - The function to check
68
+ * @returns True if the function is a constructor
69
+ */
70
+ function isConstructor(fn) {
71
+ return (fn &&
72
+ typeof fn === 'function' &&
73
+ (nativeConstructors.has(fn) || fn.toString?.().startsWith('class ')));
74
+ }
75
+ /**
76
+ * Renames a function with a new name
77
+ * @param fct - The function to rename
78
+ * @param name - The new name for the function
79
+ * @returns The function with the new name
80
+ */
81
+ function renamed(fct, name) {
82
+ return Object.defineProperties(fct, {
83
+ name: {
84
+ value: name,
85
+ },
86
+ });
87
+ }
88
+ const FoolProof = {
89
+ get(obj, prop, receiver) {
90
+ // Check if Node is available and obj is an instance of Node
91
+ if (typeof Node !== 'undefined' && obj instanceof Node)
92
+ return obj[prop];
93
+ return Reflect.get(obj, prop, receiver);
94
+ },
95
+ set(obj, prop, value, receiver) {
96
+ // Check if Node is available and obj is an instance of Node
97
+ if (typeof Node !== 'undefined' && obj instanceof Node) {
98
+ obj[prop] = value;
99
+ return true;
100
+ }
101
+ if (!(obj instanceof Object) && !Reflect.has(obj, prop)) {
102
+ Object.defineProperty(obj, prop, {
103
+ value,
104
+ configurable: true,
105
+ writable: true,
106
+ enumerable: true,
107
+ });
108
+ return true;
109
+ }
110
+ return Reflect.set(obj, prop, value, receiver);
111
+ },
112
+ };
113
+ function isOwnAccessor(obj, prop) {
114
+ const opd = Object.getOwnPropertyDescriptor(obj, prop);
115
+ return !!(opd?.get || opd?.set);
116
+ }
117
+ /**
118
+ * Deeply compares two values.
119
+ * For objects, compares prototypes with === and then own properties recursively.
120
+ * Uses a cache to handle circular references.
121
+ * @param a - First value
122
+ * @param b - Second value
123
+ * @param cache - Map for circular reference protection (internal use)
124
+ * @returns True if values are deeply equal
125
+ */
126
+ function deepCompare(a, b, cache = new Map()) {
127
+ if (a === b)
128
+ return true;
129
+ if (typeof a !== 'object' || a === null || typeof b !== 'object' || b === null) {
130
+ return a === b;
131
+ }
132
+ // Prototype check
133
+ const protoA = Object.getPrototypeOf(a);
134
+ const protoB = Object.getPrototypeOf(b);
135
+ if (protoA !== protoB) {
136
+ console.warn(`[deepCompare] prototype mismatch:`, {
137
+ nameA: a?.constructor?.name,
138
+ nameB: b?.constructor?.name,
139
+ });
140
+ return false;
141
+ }
142
+ // Circular reference protection
143
+ let compared = cache.get(a);
144
+ if (compared?.has(b))
145
+ return true;
146
+ if (!compared) {
147
+ compared = new Set();
148
+ cache.set(a, compared);
149
+ }
150
+ compared.add(b);
151
+ // Handle specific object types
152
+ if (Array.isArray(a)) {
153
+ if (!Array.isArray(b)) {
154
+ console.warn(`[deepCompare] B is not an array`);
155
+ return false;
156
+ }
157
+ if (a.length !== b.length) {
158
+ console.warn(`[deepCompare] array length mismatch:`, { lenA: a.length, lenB: b.length });
159
+ return false;
160
+ }
161
+ for (let i = 0; i < a.length; i++) {
162
+ if (!deepCompare(a[i], b[i], cache)) {
163
+ console.warn(`[deepCompare] array element mismatch at index ${i}`);
164
+ return false;
165
+ }
166
+ }
167
+ return true;
168
+ }
169
+ if (a instanceof Date) {
170
+ const match = b instanceof Date && a.getTime() === b.getTime();
171
+ if (!match)
172
+ console.warn(`[deepCompare] Date mismatch`);
173
+ return match;
174
+ }
175
+ if (a instanceof RegExp) {
176
+ const match = b instanceof RegExp && a.toString() === b.toString();
177
+ if (!match)
178
+ console.warn(`[deepCompare] RegExp mismatch`);
179
+ return match;
180
+ }
181
+ if (a instanceof Set) {
182
+ if (!(b instanceof Set) || a.size !== b.size) {
183
+ console.warn(`[deepCompare] Set size mismatch`);
184
+ return false;
185
+ }
186
+ for (const val of a) {
187
+ let found = false;
188
+ for (const bVal of b) {
189
+ if (deepCompare(val, bVal, cache)) {
190
+ found = true;
191
+ break;
192
+ }
193
+ }
194
+ if (!found) {
195
+ console.warn(`[deepCompare] missing Set element`);
196
+ return false;
197
+ }
198
+ }
199
+ return true;
200
+ }
201
+ if (a instanceof Map) {
202
+ if (!(b instanceof Map) || a.size !== b.size) {
203
+ console.warn(`[deepCompare] Map size mismatch`);
204
+ return false;
205
+ }
206
+ for (const [key, val] of a) {
207
+ if (!b.has(key)) {
208
+ let foundMatch = false;
209
+ for (const [bKey, bVal] of b) {
210
+ if (deepCompare(key, bKey, cache) && deepCompare(val, bVal, cache)) {
211
+ foundMatch = true;
212
+ break;
213
+ }
214
+ }
215
+ if (!foundMatch) {
216
+ console.warn(`[deepCompare] missing Map key`);
217
+ return false;
218
+ }
219
+ }
220
+ else {
221
+ if (!deepCompare(val, b.get(key), cache)) {
222
+ console.warn(`[deepCompare] Map value mismatch for key`);
223
+ return false;
224
+ }
225
+ }
226
+ }
227
+ return true;
228
+ }
229
+ // Compare own properties
230
+ const keysA = Object.keys(a);
231
+ const keysB = Object.keys(b);
232
+ if (keysA.length !== keysB.length) {
233
+ console.warn(`[deepCompare] keys length mismatch:`, {
234
+ lenA: keysA.length,
235
+ lenB: keysB.length,
236
+ keysA,
237
+ keysB,
238
+ a,
239
+ b,
240
+ });
241
+ return false;
242
+ }
243
+ for (const key of keysA) {
244
+ if (!Object.hasOwn(b, key)) {
245
+ console.warn(`[deepCompare] missing key ${String(key)} in B`);
246
+ return false;
247
+ }
248
+ if (!deepCompare(a[key], b[key], cache)) {
249
+ console.warn(`[deepCompare] value mismatch for key ${String(key)}:`, {
250
+ valA: a[key],
251
+ valB: b[key],
252
+ });
253
+ return false;
254
+ }
255
+ }
256
+ return true;
257
+ }
258
+ const contentRefs = new WeakMap();
259
+ function contentRef(container) {
260
+ if (!contentRefs.has(container))
261
+ contentRefs.set(container, Object.seal(Object.create(null, {
262
+ contentOf: { value: container, writable: false, configurable: false },
263
+ })));
264
+ return contentRefs.get(container);
265
+ }
266
+ function tag(name, obj) {
267
+ Object.defineProperties(obj, {
268
+ [Symbol.toStringTag]: {
269
+ value: name,
270
+ writable: false,
271
+ configurable: false,
272
+ },
273
+ toString: {
274
+ value: () => name,
275
+ writable: false,
276
+ configurable: false,
277
+ },
278
+ });
279
+ return obj;
280
+ }
281
+ function named(name, fn) {
282
+ Object.defineProperty(fn, 'name', {
283
+ value: fn.name ? `${fn.name}::${name}` : name,
284
+ writable: false,
285
+ configurable: true,
286
+ });
287
+ return fn;
288
+ }
289
+
290
+ // biome-ignore-all lint/suspicious/noConfusingVoidType: We *love* voids
291
+ // Standardized decorator system that works with both Legacy and Modern decorators
292
+ /**
293
+ * Error thrown when decorator operations fail
294
+ */
295
+ class DecoratorError extends Error {
296
+ constructor(message) {
297
+ super(message);
298
+ this.name = 'DecoratorException';
299
+ }
300
+ }
301
+ /**
302
+ * Creates a decorator that works with Legacy decorator proposals
303
+ * @param description - The decorator description object
304
+ * @returns A decorator function compatible with Legacy decorators
305
+ */
306
+ function legacyDecorator(description) {
307
+ return function (target, propertyKey, descriptor, ...args) {
308
+ if (propertyKey === undefined) {
309
+ if (isConstructor(target)) {
310
+ if (!('class' in description))
311
+ throw new Error('Decorator cannot be applied to a class');
312
+ return description.class(target);
313
+ }
314
+ }
315
+ else if (typeof target === 'object' && ['string', 'symbol'].includes(typeof propertyKey)) {
316
+ if (!descriptor)
317
+ throw new Error('Decorator cannot be applied to a field');
318
+ else if (typeof descriptor === 'object' && 'configurable' in descriptor) {
319
+ if ('get' in descriptor || 'set' in descriptor) {
320
+ if (!('getter' in description || 'setter' in description))
321
+ throw new Error('Decorator cannot be applied to a getter or setter');
322
+ if ('getter' in description) {
323
+ const newGetter = description.getter(descriptor.get, target, propertyKey);
324
+ if (newGetter)
325
+ descriptor.get = newGetter;
326
+ }
327
+ if ('setter' in description) {
328
+ const newSetter = description.setter(descriptor.set, target, propertyKey);
329
+ if (newSetter)
330
+ descriptor.set = newSetter;
331
+ }
332
+ return descriptor;
333
+ }
334
+ else if (typeof descriptor.value === 'function') {
335
+ if (!('method' in description))
336
+ throw new Error('Decorator cannot be applied to a method');
337
+ const newMethod = description.method(descriptor.value, target, propertyKey);
338
+ if (newMethod)
339
+ descriptor.value = newMethod;
340
+ return descriptor;
341
+ }
342
+ }
343
+ }
344
+ if (!('default' in description))
345
+ throw new Error('Decorator do not have a default implementation');
346
+ return description.default.call(this, target, propertyKey, descriptor, ...args);
347
+ };
348
+ }
349
+ /**
350
+ * Creates a decorator that works with Modern decorator proposals
351
+ * @param description - The decorator description object
352
+ * @returns A decorator function compatible with Modern decorators
353
+ */
354
+ function modernDecorator(description) {
355
+ /*return function (target: any, context?: DecoratorContext, ...args: any[]) {*/
356
+ return function (target, context, ...args) {
357
+ if (!context?.kind || typeof context.kind !== 'string') {
358
+ if (!('default' in description))
359
+ throw new Error('Decorator do not have a default implementation');
360
+ return description.default.call(this, target, context, ...args);
361
+ }
362
+ switch (context.kind) {
363
+ case 'class':
364
+ if (!('class' in description))
365
+ throw new Error('Decorator cannot be applied to a class');
366
+ return description.class(target);
367
+ case 'field':
368
+ throw new Error('Decorator cannot be applied to a field');
369
+ case 'getter':
370
+ if (!('getter' in description))
371
+ throw new Error('Decorator cannot be applied to a getter');
372
+ return description.getter(target, target, context.name);
373
+ case 'setter':
374
+ if (!('setter' in description))
375
+ throw new Error('Decorator cannot be applied to a setter');
376
+ return description.setter(target, target, context.name);
377
+ case 'method':
378
+ if (!('method' in description))
379
+ throw new Error('Decorator cannot be applied to a method');
380
+ return description.method(target, target, context.name);
381
+ case 'accessor': {
382
+ if (!('getter' in description || 'setter' in description))
383
+ throw new Error('Decorator cannot be applied to a getter or setter');
384
+ const rv = {};
385
+ if ('getter' in description) {
386
+ const newGetter = description.getter(target.get, target, context.name);
387
+ if (newGetter)
388
+ rv.get = newGetter;
389
+ }
390
+ if ('setter' in description) {
391
+ const newSetter = description.setter(target.set, target, context.name);
392
+ if (newSetter)
393
+ rv.set = newSetter;
394
+ }
395
+ return rv;
396
+ }
397
+ //return description.accessor?.(target, context.name, target)
398
+ }
399
+ };
400
+ }
401
+ /**
402
+ * Detects if the decorator is being called in modern (Modern) or legacy (Legacy) mode
403
+ * based on the arguments passed to the decorator function
404
+ */
405
+ function detectDecoratorMode(_target, contextOrKey, _descriptor) {
406
+ // Modern decorators have a context object as the second parameter
407
+ // Legacy decorators have a string/symbol key as the second parameter
408
+ if (typeof contextOrKey === 'object' &&
409
+ contextOrKey !== null &&
410
+ typeof contextOrKey.kind === 'string') {
411
+ return 'modern';
412
+ }
413
+ return 'legacy';
414
+ }
415
+ /**
416
+ * Main decorator factory that automatically detects and works with both Legacy and Modern decorator proposals
417
+ * @param description - The decorator description object
418
+ * @returns A decorator that works in both Legacy and Modern environments
419
+ */
420
+ const decorator = (description) => {
421
+ const modern = modernDecorator(description);
422
+ const legacy = legacyDecorator(description);
423
+ return ((target, contextOrKey, ...args) => {
424
+ const mode = detectDecoratorMode(target, contextOrKey, args[0]);
425
+ return mode === 'modern'
426
+ ? modern(target, contextOrKey, ...args)
427
+ : legacy(target, contextOrKey, ...args);
428
+ });
429
+ };
430
+
431
+ /**
432
+ * Creates a flavored (extensible) version of a function with chainable property modifiers.
433
+ *
434
+ * Each property defined in `flavors` returns a new flavored function that transforms
435
+ * how the original function is called. This enables a fluent API where properties
436
+ * create specialized variants of the base function.
437
+ *
438
+ * @param fn - The base function to flavor
439
+ * @param flavors - Object defining the flavor properties (getters or methods)
440
+ * @returns A proxy of the function with the flavor properties attached
441
+ *
442
+ * @example
443
+ * ```typescript
444
+ * function greet(name: string, options?: { loud?: boolean }) {
445
+ * const greeting = `Hello, ${name}!`
446
+ * return options?.loud ? greeting.toUpperCase() : greeting
447
+ * }
448
+ *
449
+ * const flavoredGreet = flavored(greet, {
450
+ * get loud() {
451
+ * return createFlavor(this, (name, opts) => [name, { ...opts, loud: true }])
452
+ * }
453
+ * })
454
+ *
455
+ * flavoredGreet('World') // "Hello, World!"
456
+ * flavoredGreet.loud('World') // "HELLO, WORLD!"
457
+ * ```
458
+ */
459
+ /**
460
+ * Creates a flavored (extensible) version of a function with chainable property modifiers.
461
+ */
462
+ function flavored(fn, flavors) {
463
+ fn.flavors = flavors;
464
+ return new Proxy(fn, {
465
+ get(target, prop, receiver) {
466
+ if (prop in flavors) {
467
+ return Reflect.get(flavors, prop, receiver);
468
+ }
469
+ return target[prop];
470
+ },
471
+ });
472
+ }
473
+ /**
474
+ * Creates a new flavored function that transforms arguments before calling the base.
475
+ *
476
+ * @param fn - The base flavored function
477
+ * @param transform - Function that receives the original arguments and returns transformed arguments
478
+ * @returns A new flavored function with the transformation applied
479
+ *
480
+ * @example
481
+ * ```typescript
482
+ * const loudGreet = createFlavor(greet, (name, opts) => [name, { ...opts, loud: true }])
483
+ * ```
484
+ */
485
+ function createFlavor(fn, transform, name) {
486
+ const fct = function flavorWrapper(...args) {
487
+ return fn.apply(this, transform(...args));
488
+ };
489
+ if (name)
490
+ named(name, fct);
491
+ return flavored(fct, fn.flavors || {});
492
+ }
493
+ /**
494
+ * Creates a new flavored function that merges options objects.
495
+ * Useful when the last argument is an options object that should be merged.
496
+ *
497
+ * @param fn - The base flavored function
498
+ * @param defaultOptions - Options to merge with the provided options
499
+ * @returns A new flavored function with merged options
500
+ *
501
+ * @example
502
+ * ```typescript
503
+ * const opaqueEffect = flavorOptions(effect, { opaque: true })
504
+ * const namedEffect = flavorOptions(effect, { name: 'myEffect' })
505
+ * ```
506
+ */
507
+ function flavorOptions(fn, defaultOptions, name) {
508
+ const fct = function flavorOptionsWrapper(...args) {
509
+ const lastArg = args[args.length - 1];
510
+ const mergedArgs = lastArg !== undefined && typeof lastArg === 'object'
511
+ ? [...args.slice(0, -1), { ...defaultOptions, ...lastArg }]
512
+ : [...args, defaultOptions];
513
+ return fn.apply(this, mergedArgs);
514
+ };
515
+ if (name)
516
+ named(name, fct);
517
+ return flavored(fct, fn.flavors || {});
518
+ }
519
+
520
+ /// <reference lib="esnext.collection" />
521
+ var _a, _b;
522
+ /**
523
+ * Uses weak references but still may iterate through them
524
+ * Note: The behavior is highly dependant on the garbage collector - some entries are perhaps deemed to be collected: don't resuscitate them
525
+ */
526
+ class IterableWeakMap {
527
+ constructor(entries) {
528
+ this.uuids = new WeakMap();
529
+ this.refs = {};
530
+ this[_a] = 'IterableWeakMap';
531
+ // Create a FinalizationRegistry to clean up refs when keys are garbage collected
532
+ this.registry = new FinalizationRegistry((uuid) => {
533
+ delete this.refs[uuid];
534
+ });
535
+ if (entries)
536
+ for (const [k, v] of entries)
537
+ this.set(k, v);
538
+ }
539
+ createIterator(cb) {
540
+ const { refs } = this;
541
+ return (function* () {
542
+ for (const uuid of Object.keys(refs)) {
543
+ const [keyRef, value] = refs[uuid];
544
+ const key = keyRef.deref();
545
+ if (key)
546
+ yield cb(key, value);
547
+ else
548
+ delete refs[uuid];
549
+ }
550
+ return undefined;
551
+ })();
552
+ }
553
+ clear() {
554
+ // Unregister all keys from the FinalizationRegistry
555
+ for (const uuid of Object.keys(this.refs)) {
556
+ const key = this.refs[uuid][0].deref();
557
+ if (key)
558
+ this.registry.unregister(key);
559
+ }
560
+ this.uuids = new WeakMap();
561
+ this.refs = {};
562
+ }
563
+ delete(key) {
564
+ const uuid = this.uuids.get(key);
565
+ if (!uuid)
566
+ return false;
567
+ delete this.refs[uuid];
568
+ this.uuids.delete(key);
569
+ this.registry.unregister(key);
570
+ return true;
571
+ }
572
+ forEach(callbackfn, thisArg) {
573
+ for (const [k, v] of this)
574
+ callbackfn.call(thisArg ?? this, v, k, thisArg ?? this);
575
+ }
576
+ get(key) {
577
+ const uuid = this.uuids.get(key);
578
+ if (!uuid)
579
+ return undefined;
580
+ return this.refs[uuid][1];
581
+ }
582
+ has(key) {
583
+ return this.uuids.has(key);
584
+ }
585
+ set(key, value) {
586
+ let uuid = this.uuids.get(key);
587
+ if (uuid) {
588
+ this.refs[uuid][1] = value;
589
+ }
590
+ else {
591
+ uuid = crypto.randomUUID();
592
+ this.uuids.set(key, uuid);
593
+ this.refs[uuid] = [new WeakRef(key), value];
594
+ // Register key for cleanup when garbage collected
595
+ this.registry.register(key, uuid, key);
596
+ }
597
+ return this;
598
+ }
599
+ get size() {
600
+ return [...this].length;
601
+ }
602
+ entries() {
603
+ return this.createIterator((key, value) => [key, value]);
604
+ }
605
+ keys() {
606
+ return this.createIterator((key, _value) => key);
607
+ }
608
+ values() {
609
+ return this.createIterator((_key, value) => value);
610
+ }
611
+ [Symbol.iterator]() {
612
+ return this.entries();
613
+ }
614
+ }
615
+ _a = Symbol.toStringTag;
616
+ /**
617
+ * Uses weak references but still may iterate through them
618
+ * Note: The behavior is highly dependant on the garbage collector - some entries are perhaps deemed to be collected: don't resuscitate them
619
+ */
620
+ class IterableWeakSet {
621
+ constructor(entries) {
622
+ this.uuids = new WeakMap();
623
+ this.refs = {};
624
+ this[_b] = 'IterableWeakSet';
625
+ // Create a FinalizationRegistry to clean up refs when values are garbage collected
626
+ this.registry = new FinalizationRegistry((uuid) => {
627
+ delete this.refs[uuid];
628
+ });
629
+ if (entries)
630
+ for (const k of entries)
631
+ this.add(k);
632
+ }
633
+ createIterator(cb) {
634
+ const { refs } = this;
635
+ return (function* () {
636
+ for (const uuid of Object.keys(refs)) {
637
+ const key = refs[uuid].deref();
638
+ if (key)
639
+ yield cb(key);
640
+ else
641
+ delete refs[uuid];
642
+ }
643
+ return undefined;
644
+ })();
645
+ }
646
+ clear() {
647
+ // Unregister all values from the FinalizationRegistry
648
+ for (const uuid of Object.keys(this.refs)) {
649
+ const value = this.refs[uuid].deref();
650
+ if (value)
651
+ this.registry.unregister(value);
652
+ }
653
+ this.uuids = new WeakMap();
654
+ this.refs = {};
655
+ }
656
+ add(value) {
657
+ let uuid = this.uuids.get(value);
658
+ if (!uuid) {
659
+ uuid = crypto.randomUUID();
660
+ this.uuids.set(value, uuid);
661
+ this.refs[uuid] = new WeakRef(value);
662
+ // Register value for cleanup when garbage collected
663
+ this.registry.register(value, uuid, value);
664
+ }
665
+ return this;
666
+ }
667
+ delete(value) {
668
+ const uuid = this.uuids.get(value);
669
+ if (!uuid)
670
+ return false;
671
+ delete this.refs[uuid];
672
+ this.uuids.delete(value);
673
+ this.registry.unregister(value);
674
+ return true;
675
+ }
676
+ forEach(callbackfn, thisArg) {
677
+ for (const value of this)
678
+ callbackfn.call(thisArg ?? this, value, value, thisArg ?? this);
679
+ }
680
+ has(value) {
681
+ return this.uuids.has(value);
682
+ }
683
+ get size() {
684
+ return [...this].length;
685
+ }
686
+ entries() {
687
+ return this.createIterator((key) => [key, key]);
688
+ }
689
+ keys() {
690
+ return this.createIterator((key) => key);
691
+ }
692
+ values() {
693
+ return this.createIterator((key) => key);
694
+ }
695
+ [Symbol.iterator]() {
696
+ return this.keys();
697
+ }
698
+ union(other) {
699
+ const others = {
700
+ [Symbol.iterator]() {
701
+ return other.keys();
702
+ },
703
+ };
704
+ const that = this;
705
+ return new Set((function* () {
706
+ yield* that;
707
+ for (const value of others)
708
+ if (!that.has(value))
709
+ yield value;
710
+ })());
711
+ }
712
+ intersection(other) {
713
+ const that = this;
714
+ return new Set((function* () {
715
+ for (const value of that)
716
+ if (other.has(value))
717
+ yield value;
718
+ })());
719
+ }
720
+ difference(other) {
721
+ const that = this;
722
+ return new Set((function* () {
723
+ for (const value of that)
724
+ if (!other.has(value))
725
+ yield value;
726
+ })());
727
+ }
728
+ symmetricDifference(other) {
729
+ const others = {
730
+ [Symbol.iterator]() {
731
+ return other.keys();
732
+ },
733
+ };
734
+ const that = this;
735
+ return new Set((function* () {
736
+ for (const value of that)
737
+ if (!other.has(value))
738
+ yield value;
739
+ for (const value of others)
740
+ if (!that.has(value))
741
+ yield value;
742
+ })());
743
+ }
744
+ isSubsetOf(other) {
745
+ for (const value of this)
746
+ if (!other.has(value))
747
+ return false;
748
+ return true;
749
+ }
750
+ isSupersetOf(other) {
751
+ const others = {
752
+ [Symbol.iterator]() {
753
+ return other.keys();
754
+ },
755
+ };
756
+ for (const value of others)
757
+ if (!this.has(value))
758
+ return false;
759
+ return true;
760
+ }
761
+ isDisjointFrom(other) {
762
+ for (const value of this)
763
+ if (other.has(value))
764
+ return false;
765
+ return true;
766
+ }
767
+ }
768
+ _b = Symbol.toStringTag;
769
+
770
+ /**
771
+ * Creates a mixin that can be used both as a class (extends) and as a function (mixin)
772
+ *
773
+ * This function supports:
774
+ * - Using mixins as base classes: `class MyClass extends MyMixin`
775
+ * - Using mixins as functions: `class MyClass extends MyMixin(SomeBase)`
776
+ * - Composing mixins: `const Composed = MixinA(MixinB)`
777
+ * - Type-safe property inference for all patterns
778
+ *
779
+ * @param mixinFunction - The function that creates the mixin
780
+ * @param unwrapFunction - Optional function to unwrap reactive objects for method calls
781
+ * @returns A mixin that can be used both as a class and as a function
782
+ */
783
+ function mixin(mixinFunction, unwrapFunction) {
784
+ /**
785
+ * Cache for mixin results to ensure the same base class always returns the same mixed class
786
+ */
787
+ const mixinCache = new WeakMap();
788
+ // Apply the mixin to Object as the base class
789
+ const MixedBase = mixinFunction(Object);
790
+ mixinCache.set(Object, MixedBase);
791
+ // Create the proxy that handles both constructor and function calls
792
+ return new Proxy(MixedBase, {
793
+ // Handle `MixinClass(SomeBase)` - use as mixin function
794
+ apply(_target, _thisArg, args) {
795
+ if (args.length === 0) {
796
+ throw new Error('Mixin requires a base class');
797
+ }
798
+ const baseClass = args[0];
799
+ if (typeof baseClass !== 'function') {
800
+ throw new Error('Mixin requires a constructor function');
801
+ }
802
+ // Check if it's a valid constructor or a mixin
803
+ if (!isConstructor(baseClass) &&
804
+ !(baseClass && typeof baseClass === 'function' && baseClass.prototype)) {
805
+ throw new Error('Mixin requires a valid constructor');
806
+ }
807
+ // Check cache first
808
+ const cached = mixinCache.get(baseClass);
809
+ if (cached) {
810
+ return cached;
811
+ }
812
+ let usedBase = baseClass;
813
+ if (unwrapFunction) {
814
+ // Create a proxied base class that handles method unwrapping
815
+ const ProxiedBaseClass = class extends baseClass {
816
+ };
817
+ // Proxy the prototype methods to handle unwrapping
818
+ const originalPrototype = baseClass.prototype;
819
+ const proxiedPrototype = new Proxy(originalPrototype, {
820
+ get(target, prop, receiver) {
821
+ const value = FoolProof.get(target, prop, receiver);
822
+ // Only wrap methods that are likely to access private fields
823
+ // Skip symbols and special properties that the reactive system needs
824
+ if (typeof value === 'function' &&
825
+ typeof prop === 'string' &&
826
+ !['constructor', 'toString', 'valueOf'].includes(prop)) {
827
+ // Return a wrapped version that uses unwrapped context
828
+ return function (...args) {
829
+ // Use the unwrapping function if provided, otherwise use this
830
+ const context = unwrapFunction(this);
831
+ return value.apply(context, args);
832
+ };
833
+ }
834
+ return value;
835
+ },
836
+ });
837
+ // Set the proxied prototype
838
+ Object.setPrototypeOf(ProxiedBaseClass.prototype, proxiedPrototype);
839
+ usedBase = ProxiedBaseClass;
840
+ }
841
+ // Create the mixed class using the proxied base class
842
+ const mixedClass = mixinFunction(usedBase);
843
+ // Cache the result
844
+ mixinCache.set(baseClass, mixedClass);
845
+ return mixedClass;
846
+ },
847
+ });
848
+ }
849
+
850
+ /******************************************************************************
851
+ Copyright (c) Microsoft Corporation.
852
+
853
+ Permission to use, copy, modify, and/or distribute this software for any
854
+ purpose with or without fee is hereby granted.
855
+
856
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
857
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
858
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
859
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
860
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
861
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
862
+ PERFORMANCE OF THIS SOFTWARE.
863
+ ***************************************************************************** */
864
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
865
+
866
+
867
+ function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
868
+ function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
869
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
870
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
871
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
872
+ var _, done = false;
873
+ for (var i = decorators.length - 1; i >= 0; i--) {
874
+ var context = {};
875
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
876
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
877
+ context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
878
+ var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
879
+ if (kind === "accessor") {
880
+ if (result === void 0) continue;
881
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
882
+ if (_ = accept(result.get)) descriptor.get = _;
883
+ if (_ = accept(result.set)) descriptor.set = _;
884
+ if (_ = accept(result.init)) initializers.unshift(_);
885
+ }
886
+ else if (_ = accept(result)) {
887
+ if (kind === "field") initializers.unshift(_);
888
+ else descriptor[key] = _;
889
+ }
890
+ }
891
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
892
+ done = true;
893
+ }
894
+ function __runInitializers(thisArg, initializers, value) {
895
+ var useValue = arguments.length > 2;
896
+ for (var i = 0; i < initializers.length; i++) {
897
+ value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
898
+ }
899
+ return useValue ? value : void 0;
900
+ }
901
+ function __setFunctionName(f, name, prefix) {
902
+ if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
903
+ return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
904
+ }
905
+ function __classPrivateFieldGet(receiver, state, kind, f) {
906
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
907
+ 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");
908
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
909
+ }
910
+
911
+ function __classPrivateFieldSet(receiver, state, value, kind, f) {
912
+ if (kind === "m") throw new TypeError("Private method is not writable");
913
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
914
+ 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");
915
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
916
+ }
917
+
918
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
919
+ var e = new Error(message);
920
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
921
+ };
922
+
923
+ // biome-ignore-all lint/suspicious/noConfusingVoidType: Type 'void' is not assignable to type 'ScopedCallback | undefined'.
924
+ // Argument of type '() => void' is not assignable to parameter of type '(dep: DependencyFunction) => ScopedCallback | undefined'.
925
+ // Track native reactivity
926
+ const nativeReactive = Symbol('native-reactive');
927
+ /**
928
+ * Symbol to mark individual objects as non-reactive
929
+ */
930
+ const nonReactiveMark = Symbol('non-reactive');
931
+ /**
932
+ * Symbol to mark class properties as non-reactive
933
+ */
934
+ const unreactiveProperties = Symbol('unreactive-properties');
935
+ /**
936
+ * Symbol representing all properties in reactive tracking
937
+ */
938
+ const allProps = Symbol('all-props');
939
+ /**
940
+ * Symbol for accessing projection information on reactive objects
941
+ */
942
+ const projectionInfo = Symbol('projection-info');
943
+ /**
944
+ * Symbol to check if an effect is stopped
945
+ */
946
+ const stopped = Symbol('stopped');
947
+ /**
948
+ * Symbol to access effect cleanup function
949
+ */
950
+ const cleanup = Symbol('cleanup');
951
+ // Symbol to mark functions with their root function
952
+ const rootFunction = Symbol('root-function');
953
+ /**
954
+ * Structured error codes for machine-readable diagnosis
955
+ */
956
+ exports.ReactiveErrorCode = void 0;
957
+ (function (ReactiveErrorCode) {
958
+ ReactiveErrorCode["CycleDetected"] = "CYCLE_DETECTED";
959
+ ReactiveErrorCode["MaxDepthExceeded"] = "MAX_DEPTH_EXCEEDED";
960
+ ReactiveErrorCode["MaxReactionExceeded"] = "MAX_REACTION_EXCEEDED";
961
+ ReactiveErrorCode["WriteInComputed"] = "WRITE_IN_COMPUTED";
962
+ ReactiveErrorCode["TrackingError"] = "TRACKING_ERROR";
963
+ ReactiveErrorCode["BrokenEffects"] = "BROKEN_EFFECTS";
964
+ })(exports.ReactiveErrorCode || (exports.ReactiveErrorCode = {}));
965
+ /**
966
+ * Error class for reactive system errors
967
+ */
968
+ class ReactiveError extends Error {
969
+ constructor(message, debugInfo) {
970
+ super(message);
971
+ this.debugInfo = debugInfo;
972
+ this.name = 'ReactiveError';
973
+ }
974
+ get code() {
975
+ return this.debugInfo?.code;
976
+ }
977
+ get cause() {
978
+ return this.debugInfo?.cause;
979
+ }
980
+ }
981
+ // biome-ignore-start lint/correctness/noUnusedFunctionParameters: Interface declaration with empty defaults
982
+ /**
983
+ * Global options for the reactive system
984
+ */
985
+ const options = {
986
+ /**
987
+ * Debug purpose: called when an effect is entered
988
+ * @param effect - The effect that is entered
989
+ */
990
+ enter: (_effect) => { },
991
+ /**
992
+ * Debug purpose: called when an effect is left
993
+ * @param effect - The effect that is left
994
+ */
995
+ leave: (_effect) => { },
996
+ /**
997
+ * Debug purpose: called when an effect is chained
998
+ * @param target - The effect that is being triggered
999
+ * @param caller - The effect that is calling the target
1000
+ */
1001
+ chain: (_targets, _caller) => { },
1002
+ /**
1003
+ * Debug purpose: called when an effect chain is started
1004
+ * @param target - The effect that is being triggered
1005
+ */
1006
+ beginChain: (_targets) => { },
1007
+ /**
1008
+ * Debug purpose: called when an effect chain is ended
1009
+ */
1010
+ endChain: () => { },
1011
+ garbageCollected: (_fn) => { },
1012
+ /**
1013
+ * Debug purpose: called when an object is touched
1014
+ * @param obj - The object that is touched
1015
+ * @param evolution - The type of change
1016
+ * @param props - The properties that changed
1017
+ * @param deps - The dependencies that changed
1018
+ */
1019
+ touched: (_obj, _evolution, _props, _deps) => { },
1020
+ /**
1021
+ * Debug purpose: called when an effect is skipped because it's already running
1022
+ * @param effect - The effect that is already running
1023
+ * @param runningChain - The array of effects from the detected one to the currently running one
1024
+ */
1025
+ skipRunningEffect: (_effect) => { },
1026
+ /**
1027
+ * Debug purpose: maximum effect chain (like call stack max depth)
1028
+ * Used to prevent infinite loops
1029
+ * @default 100
1030
+ */
1031
+ maxEffectChain: 100,
1032
+ /**
1033
+ * Maximum number of times an effect can be triggered by the same cause in a single batch
1034
+ * Used to detect aggressive re-computation or infinite loops
1035
+ * @default 10
1036
+ */
1037
+ maxTriggerPerBatch: 10,
1038
+ /**
1039
+ * Debug purpose: maximum effect reaction (like call stack max depth)
1040
+ * Used to prevent infinite loops
1041
+ * @default 'throw'
1042
+ */
1043
+ maxEffectReaction: 'throw',
1044
+ /**
1045
+ * Callback called when a memoization discrepancy is detected (debug only)
1046
+ * When defined, memoized functions will run a second time (untracked) to verify consistency.
1047
+ * If the untracked run returns a different value than the cached one, this callback is triggered.
1048
+ *
1049
+ * This is the primary tool for detecting missing reactive dependencies in computed values.
1050
+ *
1051
+ * @param cached - The value currently in the memoization cache
1052
+ * @param fresh - The value obtained by re-running the function untracked
1053
+ * @param fn - The memoized function itself
1054
+ * @param args - Arguments passed to the function
1055
+ *
1056
+ * @example
1057
+ * ```typescript
1058
+ * reactiveOptions.onMemoizationDiscrepancy = (cached, fresh, fn, args) => {
1059
+ * throw new Error(`Memoization discrepancy in ${fn.name}!`);
1060
+ * };
1061
+ * ```
1062
+ */
1063
+ onMemoizationDiscrepancy: undefined,
1064
+ /**
1065
+ * How to handle cycles detected in effect batches.
1066
+ *
1067
+ * - `'production'` (Default): High-performance mode. Disables dependency graph maintenance and
1068
+ * Topological Sorting in favor of a simple FIFO queue. Use this for trustworthy, acyclic UI code.
1069
+ * Cycle detection is heuristic (uses maxEffectChain execution counts).
1070
+ *
1071
+ * - `'development'`: Maintains direct dependency graph for early cycle detection during edge creation.
1072
+ * Catches cycles before effects execute via DFS check when adding edges. Throws immediately with
1073
+ * basic path information. Good balance of debugging help with moderate overhead.
1074
+ *
1075
+ * - `'debug'`: Full diagnostic mode with transitive closures and topological sorting.
1076
+ * Provides detailed cycle path reporting. Highest overhead but most informative for bug hunting.
1077
+ *
1078
+ * @default 'production'
1079
+ */
1080
+ cycleHandling: 'development',
1081
+ /**
1082
+ * Internal flag used by memoization discrepancy detector to avoid counting calls in tests
1083
+ * @warning Do not modify this flag manually, this flag is given by the engine
1084
+ */
1085
+ isVerificationRun: false,
1086
+ /**
1087
+ * Maximum depth for deep watching traversal
1088
+ * Used to prevent infinite recursion in circular references
1089
+ * @default 100
1090
+ */
1091
+ maxDeepWatchDepth: 100,
1092
+ /**
1093
+ * Only react on instance members modification (not inherited properties)
1094
+ * For instance, do not track class methods
1095
+ * @default true
1096
+ */
1097
+ instanceMembers: true,
1098
+ /**
1099
+ * Ignore accessors (getters and setters) and only track direct properties
1100
+ * @default true
1101
+ */
1102
+ ignoreAccessors: true,
1103
+ /**
1104
+ * Enable recursive touching when objects with the same prototype are replaced
1105
+ * When enabled, replacing an object with another of the same prototype triggers
1106
+ * recursive diffing instead of notifying parent effects
1107
+ * @default true
1108
+ */
1109
+ recursiveTouching: true,
1110
+ /**
1111
+ * Default async execution mode for effects that return Promises
1112
+ * - 'cancel': Cancel previous async execution when dependencies change (default, enables async zone)
1113
+ * - 'queue': Queue next execution to run after current completes (enables async zone)
1114
+ * - 'ignore': Ignore new executions while async work is running (enables async zone)
1115
+ * - false: Disable async zone and async mode handling (effects run concurrently)
1116
+ *
1117
+ * **When truthy:** Enables async zone (Promise.prototype wrapping) for automatic context
1118
+ * preservation in Promise callbacks. Warning: This modifies Promise.prototype globally.
1119
+ * Only enable if no other library modifies Promise.prototype.
1120
+ *
1121
+ * **When false:** Async zone is disabled. Use `tracked()` manually in Promise callbacks.
1122
+ *
1123
+ * Can be overridden per-effect via EffectOptions
1124
+ * @default 'cancel'
1125
+ */
1126
+ asyncMode: 'cancel',
1127
+ // biome-ignore lint/suspicious/noConsole: This is the whole point here
1128
+ warn: (...args) => console.warn(...args),
1129
+ /**
1130
+ * Configuration for the introspection system
1131
+ */
1132
+ introspection: {
1133
+ /**
1134
+ * Whether to keep a history of mutations for debugging
1135
+ * @default false
1136
+ */
1137
+ enableHistory: false,
1138
+ /**
1139
+ * Number of mutations to keep in history
1140
+ * @default 50
1141
+ */
1142
+ historySize: 50,
1143
+ },
1144
+ /**
1145
+ * Configuration for zone hooks - control which async APIs are hooked
1146
+ * Each option controls whether the corresponding async API is wrapped to preserve effect context
1147
+ * Only applies when asyncMode is enabled (truthy)
1148
+ * @deprecated Should take all when we made sure PIXI.create, Game.create, ... are -> .root()
1149
+ */
1150
+ zones: {
1151
+ /**
1152
+ * Hook setTimeout to preserve effect context
1153
+ * @default true
1154
+ */
1155
+ setTimeout: true,
1156
+ /**
1157
+ * Hook setInterval to preserve effect context
1158
+ * @default true
1159
+ */
1160
+ setInterval: true,
1161
+ /**
1162
+ * Hook requestAnimationFrame (runs in untracked context when hooked)
1163
+ * @default true
1164
+ */
1165
+ requestAnimationFrame: true,
1166
+ /**
1167
+ * Hook queueMicrotask to preserve effect context
1168
+ * @default true
1169
+ */
1170
+ queueMicrotask: true,
1171
+ },
1172
+ };
1173
+ function optionCall(name, ...args) {
1174
+ const fn = options[name];
1175
+ if (typeof fn !== 'function')
1176
+ return;
1177
+ try {
1178
+ ;
1179
+ fn(...args);
1180
+ }
1181
+ catch (error) {
1182
+ options.warn(`options.${name} threw`, error);
1183
+ }
1184
+ }
1185
+
1186
+ // Track which effects are watching which reactive objects for cleanup
1187
+ exports.effectToReactiveObjects = new WeakMap();
1188
+ // Track effects per reactive object and property
1189
+ exports.watchers = new WeakMap();
1190
+ // Track effect metadata and relationships
1191
+ let effectNodes = new WeakMap();
1192
+ function getEffectNode(effect) {
1193
+ let node = effectNodes.get(effect);
1194
+ if (!node) {
1195
+ node = {};
1196
+ effectNodes.set(effect, node);
1197
+ }
1198
+ return node;
1199
+ }
1200
+ // Track reverse mapping to ensure unicity: One Root -> One Function
1201
+ let reverseRoots = new WeakMap();
1202
+ function resetRegistry() {
1203
+ exports.effectToReactiveObjects = new WeakMap();
1204
+ exports.watchers = new WeakMap();
1205
+ effectNodes = new WeakMap();
1206
+ reverseRoots = new WeakMap();
1207
+ }
1208
+ /**
1209
+ * Marks a function with its root function for effect tracking
1210
+ * Enforces strict unicity: A root function can only identify ONE function.
1211
+ * @param fn - The function to mark
1212
+ * @param root - The root function
1213
+ * @returns The marked function
1214
+ */
1215
+ function markWithRoot(fn, root) {
1216
+ // Check for collision
1217
+ const existingRef = reverseRoots.get(root);
1218
+ const existing = existingRef?.deref();
1219
+ if (existing && existing !== fn) {
1220
+ const rootName = root.name || 'anonymous';
1221
+ const existingName = existing.name || 'anonymous';
1222
+ const fnName = fn.name || 'anonymous';
1223
+ throw new Error(`[reactive] Abusive Shared Root detected: Root '${rootName}' is already identifying function '${existingName}'. ` +
1224
+ `Cannot reuse it for '${fnName}'. Shared roots cause lost updates and broken identity logic.`);
1225
+ }
1226
+ // Always update the map so subsequent checks find this one
1227
+ // (Last writer wins for the check)
1228
+ reverseRoots.set(root, new WeakRef(fn));
1229
+ // Mark fn with the new root
1230
+ return Object.defineProperty(fn, rootFunction, {
1231
+ value: getRoot(root),
1232
+ writable: false,
1233
+ });
1234
+ }
1235
+ /**
1236
+ * Gets the root function of a function for effect tracking
1237
+ * @param fn - The function to get the root of
1238
+ * @returns The root function
1239
+ */
1240
+ function getRoot(fn) {
1241
+ while (fn && rootFunction in fn)
1242
+ fn = fn[rootFunction];
1243
+ return fn;
1244
+ }
1245
+
1246
+ var _ZoneAggregator_zones;
1247
+ function isu(z) {
1248
+ return z;
1249
+ }
1250
+ class AZone {
1251
+ enter(value) {
1252
+ const prev = this.active;
1253
+ this.active = value;
1254
+ return prev;
1255
+ }
1256
+ leave(entered) {
1257
+ this.active = entered;
1258
+ }
1259
+ with(value, fn) {
1260
+ const entered = this.enter(value);
1261
+ let res;
1262
+ try {
1263
+ res = fn();
1264
+ }
1265
+ finally {
1266
+ this.leave(entered);
1267
+ }
1268
+ // [HACK]: Sanitization
1269
+ // See BROWSER_ASYNC_POLYFILL.md
1270
+ return asyncCore.asyncHooks.sanitizePromise(res);
1271
+ }
1272
+ root(fn) {
1273
+ const prev = this.enter();
1274
+ try {
1275
+ return fn();
1276
+ }
1277
+ finally {
1278
+ this.leave(prev);
1279
+ }
1280
+ }
1281
+ get zoned() {
1282
+ const active = this.active;
1283
+ return named(`${this}@${active}`, (fn) => this.with(active, fn));
1284
+ }
1285
+ }
1286
+ class Zone extends AZone {
1287
+ }
1288
+ class ZoneHistory extends AZone {
1289
+ has(value) {
1290
+ return this.history.has(value);
1291
+ }
1292
+ some(predicate) {
1293
+ for (const value of this.history)
1294
+ if (predicate(value))
1295
+ return true;
1296
+ return false;
1297
+ }
1298
+ constructor(controlled = new Zone()) {
1299
+ super();
1300
+ this.controlled = controlled;
1301
+ this.history = new Set();
1302
+ const self = this;
1303
+ this.present = Object.create(controlled, Object.getOwnPropertyDescriptors({
1304
+ get active() {
1305
+ return controlled.active;
1306
+ },
1307
+ set active(value) {
1308
+ controlled.active = value;
1309
+ },
1310
+ enter(value) {
1311
+ if (value && self.history.has(value))
1312
+ throw new Error('ZoneHistory: re-entering historical zone');
1313
+ if (value !== undefined)
1314
+ self.history.add(value);
1315
+ return { added: value, entered: isu(controlled).enter(value) };
1316
+ },
1317
+ leave(entered) {
1318
+ if (entered.added !== undefined)
1319
+ self.history.delete(entered.added);
1320
+ return isu(controlled).leave(entered.entered);
1321
+ },
1322
+ }));
1323
+ }
1324
+ get active() {
1325
+ return { present: this.controlled.active, history: new Set(this.history) };
1326
+ }
1327
+ set active(value) {
1328
+ this.history = value?.history ? new Set(value.history) : new Set();
1329
+ this.controlled.active = value?.present;
1330
+ }
1331
+ }
1332
+ class ZoneAggregator extends AZone {
1333
+ constructor(...zones) {
1334
+ super();
1335
+ _ZoneAggregator_zones.set(this, new Set());
1336
+ for (const z of zones)
1337
+ __classPrivateFieldGet(this, _ZoneAggregator_zones, "f").add(z);
1338
+ }
1339
+ get active() {
1340
+ const rv = new Map();
1341
+ for (const z of __classPrivateFieldGet(this, _ZoneAggregator_zones, "f"))
1342
+ if (z.active !== undefined)
1343
+ rv.set(z, z.active);
1344
+ return rv;
1345
+ }
1346
+ set active(value) {
1347
+ for (const z of __classPrivateFieldGet(this, _ZoneAggregator_zones, "f"))
1348
+ z.active = value?.get(z);
1349
+ }
1350
+ enter(value) {
1351
+ const entered = new Map();
1352
+ for (const z of __classPrivateFieldGet(this, _ZoneAggregator_zones, "f")) {
1353
+ const v = value?.get(z);
1354
+ entered.set(z, isu(z).enter(v));
1355
+ }
1356
+ return entered;
1357
+ }
1358
+ leave(entered) {
1359
+ for (const z of __classPrivateFieldGet(this, _ZoneAggregator_zones, "f"))
1360
+ isu(z).leave(entered.get(z));
1361
+ }
1362
+ add(z) {
1363
+ __classPrivateFieldGet(this, _ZoneAggregator_zones, "f").add(z);
1364
+ }
1365
+ delete(z) {
1366
+ __classPrivateFieldGet(this, _ZoneAggregator_zones, "f").delete(z);
1367
+ }
1368
+ clear() {
1369
+ __classPrivateFieldGet(this, _ZoneAggregator_zones, "f").clear();
1370
+ }
1371
+ }
1372
+ _ZoneAggregator_zones = new WeakMap();
1373
+ const asyncZone = tag('async', new ZoneAggregator());
1374
+ asyncCore.asyncHooks.addHook(() => {
1375
+ const zone = asyncZone.active;
1376
+ return () => {
1377
+ const prev = asyncZone.active;
1378
+ asyncZone.active = zone;
1379
+ return () => (asyncZone.active = prev);
1380
+ };
1381
+ });
1382
+
1383
+ const effectHistory = tag('effectHistory', new ZoneHistory());
1384
+ tag('effectHistory.present', effectHistory.present);
1385
+ asyncZone.add(effectHistory);
1386
+ /**
1387
+ * Aggregator for zones that need to be tracked along effects.
1388
+ * ie. in each effect, the active zone of the given zoning will be the one active at effect's definition
1389
+ */
1390
+ const effectAggregator = tag('effectAggregator', new ZoneAggregator(effectHistory.present));
1391
+ function isRunning(effect) {
1392
+ const root = getRoot(effect);
1393
+ return effectHistory.some((e) => getRoot(e) === root);
1394
+ }
1395
+ function getActiveEffect() {
1396
+ return effectHistory.present.active;
1397
+ }
1398
+ /**
1399
+ * ADD a cleanup function to an object using the cleanup symbol.
1400
+ * The cleanup function will be called when the object needs to be disposed.
1401
+ *
1402
+ * Note: most of the time, you don't need to use this function directly.
1403
+ * 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.
1404
+ *
1405
+ * @param obj - The object to attach the cleanup function to
1406
+ * @param cleanupFn - The cleanup function to attach
1407
+ * @returns The object with the cleanup function attached
1408
+ */
1409
+ function cleanedBy(obj, cleanupFn) {
1410
+ const oldCleanup = obj[cleanup];
1411
+ return Object.defineProperty(obj, cleanup, {
1412
+ value: oldCleanup
1413
+ ? Object.defineProperties(() => {
1414
+ oldCleanup();
1415
+ cleanupFn();
1416
+ }, {
1417
+ [stopped]: { get: () => oldCleanup[stopped] || cleanupFn[stopped] },
1418
+ })
1419
+ : cleanupFn,
1420
+ writable: false,
1421
+ enumerable: false,
1422
+ configurable: true,
1423
+ });
1424
+ }
1425
+ //#region greedy caching
1426
+ /**
1427
+ * Creates a derived value that automatically recomputes when dependencies change
1428
+ * @param compute - Function that computes the derived value
1429
+ * @returns Object with value and cleanup function
1430
+ */
1431
+ function derived(compute) {
1432
+ const rv = { value: undefined };
1433
+ return cleanedBy(rv, untracked(() => effect(function derivedEffect(access) {
1434
+ rv.value = compute(access);
1435
+ })));
1436
+ }
1437
+
1438
+ const effectMarker = {
1439
+ enter: 'effect:enter',
1440
+ leave: 'effect:leave'
1441
+ };
1442
+ /**
1443
+ * Parses a single stack line into a structured frame.
1444
+ * @param line - A line from Error.stack
1445
+ */
1446
+ function parseStackLine(line) {
1447
+ // Node.js format: " at functionName (file:line:column)"
1448
+ // or " at file:line:column"
1449
+ const nodeMatch = line.match(/^\s*at\s+(?:(.+?)\s+\()?(?:(.+?):(\d+):(\d+))\)?$/);
1450
+ // Browser format (Firefox/Safari): "functionName@file:line:column" or "file:line:column"
1451
+ // Chrome/Edge use Node-like format but without "at" sometimes or with different prefixes
1452
+ const browserMatch = line.match(/(?:(.+?)(?:\@|\(?))?(?:(.+?):(\d+):(\d+))(?:\@|\)?)$/);
1453
+ const match = nodeMatch || browserMatch;
1454
+ if (!match)
1455
+ return null;
1456
+ const [, functionName = 'anonymous', fileName, lineNumber, columnNumber] = match;
1457
+ return {
1458
+ functionName: functionName.trim(),
1459
+ fileName,
1460
+ lineNumber: parseInt(lineNumber, 10),
1461
+ columnNumber: parseInt(columnNumber, 10),
1462
+ raw: line.trim(),
1463
+ };
1464
+ }
1465
+ let internalFile;
1466
+ /**
1467
+ * Gets the current call stack
1468
+ * @param skipFrames - Number of frames to skip
1469
+ * @param error - Optional error to use as source of stack
1470
+ */
1471
+ function getStackFrame(error = new Error()) {
1472
+ if (!error.stack)
1473
+ return [];
1474
+ const lines = error.stack.split('\n');
1475
+ const lastLine = lines.findIndex((line) => line.includes(effectMarker.enter));
1476
+ if (lastLine !== -1)
1477
+ lines.splice(lastLine);
1478
+ const firstLine = lines.findLastIndex((line) => line.includes(effectMarker.leave));
1479
+ if (firstLine !== -1)
1480
+ lines.splice(0, firstLine + 1);
1481
+ else {
1482
+ // Dynamically identify the library's internal files if not already done
1483
+ if (!internalFile && lines[1]) {
1484
+ const selfFrame = parseStackLine(lines[1]);
1485
+ if (selfFrame) {
1486
+ internalFile = selfFrame.fileName;
1487
+ }
1488
+ }
1489
+ // Determine the "base" directory of the library to skip other internal files
1490
+ // We look for "src" or "dist" to be more specific than just the project root
1491
+ const srcIndex = internalFile ? internalFile.lastIndexOf('/src/') : -1;
1492
+ const distIndex = internalFile ? internalFile.lastIndexOf('/dist/') : -1;
1493
+ internalFile ? (srcIndex !== -1 ? internalFile.substring(0, srcIndex + 5) :
1494
+ (distIndex !== -1 ? internalFile.substring(0, distIndex + 6) :
1495
+ internalFile.substring(0, internalFile.lastIndexOf('/') + 1))) : undefined;
1496
+ let l;
1497
+ for (l = 1; l < lines.length; l++) {
1498
+ const frame = parseStackLine(lines[l]);
1499
+ if (!frame)
1500
+ continue;
1501
+ // Robust skipping: if we are still in the internal area, skip it.
1502
+ const isInternal = /Lineage$/.test(frame.functionName) ||
1503
+ frame.functionName === 'eval' ||
1504
+ [`getStackFrame`, `captureLineage`].includes(frame.functionName);
1505
+ if (!isInternal)
1506
+ break;
1507
+ }
1508
+ lines.splice(0, l);
1509
+ }
1510
+ return lines.map(parseStackLine).filter(Boolean);
1511
+ }
1512
+ /**
1513
+ * Traces the lineage of the current execution through nested effects
1514
+ * @param effect - Starting effect (defaults to active effect)
1515
+ */
1516
+ function getLineage(effect) {
1517
+ const currentEffect = effect ?? getActiveEffect();
1518
+ const currentStack = getStackFrame(); // Robustly skips internal mutts frames
1519
+ const segments = [];
1520
+ if (!currentEffect) {
1521
+ segments.push({
1522
+ effectName: 'root',
1523
+ stack: filterNodeModules(currentStack),
1524
+ });
1525
+ return segments;
1526
+ }
1527
+ let current = currentEffect;
1528
+ let lastStack = currentStack;
1529
+ while (current) {
1530
+ const rootFn = getRoot(current);
1531
+ if (!rootFn.name)
1532
+ debugger;
1533
+ const effectName = rootFn.name || 'anonymous';
1534
+ const filteredStack = filterNodeModules(lastStack);
1535
+ segments.push({
1536
+ effectName,
1537
+ stack: filteredStack,
1538
+ });
1539
+ // Move to parent
1540
+ const node = getEffectNode(current);
1541
+ const parent = node.parent;
1542
+ const creationStack = getEffectNode(current).creationStack;
1543
+ if (parent) {
1544
+ current = parent;
1545
+ lastStack = creationStack ?? [];
1546
+ }
1547
+ else if (creationStack) {
1548
+ segments.push({
1549
+ effectName: 'root',
1550
+ stack: filterNodeModules(creationStack),
1551
+ });
1552
+ break;
1553
+ }
1554
+ else {
1555
+ break;
1556
+ }
1557
+ }
1558
+ return segments;
1559
+ }
1560
+ /**
1561
+ * Filters out node_modules frames and groups them
1562
+ * @param frames - Array of stack frames
1563
+ */
1564
+ function filterNodeModules(frames) {
1565
+ const result = [];
1566
+ let inNodeModules = false;
1567
+ for (const frame of frames) {
1568
+ const isNodeModule = frame.fileName.includes('/node_modules/');
1569
+ if (isNodeModule && !inNodeModules) {
1570
+ // Start of node_modules block
1571
+ inNodeModules = true;
1572
+ result.push({
1573
+ functionName: '...node_modules...',
1574
+ fileName: '[filtered]',
1575
+ lineNumber: 0,
1576
+ columnNumber: 0,
1577
+ raw: ' at ...node_modules...'
1578
+ });
1579
+ }
1580
+ else if (!isNodeModule && inNodeModules) {
1581
+ // End of node_modules block
1582
+ inNodeModules = false;
1583
+ result.push(frame);
1584
+ }
1585
+ else if (!isNodeModule) {
1586
+ // Regular frame
1587
+ result.push(frame);
1588
+ }
1589
+ // Skip frames inside node_modules
1590
+ }
1591
+ return result;
1592
+ }
1593
+ /**
1594
+ * Formats lineage segments into a single stack-like string
1595
+ * @param segments - Lineage segments
1596
+ */
1597
+ function formatLineage(segments) {
1598
+ const result = [];
1599
+ for (let i = 0; i < segments.length; i++) {
1600
+ const segment = segments[i];
1601
+ if (i > 0) {
1602
+ result.push(` --- effect: ${segments[i - 1].effectName} ---`);
1603
+ }
1604
+ for (const frame of segment.stack) {
1605
+ result.push(` ${frame.raw}`);
1606
+ }
1607
+ }
1608
+ return result.join('\n');
1609
+ }
1610
+ /**
1611
+ * Logs lineage segments to console with grouping
1612
+ * @param segments - Lineage segments
1613
+ */
1614
+ function nodeLineage(segments) {
1615
+ console.groupCollapsed(`🦴 Effect Lineage Trace (${segments.length} segment${segments.length === 1 ? '' : 's'})`);
1616
+ for (let i = 0; i < segments.length; i++) {
1617
+ const segment = segments[i];
1618
+ // Add segment header
1619
+ const isLast = i === segments.length - 1;
1620
+ const prefix = i === 0 ? '📍' : isLast ? '└─' : '├─';
1621
+ console.groupCollapsed(`${prefix} Effect: ${segment.effectName}`);
1622
+ // Add stack frames
1623
+ for (let j = 0; j < segment.stack.length; j++) {
1624
+ const frame = segment.stack[j];
1625
+ const isLastFrame = j === segment.stack.length - 1;
1626
+ const framePrefix = isLastFrame ? '└─' : '├─';
1627
+ if (frame.functionName === '...node_modules...') {
1628
+ console.log(`%c${framePrefix} ${frame.functionName}`, 'color: #888; font-style: italic;');
1629
+ }
1630
+ else {
1631
+ const fnStyle = frame.functionName === 'anonymous' ? 'color: #888;' : 'color: #1a7f37; font-weight: bold;';
1632
+ const fileStyle = 'color: #0550ae;';
1633
+ console.log(`%c${framePrefix} %c${frame.functionName} %c(${frame.fileName}:${frame.lineNumber}:${frame.columnNumber})`, 'color: #888;', fnStyle, fileStyle);
1634
+ }
1635
+ }
1636
+ console.groupEnd();
1637
+ }
1638
+ console.groupEnd();
1639
+ }
1640
+ /**
1641
+ * Legacy version of nodeLineage that returns a formatted string (useful for comparison or logs)
1642
+ * @param segments - Lineage segments
1643
+ * @deprecated TODO: remove me and all the code running around
1644
+ */
1645
+ function nodeLineageLegacy(segments) {
1646
+ // ANSI color codes for Node.js terminal
1647
+ const colors = {
1648
+ reset: '\x1b[0m',
1649
+ bright: '\x1b[1m',
1650
+ dim: '\x1b[2m',
1651
+ green: '\x1b[32m',
1652
+ yellow: '\x1b[33m',
1653
+ blue: '\x1b[34m',
1654
+ magenta: '\x1b[35m',
1655
+ cyan: '\x1b[36m',
1656
+ gray: '\x1b[90m',
1657
+ };
1658
+ const result = [];
1659
+ result.push(`${colors.bright}${colors.cyan}🦴 Effect Lineage Trace (${segments.length} segments)${colors.reset}`);
1660
+ for (let i = 0; i < segments.length; i++) {
1661
+ const segment = segments[i];
1662
+ const isLast = i === segments.length - 1;
1663
+ const prefix = i === 0 ? '📍' : isLast ? '└─' : '├─';
1664
+ const connector = isLast ? ' ' : '│ ';
1665
+ result.push(`${colors.gray}${connector}${colors.reset}${colors.bright}${colors.magenta}${prefix} Effect: ${segment.effectName}${colors.reset}`);
1666
+ for (let j = 0; j < segment.stack.length; j++) {
1667
+ const frame = segment.stack[j];
1668
+ const framePrefix = j === segment.stack.length - 1 ? ' └─' : ' ├─';
1669
+ if (frame.functionName === '...node_modules...') {
1670
+ result.push(`${colors.gray} ${connector}${colors.reset}${colors.dim}${framePrefix} ${colors.yellow}${frame.functionName}${colors.reset}`);
1671
+ }
1672
+ else {
1673
+ const fnColor = frame.functionName === 'anonymous' ? colors.gray : colors.green;
1674
+ result.push(`${colors.gray} ${connector}${colors.reset}${colors.dim}${framePrefix}${colors.reset} ${fnColor}${frame.functionName}${colors.reset} ${colors.gray}(${colors.reset}${colors.blue}${frame.fileName}:${frame.lineNumber}:${frame.columnNumber}${colors.reset}${colors.gray})${colors.reset}`);
1675
+ }
1676
+ }
1677
+ if (i < segments.length - 1)
1678
+ result.push('');
1679
+ }
1680
+ return result.join('\n');
1681
+ }
1682
+ /**
1683
+ * Captures and logs lineage to console
1684
+ */
1685
+ function captureNodeLineage() {
1686
+ nodeLineage(getLineage());
1687
+ }
1688
+ /**
1689
+ * Custom formatter for Chrome DevTools to render lineage data nicely.
1690
+ */
1691
+ const lineageFormatter = {
1692
+ header: (obj) => {
1693
+ if (obj && obj.__isLineage__) {
1694
+ // Try to detect DevTools theme - default to dark colors if uncertain
1695
+ const isDark = typeof window !== 'undefined' && window.matchMedia?.('(prefers-color-scheme: dark)').matches;
1696
+ const headerColor = isDark ? '#cd9d5d' : '#704214';
1697
+ return [
1698
+ 'span',
1699
+ { style: `color: ${headerColor}; font-weight: bold;` },
1700
+ `🦴 Effect Lineage (${obj.segments.length} segments)`,
1701
+ ];
1702
+ }
1703
+ return null;
1704
+ },
1705
+ hasBody: (obj) => obj && obj.__isLineage__,
1706
+ body: (obj) => {
1707
+ if (!obj || !obj.__isLineage__)
1708
+ return null;
1709
+ const segments = obj.segments;
1710
+ // Try to detect DevTools theme
1711
+ const isDark = typeof window !== 'undefined' && window.matchMedia?.('(prefers-color-scheme: dark)').matches;
1712
+ const colors = isDark ? {
1713
+ frameText: '#ccc',
1714
+ functionName: '#ffffff',
1715
+ segmentBg: '#2d2d2d',
1716
+ } : {
1717
+ frameText: '#555',
1718
+ functionName: '#222',
1719
+ segmentBg: '#eee',
1720
+ };
1721
+ const children = segments.map((segment, i) => {
1722
+ const frames = segment.stack.map((frame) => [
1723
+ 'div',
1724
+ { style: `margin-left: 20px; color: ${colors.frameText}; font-family: monospace; font-size: 11px;` },
1725
+ ['span', { style: `color: ${colors.functionName};` }, `at ${frame.functionName} `],
1726
+ ['span', {}, `${frame.fileName}:${frame.lineNumber}:${frame.columnNumber}`],
1727
+ ]);
1728
+ const segmentHeader = [
1729
+ 'div',
1730
+ { style: `margin-top: 5px; padding: 2px 5px; background: ${colors.segmentBg}; border-radius: 3px; font-weight: bold;` },
1731
+ i === 0 ? `📍 Current: ${segment.effectName}` : `↖ Effect: ${segment.effectName}`,
1732
+ ];
1733
+ return ['div', {}, segmentHeader, ...frames];
1734
+ });
1735
+ return ['div', { style: 'padding: 5px; line-height: 1.4;' }, ...children];
1736
+ },
1737
+ };
1738
+ /**
1739
+ * Wraps lineage data in a way that the Chrome Formatter can recognize.
1740
+ */
1741
+ function wrapLineageForDebug(segments) {
1742
+ return {
1743
+ __isLineage__: true,
1744
+ segments,
1745
+ toString: () => formatLineage(segments),
1746
+ };
1747
+ }
1748
+
1749
+ // Track which objects contain which other objects (back-references)
1750
+ const objectParents = new WeakMap();
1751
+ // Track which objects have deep watchers
1752
+ const objectsWithDeepWatchers = new WeakSet();
1753
+ // Track deep watchers per object
1754
+ const deepWatchers = new WeakMap();
1755
+ // Track which effects are doing deep watching
1756
+ const effectToDeepWatchedObjects = new WeakMap();
1757
+ /**
1758
+ * Add a back-reference from child to parent
1759
+ */
1760
+ function addBackReference(child, parent, prop) {
1761
+ let parents = objectParents.get(child);
1762
+ if (!parents) {
1763
+ parents = new Set();
1764
+ objectParents.set(child, parents);
1765
+ }
1766
+ parents.add({ parent, prop });
1767
+ }
1768
+ /**
1769
+ * Remove a back-reference from child to parent
1770
+ */
1771
+ function removeBackReference(child, parent, prop) {
1772
+ const parents = objectParents.get(child);
1773
+ if (parents) {
1774
+ for (const entry of parents) {
1775
+ if (entry.parent === parent && entry.prop === prop) {
1776
+ parents.delete(entry);
1777
+ break;
1778
+ }
1779
+ }
1780
+ if (parents.size === 0) {
1781
+ objectParents.delete(child);
1782
+ }
1783
+ }
1784
+ }
1785
+ /**
1786
+ * Check if an object needs back-references (has deep watchers or parents with deep watchers)
1787
+ */
1788
+ function needsBackReferences(obj) {
1789
+ // Fast path: check if object itself has deep watchers
1790
+ if (objectsWithDeepWatchers.has(obj))
1791
+ return true;
1792
+ // Slow path: check if any parent has deep watchers (recursive)
1793
+ return hasParentWithDeepWatchers(obj);
1794
+ }
1795
+ /**
1796
+ * Bubble up changes through the back-reference chain
1797
+ */
1798
+ function bubbleUpChange(changedObject, evolution) {
1799
+ const parents = objectParents.get(changedObject);
1800
+ if (!parents)
1801
+ return;
1802
+ for (const { parent } of parents) {
1803
+ // Trigger deep watchers on parent
1804
+ const parentDeepWatchers = deepWatchers.get(parent);
1805
+ if (parentDeepWatchers)
1806
+ for (const watcher of parentDeepWatchers)
1807
+ batch(watcher);
1808
+ // Continue bubbling up
1809
+ bubbleUpChange(parent);
1810
+ }
1811
+ }
1812
+ function hasParentWithDeepWatchers(obj) {
1813
+ const parents = objectParents.get(obj);
1814
+ if (!parents)
1815
+ return false;
1816
+ for (const { parent } of parents) {
1817
+ if (objectsWithDeepWatchers.has(parent))
1818
+ return true;
1819
+ if (hasParentWithDeepWatchers(parent))
1820
+ return true;
1821
+ }
1822
+ return false;
1823
+ }
1824
+
1825
+ const objectToProxy = new WeakMap();
1826
+ const proxyToObject = new WeakMap();
1827
+ function storeProxyRelationship(target, proxy) {
1828
+ objectToProxy.set(target, proxy);
1829
+ proxyToObject.set(proxy, target);
1830
+ }
1831
+ function getExistingProxy(target) {
1832
+ return objectToProxy.get(target);
1833
+ }
1834
+ function trackProxyObject(proxy, target) {
1835
+ proxyToObject.set(proxy, target);
1836
+ }
1837
+ function unwrap(obj) {
1838
+ let current = obj;
1839
+ while (current && typeof current === 'object' && current !== null && proxyToObject.has(current)) {
1840
+ current = proxyToObject.get(current);
1841
+ }
1842
+ return current;
1843
+ }
1844
+ function isReactive(obj) {
1845
+ return proxyToObject.has(obj);
1846
+ }
1847
+
1848
+ const states = new WeakMap();
1849
+ function addState(obj, evolution) {
1850
+ obj = unwrap(obj);
1851
+ const next = {};
1852
+ const state = getState(obj);
1853
+ if (state)
1854
+ Object.assign(state, { evolution, next });
1855
+ states.set(obj, next);
1856
+ }
1857
+ /**
1858
+ * Gets the current state of a reactive object for evolution tracking
1859
+ * @param obj - The reactive object
1860
+ * @returns The current state object
1861
+ */
1862
+ function getState(obj) {
1863
+ obj = unwrap(obj);
1864
+ let state = states.get(obj);
1865
+ if (!state) {
1866
+ state = {};
1867
+ states.set(obj, state);
1868
+ }
1869
+ return state;
1870
+ }
1871
+ function collectEffects(obj, evolution, effects, objectWatchers, ...keyChains) {
1872
+ const sourceEffect = getActiveEffect();
1873
+ for (const keys of keyChains)
1874
+ for (const key of keys) {
1875
+ const deps = objectWatchers.get(key);
1876
+ // console.log(`[DEBUG] collectEffects: checking ${String(key)}. Found deps: ${deps ? deps.size : 'none'}`)
1877
+ if (deps)
1878
+ for (const effect of deps) {
1879
+ // console.log(`[DEBUG] collectEffects: found dependency ${effect.name || 'anonymous'} for ${String(key)}`)
1880
+ const runningChain = isRunning(effect);
1881
+ if (runningChain) {
1882
+ optionCall('skipRunningEffect', effect);
1883
+ continue;
1884
+ }
1885
+ if (!effects.has(effect)) {
1886
+ effects.add(effect);
1887
+ if (!hasBatched(effect))
1888
+ recordActivation(effect, obj, evolution, key);
1889
+ }
1890
+ recordTriggerLink(sourceEffect, effect, obj, key, evolution);
1891
+ }
1892
+ }
1893
+ }
1894
+ /**
1895
+ * Triggers effects for a single property change
1896
+ * @param obj - The object that changed
1897
+ * @param evolution - The type of change
1898
+ * @param prop - The property that changed
1899
+ */
1900
+ function touched1(obj, evolution, prop) {
1901
+ touched(obj, evolution, [prop]);
1902
+ }
1903
+ /**
1904
+ * Triggers effects for property changes
1905
+ * @param obj - The object that changed
1906
+ * @param evolution - The type of change
1907
+ * @param props - The properties that changed
1908
+ */
1909
+ function touched(obj, evolution, props) {
1910
+ obj = unwrap(obj);
1911
+ addState(obj, evolution);
1912
+ const objectWatchers = exports.watchers.get(obj);
1913
+ if (objectWatchers) {
1914
+ // Note: we have to collect effects to remove duplicates in the specific case when no batch is running
1915
+ const effects = new Set();
1916
+ if (props)
1917
+ collectEffects(obj, evolution, effects, objectWatchers, [allProps], props);
1918
+ else
1919
+ collectEffects(obj, evolution, effects, objectWatchers, objectWatchers.keys());
1920
+ optionCall('touched', obj, evolution, props, effects);
1921
+ batch(Array.from(effects));
1922
+ }
1923
+ // Bubble up changes if this object has deep watchers
1924
+ if (objectsWithDeepWatchers.has(obj)) {
1925
+ bubbleUpChange(obj);
1926
+ }
1927
+ }
1928
+ /**
1929
+ * Triggers only opaque effects for property changes
1930
+ * Used by deep-touch to ensure opaque listeners are notified even when deep optimization is active
1931
+ */
1932
+ function touchedOpaque(obj, evolution, prop) {
1933
+ obj = unwrap(obj);
1934
+ const objectWatchers = exports.watchers.get(obj);
1935
+ if (!objectWatchers)
1936
+ return;
1937
+ const deps = objectWatchers.get(prop);
1938
+ if (!deps)
1939
+ return;
1940
+ const effects = new Set();
1941
+ const sourceEffect = getActiveEffect();
1942
+ for (const effect of deps) {
1943
+ const node = getEffectNode(effect);
1944
+ if (!node.isOpaque)
1945
+ continue;
1946
+ const runningChain = isRunning(effect);
1947
+ if (runningChain) {
1948
+ optionCall('skipRunningEffect', effect);
1949
+ continue;
1950
+ }
1951
+ effects.add(effect);
1952
+ recordActivation(effect, obj, evolution, prop);
1953
+ recordTriggerLink(sourceEffect, effect, obj, prop, evolution);
1954
+ }
1955
+ if (effects.size > 0) {
1956
+ optionCall('touched', obj, evolution, [prop], effects);
1957
+ batch(Array.from(effects));
1958
+ }
1959
+ }
1960
+
1961
+ const nonReactiveObjects = new WeakSet();
1962
+ const immutables = new Set();
1963
+ const absent = Symbol('absent');
1964
+ function markNonReactive(...obj) {
1965
+ for (const o of obj) {
1966
+ try {
1967
+ Object.defineProperty(o, nonReactiveMark, {
1968
+ value: true,
1969
+ writable: false,
1970
+ enumerable: false,
1971
+ configurable: false,
1972
+ });
1973
+ }
1974
+ catch { }
1975
+ if (!(nonReactiveMark in o))
1976
+ nonReactiveObjects.add(o);
1977
+ }
1978
+ return obj[0];
1979
+ }
1980
+ function nonReactiveClass(...cls) {
1981
+ for (const c of cls)
1982
+ if (c)
1983
+ c.prototype[nonReactiveMark] = true;
1984
+ return cls[0];
1985
+ }
1986
+ function isNonReactive(obj) {
1987
+ if (obj === null || typeof obj !== 'object')
1988
+ return true;
1989
+ if (nonReactiveObjects.has(obj))
1990
+ return true;
1991
+ if (obj[nonReactiveMark])
1992
+ return true;
1993
+ for (const fn of immutables)
1994
+ if (fn(obj))
1995
+ return true;
1996
+ return false;
1997
+ }
1998
+ function registerNativeReactivity(originalClass, reactiveClass) {
1999
+ originalClass.prototype[nativeReactive] = reactiveClass;
2000
+ nonReactiveClass(reactiveClass);
2001
+ }
2002
+ nonReactiveClass(Date, RegExp, Error, Promise, Function);
2003
+ if (typeof window !== 'undefined') {
2004
+ markNonReactive(window, document);
2005
+ nonReactiveClass(Node, Element, HTMLElement, EventTarget);
2006
+ }
2007
+
2008
+ function isObject(value) {
2009
+ return typeof value === 'object' && value !== null;
2010
+ }
2011
+ function isObjectLike(value) {
2012
+ return isObject(value);
2013
+ }
2014
+ function getPrototypeToken(value) {
2015
+ if (!isObjectLike(value))
2016
+ return undefined;
2017
+ if (Array.isArray(value))
2018
+ return Array.prototype;
2019
+ try {
2020
+ return value.constructor;
2021
+ }
2022
+ catch {
2023
+ return undefined;
2024
+ }
2025
+ }
2026
+ function shouldRecurseTouch(oldValue, newValue) {
2027
+ if (oldValue === newValue)
2028
+ return false;
2029
+ if (!isObjectLike(oldValue) || !isObjectLike(newValue))
2030
+ return false;
2031
+ if (isNonReactive(oldValue) || isNonReactive(newValue))
2032
+ return false;
2033
+ return getPrototypeToken(oldValue) === getPrototypeToken(newValue);
2034
+ }
2035
+ /**
2036
+ * Centralized function to handle property change notifications with optional recursive touch
2037
+ * @param targetObj - The object whose property changed
2038
+ * @param prop - The property that changed
2039
+ * @param oldValue - The old value (before change)
2040
+ * @param newValue - The new value (after change)
2041
+ * @param hadProperty - Whether the property existed before (for add vs set)
2042
+ */
2043
+ function notifyPropertyChange(targetObj, prop, oldValue, newValue, hadProperty) {
2044
+ const evolution = { type: hadProperty ? 'set' : 'add', prop };
2045
+ if (options.recursiveTouching &&
2046
+ oldValue !== undefined &&
2047
+ shouldRecurseTouch(oldValue, newValue)) {
2048
+ const unwrappedObj = unwrap(targetObj);
2049
+ const origin = { obj: unwrappedObj, prop };
2050
+ // Deep touch: only notify nested property changes with origin filtering
2051
+ // Don't notify direct property change - the whole point is to avoid parent effects re-running
2052
+ dispatchNotifications(recursiveTouch(oldValue, newValue, new WeakMap(), [], origin));
2053
+ // Notify opaque listeners (like memoize) that always want to know about identity changes
2054
+ touchedOpaque(targetObj, evolution, prop);
2055
+ }
2056
+ else {
2057
+ touched1(targetObj, evolution, prop);
2058
+ }
2059
+ }
2060
+ function hasVisitedPair(visited, oldObj, newObj) {
2061
+ let mapped = visited.get(oldObj);
2062
+ if (!mapped) {
2063
+ mapped = new WeakSet();
2064
+ visited.set(oldObj, mapped);
2065
+ }
2066
+ if (mapped.has(newObj))
2067
+ return true;
2068
+ mapped.add(newObj);
2069
+ return false;
2070
+ }
2071
+ function collectObjectKeys(obj) {
2072
+ const keys = new Set(Reflect.ownKeys(obj));
2073
+ let proto = Object.getPrototypeOf(obj);
2074
+ // Continue walking while prototype exists and doesn't have its own constructor
2075
+ // This stops at Object.prototype (has own constructor) and class prototypes (have own constructor)
2076
+ // but continues for data prototypes (Object.create({}), Object.create(instance), etc.)
2077
+ while (proto && !Object.hasOwn(proto, 'constructor')) {
2078
+ for (const key of Reflect.ownKeys(proto))
2079
+ keys.add(key);
2080
+ proto = Object.getPrototypeOf(proto);
2081
+ }
2082
+ return keys;
2083
+ }
2084
+ function recursiveTouch(oldValue, newValue, visited = new WeakMap(), notifications = [], origin) {
2085
+ if (!shouldRecurseTouch(oldValue, newValue))
2086
+ return notifications;
2087
+ if (!isObjectLike(oldValue) || !isObjectLike(newValue))
2088
+ return notifications;
2089
+ if (hasVisitedPair(visited, oldValue, newValue))
2090
+ return notifications;
2091
+ if (Array.isArray(oldValue) && Array.isArray(newValue)) {
2092
+ diffArrayElements(oldValue, newValue, visited, notifications, origin);
2093
+ return notifications;
2094
+ }
2095
+ diffObjectProperties(oldValue, newValue, visited, notifications, origin);
2096
+ return notifications;
2097
+ }
2098
+ function diffArrayElements(oldArray, newArray, _visited, notifications, origin) {
2099
+ const local = [];
2100
+ const oldLength = oldArray.length;
2101
+ const newLength = newArray.length;
2102
+ const max = Math.max(oldLength, newLength);
2103
+ for (let index = 0; index < max; index++) {
2104
+ const hasOld = index < oldLength;
2105
+ const hasNew = index < newLength;
2106
+ if (hasOld && !hasNew) {
2107
+ local.push({ target: oldArray, evolution: { type: 'del', prop: index }, prop: index, origin });
2108
+ continue;
2109
+ }
2110
+ if (!hasOld && hasNew) {
2111
+ local.push({ target: oldArray, evolution: { type: 'add', prop: index }, prop: index, origin });
2112
+ continue;
2113
+ }
2114
+ if (!hasOld || !hasNew)
2115
+ continue;
2116
+ const oldEntry = unwrap(oldArray[index]);
2117
+ const newEntry = unwrap(newArray[index]);
2118
+ if (!Object.is(oldEntry, newEntry)) {
2119
+ local.push({ target: oldArray, evolution: { type: 'set', prop: index }, prop: index, origin });
2120
+ }
2121
+ }
2122
+ if (oldLength !== newLength)
2123
+ local.push({
2124
+ target: oldArray,
2125
+ evolution: { type: 'set', prop: 'length' },
2126
+ prop: 'length',
2127
+ origin,
2128
+ });
2129
+ notifications.push(...local);
2130
+ }
2131
+ function diffObjectProperties(oldObj, newObj, visited, notifications, origin) {
2132
+ const oldKeys = collectObjectKeys(oldObj);
2133
+ const newKeys = collectObjectKeys(newObj);
2134
+ const local = [];
2135
+ for (const key of oldKeys)
2136
+ if (!newKeys.has(key))
2137
+ local.push({ target: oldObj, evolution: { type: 'del', prop: key }, prop: key, origin });
2138
+ for (const key of newKeys)
2139
+ if (!oldKeys.has(key))
2140
+ local.push({ target: oldObj, evolution: { type: 'add', prop: key }, prop: key, origin });
2141
+ for (const key of newKeys) {
2142
+ if (!oldKeys.has(key))
2143
+ continue;
2144
+ const oldEntry = unwrap(oldObj[key]);
2145
+ const newEntry = unwrap(newObj[key]);
2146
+ if (shouldRecurseTouch(oldEntry, newEntry)) {
2147
+ recursiveTouch(oldEntry, newEntry, visited, notifications, origin);
2148
+ }
2149
+ else if (!Object.is(oldEntry, newEntry)) {
2150
+ local.push({ target: oldObj, evolution: { type: 'set', prop: key }, prop: key, origin });
2151
+ }
2152
+ }
2153
+ notifications.push(...local);
2154
+ }
2155
+ /**
2156
+ * Checks if an effect or any of its ancestors is in the allowed set
2157
+ */
2158
+ function hasAncestorInSet(effect, allowedSet) {
2159
+ let current = effect;
2160
+ const visited = new WeakSet();
2161
+ while (current && !visited.has(current)) {
2162
+ visited.add(current);
2163
+ if (allowedSet.has(current))
2164
+ return true;
2165
+ const node = getEffectNode(current);
2166
+ current = node.parent;
2167
+ }
2168
+ return false;
2169
+ }
2170
+ function dispatchNotifications(notifications) {
2171
+ if (!notifications.length)
2172
+ return;
2173
+ const combinedEffects = new Set();
2174
+ // Extract origin from first notification (all should have the same origin from a single deep touch)
2175
+ const origin = notifications[0]?.origin;
2176
+ let allowedEffects;
2177
+ // If origin exists, compute allowed effects (those that depend on origin.obj[origin.prop])
2178
+ if (origin) {
2179
+ allowedEffects = new Set();
2180
+ const originWatchers = exports.watchers.get(origin.obj);
2181
+ if (originWatchers) {
2182
+ const originEffects = new Set();
2183
+ collectEffects(origin.obj, { type: 'set', prop: origin.prop }, originEffects, originWatchers, [allProps], [origin.prop]);
2184
+ for (const effect of originEffects)
2185
+ allowedEffects.add(effect);
2186
+ }
2187
+ // If no allowed effects, skip all notifications (no one should be notified)
2188
+ if (allowedEffects.size === 0)
2189
+ return;
2190
+ }
2191
+ for (const { target, evolution, prop } of notifications) {
2192
+ if (!isObjectLike(target))
2193
+ continue;
2194
+ const obj = unwrap(target);
2195
+ addState(obj, evolution);
2196
+ const objectWatchers = exports.watchers.get(obj);
2197
+ let currentEffects;
2198
+ const propsArray = [prop];
2199
+ if (objectWatchers) {
2200
+ // console.log(`[DEBUG] dispatchNotifications: processing ${obj.constructor.name} (has watchers)`)
2201
+ currentEffects = new Set();
2202
+ collectEffects(obj, evolution, currentEffects, objectWatchers, [allProps], propsArray);
2203
+ // Filter effects by ancestor chain if origin exists
2204
+ // Include effects that either directly depend on origin or have an ancestor that does
2205
+ if (origin && allowedEffects) {
2206
+ const filteredEffects = new Set();
2207
+ for (const effect of currentEffects) {
2208
+ // Check if effect itself is allowed OR has an ancestor that is allowed
2209
+ if (allowedEffects.has(effect) || hasAncestorInSet(effect, allowedEffects)) {
2210
+ filteredEffects.add(effect);
2211
+ }
2212
+ }
2213
+ currentEffects = filteredEffects;
2214
+ }
2215
+ for (const effect of currentEffects)
2216
+ combinedEffects.add(effect);
2217
+ }
2218
+ optionCall('touched', obj, evolution, propsArray, currentEffects);
2219
+ if (objectsWithDeepWatchers.has(obj))
2220
+ bubbleUpChange(obj);
2221
+ }
2222
+ if (combinedEffects.size)
2223
+ batch([...combinedEffects]);
2224
+ }
2225
+
2226
+ /**
2227
+ * Marks a property as a dependency of the current effect
2228
+ * @param obj - The object containing the property
2229
+ * @param prop - The property name (defaults to allProps)
2230
+ */
2231
+ function dependant(obj, prop = allProps) {
2232
+ obj = unwrap(obj);
2233
+ const currentActiveEffect = getActiveEffect();
2234
+ // Early return if no active effect, tracking disabled, or invalid prop
2235
+ if (!currentActiveEffect || (typeof prop === 'symbol' && prop !== allProps))
2236
+ return;
2237
+ if ('dependencyHook' in currentActiveEffect) {
2238
+ // @ts-expect-error We declared it nowhere - it's okay as it's really internal and for edge-case debug purpose only
2239
+ currentActiveEffect.dependencyHook(obj, prop);
2240
+ }
2241
+ let objectWatchers = exports.watchers.get(obj);
2242
+ if (!objectWatchers) {
2243
+ objectWatchers = new Map();
2244
+ exports.watchers.set(obj, objectWatchers);
2245
+ }
2246
+ let deps = objectWatchers.get(prop);
2247
+ if (!deps) {
2248
+ deps = new Set();
2249
+ objectWatchers.set(prop, deps);
2250
+ }
2251
+ deps.add(currentActiveEffect);
2252
+ // Track which reactive objects this effect is watching
2253
+ const effectObjects = exports.effectToReactiveObjects.get(currentActiveEffect);
2254
+ if (effectObjects) {
2255
+ effectObjects.add(obj);
2256
+ }
2257
+ else {
2258
+ exports.effectToReactiveObjects.set(currentActiveEffect, new Set([obj]));
2259
+ }
2260
+ }
2261
+
2262
+ const metaProtos = new WeakMap();
2263
+ const hasReentry = [];
2264
+ const reactiveHandlers = {
2265
+ [Symbol.toStringTag]: 'MutTs Reactive',
2266
+ get(obj, prop, receiver) {
2267
+ if (obj && typeof obj === 'object' && prop !== Symbol.toStringTag) {
2268
+ const metaProto = metaProtos.get(obj.constructor);
2269
+ if (metaProto && Object.hasOwn(metaProto, prop)) {
2270
+ const desc = Object.getOwnPropertyDescriptor(metaProto, prop);
2271
+ if (desc.get) {
2272
+ if (!Object.hasOwn(obj, prop))
2273
+ return desc.get.call(obj);
2274
+ // For own properties (e.g., array length): only override if writable/configurable
2275
+ const ownDesc = Object.getOwnPropertyDescriptor(obj, prop);
2276
+ if (ownDesc.configurable || ownDesc.writable || ownDesc.get)
2277
+ return desc.get.call(obj);
2278
+ }
2279
+ else if (!Object.hasOwn(obj, prop))
2280
+ return (...args) => desc.value.apply(obj, args);
2281
+ }
2282
+ }
2283
+ if (prop === nonReactiveMark)
2284
+ return false;
2285
+ const unwrappedObj = unwrap(obj);
2286
+ // Check if this property is marked as unreactive
2287
+ if (unwrappedObj[unreactiveProperties]?.has(prop) || typeof prop === 'symbol')
2288
+ return FoolProof.get(obj, prop, receiver);
2289
+ // Check if property exists and if it's an own property (cached for later use)
2290
+ const hasProp = Reflect.has(receiver, prop);
2291
+ const isOwnProp = hasProp && Object.hasOwn(receiver, prop);
2292
+ const isInheritedAccess = hasProp && !isOwnProp;
2293
+ // For accessor properties, check the unwrapped object to see if it's an accessor
2294
+ // This ensures ignoreAccessors works correctly even after operations like Object.setPrototypeOf
2295
+ const shouldIgnoreAccessor = options.ignoreAccessors &&
2296
+ isOwnProp &&
2297
+ (isOwnAccessor(receiver, prop) || isOwnAccessor(unwrappedObj, prop));
2298
+ // Depend if...
2299
+ if (!hasProp ||
2300
+ (!(options.instanceMembers && isInheritedAccess && obj instanceof Object) &&
2301
+ !shouldIgnoreAccessor))
2302
+ dependant(obj, prop);
2303
+ // Watch the whole prototype chain when requested or for null-proto objects
2304
+ if (isInheritedAccess && (!options.instanceMembers || !(obj instanceof Object))) {
2305
+ let current = reactiveObject(Object.getPrototypeOf(obj));
2306
+ while (current && current !== Object.prototype) {
2307
+ dependant(current, prop);
2308
+ if (Object.hasOwn(current, prop))
2309
+ break;
2310
+ let next = reactiveObject(Object.getPrototypeOf(current));
2311
+ if (next === current) {
2312
+ next = reactiveObject(Object.getPrototypeOf(unwrap(current)));
2313
+ }
2314
+ current = next;
2315
+ }
2316
+ }
2317
+ const value = FoolProof.get(obj, prop, receiver);
2318
+ if (typeof value === 'object' && value !== null) {
2319
+ const reactiveValue = reactiveObject(value);
2320
+ // Only create back-references if this object needs them
2321
+ if (needsBackReferences(obj)) {
2322
+ addBackReference(reactiveValue, obj, prop);
2323
+ }
2324
+ return reactiveValue;
2325
+ }
2326
+ return value;
2327
+ },
2328
+ set(obj, prop, value, receiver) {
2329
+ // Read old value directly from unwrapped object to avoid triggering dependency tracking
2330
+ const unwrappedObj = unwrap(obj);
2331
+ const unwrappedReceiver = unwrap(receiver);
2332
+ // Check if this property is marked as unreactive
2333
+ if (unwrappedObj[unreactiveProperties]?.has(prop) || unwrappedObj !== unwrappedReceiver)
2334
+ return FoolProof.set(obj, prop, value, receiver);
2335
+ const newValue = unwrap(value);
2336
+ // metaProto setter dispatch (e.g., reactive array length)
2337
+ if (obj && typeof obj === 'object' && prop !== Symbol.toStringTag) {
2338
+ const metaProto = obj.constructor && metaProtos.get(obj.constructor);
2339
+ if (metaProto && Object.hasOwn(metaProto, prop)) {
2340
+ const desc = Object.getOwnPropertyDescriptor(metaProto, prop);
2341
+ if (desc.set) {
2342
+ desc.set.call(obj, newValue);
2343
+ return true;
2344
+ }
2345
+ }
2346
+ }
2347
+ // Read old value, using withEffect(undefined, ...) for getter-only accessors to avoid
2348
+ // breaking memoization dependency tracking during SET operations
2349
+ let oldVal = absent;
2350
+ if (Reflect.has(unwrappedReceiver, prop)) {
2351
+ // Check descriptor on both receiver and target to handle proxy cases
2352
+ const receiverDesc = Object.getOwnPropertyDescriptor(unwrappedReceiver, prop);
2353
+ const targetDesc = Object.getOwnPropertyDescriptor(unwrappedObj, prop);
2354
+ const desc = receiverDesc || targetDesc;
2355
+ // We *need* to use `receiver` and not `unwrappedObj` here, otherwise we break
2356
+ // the dependency tracking for memoized getters
2357
+ if (desc?.get && !desc?.set) {
2358
+ oldVal = untracked(() => Reflect.get(unwrappedObj, prop, receiver));
2359
+ }
2360
+ else {
2361
+ oldVal = untracked(() => Reflect.get(unwrappedObj, prop, receiver));
2362
+ }
2363
+ }
2364
+ if (objectsWithDeepWatchers.has(obj)) {
2365
+ if (typeof oldVal === 'object' && oldVal !== null) {
2366
+ removeBackReference(oldVal, obj, prop);
2367
+ }
2368
+ if (typeof newValue === 'object' && newValue !== null) {
2369
+ const reactiveValue = reactiveObject(newValue);
2370
+ addBackReference(reactiveValue, obj, prop);
2371
+ }
2372
+ }
2373
+ if (oldVal !== newValue) {
2374
+ // For getter-only accessors, Reflect.set() may fail, but we still return true
2375
+ // to avoid throwing errors. Only proceed with change notifications if set succeeded.
2376
+ if (FoolProof.set(obj, prop, newValue, receiver)) {
2377
+ notifyPropertyChange(obj, prop, oldVal, newValue, oldVal !== absent);
2378
+ }
2379
+ }
2380
+ return true;
2381
+ },
2382
+ has(obj, prop) {
2383
+ if (hasReentry.includes(obj))
2384
+ throw new ReactiveError(`[reactive] Circular dependency detected in 'has' check for property '${String(prop)}'`, {
2385
+ code: exports.ReactiveErrorCode.CycleDetected,
2386
+ cycle: [], // We don't have the full cycle here, but we know it involves obj
2387
+ });
2388
+ hasReentry.push(obj);
2389
+ dependant(obj, prop);
2390
+ const rv = Reflect.has(obj, prop);
2391
+ hasReentry.pop();
2392
+ return rv;
2393
+ },
2394
+ deleteProperty(obj, prop) {
2395
+ if (!Object.hasOwn(obj, prop))
2396
+ return false;
2397
+ const oldVal = obj[prop];
2398
+ // Remove back-references if this object has deep watchers
2399
+ if (objectsWithDeepWatchers.has(obj) && typeof oldVal === 'object' && oldVal !== null) {
2400
+ removeBackReference(oldVal, obj, prop);
2401
+ }
2402
+ delete obj[prop];
2403
+ touched1(obj, { type: 'del', prop }, prop);
2404
+ // Bubble up changes if this object has deep watchers
2405
+ if (objectsWithDeepWatchers.has(obj)) {
2406
+ bubbleUpChange(obj);
2407
+ }
2408
+ return true;
2409
+ },
2410
+ ownKeys(obj) {
2411
+ dependant(obj, allProps);
2412
+ return Reflect.ownKeys(obj);
2413
+ },
2414
+ };
2415
+ const reactiveClasses = new WeakSet();
2416
+ // Create the ReactiveBase mixin
2417
+ /**
2418
+ * Base mixin for reactive classes that provides proper constructor reactivity
2419
+ * Solves constructor reactivity issues in complex inheritance trees
2420
+ */
2421
+ const ReactiveBase = mixin((base) => {
2422
+ class ReactiveMixin extends base {
2423
+ constructor(...args) {
2424
+ super(...args);
2425
+ // Only apply reactive transformation if the class is marked with @reactive
2426
+ // This allows the mixin to work properly with method inheritance
2427
+ // biome-ignore lint/correctness/noConstructorReturn: This is the whole point here
2428
+ return reactiveClasses.has(new.target) ? reactive(this) : this;
2429
+ }
2430
+ }
2431
+ return ReactiveMixin;
2432
+ });
2433
+ function reactiveObject(anyTarget) {
2434
+ if (!anyTarget || typeof anyTarget !== 'object')
2435
+ return anyTarget;
2436
+ const target = anyTarget;
2437
+ // If target is already a proxy, return it
2438
+ if (isNonReactive(target))
2439
+ return target;
2440
+ const isProxy = proxyToObject.has(target);
2441
+ if (isProxy)
2442
+ return target;
2443
+ // If we already have a proxy for this object, return it (optimized: get returns undefined if not found)
2444
+ const existing = getExistingProxy(target);
2445
+ if (existing !== undefined)
2446
+ return existing;
2447
+ const proxied = nativeReactive in target && !(target instanceof target[nativeReactive])
2448
+ ? new target[nativeReactive](target)
2449
+ : target;
2450
+ if (proxied !== target)
2451
+ trackProxyObject(proxied, target);
2452
+ const proxy = new Proxy(proxied, reactiveHandlers);
2453
+ // Store the relationships
2454
+ storeProxyRelationship(target, proxy);
2455
+ return proxy;
2456
+ }
2457
+ /**
2458
+ * Main decorator for making classes reactive
2459
+ * Automatically makes class instances reactive when created
2460
+ */
2461
+ const reactive = decorator({
2462
+ class(original) {
2463
+ if (original.prototype instanceof ReactiveBase) {
2464
+ reactiveClasses.add(original);
2465
+ return original;
2466
+ }
2467
+ class Reactive extends original {
2468
+ constructor(...args) {
2469
+ super(...args);
2470
+ if (new.target !== Reactive && !reactiveClasses.has(new.target))
2471
+ options.warn(`${original.name} has been inherited by ${this.constructor.name} that is not reactive.
2472
+ @reactive decorator must be applied to the leaf class OR classes have to extend ReactiveBase.`);
2473
+ // biome-ignore lint/correctness/noConstructorReturn: This is the whole point here
2474
+ return reactive(this);
2475
+ }
2476
+ }
2477
+ Object.defineProperty(Reactive, 'name', {
2478
+ value: `Reactive<${original.name}>`,
2479
+ });
2480
+ return Reactive;
2481
+ },
2482
+ get(original) {
2483
+ return reactiveObject(original);
2484
+ },
2485
+ default: reactiveObject,
2486
+ });
2487
+
2488
+ /**
2489
+ * Displays a floating reactive panel in the browser showing the lineage of triggered effects.
2490
+ */
2491
+ function showLineagePanel() {
2492
+ if (typeof document === 'undefined')
2493
+ return;
2494
+ // Detect color scheme preference
2495
+ const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
2496
+ // Color schemes
2497
+ const colors = isDarkMode ? {
2498
+ panelBg: 'rgba(30, 30, 30, 0.95)',
2499
+ panelBorder: '#444',
2500
+ headerBg: '#8B4513',
2501
+ headerText: '#ffffff',
2502
+ closeBtn: '#ffffff',
2503
+ placeholderText: '#999',
2504
+ segmentBorder: '#8B4513',
2505
+ titleText: '#ffffff',
2506
+ frameText: '#ccc',
2507
+ atText: '#888',
2508
+ linkText: '#58a6ff',
2509
+ } : {
2510
+ panelBg: 'rgba(255, 255, 255, 0.95)',
2511
+ panelBorder: '#ddd',
2512
+ headerBg: '#704214',
2513
+ headerText: '#ffffff',
2514
+ closeBtn: '#ffffff',
2515
+ placeholderText: '#666',
2516
+ segmentBorder: '#704214',
2517
+ titleText: '#222',
2518
+ frameText: '#555',
2519
+ atText: '#999',
2520
+ linkText: '#005cc5',
2521
+ };
2522
+ const state = reactive({
2523
+ activeLineage: [],
2524
+ isVisible: true,
2525
+ });
2526
+ // Track the last triggered effect
2527
+ /* TODO: this is really not how effect triggers work - `onEffectTrigger` is called when "this effect" (here nothing) is triggered
2528
+ What we could try is to add events or such in zones... but it's really cosmetic and the whole panel is buggy - not worth doing yet (260206).
2529
+ onEffectTrigger((_obj, _evol, _prop, effectTrigger) => {
2530
+ state.activeLineage = getLineage(effectTrigger)
2531
+ })*/
2532
+ // UI Creation
2533
+ const panel = document.createElement('div');
2534
+ panel.id = 'mutts-lineage-panel';
2535
+ Object.assign(panel.style, {
2536
+ position: 'fixed',
2537
+ bottom: '20px',
2538
+ right: '20px',
2539
+ width: '400px',
2540
+ maxHeight: '80vh',
2541
+ backgroundColor: colors.panelBg,
2542
+ backdropFilter: 'blur(10px)',
2543
+ border: `1px solid ${colors.panelBorder}`,
2544
+ borderRadius: '12px',
2545
+ boxShadow: '0 10px 25px rgba(0,0,0,0.15)',
2546
+ zIndex: '999999',
2547
+ fontFamily: 'Inter, system-ui, sans-serif',
2548
+ fontSize: '12px',
2549
+ display: 'flex',
2550
+ flexDirection: 'column',
2551
+ overflow: 'hidden',
2552
+ transition: 'opacity 0.3s, transform 0.3s',
2553
+ });
2554
+ const header = document.createElement('div');
2555
+ Object.assign(header.style, {
2556
+ padding: '12px 16px',
2557
+ background: colors.headerBg,
2558
+ color: colors.headerText,
2559
+ fontWeight: '600',
2560
+ display: 'flex',
2561
+ justifyContent: 'space-between',
2562
+ alignItems: 'center',
2563
+ cursor: 'grab',
2564
+ });
2565
+ header.innerHTML = '<span><span style="font-size: 14px; margin-right: 5px;">🦴</span> Mutts Lineage</span>';
2566
+ const closeBtn = document.createElement('button');
2567
+ closeBtn.innerText = '×';
2568
+ Object.assign(closeBtn.style, {
2569
+ background: 'none',
2570
+ border: 'none',
2571
+ color: colors.closeBtn,
2572
+ fontSize: '20px',
2573
+ cursor: 'pointer',
2574
+ padding: '0 5px',
2575
+ });
2576
+ closeBtn.onclick = () => {
2577
+ state.isVisible = false;
2578
+ };
2579
+ header.appendChild(closeBtn);
2580
+ panel.appendChild(header);
2581
+ const content = document.createElement('div');
2582
+ Object.assign(content.style, {
2583
+ padding: '16px',
2584
+ overflowY: 'auto',
2585
+ flex: '1',
2586
+ });
2587
+ panel.appendChild(content);
2588
+ document.body.appendChild(panel);
2589
+ // Reactivity: Update Visibility
2590
+ effect(() => {
2591
+ panel.style.opacity = state.isVisible ? '1' : '0';
2592
+ panel.style.pointerEvents = state.isVisible ? 'all' : 'none';
2593
+ panel.style.transform = state.isVisible ? 'translateY(0)' : 'translateY(20px)';
2594
+ });
2595
+ // Reactivity: Update Content
2596
+ effect(() => {
2597
+ if (state.activeLineage.length === 0) {
2598
+ content.innerHTML = `<div style="color: ${colors.placeholderText}; font-style: italic; text-align: center; margin-top: 20px;">No effect triggered yet...</div>`;
2599
+ return;
2600
+ }
2601
+ content.innerHTML = '';
2602
+ state.activeLineage.forEach((segment, i) => {
2603
+ const segDiv = document.createElement('div');
2604
+ Object.assign(segDiv.style, {
2605
+ marginBottom: '16px',
2606
+ borderLeft: `2px solid ${colors.segmentBorder}`,
2607
+ paddingLeft: '12px',
2608
+ });
2609
+ const title = document.createElement('div');
2610
+ Object.assign(title.style, {
2611
+ fontWeight: 'bold',
2612
+ marginBottom: '6px',
2613
+ color: colors.titleText,
2614
+ });
2615
+ title.innerText = i === 0 ? `📍 Current: ${segment.effectName}` : `↖ Effect: ${segment.effectName}`;
2616
+ segDiv.appendChild(title);
2617
+ segment.stack.forEach(frame => {
2618
+ const frameDiv = document.createElement('div');
2619
+ Object.assign(frameDiv.style, {
2620
+ color: colors.frameText,
2621
+ marginBottom: '3px',
2622
+ fontSize: '11px',
2623
+ whiteSpace: 'nowrap',
2624
+ overflow: 'hidden',
2625
+ textOverflow: 'ellipsis',
2626
+ cursor: 'pointer',
2627
+ });
2628
+ frameDiv.title = frame.raw;
2629
+ frameDiv.innerHTML = `<span style="color: ${colors.atText}">at</span> ${frame.functionName} <span style="color: ${colors.linkText}; text-decoration: underline;">(${frame.fileName.split('/').pop()}:${frame.lineNumber})</span>`;
2630
+ segDiv.appendChild(frameDiv);
2631
+ });
2632
+ content.appendChild(segDiv);
2633
+ });
2634
+ });
2635
+ }
2636
+
2637
+ /**
2638
+ * Debug utilities for the reactivity system
2639
+ * - Captures effect metadata (names, parent relationships)
2640
+ * - Records cause → consequence edges with object/prop labels
2641
+ * - Provides graph data for tooling (DevTools panel, etc.)
2642
+ */
2643
+ /**
2644
+ * Log an error with detailed context if error logging is enabled
2645
+ */
2646
+ function logError(error, context, effect) {
2647
+ if (!debugOptions.logErrors)
2648
+ return;
2649
+ const contextStr = context === 'throw' ? '🔴 Thrown' : '🟡 Caught';
2650
+ console.group(`${contextStr} Error: ${error.message}`);
2651
+ console.error('Error:', error);
2652
+ // Try to get effect name if available
2653
+ if (effect && typeof effect === 'object' && effect.name) {
2654
+ console.log('Effect:', effect.name);
2655
+ }
2656
+ console.groupEnd();
2657
+ }
2658
+ // Log initialization for debugging
2659
+ const EXTERNAL_SOURCE = Symbol('external-source');
2660
+ let devtoolsEnabled = false;
2661
+ // Registry for debugging (populated lazily when DevTools are enabled)
2662
+ const debugEffectRegistry = new Set();
2663
+ const debugObjectRegistry = new Set();
2664
+ // Human-friendly names
2665
+ const effectNames = new WeakMap();
2666
+ const objectNames = new WeakMap();
2667
+ let effectCounter = 0;
2668
+ let objectCounter = 0;
2669
+ // Debug options system
2670
+ const debugOptions = {
2671
+ /**
2672
+ * Whether DevTools are enabled
2673
+ */
2674
+ get enabled() {
2675
+ return devtoolsEnabled;
2676
+ },
2677
+ logErrors: false
2678
+ };
2679
+ const triggerGraph = new Map();
2680
+ function ensureEffectName(effect) {
2681
+ let name = effectNames.get(effect);
2682
+ if (!name) {
2683
+ const root = getRoot(effect);
2684
+ name = root?.name?.trim() || `effect_${++effectCounter}`;
2685
+ effectNames.set(effect, name);
2686
+ }
2687
+ return name;
2688
+ }
2689
+ function ensureObjectName(obj) {
2690
+ let name = objectNames.get(obj);
2691
+ if (!name) {
2692
+ const ctorName = obj?.constructor?.name;
2693
+ const base = ctorName && ctorName !== 'Object' ? ctorName : 'object';
2694
+ name = `${base}_${++objectCounter}`;
2695
+ objectNames.set(obj, name);
2696
+ }
2697
+ return name;
2698
+ }
2699
+ function describeProp(obj, prop) {
2700
+ const objectName = ensureObjectName(obj);
2701
+ if (prop === allProps)
2702
+ return `${objectName}.*`;
2703
+ if (typeof prop === 'symbol')
2704
+ return `${objectName}.${prop.description ?? prop.toString()}`;
2705
+ return `${objectName}.${String(prop)}`;
2706
+ }
2707
+ function addEffectToRegistry(effect) {
2708
+ if (!effect || debugEffectRegistry.has(effect))
2709
+ return;
2710
+ debugEffectRegistry.add(effect);
2711
+ const deps = exports.effectToReactiveObjects.get(effect);
2712
+ if (deps) {
2713
+ for (const obj of deps) {
2714
+ documentObject(obj);
2715
+ }
2716
+ }
2717
+ }
2718
+ function documentObject(obj) {
2719
+ if (!debugObjectRegistry.has(obj)) {
2720
+ dbRegisterObject(obj);
2721
+ }
2722
+ }
2723
+ function dbRegisterObject(obj) {
2724
+ debugObjectRegistry.add(obj);
2725
+ ensureObjectName(obj);
2726
+ }
2727
+ function ensureParentChains(effects) {
2728
+ const queue = Array.from(effects);
2729
+ for (let i = 0; i < queue.length; i++) {
2730
+ const effect = queue[i];
2731
+ const parent = getEffectNode(effect).parent;
2732
+ if (parent && !effects.has(parent)) {
2733
+ effects.add(parent);
2734
+ queue.push(parent);
2735
+ }
2736
+ }
2737
+ }
2738
+ function ensureTriggerContainers(source) {
2739
+ let targetMap = triggerGraph.get(source);
2740
+ if (!targetMap) {
2741
+ targetMap = new Map();
2742
+ triggerGraph.set(source, targetMap);
2743
+ }
2744
+ return targetMap;
2745
+ }
2746
+ function ensureTriggerRecord(source, target, label, obj, prop, evolution) {
2747
+ const targetMap = ensureTriggerContainers(source);
2748
+ let labelMap = targetMap.get(target);
2749
+ if (!labelMap) {
2750
+ labelMap = new Map();
2751
+ targetMap.set(target, labelMap);
2752
+ }
2753
+ let record = labelMap.get(label);
2754
+ if (!record) {
2755
+ record = { label, object: obj, prop, evolution, count: 0, lastTriggered: Date.now() };
2756
+ labelMap.set(label, record);
2757
+ }
2758
+ return record;
2759
+ }
2760
+ /**
2761
+ * Assign a debug-friendly name to an effect (shown in DevTools)
2762
+ */
2763
+ function setEffectName(effect, name) {
2764
+ effectNames.set(effect, name);
2765
+ }
2766
+ /**
2767
+ * Assign a debug-friendly name to a reactive object
2768
+ */
2769
+ function setObjectName(obj, name) {
2770
+ objectNames.set(obj, name);
2771
+ debugObjectRegistry.add(obj);
2772
+ }
2773
+ /**
2774
+ * Register an effect so it appears in the DevTools graph
2775
+ */
2776
+ function registerEffectForDebug(effect) {
2777
+ if (!effect || !devtoolsEnabled)
2778
+ return;
2779
+ addEffectToRegistry(effect);
2780
+ }
2781
+ /**
2782
+ * Register a reactive object so it appears in the DevTools graph
2783
+ */
2784
+ function registerObjectForDebug(obj) {
2785
+ if (!devtoolsEnabled)
2786
+ return;
2787
+ documentObject(obj);
2788
+ }
2789
+ /**
2790
+ * Records a cause → consequence relationship between effects.
2791
+ * @param source - The effect performing the write (undefined if external/user input)
2792
+ * @param target - The effect that re-ran because of the write
2793
+ * @param obj - The reactive object that changed
2794
+ * @param prop - The property that changed
2795
+ * @param evolution - The type of change (set/add/del/bunch)
2796
+ */
2797
+ function recordTriggerLink(source, target, obj, prop, evolution) {
2798
+ raiseEffectTrackers(target, obj, evolution, prop);
2799
+ if (options.introspection.enableHistory) {
2800
+ addToMutationHistory(source, target, obj, prop, evolution);
2801
+ }
2802
+ if (!devtoolsEnabled)
2803
+ return;
2804
+ addEffectToRegistry(target);
2805
+ if (source)
2806
+ addEffectToRegistry(source);
2807
+ const descriptor = describeProp(obj, prop);
2808
+ const record = ensureTriggerRecord(source ?? EXTERNAL_SOURCE, target, descriptor, obj, prop, evolution);
2809
+ record.count += 1;
2810
+ record.lastTriggered = Date.now();
2811
+ documentObject(obj);
2812
+ }
2813
+ /**
2814
+ * Traces back the chain of triggers that led to a specific effect
2815
+ * @param effect The effect to trace back
2816
+ * @param limit Max depth
2817
+ */
2818
+ function getTriggerChain(effect, limit = 5) {
2819
+ const chain = [];
2820
+ let current = effect;
2821
+ for (let i = 0; i < limit; i++) {
2822
+ // Find who triggered 'current'
2823
+ // We need to reverse search the triggerGraph (source -> target)
2824
+ // This is expensive O(Edges) but okay for error reporting
2825
+ let foundSource;
2826
+ let foundReason = '';
2827
+ search: for (const [source, targetMap] of triggerGraph) {
2828
+ for (const [target, labelMap] of targetMap) {
2829
+ if (target === current) {
2830
+ // Found a source! Use the most recent trigger record
2831
+ let lastTime = 0;
2832
+ for (const record of labelMap.values()) {
2833
+ if (record.lastTriggered > lastTime) {
2834
+ lastTime = record.lastTriggered;
2835
+ foundReason = record.label;
2836
+ foundSource = source === EXTERNAL_SOURCE ? undefined : source;
2837
+ }
2838
+ }
2839
+ if (foundSource || foundReason)
2840
+ break search;
2841
+ }
2842
+ }
2843
+ }
2844
+ if (foundSource) {
2845
+ chain.push(`${ensureEffectName(foundSource)} -> (${foundReason}) -> ${ensureEffectName(current)}`);
2846
+ current = foundSource;
2847
+ }
2848
+ else if (foundReason) {
2849
+ chain.push(`External -> (${foundReason}) -> ${ensureEffectName(current)}`);
2850
+ break;
2851
+ }
2852
+ else {
2853
+ break;
2854
+ }
2855
+ }
2856
+ return chain.reverse();
2857
+ }
2858
+ function buildEffectNodes(allEffects) {
2859
+ const nodes = [];
2860
+ const nodeByEffect = new Map();
2861
+ const ordered = Array.from(allEffects);
2862
+ for (const effect of ordered) {
2863
+ const label = ensureEffectName(effect);
2864
+ const node = {
2865
+ id: `effect_${nodes.length}`,
2866
+ label,
2867
+ type: 'effect',
2868
+ depth: 0,
2869
+ debugName: label,
2870
+ };
2871
+ nodes.push(node);
2872
+ nodeByEffect.set(effect, node);
2873
+ }
2874
+ const depthCache = new Map();
2875
+ const computeDepth = (effect) => {
2876
+ if (!effect)
2877
+ return 0;
2878
+ const cached = depthCache.get(effect);
2879
+ if (cached !== undefined)
2880
+ return cached;
2881
+ const parent = getEffectNode(effect).parent;
2882
+ const depth = computeDepth(parent) + (parent ? 1 : 0);
2883
+ depthCache.set(effect, depth);
2884
+ return depth;
2885
+ };
2886
+ for (const [effect, node] of nodeByEffect) {
2887
+ node.depth = computeDepth(effect);
2888
+ const parent = getEffectNode(effect).parent;
2889
+ if (parent) {
2890
+ const parentNode = nodeByEffect.get(parent);
2891
+ if (parentNode) {
2892
+ node.parentId = parentNode.id;
2893
+ }
2894
+ }
2895
+ }
2896
+ return { nodes, nodeByEffect };
2897
+ }
2898
+ /**
2899
+ * Builds a graph representing current reactive state (effects, objects, and trigger edges)
2900
+ */
2901
+ function buildReactivityGraph() {
2902
+ const nodes = [];
2903
+ const edges = [];
2904
+ const nodeIds = new Map();
2905
+ const allEffects = new Set(debugEffectRegistry);
2906
+ ensureParentChains(allEffects);
2907
+ const { nodes: effectNodes, nodeByEffect } = buildEffectNodes(allEffects);
2908
+ for (const node of effectNodes)
2909
+ nodes.push(node);
2910
+ for (const [effect, node] of nodeByEffect) {
2911
+ nodeIds.set(effect, node.id);
2912
+ }
2913
+ // Object nodes (optional, used for dependency inspection)
2914
+ for (const obj of debugObjectRegistry) {
2915
+ const id = `object_${nodes.length}`;
2916
+ nodes.push({ id, label: ensureObjectName(obj), type: 'state', debugName: objectNames.get(obj) });
2917
+ nodeIds.set(obj, id);
2918
+ }
2919
+ // External source node (user/system outside of effects)
2920
+ if (triggerGraph.has(EXTERNAL_SOURCE)) {
2921
+ const externalId = `effect_external`;
2922
+ nodes.push({ id: externalId, label: 'External', type: 'external', depth: 0 });
2923
+ nodeIds.set(EXTERNAL_SOURCE, externalId);
2924
+ }
2925
+ // Dependency edges (effect → object)
2926
+ for (const effect of allEffects) {
2927
+ const effectId = nodeIds.get(effect);
2928
+ if (!effectId)
2929
+ continue;
2930
+ const deps = exports.effectToReactiveObjects.get(effect);
2931
+ if (!deps)
2932
+ continue;
2933
+ for (const obj of deps) {
2934
+ const objId = nodeIds.get(obj);
2935
+ if (!objId)
2936
+ continue;
2937
+ edges.push({
2938
+ id: `${effectId}->${objId}`,
2939
+ source: effectId,
2940
+ target: objId,
2941
+ type: 'dependency',
2942
+ label: 'depends',
2943
+ });
2944
+ }
2945
+ }
2946
+ // Cause edges (effect/object/prop → effect)
2947
+ for (const [source, targetMap] of triggerGraph) {
2948
+ for (const [targetEffect, labelMap] of targetMap) {
2949
+ const targetId = nodeIds.get(targetEffect);
2950
+ if (!targetId)
2951
+ continue;
2952
+ const sourceId = nodeIds.get(source);
2953
+ if (!sourceId)
2954
+ continue;
2955
+ for (const record of labelMap.values()) {
2956
+ edges.push({
2957
+ id: `${sourceId}->${targetId}:${record.label}`,
2958
+ source: sourceId,
2959
+ target: targetId,
2960
+ type: 'cause',
2961
+ label: record.count > 1 ? `${record.label} (${record.count})` : record.label,
2962
+ count: record.count,
2963
+ });
2964
+ }
2965
+ }
2966
+ }
2967
+ return {
2968
+ nodes,
2969
+ edges,
2970
+ meta: {
2971
+ generatedAt: Date.now(),
2972
+ devtoolsEnabled,
2973
+ },
2974
+ };
2975
+ }
2976
+ /**
2977
+ * Enables the DevTools bridge and exposes the debug API on window/global.
2978
+ * Call as early as possible in development builds.
2979
+ */
2980
+ function enableDevTools() {
2981
+ const globalScope = (typeof globalThis !== 'undefined'
2982
+ ? globalThis
2983
+ : typeof window !== 'undefined'
2984
+ ? window
2985
+ : typeof global !== 'undefined'
2986
+ ? global
2987
+ : undefined);
2988
+ if (!globalScope)
2989
+ return;
2990
+ if (devtoolsEnabled)
2991
+ return;
2992
+ devtoolsEnabled = true;
2993
+ globalScope.__MUTTS_DEVTOOLS__ = {
2994
+ getGraph: buildReactivityGraph,
2995
+ nodeLineage(tag) {
2996
+ nodeLineage(getLineage());
2997
+ return '🦴 Effect Lineage Trace' + (tag ? ` (${tag})` : '');
2998
+ },
2999
+ nodeLineageLegacy() {
3000
+ console.groupCollapsed('nodeLineageLegacy');
3001
+ console.log(nodeLineageLegacy(getLineage()));
3002
+ console.groupEnd();
3003
+ },
3004
+ get browserLineage() {
3005
+ return wrapLineageForDebug(getLineage());
3006
+ },
3007
+ getLineage,
3008
+ captureLineage: getStackFrame,
3009
+ formatLineage,
3010
+ showLineagePanel,
3011
+ setEffectName,
3012
+ setObjectName,
3013
+ registerEffect: registerEffectForDebug,
3014
+ registerObject: registerObjectForDebug,
3015
+ // Debug options for controlling runtime behavior
3016
+ debug: debugOptions
3017
+ };
3018
+ // @ts-ignore - devtoolsFormatters is a Chrome-specific array
3019
+ if (globalScope.devtoolsFormatters) {
3020
+ globalScope.devtoolsFormatters.push(lineageFormatter);
3021
+ }
3022
+ else {
3023
+ globalScope.devtoolsFormatters = [lineageFormatter];
3024
+ }
3025
+ }
3026
+ function forceEnableGraphTracking() {
3027
+ devtoolsEnabled = true;
3028
+ }
3029
+ function isDevtoolsEnabled() {
3030
+ return devtoolsEnabled;
3031
+ }
3032
+ // --- Introspection API ---
3033
+ /**
3034
+ * Returns the raw dependency graph data structure.
3035
+ * This is useful for programmatic analysis of the reactive system.
3036
+ */
3037
+ function getDependencyGraph() {
3038
+ return {
3039
+ nodes: buildReactivityGraph().nodes,
3040
+ edges: buildReactivityGraph().edges,
3041
+ };
3042
+ }
3043
+ /**
3044
+ * Returns a list of effects that depend on the given object.
3045
+ */
3046
+ function getDependents(obj) {
3047
+ const dependents = [];
3048
+ // Scan the trigger graph for effects triggered by this object
3049
+ // This is O(E) where E is the number of edges, might need optimization for large graphs
3050
+ // but acceptable for introspection
3051
+ for (const [_source, targetMap] of triggerGraph) {
3052
+ for (const [targetEffect, labelMap] of targetMap) {
3053
+ for (const record of labelMap.values()) {
3054
+ if (record.object === obj) {
3055
+ dependents.push(targetEffect);
3056
+ }
3057
+ }
3058
+ }
3059
+ }
3060
+ // Also check direct dependencies (dependency graph)
3061
+ // We don't have a direct obj -> effect map without walking all effects
3062
+ // unless we use `watchers` from tracking.ts but that's internal
3063
+ return [...new Set(dependents)];
3064
+ }
3065
+ /**
3066
+ * Returns a list of objects that the given effect depends on.
3067
+ */
3068
+ function getDependencies(effect) {
3069
+ const deps = exports.effectToReactiveObjects.get(effect);
3070
+ return deps ? Array.from(deps) : [];
3071
+ }
3072
+ const mutationHistory = [];
3073
+ let mutationCounter = 0;
3074
+ function addToMutationHistory(source, target, obj, prop, evolution) {
3075
+ const record = {
3076
+ id: ++mutationCounter,
3077
+ timestamp: Date.now(),
3078
+ source: source ? ensureEffectName(source) : 'External',
3079
+ target: ensureEffectName(target),
3080
+ objectName: ensureObjectName(obj),
3081
+ prop: String(prop),
3082
+ type: evolution.type,
3083
+ };
3084
+ mutationHistory.push(record);
3085
+ if (mutationHistory.length > options.introspection.historySize) {
3086
+ mutationHistory.shift();
3087
+ }
3088
+ }
3089
+ /**
3090
+ * Get the recent mutation history
3091
+ */
3092
+ function getMutationHistory() {
3093
+ return [...mutationHistory];
3094
+ }
3095
+ // --- Auto DevTools Initialization ---
3096
+ // Automatically enable devtools in development environments
3097
+ /**
3098
+ * Checks if we're in a development environment
3099
+ * Detection order:
3100
+ * 1. process.env.NODE_ENV (Node.js)
3101
+ * 2. import.meta.env.DEV (Vite)
3102
+ * 3. import.meta.env.PROD === false (Vite alternative)
3103
+ * 4. Assumes development if none of the above are set (safe default)
3104
+ */
3105
+ function isDevelopmentMode() {
3106
+ // Check for explicit production flag first
3107
+ if (typeof process !== 'undefined' && process.env?.NODE_ENV === 'production') {
3108
+ return false;
3109
+ }
3110
+ // Check for Vite's DEV flag
3111
+ if (typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunks/index-VTO-b2vR.cjs', document.baseURI).href)) }) !== 'undefined') {
3112
+ const meta = ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunks/index-VTO-b2vR.cjs', document.baseURI).href)) });
3113
+ if (meta.env?.PROD === true) {
3114
+ return false;
3115
+ }
3116
+ if (meta.env?.DEV === true) {
3117
+ return true;
3118
+ }
3119
+ }
3120
+ // Check for custom global override
3121
+ if (typeof globalThis !== 'undefined' && '__MUTTS_DEV_MODE__' in globalThis) {
3122
+ return globalThis.__MUTTS_DEV_MODE__ !== false;
3123
+ }
3124
+ // Default to development (safer to enable in dev than disable in prod)
3125
+ return true;
3126
+ }
3127
+ // Auto-enable devtools when the module loads in development
3128
+ if (isDevelopmentMode() && !devtoolsEnabled) {
3129
+ enableDevTools();
3130
+ // Optional: Log that devtools were enabled (only in development)
3131
+ if (typeof console !== 'undefined' && console.info) {
3132
+ // Do not log these in when mode === 'test'
3133
+ console.info('🦴 Mutts DevTools enabled automatically in development mode');
3134
+ }
3135
+ }
3136
+
3137
+ /**
3138
+ * Finds a cycle in a sequence of functions by looking for the first repetition
3139
+ */
3140
+ function findCycleInChain(roots) {
3141
+ const seen = new Map();
3142
+ for (let i = 0; i < roots.length; i++) {
3143
+ const root = roots[i];
3144
+ if (seen.has(root)) {
3145
+ return roots.slice(seen.get(root));
3146
+ }
3147
+ seen.set(root, i);
3148
+ }
3149
+ return null;
3150
+ }
3151
+ /**
3152
+ * Formats a list of function roots into a readable trace
3153
+ */
3154
+ function formatRoots(roots, limit = 20) {
3155
+ const names = roots.map((r) => r.name || '<anonymous>');
3156
+ if (names.length <= limit)
3157
+ return names.join(' → ');
3158
+ const start = names.slice(0, 5);
3159
+ const end = names.slice(-10);
3160
+ return `${start.join(' → ')} ... (${names.length - 15} more) ... ${end.join(' → ')}`;
3161
+ }
3162
+ // Nested map structure for efficient counting and batch cleanup
3163
+ // batchId -> effect root -> obj -> prop -> count
3164
+ let activationRegistry;
3165
+ const activationLog = new Array(100);
3166
+ /**
3167
+ * Returns the activation log containing recent effect activations for debugging.
3168
+ * The log is a circular buffer of the last 100 activations.
3169
+ *
3170
+ * @returns Array of activation records
3171
+ */
3172
+ function getActivationLog() {
3173
+ return activationLog;
3174
+ }
3175
+ function recordActivation(effect, obj, evolution, prop) {
3176
+ const root = getRoot(effect);
3177
+ if (!activationRegistry)
3178
+ return;
3179
+ let effectData = activationRegistry.get(root);
3180
+ if (!effectData) {
3181
+ effectData = new Map();
3182
+ activationRegistry.set(root, effectData);
3183
+ }
3184
+ let objData = effectData.get(obj);
3185
+ if (!objData) {
3186
+ objData = new Map();
3187
+ effectData.set(obj, objData);
3188
+ }
3189
+ const count = (objData.get(prop) ?? 0) + 1;
3190
+ objData.set(prop, count);
3191
+ // Keep a limited history for diagnostics
3192
+ activationLog.unshift({
3193
+ effect,
3194
+ obj,
3195
+ evolution,
3196
+ prop,
3197
+ });
3198
+ activationLog.pop();
3199
+ if (count >= options.maxTriggerPerBatch) {
3200
+ const effectName = root?.name || 'anonymous';
3201
+ const message = `Aggressive trigger detected: effect "${effectName}" triggered ${count} times in the batch by the same cause.`;
3202
+ if (options.maxEffectReaction === 'throw') {
3203
+ throw new ReactiveError(message, {
3204
+ code: exports.ReactiveErrorCode.MaxReactionExceeded,
3205
+ count,
3206
+ effect: effectName,
3207
+ });
3208
+ }
3209
+ options.warn(`[reactive] ${message}`);
3210
+ }
3211
+ }
3212
+ /**
3213
+ * Registers a debug callback that is called when the current effect is triggered by a dependency change
3214
+ *
3215
+ * This function is useful for debugging purposes as it pin-points exactly which reactive property
3216
+ * change triggered the effect. The callback receives information about:
3217
+ * - The object that changed
3218
+ * - The type of change (evolution)
3219
+ * - The specific property that changed
3220
+ *
3221
+ * **Note:** The tracker callback is automatically removed after being called once. If you need
3222
+ * to track multiple triggers, call `onEffectTrigger` again within the effect.
3223
+ *
3224
+ * @param onTouch - Callback function that receives (obj, evolution, prop) when the effect is triggered
3225
+ * @throws {Error} If called outside of an effect context
3226
+ *
3227
+ * @example
3228
+ * ```typescript
3229
+ * const state = reactive({ count: 0, name: 'John' })
3230
+ *
3231
+ * effect(() => {
3232
+ * // Register a tracker to see what triggers this effect
3233
+ * onEffectTrigger((obj, evolution, prop) => {
3234
+ * console.log(`Effect triggered by:`, {
3235
+ * object: obj,
3236
+ * change: evolution.type,
3237
+ * property: prop
3238
+ * })
3239
+ * })
3240
+ *
3241
+ * // Access reactive properties
3242
+ * console.log(state.count, state.name)
3243
+ * })
3244
+ *
3245
+ * state.count = 5
3246
+ * ```
3247
+ */
3248
+ function onEffectTrigger(onTouch, effect) {
3249
+ effect ?? (effect = getActiveEffect());
3250
+ if (!effect)
3251
+ throw new Error('Tracking an effect trigger while not in an effect');
3252
+ const node = getEffectNode(effect);
3253
+ if (!node.trackers)
3254
+ node.trackers = [onTouch];
3255
+ else
3256
+ node.trackers.push(onTouch);
3257
+ }
3258
+ function raiseEffectTrackers(effect, obj, evolution, prop) {
3259
+ const node = getEffectNode(effect);
3260
+ const trackers = node.trackers;
3261
+ if (trackers) {
3262
+ for (const tracker of trackers)
3263
+ tracker(obj, evolution, prop, effect);
3264
+ }
3265
+ }
3266
+ function onEffectThrow(onThrow, effect) {
3267
+ effect ?? (effect = getActiveEffect());
3268
+ if (!effect)
3269
+ throw new Error('Tracking an effect throw while not in an effect');
3270
+ const node = getEffectNode(effect);
3271
+ if (!node.catchers)
3272
+ node.catchers = [onThrow];
3273
+ else
3274
+ node.catchers.push(onThrow);
3275
+ }
3276
+ // Dependency graph: tracks which effects trigger which other effects
3277
+ // Uses roots (Function) as keys for consistency
3278
+ let effectTriggers = new WeakMap();
3279
+ let effectTriggeredBy = new WeakMap();
3280
+ // Transitive closures: track all indirect relationships
3281
+ // causesClosure: for each effect, all effects that trigger it (directly or indirectly)
3282
+ // consequencesClosure: for each effect, all effects that it triggers (directly or indirectly)
3283
+ let causesClosure = new WeakMap();
3284
+ let consequencesClosure = new WeakMap();
3285
+ let broken = false;
3286
+ /**
3287
+ * Gets or creates an IterableWeakSet for a closure map
3288
+ */
3289
+ function getOrCreateClosure(closure, root) {
3290
+ let set = closure.get(root);
3291
+ if (!set) {
3292
+ set = new IterableWeakSet();
3293
+ closure.set(root, set);
3294
+ }
3295
+ return set;
3296
+ }
3297
+ /**
3298
+ * Adds an edge to the dependency graph: callerRoot → targetRoot
3299
+ * Also maintains transitive closures
3300
+ * @param callerRoot - Root function of the effect that triggers
3301
+ * @param targetRoot - Root function of the effect being triggered
3302
+ */
3303
+ function addGraphEdge(callerRoot, targetRoot) {
3304
+ if (options.cycleHandling === 'production')
3305
+ return;
3306
+ // Add to forward graph: callerRoot → targetRoot
3307
+ const triggers = effectTriggers.get(callerRoot);
3308
+ if (!triggers) {
3309
+ const newTriggers = new IterableWeakSet();
3310
+ newTriggers.add(targetRoot);
3311
+ effectTriggers.set(callerRoot, newTriggers);
3312
+ }
3313
+ else {
3314
+ triggers.add(targetRoot);
3315
+ }
3316
+ // Add to reverse graph: targetRoot ← callerRoot
3317
+ let triggeredBy = effectTriggeredBy.get(targetRoot);
3318
+ if (!triggeredBy) {
3319
+ triggeredBy = new IterableWeakSet();
3320
+ effectTriggeredBy.set(targetRoot, triggeredBy);
3321
+ }
3322
+ triggeredBy.add(callerRoot);
3323
+ // Update transitive closures
3324
+ // When U→V is added, we need to propagate the relationship:
3325
+ // 1. Add U to causesClosure(V) and V to consequencesClosure(U) (direct relationship)
3326
+ // 2. For each X in causesClosure(U): add V to consequencesClosure(X) and X to causesClosure(V)
3327
+ // 3. For each Y in consequencesClosure(V): add U to causesClosure(Y) and Y to consequencesClosure(U)
3328
+ // Note: Self-loops (U→U) are not added to closures - if an effect appears in its own closure,
3329
+ // it means there's an indirect cycle that should be detected
3330
+ // Self-loops are explicitly ignored - an effect reading and writing the same property
3331
+ // (e.g., obj.prop++) should not create a dependency relationship or appear in closures
3332
+ if (callerRoot === targetRoot) {
3333
+ return;
3334
+ }
3335
+ const uConsequences = getOrCreateClosure(consequencesClosure, callerRoot);
3336
+ const vCauses = getOrCreateClosure(causesClosure, targetRoot);
3337
+ // 1. Add direct relationship
3338
+ uConsequences.add(targetRoot);
3339
+ vCauses.add(callerRoot);
3340
+ // 2. For each X in causesClosure(U): X→U→V means X→V
3341
+ const uCausesSet = causesClosure.get(callerRoot);
3342
+ if (uCausesSet) {
3343
+ for (const x of uCausesSet) {
3344
+ // Skip if this would create a self-loop
3345
+ if (x === targetRoot)
3346
+ continue;
3347
+ const xConsequences = getOrCreateClosure(consequencesClosure, x);
3348
+ xConsequences.add(targetRoot);
3349
+ vCauses.add(x);
3350
+ }
3351
+ }
3352
+ // 3. For each Y in consequencesClosure(V): U→V→Y means U→Y
3353
+ const vConsequencesSet = consequencesClosure.get(targetRoot);
3354
+ if (vConsequencesSet) {
3355
+ for (const y of vConsequencesSet) {
3356
+ // Skip if this would create a self-loop
3357
+ if (y === callerRoot)
3358
+ continue;
3359
+ const yCauses = getOrCreateClosure(causesClosure, y);
3360
+ yCauses.add(callerRoot);
3361
+ uConsequences.add(y);
3362
+ }
3363
+ }
3364
+ // 4. Cross-product: for each X in causesClosure(U) and Y in consequencesClosure(V): X→Y
3365
+ if (uCausesSet?.size && vConsequencesSet?.size) {
3366
+ for (const x of uCausesSet) {
3367
+ const xConsequences = getOrCreateClosure(consequencesClosure, x);
3368
+ for (const y of vConsequencesSet) {
3369
+ // Skip if this would create a self-loop
3370
+ if (x === y)
3371
+ continue;
3372
+ xConsequences.add(y);
3373
+ const yCauses = getOrCreateClosure(causesClosure, y);
3374
+ yCauses.add(x);
3375
+ }
3376
+ }
3377
+ }
3378
+ }
3379
+ /**
3380
+ * Checks if there's a path from start to end in the dependency graph, excluding a specific node
3381
+ * Uses BFS to find any path that doesn't go through the excluded node
3382
+ * @param start - Starting node
3383
+ * @param end - Target node
3384
+ * @param exclude - Node to exclude from the path
3385
+ * @returns true if a path exists without going through the excluded node
3386
+ */
3387
+ function hasPathExcluding(start, end, exclude) {
3388
+ if (start === end)
3389
+ return true;
3390
+ if (start === exclude)
3391
+ return false;
3392
+ const visited = new Set();
3393
+ const queue = [start];
3394
+ visited.add(start);
3395
+ visited.add(exclude); // Pre-mark excluded node as visited to skip it
3396
+ while (queue.length > 0) {
3397
+ const current = queue.shift();
3398
+ const triggers = effectTriggers.get(current);
3399
+ if (!triggers)
3400
+ continue;
3401
+ for (const next of triggers) {
3402
+ if (next === end)
3403
+ return true;
3404
+ if (!visited.has(next)) {
3405
+ visited.add(next);
3406
+ queue.push(next);
3407
+ }
3408
+ }
3409
+ }
3410
+ return false;
3411
+ }
3412
+ /**
3413
+ * Removes all edges involving the given effect from the dependency graph
3414
+ * Also cleans up transitive closures by propagating cleanup to all affected effects
3415
+ * Called when an effect is stopped/cleaned up
3416
+ * @param effect - The effect being cleaned up
3417
+ */
3418
+ function cleanupEffectFromGraph(effect) {
3419
+ if (options.cycleHandling === 'production')
3420
+ return;
3421
+ const root = getRoot(effect);
3422
+ // Get closures before removing direct edges (needed for propagation)
3423
+ const rootCauses = causesClosure.get(root);
3424
+ const rootConsequences = consequencesClosure.get(root);
3425
+ // Remove from effectTriggers (outgoing edges)
3426
+ const triggers = effectTriggers.get(root);
3427
+ if (triggers) {
3428
+ // Remove this root from all targets' effectTriggeredBy sets
3429
+ for (const targetRoot of triggers) {
3430
+ const triggeredBy = effectTriggeredBy.get(targetRoot);
3431
+ triggeredBy?.delete(root);
3432
+ }
3433
+ effectTriggers.delete(root);
3434
+ }
3435
+ // Remove from effectTriggeredBy (incoming edges)
3436
+ const triggeredBy = effectTriggeredBy.get(root);
3437
+ if (triggeredBy) {
3438
+ // Remove this root from all sources' effectTriggers sets
3439
+ for (const sourceRoot of triggeredBy) {
3440
+ const triggers = effectTriggers.get(sourceRoot);
3441
+ triggers?.delete(root);
3442
+ }
3443
+ effectTriggeredBy.delete(root);
3444
+ }
3445
+ // Propagate closure cleanup to all affected effects
3446
+ // When removing B from A → B → C:
3447
+ // - Remove B from causesClosure(C) and consequencesClosure(A)
3448
+ // - For each X in causesClosure(B): remove C from consequencesClosure(X) if B was the only path
3449
+ // - For each Y in consequencesClosure(B): remove A from causesClosure(Y) if B was the only path
3450
+ // - Remove transitive relationships that depended on B
3451
+ if (rootCauses) {
3452
+ // For each X that triggers root: remove root from X's consequences
3453
+ // Only remove root's consequences if no alternate path exists
3454
+ for (const causeRoot of rootCauses) {
3455
+ const causeConsequences = consequencesClosure.get(causeRoot);
3456
+ if (causeConsequences) {
3457
+ // Remove root itself (it's being cleaned up)
3458
+ causeConsequences.delete(root);
3459
+ // Only remove consequences of root if there's no alternate path from causeRoot to them
3460
+ if (rootConsequences) {
3461
+ for (const consequence of rootConsequences) {
3462
+ // Check if causeRoot can still reach consequence without going through root
3463
+ if (!hasPathExcluding(causeRoot, consequence, root)) {
3464
+ causeConsequences.delete(consequence);
3465
+ }
3466
+ }
3467
+ }
3468
+ }
3469
+ }
3470
+ }
3471
+ if (rootConsequences) {
3472
+ // For each Y that root triggers: remove root from Y's causes
3473
+ // Only remove root's causes if no alternate path exists
3474
+ for (const consequenceRoot of rootConsequences) {
3475
+ const consequenceCauses = causesClosure.get(consequenceRoot);
3476
+ if (consequenceCauses) {
3477
+ // Remove root itself (it's being cleaned up)
3478
+ consequenceCauses.delete(root);
3479
+ // Only remove causes of root if there's no alternate path from them to consequenceRoot
3480
+ if (rootCauses) {
3481
+ for (const cause of rootCauses) {
3482
+ // Check if cause can still reach consequenceRoot without going through root
3483
+ if (!hasPathExcluding(cause, consequenceRoot, root)) {
3484
+ consequenceCauses.delete(cause);
3485
+ }
3486
+ }
3487
+ }
3488
+ }
3489
+ }
3490
+ }
3491
+ // Cross-product cleanup: for each X in causesClosure(B) and Y in consequencesClosure(B),
3492
+ // remove X→Y if B was the only path connecting them
3493
+ if (rootCauses && rootConsequences) {
3494
+ for (const x of rootCauses) {
3495
+ const xConsequences = consequencesClosure.get(x);
3496
+ if (xConsequences) {
3497
+ for (const y of rootConsequences) {
3498
+ // Check if there's still a path from X to Y without going through root
3499
+ // Use BFS to find any path that doesn't include root
3500
+ if (!hasPathExcluding(x, y, root)) {
3501
+ xConsequences.delete(y);
3502
+ const yCauses = causesClosure.get(y);
3503
+ yCauses?.delete(x);
3504
+ }
3505
+ }
3506
+ }
3507
+ }
3508
+ }
3509
+ // Finally, delete the closures for this effect
3510
+ causesClosure.delete(root);
3511
+ consequencesClosure.delete(root);
3512
+ }
3513
+ // Track currently executing effects to prevent re-execution
3514
+ // These are all the effects triggered under `activeEffect`
3515
+ let batchQueue;
3516
+ function hasBatched(effect) {
3517
+ return batchQueue?.all.has(getRoot(effect));
3518
+ }
3519
+ const batchCleanups = new Set();
3520
+ /**
3521
+ * Computes and caches in-degrees for all effects in the batch
3522
+ * Called once when batch starts or when new effects are added
3523
+ */
3524
+ function computeAllInDegrees(batch) {
3525
+ if (options.cycleHandling === 'production')
3526
+ return;
3527
+ const activeEffect = getActiveEffect();
3528
+ const activeRoot = activeEffect ? getRoot(activeEffect) : null;
3529
+ // Reset all in-degrees
3530
+ batch.inDegrees.clear();
3531
+ for (const [root] of batch.all) {
3532
+ let inDegree = 0;
3533
+ const causes = causesClosure.get(root);
3534
+ if (causes) {
3535
+ for (const causeRoot of causes) {
3536
+ // Only count if it's in the batch and not the active/self effect
3537
+ if (batch.all.has(causeRoot) && causeRoot !== activeRoot && causeRoot !== root) {
3538
+ inDegree++;
3539
+ }
3540
+ }
3541
+ }
3542
+ batch.inDegrees.set(root, inDegree);
3543
+ }
3544
+ }
3545
+ /**
3546
+ * Decrements in-degrees of all effects that depend on the executed effect
3547
+ * Called after an effect is executed to update the cached in-degrees
3548
+ */
3549
+ function decrementInDegreesForExecuted(batch, executedRoot) {
3550
+ // Get all effects that this executed effect triggers
3551
+ const consequences = consequencesClosure.get(executedRoot);
3552
+ if (!consequences)
3553
+ return;
3554
+ for (const consequenceRoot of consequences) {
3555
+ // Only update if it's still in the batch
3556
+ if (batch.all.has(consequenceRoot)) {
3557
+ const currentDegree = batch.inDegrees.get(consequenceRoot) ?? 0;
3558
+ if (currentDegree > 0) {
3559
+ batch.inDegrees.set(consequenceRoot, currentDegree - 1);
3560
+ }
3561
+ }
3562
+ }
3563
+ }
3564
+ /**
3565
+ * Finds a path from startRoot to endRoot in the dependency graph
3566
+ * Uses DFS to find the path through direct edges
3567
+ * @param startRoot - Starting effect root
3568
+ * @param endRoot - Target effect root
3569
+ * @param visited - Set of visited nodes (for recursion)
3570
+ * @param path - Current path being explored
3571
+ * @returns Path from startRoot to endRoot, or empty array if no path exists
3572
+ */
3573
+ function findPath(startRoot, endRoot, visited = new Set(), path = []) {
3574
+ if (startRoot === endRoot) {
3575
+ return [...path, endRoot];
3576
+ }
3577
+ if (visited.has(startRoot)) {
3578
+ return [];
3579
+ }
3580
+ visited.add(startRoot);
3581
+ const newPath = [...path, startRoot];
3582
+ const triggers = effectTriggers.get(startRoot);
3583
+ if (triggers) {
3584
+ for (const targetRoot of triggers) {
3585
+ const result = findPath(targetRoot, endRoot, visited, newPath);
3586
+ if (result.length > 0) {
3587
+ return result;
3588
+ }
3589
+ }
3590
+ }
3591
+ return [];
3592
+ }
3593
+ /**
3594
+ * Gets the cycle path when adding an edge would create a cycle
3595
+ * @param callerRoot - Root of the effect that triggers
3596
+ * @param targetRoot - Root of the effect being triggered
3597
+ * @returns Array of effect roots forming the cycle, or empty array if no cycle
3598
+ */
3599
+ function getCyclePathForEdge(callerRoot, targetRoot) {
3600
+ // Find path from targetRoot back to callerRoot (this is the existing path)
3601
+ // Then adding callerRoot -> targetRoot completes the cycle
3602
+ const path = findPath(targetRoot, callerRoot);
3603
+ if (path.length > 0) {
3604
+ // The cycle is: callerRoot -> targetRoot -> ... -> callerRoot
3605
+ return [callerRoot, ...path];
3606
+ }
3607
+ return [];
3608
+ }
3609
+ /**
3610
+ * Checks if adding an edge would create a cycle
3611
+ * Uses causesClosure to check if callerRoot is already a cause of targetRoot
3612
+ * Self-loops (callerRoot === targetRoot) are explicitly ignored and return false
3613
+ *
3614
+ * **Note**: This is the primary optimization benefit of the transitive closure system.
3615
+ * It allows detecting cycles in O(1) time before they are executed.
3616
+ *
3617
+ * @param callerRoot - Root of the effect that triggers
3618
+ * @param targetRoot - Root of the effect being triggered
3619
+ * @returns true if adding this edge would create a cycle
3620
+ */
3621
+ function wouldCreateCycle(callerRoot, targetRoot) {
3622
+ // Self-loops are explicitly ignored - an effect reading and writing the same property
3623
+ // (e.g., obj.prop++) should not create a dependency relationship
3624
+ if (callerRoot === targetRoot) {
3625
+ return false;
3626
+ }
3627
+ // Check if targetRoot already triggers callerRoot (directly or indirectly)
3628
+ // This would create a cycle: callerRoot -> targetRoot -> ... -> callerRoot
3629
+ // Using consequencesClosure: if targetRoot triggers callerRoot, then callerRoot is in consequencesClosure(targetRoot)
3630
+ const targetConsequences = consequencesClosure.get(targetRoot);
3631
+ if (targetConsequences?.has(callerRoot)) {
3632
+ return true; // Cycle detected: targetRoot -> ... -> callerRoot, and we're adding callerRoot -> targetRoot
3633
+ }
3634
+ return false;
3635
+ }
3636
+ /**
3637
+ * Adds an effect to the batch queue
3638
+ * @param effect - The effect to add
3639
+ * @param caller - The active effect that triggered this one (optional)
3640
+ * @param immediate - If true, don't create edges in the dependency graph
3641
+ */
3642
+ function addToBatch(effect, caller, immediate) {
3643
+ const node = getEffectNode(effect);
3644
+ node.cleanup?.();
3645
+ // If the effect was stopped during cleanup (e.g. lazy memoization), don't add it to the batch
3646
+ if (node.stopped) {
3647
+ // console.log(`[DEBUG] addToBatch: ${effect.name} is stopped`)
3648
+ return;
3649
+ }
3650
+ if (!batchQueue) {
3651
+ // console.log(`[DEBUG] addToBatch: no batchQueue`)
3652
+ return;
3653
+ }
3654
+ const root = getRoot(effect);
3655
+ // 1. Add to batch first (needed for cycle detection)
3656
+ if (options.cycleHandling === 'production') {
3657
+ // Production mode: FIFO (delete and re-add to move to end)
3658
+ if (batchQueue.all.has(root)) {
3659
+ batchQueue.all.delete(root);
3660
+ }
3661
+ batchQueue.all.set(root, effect);
3662
+ }
3663
+ else {
3664
+ // Dev/Debug mode: Set if not present (preserve order?)
3665
+ // actually, we might want to update it?
3666
+ // For now, simple set
3667
+ if (batchQueue.all.has(root)) {
3668
+ // console.log(`[DEBUG] ${root.name} already in batch`)
3669
+ return;
3670
+ }
3671
+ batchQueue.all.set(root, effect);
3672
+ // console.log(`[DEBUG] ${root.name} added to batch`)
3673
+ }
3674
+ // batchQueue.all.set(root, effect)
3675
+ // console.log(`[DEBUG] addToBatch: ${root.name} added to batch`)
3676
+ if (caller && !immediate && options.cycleHandling !== 'production') {
3677
+ const callerRoot = getRoot(caller);
3678
+ // const root = getRoot(effect) // Already have root
3679
+ // Check for cycle BEFORE adding edge
3680
+ if (wouldCreateCycle(callerRoot, root)) {
3681
+ const cyclePath = getCyclePathForEdge(callerRoot, root);
3682
+ const cycleMessage = cyclePath.length > 0
3683
+ ? `Cycle detected: ${cyclePath.map((r) => r.name || r.toString()).join(' → ')}`
3684
+ : `Cycle detected: ${callerRoot.name || callerRoot.toString()} → ${root.name || root.toString()} (and back)`;
3685
+ batchQueue.all.delete(root);
3686
+ const causalChain = getTriggerChain(effect);
3687
+ const creationStack = getEffectNode(effect).creationStack;
3688
+ throw new ReactiveError(`[reactive] ${cycleMessage}`, {
3689
+ code: exports.ReactiveErrorCode.CycleDetected,
3690
+ cycle: cyclePath.map((r) => r.name || r.toString()),
3691
+ details: cycleMessage,
3692
+ causalChain,
3693
+ creationStack,
3694
+ });
3695
+ }
3696
+ addGraphEdge(callerRoot, root);
3697
+ }
3698
+ }
3699
+ /**
3700
+ * Adds a cleanup function to be called when the current batch of effects completes
3701
+ * @param cleanup - The cleanup function to add
3702
+ */
3703
+ function addBatchCleanup(cleanup) {
3704
+ if (!batchQueue)
3705
+ cleanup();
3706
+ else
3707
+ batchCleanups.add(cleanup);
3708
+ }
3709
+ /**
3710
+ * Semantic alias for `addBatchCleanup` - defers work to the end of the current reactive batch.
3711
+ *
3712
+ * Use this when an effect needs to perform an action that would modify state the effect depends on,
3713
+ * which would create a reactive cycle. The deferred callback runs after all effects complete.
3714
+ *
3715
+ * @param callback - The callback to defer until after the current batch completes
3716
+ *
3717
+ * @example
3718
+ * ```typescript
3719
+ * effect(() => {
3720
+ * processData()
3721
+ *
3722
+ * // Defer to avoid cycle (createMovement modifies state this effect reads)
3723
+ * defer(() => {
3724
+ * createMovement(data)
3725
+ * })
3726
+ * })
3727
+ * ```
3728
+ */
3729
+ const defer = addBatchCleanup;
3730
+ /**
3731
+ * Gets a cycle path for debugging
3732
+ * Uses DFS to find cycles in the batch
3733
+ * @param batchQueue - The batch queue
3734
+ * @returns Array of effect roots forming a cycle
3735
+ */
3736
+ function getCyclePath(batchQueue) {
3737
+ // If all effects have in-degree > 0, there must be a cycle
3738
+ // Use DFS to find it
3739
+ const visited = new Set();
3740
+ const recursionStack = new Set();
3741
+ const path = [];
3742
+ for (const [root] of batchQueue.all) {
3743
+ if (visited.has(root))
3744
+ continue;
3745
+ const cycle = findCycle(root, visited, recursionStack, path, batchQueue);
3746
+ if (cycle.length > 0) {
3747
+ return cycle;
3748
+ }
3749
+ }
3750
+ return [];
3751
+ }
3752
+ function findCycle(root, visited, recursionStack, path, batchQueue) {
3753
+ if (recursionStack.has(root)) {
3754
+ // Found a cycle! Return the path from the cycle start to root
3755
+ const cycleStart = path.indexOf(root);
3756
+ return path.slice(cycleStart).concat([root]);
3757
+ }
3758
+ if (visited.has(root)) {
3759
+ return [];
3760
+ }
3761
+ visited.add(root);
3762
+ recursionStack.add(root);
3763
+ path.push(root);
3764
+ // Follow edges to effects in the batch
3765
+ // Use direct edges (effectTriggers) for cycle detection
3766
+ const triggers = effectTriggers.get(root);
3767
+ if (triggers) {
3768
+ for (const targetRoot of triggers) {
3769
+ if (batchQueue.all.has(targetRoot)) {
3770
+ const cycle = findCycle(targetRoot, visited, recursionStack, path, batchQueue);
3771
+ if (cycle.length > 0) {
3772
+ return cycle;
3773
+ }
3774
+ }
3775
+ }
3776
+ }
3777
+ path.pop();
3778
+ recursionStack.delete(root);
3779
+ return [];
3780
+ }
3781
+ /**
3782
+ * Executes the next effect in dependency order (using cached in-degrees)
3783
+ * Finds an effect with in-degree 0 and executes it
3784
+ * @returns The return value of the executed effect, or null if batch is complete
3785
+ */
3786
+ function executeNext(effectuatedRoots) {
3787
+ // Find an effect with in-degree 0 using cached values
3788
+ let nextEffect = null;
3789
+ let nextRoot = null;
3790
+ if (options.cycleHandling === 'production') {
3791
+ // In flat mode, we just take the first effect in the queue (FIFO)
3792
+ const first = batchQueue.all.entries().next().value;
3793
+ if (first) {
3794
+ [nextRoot, nextEffect] = first;
3795
+ }
3796
+ }
3797
+ else {
3798
+ // Find an effect with in-degree 0 (no dependencies in batch that still need execution)
3799
+ // Using cached in-degrees for O(n) lookup instead of O(n²)
3800
+ for (const [root, effect] of batchQueue.all) {
3801
+ const inDegree = batchQueue.inDegrees.get(root) ?? 0;
3802
+ // console.log(`[DEBUG] executeNext: checking ${root.name}, inDegree: ${inDegree}`)
3803
+ if (inDegree === 0) {
3804
+ nextEffect = effect;
3805
+ nextRoot = root;
3806
+ break;
3807
+ }
3808
+ }
3809
+ }
3810
+ if (!nextEffect) {
3811
+ // No effect with in-degree 0 - there must be a cycle
3812
+ // If all effects have dependencies, it means there's a circular dependency
3813
+ if (batchQueue.all.size > 0) {
3814
+ let cycle = getCyclePath(batchQueue);
3815
+ // If we couldn't find a cycle path using direct edges, try using closures
3816
+ // (transitive relationships) - if all effects have in-degree > 0, there must be a cycle
3817
+ if (cycle.length === 0) {
3818
+ // Try to find a cycle using consequencesClosure (transitive relationships)
3819
+ // Note: Self-loops are ignored - we only look for cycles between different effects
3820
+ for (const [root] of batchQueue.all) {
3821
+ const consequences = consequencesClosure.get(root);
3822
+ if (consequences) {
3823
+ // Check if any consequence in the batch also has root as a consequence
3824
+ for (const consequence of consequences) {
3825
+ // Skip self-loops - they are ignored
3826
+ if (consequence === root)
3827
+ continue;
3828
+ if (batchQueue.all.has(consequence)) {
3829
+ const consequenceConsequences = consequencesClosure.get(consequence);
3830
+ if (consequenceConsequences?.has(root)) {
3831
+ // Found cycle: root -> consequence -> root
3832
+ cycle = [root, consequence, root];
3833
+ break;
3834
+ }
3835
+ }
3836
+ }
3837
+ if (cycle.length > 0)
3838
+ break;
3839
+ }
3840
+ }
3841
+ }
3842
+ const cycleMessage = cycle.length > 0
3843
+ ? `Cycle detected: ${cycle.map((r) => r.name || '<anonymous>').join(' → ')}`
3844
+ : 'Cycle detected in effect batch - all effects have dependencies that prevent execution';
3845
+ throw new ReactiveError(`[reactive] ${cycleMessage}`, {
3846
+ code: exports.ReactiveErrorCode.CycleDetected,
3847
+ cycle: cycle.map((r) => r.name || r.toString()),
3848
+ details: cycleMessage,
3849
+ });
3850
+ }
3851
+ return null; // Batch complete
3852
+ }
3853
+ effectuatedRoots.push(getRoot(nextEffect));
3854
+ // Execute the effect
3855
+ const result = nextEffect();
3856
+ // Remove from batch and update in-degrees of dependents
3857
+ batchQueue.all.delete(nextRoot);
3858
+ batchQueue.inDegrees.delete(nextRoot);
3859
+ decrementInDegreesForExecuted(batchQueue, nextRoot);
3860
+ return result;
3861
+ }
3862
+ // Track which sub-effects have been executed to prevent infinite loops
3863
+ // These are all the effects triggered under `activeEffect` and all their sub-effects
3864
+ function batch(effect, immediate) {
3865
+ if (broken) {
3866
+ throw new ReactiveError('[reactive] Reactive system is broken after an unrecoverable error. Call reset() to recover.', { code: exports.ReactiveErrorCode.BrokenEffects });
3867
+ }
3868
+ if (!Array.isArray(effect))
3869
+ effect = [effect];
3870
+ const roots = effect.map(getRoot);
3871
+ try {
3872
+ if (batchQueue) {
3873
+ // Nested batch - add to existing
3874
+ options?.chain(roots, getRoot(getActiveEffect()));
3875
+ const caller = getActiveEffect();
3876
+ for (let i = 0; i < effect.length; i++)
3877
+ addToBatch(effect[i], caller, immediate === 'immediate');
3878
+ if (immediate) {
3879
+ const firstReturn = {};
3880
+ // Execute immediately (before batch returns)
3881
+ for (let i = 0; i < effect.length; i++) {
3882
+ try {
3883
+ const rv = effect[i]();
3884
+ if (rv !== undefined && !('value' in firstReturn))
3885
+ firstReturn.value = rv;
3886
+ }
3887
+ finally {
3888
+ const root = getRoot(effect[i]);
3889
+ batchQueue.all.delete(root);
3890
+ }
3891
+ }
3892
+ return firstReturn.value;
3893
+ }
3894
+ // Otherwise, effects will be picked up in next executeNext() call
3895
+ }
3896
+ else {
3897
+ // New batch - initialize
3898
+ if (!activationRegistry)
3899
+ activationRegistry = new Map();
3900
+ else
3901
+ throw new Error('Batch already in progress');
3902
+ optionCall('beginChain', roots);
3903
+ batchQueue = {
3904
+ all: new Map(),
3905
+ inDegrees: new Map(),
3906
+ };
3907
+ const caller = getActiveEffect();
3908
+ const effectuatedRoots = [];
3909
+ const firstReturn = {};
3910
+ let success = false;
3911
+ try {
3912
+ if (immediate) {
3913
+ // Execute initial effects in providing order
3914
+ for (let i = 0; i < effect.length; i++) {
3915
+ try {
3916
+ const rv = effect[i]();
3917
+ if (rv !== undefined && !('value' in firstReturn))
3918
+ firstReturn.value = rv;
3919
+ }
3920
+ finally {
3921
+ batchQueue.all.delete(getRoot(effect[i]));
3922
+ }
3923
+ }
3924
+ }
3925
+ else {
3926
+ // Add initial effects to batch and compute dependencies
3927
+ const len = effect.length;
3928
+ for (let i = 0; i < len; i++) {
3929
+ addToBatch(effect[i], caller, false);
3930
+ }
3931
+ computeAllInDegrees(batchQueue);
3932
+ }
3933
+ // Process the batch
3934
+ while (batchQueue.all.size > 0 || batchCleanups.size > 0) {
3935
+ if (batchQueue.all.size > 0) {
3936
+ if (effectuatedRoots.length > options.maxEffectChain) {
3937
+ const cycle = findCycleInChain(effectuatedRoots);
3938
+ const trace = formatRoots(effectuatedRoots);
3939
+ const message = cycle
3940
+ ? `Max effect chain reached (cycle detected: ${formatRoots(cycle)})`
3941
+ : `Max effect chain reached (trace: ${trace})`;
3942
+ const queuedRoots = batchQueue ? Array.from(batchQueue.all.keys()) : [];
3943
+ const queued = queuedRoots.map((r) => r.name || '<anonymous>');
3944
+ const debugInfo = {
3945
+ code: exports.ReactiveErrorCode.MaxDepthExceeded,
3946
+ effectuatedRoots,
3947
+ cycle,
3948
+ trace,
3949
+ maxEffectChain: options.maxEffectChain,
3950
+ queued: queued.slice(0, 50),
3951
+ queuedCount: queued.length,
3952
+ // Try to get causation for the last effect
3953
+ causalChain: effectuatedRoots.length > 0
3954
+ ? getTriggerChain(batchQueue.all.get(effectuatedRoots[effectuatedRoots.length - 1]))
3955
+ : [],
3956
+ };
3957
+ switch (options.maxEffectReaction) {
3958
+ case 'throw':
3959
+ throw new ReactiveError(`[reactive] ${message}`, debugInfo);
3960
+ case 'debug':
3961
+ // biome-ignore lint/suspicious/noDebugger: This is the whole point here
3962
+ debugger;
3963
+ throw new ReactiveError(`[reactive] ${message}`, debugInfo);
3964
+ case 'warn':
3965
+ options.warn(`[reactive] ${message} (queued: ${queued.slice(0, 10).join(', ')}${queued.length > 10 ? ', …' : ''})`);
3966
+ break;
3967
+ }
3968
+ }
3969
+ const rv = executeNext(effectuatedRoots);
3970
+ if (rv !== undefined && !('value' in firstReturn))
3971
+ firstReturn.value = rv;
3972
+ }
3973
+ else {
3974
+ // Process cleanups. If they trigger more effects, they will be caught in the next iteration.
3975
+ const cleanups = Array.from(batchCleanups);
3976
+ batchCleanups.clear();
3977
+ for (const cleanup of cleanups)
3978
+ cleanup();
3979
+ // In immediate mode, we traditionally don't process recursive effects from cleanups.
3980
+ // If we want to keep that behavior: if (immediate) break
3981
+ }
3982
+ }
3983
+ success = true;
3984
+ }
3985
+ finally {
3986
+ if (!success)
3987
+ panicThrow();
3988
+ activationRegistry = undefined;
3989
+ batchQueue = undefined;
3990
+ batchCleanups.clear();
3991
+ optionCall('endChain');
3992
+ }
3993
+ return firstReturn.value;
3994
+ }
3995
+ }
3996
+ finally {
3997
+ }
3998
+ }
3999
+ function panicThrow() {
4000
+ broken = true;
4001
+ }
4002
+ /**
4003
+ * Resets the reactive system to a consistent state.
4004
+ * Call this after an unrecoverable error has set the system to "broken".
4005
+ * This clears all batch state, effect dependency graphs, and watcher registrations.
4006
+ * All existing effects become orphaned and must be recreated.
4007
+ */
4008
+ function reset() {
4009
+ broken = false;
4010
+ activationRegistry = undefined;
4011
+ batchQueue = undefined;
4012
+ batchCleanups.clear();
4013
+ effectTriggers = new WeakMap();
4014
+ effectTriggeredBy = new WeakMap();
4015
+ causesClosure = new WeakMap();
4016
+ consequencesClosure = new WeakMap();
4017
+ resetRegistry();
4018
+ effectHistory.present.active = undefined;
4019
+ }
4020
+ // Inject batch function to allow atomic game loops in requestAnimationFrame/setTimeout/...
4021
+ // Note: Automatic batching of async callbacks (setTimeout, Promise.then, etc.) is NOT implemented.
4022
+ // Rationale: (1) asyncHooks.addHook API doesn't support knowing when callbacks complete (needed for batching),
4023
+ // (2) hooking all callback-creating functions adds overhead without guaranteed benefit,
4024
+ // (3) incomplete coverage in Node (async_hooks misses user-land patterns).
4025
+ // Solution: Use explicit @atomic decorator or manual batch() calls where optimization is needed.
4026
+ /**
4027
+ * Decorator that makes methods atomic - batches all effects triggered within the method
4028
+ */
4029
+ const atomic = decorator({
4030
+ method(original) {
4031
+ return function (...args) {
4032
+ const atomicEffect = () => original.apply(this, args);
4033
+ // Debug: helpful to have a name
4034
+ Object.defineProperty(atomicEffect, 'name', { value: `atomic(${original.name})` });
4035
+ return batch(atomicEffect, 'immediate');
4036
+ };
4037
+ },
4038
+ default(original) {
4039
+ return function (...args) {
4040
+ const atomicEffect = () => original.apply(this, args);
4041
+ // Debug: helpful to have a name
4042
+ Object.defineProperty(atomicEffect, 'name', { value: `atomic(${original.name})` });
4043
+ return batch(atomicEffect, 'immediate');
4044
+ };
4045
+ },
4046
+ });
4047
+ const fr = new FinalizationRegistry((f) => f());
4048
+ /**
4049
+ * @param fn - The effect function to run - provides the cleaner
4050
+ * @returns The cleanup function
4051
+ */
4052
+ /**
4053
+ * Creates a reactive effect that automatically re-runs when dependencies change
4054
+ * @param fn - The effect function that provides dependencies and may return a cleanup function or Promise
4055
+ * @param options - Options for effect execution
4056
+ * @returns A cleanup function to stop the effect
4057
+ */
4058
+ const effect = named(effectMarker.leave, flavored(function effect(fn, effectOptions) {
4059
+ if (effectOptions?.name)
4060
+ Object.defineProperty(fn, 'name', { value: effectOptions.name });
4061
+ // Use per-effect asyncMode or fall back to global option
4062
+ const asyncMode = effectOptions?.asyncMode ?? options.asyncMode ?? 'cancel';
4063
+ // Create the effect function - naming it for debug
4064
+ const runEffect = () => {
4065
+ const node = getEffectNode(runEffect);
4066
+ // Clear previous dependencies
4067
+ if (node.cleanup) {
4068
+ const prevCleanup = node.cleanup;
4069
+ node.cleanup = undefined;
4070
+ try {
4071
+ untracked(() => prevCleanup());
4072
+ }
4073
+ catch (error) {
4074
+ // If we want to report them, we could use options.warn or similar
4075
+ options.warn('Error during effect cleanup', error);
4076
+ }
4077
+ }
4078
+ // Handle async modes when effect is retriggered
4079
+ if (runningPromise) {
4080
+ if (asyncMode === 'cancel' && cancelPrevious) {
4081
+ // Cancel previous execution
4082
+ cancelPrevious();
4083
+ cancelPrevious = null;
4084
+ runningPromise = null;
4085
+ }
4086
+ else if (asyncMode === 'ignore') {
4087
+ // Ignore new execution while async work is running
4088
+ return;
4089
+ }
4090
+ // Note: 'queue' mode not yet implemented
4091
+ }
4092
+ // The effect has been stopped after having been planned
4093
+ if (effectStopped)
4094
+ return;
4095
+ optionCall('enter', getRoot(fn));
4096
+ let reactionCleanup;
4097
+ let result;
4098
+ let caught = 0;
4099
+ // Default thrower (self)
4100
+ let thrower = (error) => {
4101
+ throw error;
4102
+ };
4103
+ node.forwardThrow = thrower;
4104
+ let errorToThrow;
4105
+ try {
4106
+ result = tracked(named(effectMarker.enter, () => fn.call(null, access)));
4107
+ optionCall('leave', fn);
4108
+ if (result &&
4109
+ typeof result !== 'function' &&
4110
+ (typeof result !== 'object' || !('then' in result)))
4111
+ throw new ReactiveError(`[reactive] Effect returned a non-function value: ${result}`);
4112
+ // Check if result is a Promise (async effect)
4113
+ if (result && typeof result === 'object' && typeof result.then === 'function') {
4114
+ const originalPromise = result;
4115
+ // Create a cancellation promise that we can reject
4116
+ let cancelReject = null;
4117
+ const cancelPromise = new Promise((_, reject) => {
4118
+ cancelReject = reject;
4119
+ });
4120
+ const cancelError = new ReactiveError('[reactive] Effect canceled due to dependency change');
4121
+ // Race between the actual promise and cancellation
4122
+ // If canceled, the race rejects, which will propagate through any promise chain
4123
+ runningPromise = Promise.race([originalPromise, cancelPromise]);
4124
+ // Store the cancellation function
4125
+ cancelPrevious = () => {
4126
+ if (cancelReject) {
4127
+ cancelReject(cancelError);
4128
+ }
4129
+ };
4130
+ // Wrap the original promise chain so cancellation propagates
4131
+ // This ensures that when we cancel, the original promise's .catch() handlers are triggered
4132
+ // We do this by rejecting the race promise, which makes the original promise chain see the rejection
4133
+ // through the zone-wrapped .then()/.catch() handlers
4134
+ runningPromise = runningPromise.catch((error) => {
4135
+ // Propagate async errors to the effect's error handler
4136
+ // This ensures onEffectThrow handlers are triggered for async errors
4137
+ if (error !== cancelError) {
4138
+ thrower(error);
4139
+ }
4140
+ // If thrower didn't throw (handled), we absorb the error.
4141
+ // If thrower threw (unhandled), it propagates as a new unhandled rejection, which is correct.
4142
+ });
4143
+ }
4144
+ else {
4145
+ // Synchronous result - treat as cleanup function
4146
+ reactionCleanup = result;
4147
+ }
4148
+ }
4149
+ catch (error) {
4150
+ // catcher:self`
4151
+ errorToThrow = error;
4152
+ }
4153
+ finally {
4154
+ access.reaction = true;
4155
+ }
4156
+ // Create cleanup function for next run
4157
+ node.cleanup = () => {
4158
+ node.cleanup = undefined;
4159
+ reactionCleanup?.();
4160
+ reactionCleanup = undefined;
4161
+ delete node.trackers;
4162
+ delete node.catchers;
4163
+ // Remove this effect from all reactive objects it's watching
4164
+ const effectObjects = exports.effectToReactiveObjects.get(runEffect);
4165
+ if (effectObjects) {
4166
+ for (const reactiveObj of effectObjects) {
4167
+ const objectWatchers = exports.watchers.get(reactiveObj);
4168
+ if (objectWatchers) {
4169
+ for (const [prop, deps] of objectWatchers.entries()) {
4170
+ deps.delete(runEffect);
4171
+ if (deps.size === 0) {
4172
+ objectWatchers.delete(prop);
4173
+ }
4174
+ }
4175
+ if (objectWatchers.size === 0) {
4176
+ exports.watchers.delete(reactiveObj);
4177
+ }
4178
+ }
4179
+ }
4180
+ exports.effectToReactiveObjects.delete(runEffect);
4181
+ }
4182
+ // Invoke all child stops (recursive via subEffectCleanup calling its own mainCleanup)
4183
+ const children = node.children;
4184
+ if (children) {
4185
+ for (const childCleanup of children)
4186
+ childCleanup();
4187
+ delete node.children;
4188
+ }
4189
+ };
4190
+ // Define bubbling thrower
4191
+ thrower = (error) => {
4192
+ const catches = node.catchers;
4193
+ if (catches)
4194
+ while (caught < catches.length) {
4195
+ reactionCleanup?.(error);
4196
+ reactionCleanup = undefined;
4197
+ try {
4198
+ reactionCleanup = catches[caught](error);
4199
+ return;
4200
+ }
4201
+ catch (e) {
4202
+ caught++;
4203
+ }
4204
+ }
4205
+ if (parent) {
4206
+ const parentNode = getEffectNode(parent);
4207
+ if (parentNode.forwardThrow)
4208
+ parentNode.forwardThrow(error);
4209
+ else
4210
+ throw error;
4211
+ }
4212
+ else
4213
+ throw error;
4214
+ };
4215
+ // Update the node's forwardThrow to the bubbling one
4216
+ node.forwardThrow = thrower;
4217
+ if (errorToThrow)
4218
+ thrower(errorToThrow);
4219
+ };
4220
+ // Initialize metadata node
4221
+ const node = getEffectNode(runEffect);
4222
+ if (isDevtoolsEnabled()) {
4223
+ const stack = getStackFrame(); // Robustly skips internal mutts frames
4224
+ if (stack.length > 0) {
4225
+ node.creationStack = stack;
4226
+ }
4227
+ }
4228
+ const tracked = named(effectMarker.leave, effectHistory.present.with(runEffect, () => named(effectMarker.leave, effectAggregator.zoned)));
4229
+ const ascended = named(effectMarker.leave, effectHistory.zoned);
4230
+ const parent = effectHistory.present.active;
4231
+ // Set parent relationship in node
4232
+ node.parent = parent;
4233
+ // let thrower: CatchFunction | undefined // Moved inside runEffect
4234
+ let effectStopped = false;
4235
+ const access = {
4236
+ tracked,
4237
+ ascend: named(effectMarker.leave, (fn) => ascended(named(effectMarker.enter, () => fn.call(null)))),
4238
+ //named(effectMarker.enter, (fn) => ascended(fn)),
4239
+ reaction: false,
4240
+ };
4241
+ let runningPromise = null;
4242
+ let cancelPrevious = null;
4243
+ if (effectOptions?.dependencyHook) {
4244
+ node.dependencyHook = effectOptions.dependencyHook;
4245
+ }
4246
+ // Mark the runEffect callback with the original function as its root
4247
+ markWithRoot(runEffect, fn);
4248
+ function augmentedRv(rv) {
4249
+ return Object.defineProperties(rv, {
4250
+ [stopped]: {
4251
+ get: () => effectStopped,
4252
+ },
4253
+ });
4254
+ }
4255
+ // Register strict mode if enabled
4256
+ if (effectOptions?.opaque) {
4257
+ node.isOpaque = true;
4258
+ }
4259
+ if (isDevtoolsEnabled()) {
4260
+ registerEffectForDebug(runEffect);
4261
+ }
4262
+ // Store parent relationship for hierarchy traversal - ALREADY DONE ABOVE via getEffectNode
4263
+ batch(runEffect, 'immediate');
4264
+ // Only ROOT effects are registered for GC cleanup and zone tracking
4265
+ const isRootEffect = !parent;
4266
+ const stopEffect = () => {
4267
+ if (effectStopped)
4268
+ return;
4269
+ effectStopped = true;
4270
+ node.stopped = true;
4271
+ // Cancel any running async work
4272
+ if (cancelPrevious) {
4273
+ cancelPrevious();
4274
+ cancelPrevious = null;
4275
+ runningPromise = null;
4276
+ }
4277
+ try {
4278
+ node.cleanup?.();
4279
+ }
4280
+ catch (error) {
4281
+ // Cleanup errors should basically be ignored or at least not stop the world
4282
+ // If we want to report them, we could use options.warn or similar
4283
+ options.warn('Error during effect cleanup', error);
4284
+ }
4285
+ // Clean up dependency graph edges
4286
+ cleanupEffectFromGraph(runEffect);
4287
+ fr.unregister(stopEffect);
4288
+ };
4289
+ if (isRootEffect) {
4290
+ const callIfCollected = augmentedRv(() => stopEffect());
4291
+ fr.register(callIfCollected, () => {
4292
+ stopEffect();
4293
+ optionCall('garbageCollected', fn);
4294
+ }, stopEffect);
4295
+ return callIfCollected;
4296
+ }
4297
+ // Register this effect to be stopped when the parent effect is cleaned up
4298
+ if (parent) {
4299
+ const parentNode = getEffectNode(parent);
4300
+ if (!parentNode.children) {
4301
+ parentNode.children = new Set();
4302
+ }
4303
+ const children = parentNode.children;
4304
+ const subEffectCleanup = augmentedRv(() => {
4305
+ children.delete(subEffectCleanup);
4306
+ // Execute this child effect cleanup (which triggers its own mainCleanup)
4307
+ stopEffect();
4308
+ });
4309
+ children.add(subEffectCleanup);
4310
+ return subEffectCleanup;
4311
+ }
4312
+ // Should not be reachable given isRootEffect check, but for type safety
4313
+ return augmentedRv(stopEffect);
4314
+ }, {
4315
+ get opaque() {
4316
+ return flavorOptions(this, { opaque: true }, 'opaque');
4317
+ },
4318
+ named(name) {
4319
+ return flavorOptions(this, { name }, 'named');
4320
+ },
4321
+ }));
4322
+ /**
4323
+ * Executes a function without tracking dependencies but maintains parent cleanup relationship
4324
+ * Effects created inside will still be cleaned up when the parent effect is destroyed
4325
+ * @param fn - The function to execute
4326
+ */
4327
+ function untracked(fn) {
4328
+ return effectHistory.present.root(fn);
4329
+ }
4330
+ /**
4331
+ * Executes a function from a virgin/root context - no parent effect, no tracking
4332
+ * Creates completely independent effects that won't be cleaned up by any parent
4333
+ * @param fn - The function to execute
4334
+ */
4335
+ function root(fn) {
4336
+ return effectHistory.root(fn);
4337
+ }
4338
+ function biDi(received, get, set) {
4339
+ if (typeof get !== 'function') {
4340
+ set = get.set;
4341
+ get = get.get;
4342
+ }
4343
+ let programmaticallySetValue = Symbol();
4344
+ effect(markWithRoot(() => {
4345
+ const newValue = get();
4346
+ if (unwrap(newValue) !== programmaticallySetValue)
4347
+ received(newValue);
4348
+ }, received));
4349
+ return set
4350
+ ? atomic((value) => {
4351
+ programmaticallySetValue = unwrap(value);
4352
+ set(value);
4353
+ })
4354
+ : () => { };
4355
+ }
4356
+
4357
+ exports.AZone = AZone;
4358
+ exports.DecoratorError = DecoratorError;
4359
+ exports.FoolProof = FoolProof;
4360
+ exports.IterableWeakMap = IterableWeakMap;
4361
+ exports.IterableWeakSet = IterableWeakSet;
4362
+ exports.ReactiveBase = ReactiveBase;
4363
+ exports.ReactiveError = ReactiveError;
4364
+ exports.Zone = Zone;
4365
+ exports.ZoneAggregator = ZoneAggregator;
4366
+ exports.ZoneHistory = ZoneHistory;
4367
+ exports.__classPrivateFieldGet = __classPrivateFieldGet;
4368
+ exports.__classPrivateFieldSet = __classPrivateFieldSet;
4369
+ exports.__esDecorate = __esDecorate;
4370
+ exports.__runInitializers = __runInitializers;
4371
+ exports.__setFunctionName = __setFunctionName;
4372
+ exports.addBatchCleanup = addBatchCleanup;
4373
+ exports.arrayEquals = arrayEquals;
4374
+ exports.asyncZone = asyncZone;
4375
+ exports.atomic = atomic;
4376
+ exports.biDi = biDi;
4377
+ exports.buildReactivityGraph = buildReactivityGraph;
4378
+ exports.captureNodeLineage = captureNodeLineage;
4379
+ exports.cleanedBy = cleanedBy;
4380
+ exports.cleanup = cleanup;
4381
+ exports.contentRef = contentRef;
4382
+ exports.createFlavor = createFlavor;
4383
+ exports.debugOptions = debugOptions;
4384
+ exports.decorator = decorator;
4385
+ exports.deepCompare = deepCompare;
4386
+ exports.deepWatchers = deepWatchers;
4387
+ exports.defer = defer;
4388
+ exports.dependant = dependant;
4389
+ exports.derived = derived;
4390
+ exports.effect = effect;
4391
+ exports.effectAggregator = effectAggregator;
4392
+ exports.effectMarker = effectMarker;
4393
+ exports.effectToDeepWatchedObjects = effectToDeepWatchedObjects;
4394
+ exports.enableDevTools = enableDevTools;
4395
+ exports.flavorOptions = flavorOptions;
4396
+ exports.flavored = flavored;
4397
+ exports.forceEnableGraphTracking = forceEnableGraphTracking;
4398
+ exports.formatLineage = formatLineage;
4399
+ exports.getActivationLog = getActivationLog;
4400
+ exports.getActiveEffect = getActiveEffect;
4401
+ exports.getDependencies = getDependencies;
4402
+ exports.getDependencyGraph = getDependencyGraph;
4403
+ exports.getDependents = getDependents;
4404
+ exports.getLineage = getLineage;
4405
+ exports.getMutationHistory = getMutationHistory;
4406
+ exports.getRoot = getRoot;
4407
+ exports.getStackFrame = getStackFrame;
4408
+ exports.getState = getState;
4409
+ exports.getTriggerChain = getTriggerChain;
4410
+ exports.immutables = immutables;
4411
+ exports.isConstructor = isConstructor;
4412
+ exports.isDevtoolsEnabled = isDevtoolsEnabled;
4413
+ exports.isNonReactive = isNonReactive;
4414
+ exports.isOwnAccessor = isOwnAccessor;
4415
+ exports.isReactive = isReactive;
4416
+ exports.legacyDecorator = legacyDecorator;
4417
+ exports.lineageFormatter = lineageFormatter;
4418
+ exports.logError = logError;
4419
+ exports.markWithRoot = markWithRoot;
4420
+ exports.metaProtos = metaProtos;
4421
+ exports.mixin = mixin;
4422
+ exports.modernDecorator = modernDecorator;
4423
+ exports.named = named;
4424
+ exports.nodeLineage = nodeLineage;
4425
+ exports.nodeLineageLegacy = nodeLineageLegacy;
4426
+ exports.nonReactiveClass = nonReactiveClass;
4427
+ exports.nonReactiveMark = nonReactiveMark;
4428
+ exports.nonReactiveObjects = nonReactiveObjects;
4429
+ exports.notifyPropertyChange = notifyPropertyChange;
4430
+ exports.objectParents = objectParents;
4431
+ exports.objectToProxy = objectToProxy;
4432
+ exports.objectsWithDeepWatchers = objectsWithDeepWatchers;
4433
+ exports.onEffectThrow = onEffectThrow;
4434
+ exports.onEffectTrigger = onEffectTrigger;
4435
+ exports.optionCall = optionCall;
4436
+ exports.options = options;
4437
+ exports.parseStackLine = parseStackLine;
4438
+ exports.projectionInfo = projectionInfo;
4439
+ exports.proxyToObject = proxyToObject;
4440
+ exports.reactive = reactive;
4441
+ exports.recordTriggerLink = recordTriggerLink;
4442
+ exports.registerEffectForDebug = registerEffectForDebug;
4443
+ exports.registerNativeReactivity = registerNativeReactivity;
4444
+ exports.registerObjectForDebug = registerObjectForDebug;
4445
+ exports.renamed = renamed;
4446
+ exports.reset = reset;
4447
+ exports.root = root;
4448
+ exports.rootFunction = rootFunction;
4449
+ exports.setEffectName = setEffectName;
4450
+ exports.setObjectName = setObjectName;
4451
+ exports.showLineagePanel = showLineagePanel;
4452
+ exports.stopped = stopped;
4453
+ exports.tag = tag;
4454
+ exports.touched = touched;
4455
+ exports.touched1 = touched1;
4456
+ exports.unreactiveProperties = unreactiveProperties;
4457
+ exports.untracked = untracked;
4458
+ exports.unwrap = unwrap;
4459
+ exports.wrapLineageForDebug = wrapLineageForDebug;
4460
+ exports.zip = zip;
4461
+ //# sourceMappingURL=index-VTO-b2vR.cjs.map